commons-lang-2.6-src/build.xml100644 0 0 32203 11513702447 13534 0ustar 0 0 commons-lang-2.6-src/checkstyle.xml100644 0 0 3605 11513702447 14557 0ustar 0 0 commons-lang-2.6-src/default.properties100644 0 0 5174 11513702447 15444 0ustar 0 0 # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "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 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # $Id: default.properties 1058784 2011-01-13 23:03:42Z niallp $ # The pathname of the "junit.jar" JAR file junit.jar = ${junit.home}/junit-3.8.1.jar # Whether or not to fork tests junit.fork = true # The name of this component component.name = commons-lang # The primary package name of this component component.package = org.apache.commons.lang # The title of this component component.title = Core Language Utilities # The current version number of this component component.version = 2.6 # The name that is used to create the jar file final.name = ${component.name}-${component.version} # The base directory for compilation targets build.home = target # The base directory for component configuration files conf.home = src/conf # The base directory for component sources source.home = src/main/java # The base directory for unit test sources test.home = src/test/java # Should Java compilations set the 'debug' compiler option? compile.debug = true # Should Java compilations set the 'deprecation' compiler option? compile.deprecation = true # Should Java compilations set the 'optimize' compiler option? compile.optimize = true # Generate class files for specific VM version (e.g., 1.1 or 1.2). # Note that the default value depends on the JVM that is running Ant. # In particular, if you use JDK 1.4+ the generated classes will not be usable # for a 1.1 Java VM unless you explicitly set this attribute to the value 1.1 # (which is the default value for JDK 1.1 to 1.3). compile.target = 1.3 # Specifies the source version for the Java compiler. # Corresponds to the source attribute for the ant javac task. # Valid values are 1.3, 1.4, 1.5. compile.source = 1.3 # Should all tests fail if one does? test.failonerror = true # The test runner to execute test.runner = junit.textui.TestRunner commons-lang-2.6-src/findbugs-exclude-filter.xml100644 0 0 7430 11513702447 17134 0ustar 0 0 commons-lang-2.6-src/LICENSE.txt100644 0 0 26450 11513702447 13545 0ustar 0 0 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "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 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. commons-lang-2.6-src/NOTICE.txt100644 0 0 262 11513702447 13375 0ustar 0 0 Apache Commons Lang Copyright 2001-2011 The Apache Software Foundation This product includes software developed by The Apache Software Foundation (http://www.apache.org/). commons-lang-2.6-src/pom.xml100644 0 0 42126 11513702447 13235 0ustar 0 0 org.apache.commons commons-parent 17 4.0.0 commons-lang commons-lang 2.6 Commons Lang 2001 Commons Lang, a package of Java utility classes for the classes that are in java.lang's hierarchy, or are considered to be so standard as to justify existence in java.lang. http://commons.apache.org/lang/ jira http://issues.apache.org/jira/browse/LANG scm:svn:http://svn.apache.org/repos/asf/commons/proper/lang/branches/LANG_2_X scm:svn:https://svn.apache.org/repos/asf/commons/proper/lang/branches/LANG_2_X http://svn.apache.org/viewvc/commons/proper/lang/branches/LANG_2_X Daniel Rall dlr dlr@finemaltcoding.com CollabNet, Inc. Java Developer Stephen Colebourne scolebourne scolebourne@joda.org SITA ATS Ltd 0 Java Developer Henri Yandell bayard bayard@apache.org Java Developer Steven Caswell scaswell stevencaswell@apache.org Java Developer -5 Robert Burrell Donkin rdonkin rdonkin@apache.org Java Developer Gary D. Gregory ggregory ggregory@seagullsw.com Seagull Software -8 Java Developer Phil Steitz psteitz phil@steitz.com Java Developer Fredrik Westermarck fredrik Java Developer James Carman jcarman jcarman@apache.org Carman Consulting, Inc. Java Developer Niall Pemberton niallp Java Developer Matt Benson mbenson Java Developer Joerg Schaible joehni joerg.schaible@gmx.de Java Developer +1 Oliver Heger oheger oheger@apache.org +1 Java Developer Paul Benedict pbenedict pbenedict@apache.org Java Developer C. Scott Ananian Chris Audley Stephane Bailliez Michael Becke Benjamin Bentmann Ola Berg Nathan Beyer Stefan Bodewig Janek Bogucki Mike Bowler Sean Brown Alexander Day Chaffee Al Chou Greg Coladonato Maarten Coene Justin Couch Michael Davey Norm Deane Ringo De Smet Russel Dittmar Steve Downey Matthias Eichel Christopher Elkins Chris Feldhacker Pete Gieser Jason Gritman Matthew Hawthorne Michael Heuer Chris Hyzer Marc Johnson Shaun Kalley Tetsuya Kaneuchi Nissim Karpenstein Ed Korthof Holger Krauth Rafal Krupinski Rafal Krzewski Craig R. McClanahan Rand McNeely Hendrik Maryns Dave Meikle Nikolay Metchev Kasper Nielsen Tim O'Brien Brian S O'Neill Andrew C. Oliver Alban Peignier Moritz Petersen Dmitri Plotnikov Neeme Praks Eric Pugh Stephen Putman Travis Reeder Antony Riley Scott Sanders Ralph Schaer Henning P. Schmiedehausen Sean Schofield Robert Scholte Reuben Sivan Ville Skytta Jan Sorensen Glen Stampoultzis Scott Stanchfield Jon S. Stevens Sean C. Sullivan Ashwin Suresh Helge Tesgaard Arun Mammen Thomas Masato Tezuka Jeff Varszegi Chris Webb Mario Winterer Stepan Koltsov Holger Hoffstatte Derek C. Ashmore junit junit 3.8.1 test UTF-8 UTF-8 1.3 1.3 lang 2.6 (Java 1.3+) 3.0-beta (Java 5.0+) LANG 12310481 **/RandomUtilsFreqTest.java org.apache.maven.plugins maven-surefire-plugin **/*Test.java **/EntitiesPerformanceTest.java ${random.exclude.test} maven-assembly-plugin src/assembly/bin.xml src/assembly/src.xml gnu test-random-freq org.apache.maven.plugins maven-surefire-plugin **/RandomUtilsFreqTest.java org.apache.maven.plugins maven-changes-plugin 2.3 ${basedir}/src/site/changes/changes.xml %URL%/%ISSUE% changes-report maven-checkstyle-plugin 2.6 ${basedir}/checkstyle.xml false org.codehaus.mojo findbugs-maven-plugin 2.3.1 Normal Default ${basedir}/findbugs-exclude-filter.xml org.codehaus.mojo cobertura-maven-plugin 2.4 org.codehaus.mojo clirr-maven-plugin 2.2.2 2.5 info commons-lang-2.6-src/PROPOSAL.html100644 0 0 6127 11513702447 14026 0ustar 0 0 Proposal for Lang Package

Proposal for Lang Package

(0) Rationale

The standard Java libraries fail to provide enough methods for manipulation of its main components. The Lang Package provides these extra methods. There are other classes which might justifiably be included in java.lang someday, this package also provides for them.

(1) Scope of the Package

This proposal is to create a package of Java utility classes for the classes that are in java.lang's hierarchy, or are considered to be so standard as to justify existence in java.lang. The Lang Package also applies to primitives and arrays.

(1.5) Interaction With Other Packages

Lang relies only on standard JDK 1.2 (or later) APIs for production deployment. It utilizes the JUnit unit testing framework for developing and executing unit tests, but this is of interest only to developers of the component. Lang will be a dependency for several existing components in the open source world.

No external configuration files are utilized.

(2) Initial Source of the Package

The initial classes came from the Commons.Util subproject.

The proposed package name for the new component is org.apache.commons.lang.

(3) Required Jakarta-Commons Resources

  • CVS Repository - New directory lang in the jakarta-commons CVS repository.
  • Mailing List - Discussions will take place on the general dev@commons.apache.org mailing list. To help list subscribers identify messages of interest, it is suggested that the message subject of messages about this component be prefixed with [lang].
  • Bugzilla - New component "Lang" under the "Commons" product category, with appropriate version identifiers as needed.
  • Jyve FAQ - New category "commons-lang" (when available).

(4) Initial Committers

The initial committers on the Lang component shall be as follows:

  • Henri Yandell (bayard)
  • Daniel Rall (dlr)
  • Stephen Colebourne (scolebourne)

commons-lang-2.6-src/RELEASE-NOTES.txt100644 0 0 5717 11513702447 14414 0ustar 0 0 $Id: RELEASE-NOTES.txt 1058313 2011-01-12 20:59:27Z niallp $ Commons Lang Package Version 2.6 Release Notes INTRODUCTION: This document contains the release notes for the 2.6 version of Apache Commons Lang. Commons Lang is a set of utility functions and reusable components that should be of use in any Java environment. COMPATIBILITY WITH 2.5 ====================== Lang 2.6 is binary compatible release with Lang 2.5, containing bug fixes and small enhancements. Lang 2.6 requires a minimum of JDK 1.3. IMPROVEMENTS IN 2.6 =================== * [LANG-633] - BooleanUtils: use same optimization in toBooleanObject(String) as in toBoolean(String) * [LANG-599] - ClassUtils: allow Dots as Inner Class Separators in getClass() * [LANG-594] - DateUtils: equal and compare functions up to most significant field * [LANG-632] - DateUtils: provide a Date to Calendar convenience method * [LANG-576] - ObjectUtils: add clone methods to ObjectUtils * [LANG-667] - ObjectUtils: add a Null-safe compare() method * [LANG-670] - ObjectUtils: add notEqual() method * [LANG-302] - StrBuilder: implement clone() method * [LANG-640] - StringUtils: add a normalizeSpace() method * [LANG-614] - StringUtils: add endsWithAny() method * [LANG-655] - StringUtils: add defaultIfBlank() method * [LANG-596] - StrSubstitutor: add a replace(String, Properties) variant * [LANG-482] - StrSubstitutor: support substitution in variable names * [LANG-669] - Use StrBuilder instead of StringBuffer to improve performance where sync. is not an issue BUG FIXES IN 2.6 ================ * [LANG-629] - CharSet: make the underlying set synchronized * [LANG-635] - CompareToBuilder: fix passing along compareTransients to the reflectionCompare method * [LANG-636] - ExtendedMessageFormat doesn't override equals(Object) * [LANG-645] - FastDateFormat: fix to properly include the locale when formatting a Date * [LANG-638] - NumberUtils: createNumber() throws a StringIndexOutOfBoundsException when argument containing "e" and "E" is passed in * [LANG-607] - StringUtils methods do not handle Unicode 2.0+ supplementary characters correctly * [LANG-624] - SystemUtils: getJavaVersionAsFloat throws StringIndexOutOfBoundsException on Android runtime/Dalvik VM * [BEANUTILS-381] - MemberUtils: getMatchingAccessibleMethod does not correctly handle inheritance and method overloading OTHER CHANGES IN 2.6 ==================== * [LANG-600] - Javadoc is incorrect for lastIndexOf() method * [LANG-628] - Javadoc for HashCodeBuilder.append(boolean) does not match implementation * [LANG-643] - Javadoc StringUtils.left() claims to throw an exception on negative lenth, but doesn't * [LANG-370] - Javadoc - document thread safety * [LANG-623] - Test for StringUtils replaceChars() icelandic characters commons-lang-2.6-src/src/ 40755 0 0 0 11513702446 12364 5ustar 0 0 commons-lang-2.6-src/src/assembly/ 40755 0 0 0 11513702433 14177 5ustar 0 0 commons-lang-2.6-src/src/main/ 40755 0 0 0 11513702441 13303 5ustar 0 0 commons-lang-2.6-src/src/main/java/ 40755 0 0 0 11513702441 14224 5ustar 0 0 commons-lang-2.6-src/src/main/java/org/ 40755 0 0 0 11513702441 15013 5ustar 0 0 commons-lang-2.6-src/src/main/java/org/apache/ 40755 0 0 0 11513702441 16234 5ustar 0 0 commons-lang-2.6-src/src/main/java/org/apache/commons/ 40755 0 0 0 11513702441 17707 5ustar 0 0 commons-lang-2.6-src/src/main/java/org/apache/commons/lang/ 40755 0 0 0 11513702446 20635 5ustar 0 0 commons-lang-2.6-src/src/main/java/org/apache/commons/lang/builder/ 40755 0 0 0 11513702444 22261 5ustar 0 0 commons-lang-2.6-src/src/main/java/org/apache/commons/lang/enum/ 40755 0 0 0 11513702445 21600 5ustar 0 0 commons-lang-2.6-src/src/main/java/org/apache/commons/lang/enums/ 40755 0 0 0 11513702442 21760 5ustar 0 0 commons-lang-2.6-src/src/main/java/org/apache/commons/lang/exception/ 40755 0 0 0 11513702442 22627 5ustar 0 0 commons-lang-2.6-src/src/main/java/org/apache/commons/lang/math/ 40755 0 0 0 11513702442 21562 5ustar 0 0 commons-lang-2.6-src/src/main/java/org/apache/commons/lang/mutable/ 40755 0 0 0 11513702444 22264 5ustar 0 0 commons-lang-2.6-src/src/main/java/org/apache/commons/lang/reflect/ 40755 0 0 0 11513702443 22256 5ustar 0 0 commons-lang-2.6-src/src/main/java/org/apache/commons/lang/text/ 40755 0 0 0 11513702441 21614 5ustar 0 0 commons-lang-2.6-src/src/main/java/org/apache/commons/lang/time/ 40755 0 0 0 11513702443 21570 5ustar 0 0 commons-lang-2.6-src/src/media/ 40755 0 0 0 11513702433 13437 5ustar 0 0 commons-lang-2.6-src/src/site/ 40755 0 0 0 11513702447 13331 5ustar 0 0 commons-lang-2.6-src/src/site/changes/ 40755 0 0 0 11513702446 14740 5ustar 0 0 commons-lang-2.6-src/src/site/resources/ 40755 0 0 0 11513702446 15342 5ustar 0 0 commons-lang-2.6-src/src/site/resources/images/ 40755 0 0 0 11513702446 16607 5ustar 0 0 commons-lang-2.6-src/src/site/xdoc/ 40755 0 0 0 11513702447 14266 5ustar 0 0 commons-lang-2.6-src/src/test/ 40755 0 0 0 11513702433 13337 5ustar 0 0 commons-lang-2.6-src/src/test/java/ 40755 0 0 0 11513702433 14260 5ustar 0 0 commons-lang-2.6-src/src/test/java/org/ 40755 0 0 0 11513702433 15047 5ustar 0 0 commons-lang-2.6-src/src/test/java/org/apache/ 40755 0 0 0 11513702433 16270 5ustar 0 0 commons-lang-2.6-src/src/test/java/org/apache/commons/ 40755 0 0 0 11513702433 17743 5ustar 0 0 commons-lang-2.6-src/src/test/java/org/apache/commons/lang/ 40755 0 0 0 11513702441 20663 5ustar 0 0 commons-lang-2.6-src/src/test/java/org/apache/commons/lang/builder/ 40755 0 0 0 11513702437 22316 5ustar 0 0 commons-lang-2.6-src/src/test/java/org/apache/commons/lang/enum/ 40755 0 0 0 11513702440 21626 5ustar 0 0 commons-lang-2.6-src/src/test/java/org/apache/commons/lang/enums/ 40755 0 0 0 11513702434 22014 5ustar 0 0 commons-lang-2.6-src/src/test/java/org/apache/commons/lang/exception/ 40755 0 0 0 11513702435 22664 5ustar 0 0 commons-lang-2.6-src/src/test/java/org/apache/commons/lang/math/ 40755 0 0 0 11513702435 21617 5ustar 0 0 commons-lang-2.6-src/src/test/java/org/apache/commons/lang/mutable/ 40755 0 0 0 11513702437 22321 5ustar 0 0 commons-lang-2.6-src/src/test/java/org/apache/commons/lang/reflect/ 40755 0 0 0 11513702436 22313 5ustar 0 0 commons-lang-2.6-src/src/test/java/org/apache/commons/lang/reflect/testbed/ 40755 0 0 0 11513702436 23745 5ustar 0 0 commons-lang-2.6-src/src/test/java/org/apache/commons/lang/text/ 40755 0 0 0 11513702433 21650 5ustar 0 0 commons-lang-2.6-src/src/test/java/org/apache/commons/lang/time/ 40755 0 0 0 11513702435 21624 5ustar 0 0 commons-lang-2.6-src/src/assembly/bin.xml100644 0 0 3135 11513702433 15570 0ustar 0 0 bin tar.gz zip false LICENSE.txt NOTICE.txt RELEASE-NOTES.txt target *.jar target/site/apidocs apidocs commons-lang-2.6-src/src/assembly/src.xml100644 0 0 3206 11513702433 15606 0ustar 0 0 src tar.gz zip ${project.artifactId}-${project.version}-src build.xml checkstyle.xml default.properties findbugs-exclude-filter.xml LICENSE.txt NOTICE.txt pom.xml PROPOSAL.html RELEASE-NOTES.txt src commons-lang-2.6-src/src/main/java/org/apache/commons/lang/ArrayUtils.java100644 0 0 607611 11513702446 23747 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang; import java.lang.reflect.Array; import java.util.HashMap; import java.util.Map; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; /** *

Operations on arrays, primitive arrays (like int[]) and * primitive wrapper arrays (like Integer[]).

* *

This class tries to handle null input gracefully. * An exception will not be thrown for a null * array input. However, an Object array that contains a null * element may throw an exception. Each method documents its behaviour.

* *

#ThreadSafe#

* @author Apache Software Foundation * @author Moritz Petersen * @author Fredrik Westermarck * @author Nikolay Metchev * @author Matthew Hawthorne * @author Tim O'Brien * @author Pete Gieser * @author Gary Gregory * @author Ashwin S * @author Maarten Coene * @since 2.0 * @version $Id: ArrayUtils.java 1056988 2011-01-09 17:58:53Z niallp $ */ public class ArrayUtils { /** * An empty immutable Object array. */ public static final Object[] EMPTY_OBJECT_ARRAY = new Object[0]; /** * An empty immutable Class array. */ public static final Class[] EMPTY_CLASS_ARRAY = new Class[0]; /** * An empty immutable String array. */ public static final String[] EMPTY_STRING_ARRAY = new String[0]; /** * An empty immutable long array. */ public static final long[] EMPTY_LONG_ARRAY = new long[0]; /** * An empty immutable Long array. */ public static final Long[] EMPTY_LONG_OBJECT_ARRAY = new Long[0]; /** * An empty immutable int array. */ public static final int[] EMPTY_INT_ARRAY = new int[0]; /** * An empty immutable Integer array. */ public static final Integer[] EMPTY_INTEGER_OBJECT_ARRAY = new Integer[0]; /** * An empty immutable short array. */ public static final short[] EMPTY_SHORT_ARRAY = new short[0]; /** * An empty immutable Short array. */ public static final Short[] EMPTY_SHORT_OBJECT_ARRAY = new Short[0]; /** * An empty immutable byte array. */ public static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; /** * An empty immutable Byte array. */ public static final Byte[] EMPTY_BYTE_OBJECT_ARRAY = new Byte[0]; /** * An empty immutable double array. */ public static final double[] EMPTY_DOUBLE_ARRAY = new double[0]; /** * An empty immutable Double array. */ public static final Double[] EMPTY_DOUBLE_OBJECT_ARRAY = new Double[0]; /** * An empty immutable float array. */ public static final float[] EMPTY_FLOAT_ARRAY = new float[0]; /** * An empty immutable Float array. */ public static final Float[] EMPTY_FLOAT_OBJECT_ARRAY = new Float[0]; /** * An empty immutable boolean array. */ public static final boolean[] EMPTY_BOOLEAN_ARRAY = new boolean[0]; /** * An empty immutable Boolean array. */ public static final Boolean[] EMPTY_BOOLEAN_OBJECT_ARRAY = new Boolean[0]; /** * An empty immutable char array. */ public static final char[] EMPTY_CHAR_ARRAY = new char[0]; /** * An empty immutable Character array. */ public static final Character[] EMPTY_CHARACTER_OBJECT_ARRAY = new Character[0]; /** * The index value when an element is not found in a list or array: -1. * This value is returned by methods in this class and can also be used in comparisons with values returned by * various method from {@link java.util.List}. */ public static final int INDEX_NOT_FOUND = -1; /** *

ArrayUtils instances should NOT be constructed in standard programming. * Instead, the class should be used as ArrayUtils.clone(new int[] {2}).

* *

This constructor is public to permit tools that require a JavaBean instance * to operate.

*/ public ArrayUtils() { super(); } // Basic methods handling multi-dimensional arrays //----------------------------------------------------------------------- /** *

Outputs an array as a String, treating null as an empty array.

* *

Multi-dimensional arrays are handled correctly, including * multi-dimensional primitive arrays.

* *

The format is that of Java source code, for example {a,b}.

* * @param array the array to get a toString for, may be null * @return a String representation of the array, '{}' if null array input */ public static String toString(Object array) { return toString(array, "{}"); } /** *

Outputs an array as a String handling nulls.

* *

Multi-dimensional arrays are handled correctly, including * multi-dimensional primitive arrays.

* *

The format is that of Java source code, for example {a,b}.

* * @param array the array to get a toString for, may be null * @param stringIfNull the String to return if the array is null * @return a String representation of the array */ public static String toString(Object array, String stringIfNull) { if (array == null) { return stringIfNull; } return new ToStringBuilder(array, ToStringStyle.SIMPLE_STYLE).append(array).toString(); } /** *

Get a hashCode for an array handling multi-dimensional arrays correctly.

* *

Multi-dimensional primitive arrays are also handled correctly by this method.

* * @param array the array to get a hashCode for, may be null * @return a hashCode for the array, zero if null array input */ public static int hashCode(Object array) { return new HashCodeBuilder().append(array).toHashCode(); } /** *

Compares two arrays, using equals(), handling multi-dimensional arrays * correctly.

* *

Multi-dimensional primitive arrays are also handled correctly by this method.

* * @param array1 the left hand array to compare, may be null * @param array2 the right hand array to compare, may be null * @return true if the arrays are equal */ public static boolean isEquals(Object array1, Object array2) { return new EqualsBuilder().append(array1, array2).isEquals(); } // To map //----------------------------------------------------------------------- /** *

Converts the given array into a {@link java.util.Map}. Each element of the array * must be either a {@link java.util.Map.Entry} or an Array, containing at least two * elements, where the first element is used as key and the second as * value.

* *

This method can be used to initialize:

*
     * // Create a Map mapping colors.
     * Map colorMap = MapUtils.toMap(new String[][] {{
     *     {"RED", "#FF0000"},
     *     {"GREEN", "#00FF00"},
     *     {"BLUE", "#0000FF"}});
     * 
* *

This method returns null for a null input array.

* * @param array an array whose elements are either a {@link java.util.Map.Entry} or * an Array containing at least two elements, may be null * @return a Map that was created from the array * @throws IllegalArgumentException if one element of this Array is * itself an Array containing less then two elements * @throws IllegalArgumentException if the array contains elements other * than {@link java.util.Map.Entry} and an Array */ public static Map toMap(Object[] array) { if (array == null) { return null; } final Map map = new HashMap((int) (array.length * 1.5)); for (int i = 0; i < array.length; i++) { Object object = array[i]; if (object instanceof Map.Entry) { Map.Entry entry = (Map.Entry) object; map.put(entry.getKey(), entry.getValue()); } else if (object instanceof Object[]) { Object[] entry = (Object[]) object; if (entry.length < 2) { throw new IllegalArgumentException("Array element " + i + ", '" + object + "', has a length less than 2"); } map.put(entry[0], entry[1]); } else { throw new IllegalArgumentException("Array element " + i + ", '" + object + "', is neither of type Map.Entry nor an Array"); } } return map; } // Clone //----------------------------------------------------------------------- /** *

Shallow clones an array returning a typecast result and handling * null.

* *

The objects in the array are not cloned, thus there is no special * handling for multi-dimensional arrays.

* *

This method returns null for a null input array.

* * @param array the array to shallow clone, may be null * @return the cloned array, null if null input */ public static Object[] clone(Object[] array) { if (array == null) { return null; } return (Object[]) array.clone(); } /** *

Clones an array returning a typecast result and handling * null.

* *

This method returns null for a null input array.

* * @param array the array to clone, may be null * @return the cloned array, null if null input */ public static long[] clone(long[] array) { if (array == null) { return null; } return (long[]) array.clone(); } /** *

Clones an array returning a typecast result and handling * null.

* *

This method returns null for a null input array.

* * @param array the array to clone, may be null * @return the cloned array, null if null input */ public static int[] clone(int[] array) { if (array == null) { return null; } return (int[]) array.clone(); } /** *

Clones an array returning a typecast result and handling * null.

* *

This method returns null for a null input array.

* * @param array the array to clone, may be null * @return the cloned array, null if null input */ public static short[] clone(short[] array) { if (array == null) { return null; } return (short[]) array.clone(); } /** *

Clones an array returning a typecast result and handling * null.

* *

This method returns null for a null input array.

* * @param array the array to clone, may be null * @return the cloned array, null if null input */ public static char[] clone(char[] array) { if (array == null) { return null; } return (char[]) array.clone(); } /** *

Clones an array returning a typecast result and handling * null.

* *

This method returns null for a null input array.

* * @param array the array to clone, may be null * @return the cloned array, null if null input */ public static byte[] clone(byte[] array) { if (array == null) { return null; } return (byte[]) array.clone(); } /** *

Clones an array returning a typecast result and handling * null.

* *

This method returns null for a null input array.

* * @param array the array to clone, may be null * @return the cloned array, null if null input */ public static double[] clone(double[] array) { if (array == null) { return null; } return (double[]) array.clone(); } /** *

Clones an array returning a typecast result and handling * null.

* *

This method returns null for a null input array.

* * @param array the array to clone, may be null * @return the cloned array, null if null input */ public static float[] clone(float[] array) { if (array == null) { return null; } return (float[]) array.clone(); } /** *

Clones an array returning a typecast result and handling * null.

* *

This method returns null for a null input array.

* * @param array the array to clone, may be null * @return the cloned array, null if null input */ public static boolean[] clone(boolean[] array) { if (array == null) { return null; } return (boolean[]) array.clone(); } // nullToEmpty //----------------------------------------------------------------------- /** *

Defensive programming technique to change a null * reference to an empty one.

* *

This method returns an empty array for a null input array.

* *

As a memory optimizing technique an empty array passed in will be overridden with * the empty public static references in this class.

* * @param array the array to check for null or empty * @return the same array, public static empty array if null or empty input * @since 2.5 */ public static Object[] nullToEmpty(Object[] array) { if (array == null || array.length == 0) { return EMPTY_OBJECT_ARRAY; } return array; } /** *

Defensive programming technique to change a null * reference to an empty one.

* *

This method returns an empty array for a null input array.

* *

As a memory optimizing technique an empty array passed in will be overridden with * the empty public static references in this class.

* * @param array the array to check for null or empty * @return the same array, public static empty array if null or empty input * @since 2.5 */ public static String[] nullToEmpty(String[] array) { if (array == null || array.length == 0) { return EMPTY_STRING_ARRAY; } return array; } /** *

Defensive programming technique to change a null * reference to an empty one.

* *

This method returns an empty array for a null input array.

* *

As a memory optimizing technique an empty array passed in will be overridden with * the empty public static references in this class.

* * @param array the array to check for null or empty * @return the same array, public static empty array if null or empty input * @since 2.5 */ public static long[] nullToEmpty(long[] array) { if (array == null || array.length == 0) { return EMPTY_LONG_ARRAY; } return array; } /** *

Defensive programming technique to change a null * reference to an empty one.

* *

This method returns an empty array for a null input array.

* *

As a memory optimizing technique an empty array passed in will be overridden with * the empty public static references in this class.

* * @param array the array to check for null or empty * @return the same array, public static empty array if null or empty input * @since 2.5 */ public static int[] nullToEmpty(int[] array) { if (array == null || array.length == 0) { return EMPTY_INT_ARRAY; } return array; } /** *

Defensive programming technique to change a null * reference to an empty one.

* *

This method returns an empty array for a null input array.

* *

As a memory optimizing technique an empty array passed in will be overridden with * the empty public static references in this class.

* * @param array the array to check for null or empty * @return the same array, public static empty array if null or empty input * @since 2.5 */ public static short[] nullToEmpty(short[] array) { if (array == null || array.length == 0) { return EMPTY_SHORT_ARRAY; } return array; } /** *

Defensive programming technique to change a null * reference to an empty one.

* *

This method returns an empty array for a null input array.

* *

As a memory optimizing technique an empty array passed in will be overridden with * the empty public static references in this class.

* * @param array the array to check for null or empty * @return the same array, public static empty array if null or empty input * @since 2.5 */ public static char[] nullToEmpty(char[] array) { if (array == null || array.length == 0) { return EMPTY_CHAR_ARRAY; } return array; } /** *

Defensive programming technique to change a null * reference to an empty one.

* *

This method returns an empty array for a null input array.

* *

As a memory optimizing technique an empty array passed in will be overridden with * the empty public static references in this class.

* * @param array the array to check for null or empty * @return the same array, public static empty array if null or empty input * @since 2.5 */ public static byte[] nullToEmpty(byte[] array) { if (array == null || array.length == 0) { return EMPTY_BYTE_ARRAY; } return array; } /** *

Defensive programming technique to change a null * reference to an empty one.

* *

This method returns an empty array for a null input array.

* *

As a memory optimizing technique an empty array passed in will be overridden with * the empty public static references in this class.

* * @param array the array to check for null or empty * @return the same array, public static empty array if null or empty input * @since 2.5 */ public static double[] nullToEmpty(double[] array) { if (array == null || array.length == 0) { return EMPTY_DOUBLE_ARRAY; } return array; } /** *

Defensive programming technique to change a null * reference to an empty one.

* *

This method returns an empty array for a null input array.

* *

As a memory optimizing technique an empty array passed in will be overridden with * the empty public static references in this class.

* * @param array the array to check for null or empty * @return the same array, public static empty array if null or empty input * @since 2.5 */ public static float[] nullToEmpty(float[] array) { if (array == null || array.length == 0) { return EMPTY_FLOAT_ARRAY; } return array; } /** *

Defensive programming technique to change a null * reference to an empty one.

* *

This method returns an empty array for a null input array.

* *

As a memory optimizing technique an empty array passed in will be overridden with * the empty public static references in this class.

* * @param array the array to check for null or empty * @return the same array, public static empty array if null or empty input * @since 2.5 */ public static boolean[] nullToEmpty(boolean[] array) { if (array == null || array.length == 0) { return EMPTY_BOOLEAN_ARRAY; } return array; } /** *

Defensive programming technique to change a null * reference to an empty one.

* *

This method returns an empty array for a null input array.

* *

As a memory optimizing technique an empty array passed in will be overridden with * the empty public static references in this class.

* * @param array the array to check for null or empty * @return the same array, public static empty array if null or empty input * @since 2.5 */ public static Long[] nullToEmpty(Long[] array) { if (array == null || array.length == 0) { return EMPTY_LONG_OBJECT_ARRAY; } return array; } /** *

Defensive programming technique to change a null * reference to an empty one.

* *

This method returns an empty array for a null input array.

* *

As a memory optimizing technique an empty array passed in will be overridden with * the empty public static references in this class.

* * @param array the array to check for null or empty * @return the same array, public static empty array if null or empty input * @since 2.5 */ public static Integer[] nullToEmpty(Integer[] array) { if (array == null || array.length == 0) { return EMPTY_INTEGER_OBJECT_ARRAY; } return array; } /** *

Defensive programming technique to change a null * reference to an empty one.

* *

This method returns an empty array for a null input array.

* *

As a memory optimizing technique an empty array passed in will be overridden with * the empty public static references in this class.

* * @param array the array to check for null or empty * @return the same array, public static empty array if null or empty input * @since 2.5 */ public static Short[] nullToEmpty(Short[] array) { if (array == null || array.length == 0) { return EMPTY_SHORT_OBJECT_ARRAY; } return array; } /** *

Defensive programming technique to change a null * reference to an empty one.

* *

This method returns an empty array for a null input array.

* *

As a memory optimizing technique an empty array passed in will be overridden with * the empty public static references in this class.

* * @param array the array to check for null or empty * @return the same array, public static empty array if null or empty input * @since 2.5 */ public static Character[] nullToEmpty(Character[] array) { if (array == null || array.length == 0) { return EMPTY_CHARACTER_OBJECT_ARRAY; } return array; } /** *

Defensive programming technique to change a null * reference to an empty one.

* *

This method returns an empty array for a null input array.

* *

As a memory optimizing technique an empty array passed in will be overridden with * the empty public static references in this class.

* * @param array the array to check for null or empty * @return the same array, public static empty array if null or empty input * @since 2.5 */ public static Byte[] nullToEmpty(Byte[] array) { if (array == null || array.length == 0) { return EMPTY_BYTE_OBJECT_ARRAY; } return array; } /** *

Defensive programming technique to change a null * reference to an empty one.

* *

This method returns an empty array for a null input array.

* *

As a memory optimizing technique an empty array passed in will be overridden with * the empty public static references in this class.

* * @param array the array to check for null or empty * @return the same array, public static empty array if null or empty input * @since 2.5 */ public static Double[] nullToEmpty(Double[] array) { if (array == null || array.length == 0) { return EMPTY_DOUBLE_OBJECT_ARRAY; } return array; } /** *

Defensive programming technique to change a null * reference to an empty one.

* *

This method returns an empty array for a null input array.

* *

As a memory optimizing technique an empty array passed in will be overridden with * the empty public static references in this class.

* * @param array the array to check for null or empty * @return the same array, public static empty array if null or empty input * @since 2.5 */ public static Float[] nullToEmpty(Float[] array) { if (array == null || array.length == 0) { return EMPTY_FLOAT_OBJECT_ARRAY; } return array; } /** *

Defensive programming technique to change a null * reference to an empty one.

* *

This method returns an empty array for a null input array.

* *

As a memory optimizing technique an empty array passed in will be overridden with * the empty public static references in this class.

* * @param array the array to check for null or empty * @return the same array, public static empty array if null or empty input * @since 2.5 */ public static Boolean[] nullToEmpty(Boolean[] array) { if (array == null || array.length == 0) { return EMPTY_BOOLEAN_OBJECT_ARRAY; } return array; } // Subarrays //----------------------------------------------------------------------- /** *

Produces a new array containing the elements between * the start and end indices.

* *

The start index is inclusive, the end index exclusive. * Null array input produces null output.

* *

The component type of the subarray is always the same as * that of the input array. Thus, if the input is an array of type * Date, the following usage is envisaged:

* *
     * Date[] someDates = (Date[])ArrayUtils.subarray(allDates, 2, 5);
     * 
* * @param array the array * @param startIndexInclusive the starting index. Undervalue (<0) * is promoted to 0, overvalue (>array.length) results * in an empty array. * @param endIndexExclusive elements up to endIndex-1 are present in the * returned subarray. Undervalue (< startIndex) produces * empty array, overvalue (>array.length) is demoted to * array length. * @return a new array containing the elements between * the start and end indices. * @since 2.1 */ public static Object[] subarray(Object[] array, int startIndexInclusive, int endIndexExclusive) { if (array == null) { return null; } if (startIndexInclusive < 0) { startIndexInclusive = 0; } if (endIndexExclusive > array.length) { endIndexExclusive = array.length; } int newSize = endIndexExclusive - startIndexInclusive; Class type = array.getClass().getComponentType(); if (newSize <= 0) { return (Object[]) Array.newInstance(type, 0); } Object[] subarray = (Object[]) Array.newInstance(type, newSize); System.arraycopy(array, startIndexInclusive, subarray, 0, newSize); return subarray; } /** *

Produces a new long array containing the elements * between the start and end indices.

* *

The start index is inclusive, the end index exclusive. * Null array input produces null output.

* * @param array the array * @param startIndexInclusive the starting index. Undervalue (<0) * is promoted to 0, overvalue (>array.length) results * in an empty array. * @param endIndexExclusive elements up to endIndex-1 are present in the * returned subarray. Undervalue (< startIndex) produces * empty array, overvalue (>array.length) is demoted to * array length. * @return a new array containing the elements between * the start and end indices. * @since 2.1 */ public static long[] subarray(long[] array, int startIndexInclusive, int endIndexExclusive) { if (array == null) { return null; } if (startIndexInclusive < 0) { startIndexInclusive = 0; } if (endIndexExclusive > array.length) { endIndexExclusive = array.length; } int newSize = endIndexExclusive - startIndexInclusive; if (newSize <= 0) { return EMPTY_LONG_ARRAY; } long[] subarray = new long[newSize]; System.arraycopy(array, startIndexInclusive, subarray, 0, newSize); return subarray; } /** *

Produces a new int array containing the elements * between the start and end indices.

* *

The start index is inclusive, the end index exclusive. * Null array input produces null output.

* * @param array the array * @param startIndexInclusive the starting index. Undervalue (<0) * is promoted to 0, overvalue (>array.length) results * in an empty array. * @param endIndexExclusive elements up to endIndex-1 are present in the * returned subarray. Undervalue (< startIndex) produces * empty array, overvalue (>array.length) is demoted to * array length. * @return a new array containing the elements between * the start and end indices. * @since 2.1 */ public static int[] subarray(int[] array, int startIndexInclusive, int endIndexExclusive) { if (array == null) { return null; } if (startIndexInclusive < 0) { startIndexInclusive = 0; } if (endIndexExclusive > array.length) { endIndexExclusive = array.length; } int newSize = endIndexExclusive - startIndexInclusive; if (newSize <= 0) { return EMPTY_INT_ARRAY; } int[] subarray = new int[newSize]; System.arraycopy(array, startIndexInclusive, subarray, 0, newSize); return subarray; } /** *

Produces a new short array containing the elements * between the start and end indices.

* *

The start index is inclusive, the end index exclusive. * Null array input produces null output.

* * @param array the array * @param startIndexInclusive the starting index. Undervalue (<0) * is promoted to 0, overvalue (>array.length) results * in an empty array. * @param endIndexExclusive elements up to endIndex-1 are present in the * returned subarray. Undervalue (< startIndex) produces * empty array, overvalue (>array.length) is demoted to * array length. * @return a new array containing the elements between * the start and end indices. * @since 2.1 */ public static short[] subarray(short[] array, int startIndexInclusive, int endIndexExclusive) { if (array == null) { return null; } if (startIndexInclusive < 0) { startIndexInclusive = 0; } if (endIndexExclusive > array.length) { endIndexExclusive = array.length; } int newSize = endIndexExclusive - startIndexInclusive; if (newSize <= 0) { return EMPTY_SHORT_ARRAY; } short[] subarray = new short[newSize]; System.arraycopy(array, startIndexInclusive, subarray, 0, newSize); return subarray; } /** *

Produces a new char array containing the elements * between the start and end indices.

* *

The start index is inclusive, the end index exclusive. * Null array input produces null output.

* * @param array the array * @param startIndexInclusive the starting index. Undervalue (<0) * is promoted to 0, overvalue (>array.length) results * in an empty array. * @param endIndexExclusive elements up to endIndex-1 are present in the * returned subarray. Undervalue (< startIndex) produces * empty array, overvalue (>array.length) is demoted to * array length. * @return a new array containing the elements between * the start and end indices. * @since 2.1 */ public static char[] subarray(char[] array, int startIndexInclusive, int endIndexExclusive) { if (array == null) { return null; } if (startIndexInclusive < 0) { startIndexInclusive = 0; } if (endIndexExclusive > array.length) { endIndexExclusive = array.length; } int newSize = endIndexExclusive - startIndexInclusive; if (newSize <= 0) { return EMPTY_CHAR_ARRAY; } char[] subarray = new char[newSize]; System.arraycopy(array, startIndexInclusive, subarray, 0, newSize); return subarray; } /** *

Produces a new byte array containing the elements * between the start and end indices.

* *

The start index is inclusive, the end index exclusive. * Null array input produces null output.

* * @param array the array * @param startIndexInclusive the starting index. Undervalue (<0) * is promoted to 0, overvalue (>array.length) results * in an empty array. * @param endIndexExclusive elements up to endIndex-1 are present in the * returned subarray. Undervalue (< startIndex) produces * empty array, overvalue (>array.length) is demoted to * array length. * @return a new array containing the elements between * the start and end indices. * @since 2.1 */ public static byte[] subarray(byte[] array, int startIndexInclusive, int endIndexExclusive) { if (array == null) { return null; } if (startIndexInclusive < 0) { startIndexInclusive = 0; } if (endIndexExclusive > array.length) { endIndexExclusive = array.length; } int newSize = endIndexExclusive - startIndexInclusive; if (newSize <= 0) { return EMPTY_BYTE_ARRAY; } byte[] subarray = new byte[newSize]; System.arraycopy(array, startIndexInclusive, subarray, 0, newSize); return subarray; } /** *

Produces a new double array containing the elements * between the start and end indices.

* *

The start index is inclusive, the end index exclusive. * Null array input produces null output.

* * @param array the array * @param startIndexInclusive the starting index. Undervalue (<0) * is promoted to 0, overvalue (>array.length) results * in an empty array. * @param endIndexExclusive elements up to endIndex-1 are present in the * returned subarray. Undervalue (< startIndex) produces * empty array, overvalue (>array.length) is demoted to * array length. * @return a new array containing the elements between * the start and end indices. * @since 2.1 */ public static double[] subarray(double[] array, int startIndexInclusive, int endIndexExclusive) { if (array == null) { return null; } if (startIndexInclusive < 0) { startIndexInclusive = 0; } if (endIndexExclusive > array.length) { endIndexExclusive = array.length; } int newSize = endIndexExclusive - startIndexInclusive; if (newSize <= 0) { return EMPTY_DOUBLE_ARRAY; } double[] subarray = new double[newSize]; System.arraycopy(array, startIndexInclusive, subarray, 0, newSize); return subarray; } /** *

Produces a new float array containing the elements * between the start and end indices.

* *

The start index is inclusive, the end index exclusive. * Null array input produces null output.

* * @param array the array * @param startIndexInclusive the starting index. Undervalue (<0) * is promoted to 0, overvalue (>array.length) results * in an empty array. * @param endIndexExclusive elements up to endIndex-1 are present in the * returned subarray. Undervalue (< startIndex) produces * empty array, overvalue (>array.length) is demoted to * array length. * @return a new array containing the elements between * the start and end indices. * @since 2.1 */ public static float[] subarray(float[] array, int startIndexInclusive, int endIndexExclusive) { if (array == null) { return null; } if (startIndexInclusive < 0) { startIndexInclusive = 0; } if (endIndexExclusive > array.length) { endIndexExclusive = array.length; } int newSize = endIndexExclusive - startIndexInclusive; if (newSize <= 0) { return EMPTY_FLOAT_ARRAY; } float[] subarray = new float[newSize]; System.arraycopy(array, startIndexInclusive, subarray, 0, newSize); return subarray; } /** *

Produces a new boolean array containing the elements * between the start and end indices.

* *

The start index is inclusive, the end index exclusive. * Null array input produces null output.

* * @param array the array * @param startIndexInclusive the starting index. Undervalue (<0) * is promoted to 0, overvalue (>array.length) results * in an empty array. * @param endIndexExclusive elements up to endIndex-1 are present in the * returned subarray. Undervalue (< startIndex) produces * empty array, overvalue (>array.length) is demoted to * array length. * @return a new array containing the elements between * the start and end indices. * @since 2.1 */ public static boolean[] subarray(boolean[] array, int startIndexInclusive, int endIndexExclusive) { if (array == null) { return null; } if (startIndexInclusive < 0) { startIndexInclusive = 0; } if (endIndexExclusive > array.length) { endIndexExclusive = array.length; } int newSize = endIndexExclusive - startIndexInclusive; if (newSize <= 0) { return EMPTY_BOOLEAN_ARRAY; } boolean[] subarray = new boolean[newSize]; System.arraycopy(array, startIndexInclusive, subarray, 0, newSize); return subarray; } // Is same length //----------------------------------------------------------------------- /** *

Checks whether two arrays are the same length, treating * null arrays as length 0. * *

Any multi-dimensional aspects of the arrays are ignored.

* * @param array1 the first array, may be null * @param array2 the second array, may be null * @return true if length of arrays matches, treating * null as an empty array */ public static boolean isSameLength(Object[] array1, Object[] array2) { if ((array1 == null && array2 != null && array2.length > 0) || (array2 == null && array1 != null && array1.length > 0) || (array1 != null && array2 != null && array1.length != array2.length)) { return false; } return true; } /** *

Checks whether two arrays are the same length, treating * null arrays as length 0.

* * @param array1 the first array, may be null * @param array2 the second array, may be null * @return true if length of arrays matches, treating * null as an empty array */ public static boolean isSameLength(long[] array1, long[] array2) { if ((array1 == null && array2 != null && array2.length > 0) || (array2 == null && array1 != null && array1.length > 0) || (array1 != null && array2 != null && array1.length != array2.length)) { return false; } return true; } /** *

Checks whether two arrays are the same length, treating * null arrays as length 0.

* * @param array1 the first array, may be null * @param array2 the second array, may be null * @return true if length of arrays matches, treating * null as an empty array */ public static boolean isSameLength(int[] array1, int[] array2) { if ((array1 == null && array2 != null && array2.length > 0) || (array2 == null && array1 != null && array1.length > 0) || (array1 != null && array2 != null && array1.length != array2.length)) { return false; } return true; } /** *

Checks whether two arrays are the same length, treating * null arrays as length 0.

* * @param array1 the first array, may be null * @param array2 the second array, may be null * @return true if length of arrays matches, treating * null as an empty array */ public static boolean isSameLength(short[] array1, short[] array2) { if ((array1 == null && array2 != null && array2.length > 0) || (array2 == null && array1 != null && array1.length > 0) || (array1 != null && array2 != null && array1.length != array2.length)) { return false; } return true; } /** *

Checks whether two arrays are the same length, treating * null arrays as length 0.

* * @param array1 the first array, may be null * @param array2 the second array, may be null * @return true if length of arrays matches, treating * null as an empty array */ public static boolean isSameLength(char[] array1, char[] array2) { if ((array1 == null && array2 != null && array2.length > 0) || (array2 == null && array1 != null && array1.length > 0) || (array1 != null && array2 != null && array1.length != array2.length)) { return false; } return true; } /** *

Checks whether two arrays are the same length, treating * null arrays as length 0.

* * @param array1 the first array, may be null * @param array2 the second array, may be null * @return true if length of arrays matches, treating * null as an empty array */ public static boolean isSameLength(byte[] array1, byte[] array2) { if ((array1 == null && array2 != null && array2.length > 0) || (array2 == null && array1 != null && array1.length > 0) || (array1 != null && array2 != null && array1.length != array2.length)) { return false; } return true; } /** *

Checks whether two arrays are the same length, treating * null arrays as length 0.

* * @param array1 the first array, may be null * @param array2 the second array, may be null * @return true if length of arrays matches, treating * null as an empty array */ public static boolean isSameLength(double[] array1, double[] array2) { if ((array1 == null && array2 != null && array2.length > 0) || (array2 == null && array1 != null && array1.length > 0) || (array1 != null && array2 != null && array1.length != array2.length)) { return false; } return true; } /** *

Checks whether two arrays are the same length, treating * null arrays as length 0.

* * @param array1 the first array, may be null * @param array2 the second array, may be null * @return true if length of arrays matches, treating * null as an empty array */ public static boolean isSameLength(float[] array1, float[] array2) { if ((array1 == null && array2 != null && array2.length > 0) || (array2 == null && array1 != null && array1.length > 0) || (array1 != null && array2 != null && array1.length != array2.length)) { return false; } return true; } /** *

Checks whether two arrays are the same length, treating * null arrays as length 0.

* * @param array1 the first array, may be null * @param array2 the second array, may be null * @return true if length of arrays matches, treating * null as an empty array */ public static boolean isSameLength(boolean[] array1, boolean[] array2) { if ((array1 == null && array2 != null && array2.length > 0) || (array2 == null && array1 != null && array1.length > 0) || (array1 != null && array2 != null && array1.length != array2.length)) { return false; } return true; } //----------------------------------------------------------------------- /** *

Returns the length of the specified array. * This method can deal with Object arrays and with primitive arrays.

* *

If the input array is null, 0 is returned.

* *
     * ArrayUtils.getLength(null)            = 0
     * ArrayUtils.getLength([])              = 0
     * ArrayUtils.getLength([null])          = 1
     * ArrayUtils.getLength([true, false])   = 2
     * ArrayUtils.getLength([1, 2, 3])       = 3
     * ArrayUtils.getLength(["a", "b", "c"]) = 3
     * 
* * @param array the array to retrieve the length from, may be null * @return The length of the array, or 0 if the array is null * @throws IllegalArgumentException if the object arguement is not an array. * @since 2.1 */ public static int getLength(Object array) { if (array == null) { return 0; } return Array.getLength(array); } /** *

Checks whether two arrays are the same type taking into account * multi-dimensional arrays.

* * @param array1 the first array, must not be null * @param array2 the second array, must not be null * @return true if type of arrays matches * @throws IllegalArgumentException if either array is null */ public static boolean isSameType(Object array1, Object array2) { if (array1 == null || array2 == null) { throw new IllegalArgumentException("The Array must not be null"); } return array1.getClass().getName().equals(array2.getClass().getName()); } // Reverse //----------------------------------------------------------------------- /** *

Reverses the order of the given array.

* *

There is no special handling for multi-dimensional arrays.

* *

This method does nothing for a null input array.

* * @param array the array to reverse, may be null */ public static void reverse(Object[] array) { if (array == null) { return; } int i = 0; int j = array.length - 1; Object tmp; while (j > i) { tmp = array[j]; array[j] = array[i]; array[i] = tmp; j--; i++; } } /** *

Reverses the order of the given array.

* *

This method does nothing for a null input array.

* * @param array the array to reverse, may be null */ public static void reverse(long[] array) { if (array == null) { return; } int i = 0; int j = array.length - 1; long tmp; while (j > i) { tmp = array[j]; array[j] = array[i]; array[i] = tmp; j--; i++; } } /** *

Reverses the order of the given array.

* *

This method does nothing for a null input array.

* * @param array the array to reverse, may be null */ public static void reverse(int[] array) { if (array == null) { return; } int i = 0; int j = array.length - 1; int tmp; while (j > i) { tmp = array[j]; array[j] = array[i]; array[i] = tmp; j--; i++; } } /** *

Reverses the order of the given array.

* *

This method does nothing for a null input array.

* * @param array the array to reverse, may be null */ public static void reverse(short[] array) { if (array == null) { return; } int i = 0; int j = array.length - 1; short tmp; while (j > i) { tmp = array[j]; array[j] = array[i]; array[i] = tmp; j--; i++; } } /** *

Reverses the order of the given array.

* *

This method does nothing for a null input array.

* * @param array the array to reverse, may be null */ public static void reverse(char[] array) { if (array == null) { return; } int i = 0; int j = array.length - 1; char tmp; while (j > i) { tmp = array[j]; array[j] = array[i]; array[i] = tmp; j--; i++; } } /** *

Reverses the order of the given array.

* *

This method does nothing for a null input array.

* * @param array the array to reverse, may be null */ public static void reverse(byte[] array) { if (array == null) { return; } int i = 0; int j = array.length - 1; byte tmp; while (j > i) { tmp = array[j]; array[j] = array[i]; array[i] = tmp; j--; i++; } } /** *

Reverses the order of the given array.

* *

This method does nothing for a null input array.

* * @param array the array to reverse, may be null */ public static void reverse(double[] array) { if (array == null) { return; } int i = 0; int j = array.length - 1; double tmp; while (j > i) { tmp = array[j]; array[j] = array[i]; array[i] = tmp; j--; i++; } } /** *

Reverses the order of the given array.

* *

This method does nothing for a null input array.

* * @param array the array to reverse, may be null */ public static void reverse(float[] array) { if (array == null) { return; } int i = 0; int j = array.length - 1; float tmp; while (j > i) { tmp = array[j]; array[j] = array[i]; array[i] = tmp; j--; i++; } } /** *

Reverses the order of the given array.

* *

This method does nothing for a null input array.

* * @param array the array to reverse, may be null */ public static void reverse(boolean[] array) { if (array == null) { return; } int i = 0; int j = array.length - 1; boolean tmp; while (j > i) { tmp = array[j]; array[j] = array[i]; array[i] = tmp; j--; i++; } } // IndexOf search // ---------------------------------------------------------------------- // Object IndexOf //----------------------------------------------------------------------- /** *

Finds the index of the given object in the array.

* *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

* * @param array the array to search through for the object, may be null * @param objectToFind the object to find, may be null * @return the index of the object within the array, * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input */ public static int indexOf(Object[] array, Object objectToFind) { return indexOf(array, objectToFind, 0); } /** *

Finds the index of the given object in the array starting at the given index.

* *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

* *

A negative startIndex is treated as zero. A startIndex larger than the array * length will return {@link #INDEX_NOT_FOUND} (-1).

* * @param array the array to search through for the object, may be null * @param objectToFind the object to find, may be null * @param startIndex the index to start searching at * @return the index of the object within the array starting at the index, * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input */ public static int indexOf(Object[] array, Object objectToFind, int startIndex) { if (array == null) { return INDEX_NOT_FOUND; } if (startIndex < 0) { startIndex = 0; } if (objectToFind == null) { for (int i = startIndex; i < array.length; i++) { if (array[i] == null) { return i; } } } else if (array.getClass().getComponentType().isInstance(objectToFind)) { for (int i = startIndex; i < array.length; i++) { if (objectToFind.equals(array[i])) { return i; } } } return INDEX_NOT_FOUND; } /** *

Finds the last index of the given object within the array.

* *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

* * @param array the array to travers backwords looking for the object, may be null * @param objectToFind the object to find, may be null * @return the last index of the object within the array, * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input */ public static int lastIndexOf(Object[] array, Object objectToFind) { return lastIndexOf(array, objectToFind, Integer.MAX_VALUE); } /** *

Finds the last index of the given object in the array starting at the given index.

* *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

* *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than * the array length will search from the end of the array.

* * @param array the array to traverse for looking for the object, may be null * @param objectToFind the object to find, may be null * @param startIndex the start index to travers backwards from * @return the last index of the object within the array, * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input */ public static int lastIndexOf(Object[] array, Object objectToFind, int startIndex) { if (array == null) { return INDEX_NOT_FOUND; } if (startIndex < 0) { return INDEX_NOT_FOUND; } else if (startIndex >= array.length) { startIndex = array.length - 1; } if (objectToFind == null) { for (int i = startIndex; i >= 0; i--) { if (array[i] == null) { return i; } } } else if (array.getClass().getComponentType().isInstance(objectToFind)) { for (int i = startIndex; i >= 0; i--) { if (objectToFind.equals(array[i])) { return i; } } } return INDEX_NOT_FOUND; } /** *

Checks if the object is in the given array.

* *

The method returns false if a null array is passed in.

* * @param array the array to search through * @param objectToFind the object to find * @return true if the array contains the object */ public static boolean contains(Object[] array, Object objectToFind) { return indexOf(array, objectToFind) != INDEX_NOT_FOUND; } // long IndexOf //----------------------------------------------------------------------- /** *

Finds the index of the given value in the array.

* *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

* * @param array the array to search through for the object, may be null * @param valueToFind the value to find * @return the index of the value within the array, * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input */ public static int indexOf(long[] array, long valueToFind) { return indexOf(array, valueToFind, 0); } /** *

Finds the index of the given value in the array starting at the given index.

* *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

* *

A negative startIndex is treated as zero. A startIndex larger than the array * length will return {@link #INDEX_NOT_FOUND} (-1).

* * @param array the array to search through for the object, may be null * @param valueToFind the value to find * @param startIndex the index to start searching at * @return the index of the value within the array, * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input */ public static int indexOf(long[] array, long valueToFind, int startIndex) { if (array == null) { return INDEX_NOT_FOUND; } if (startIndex < 0) { startIndex = 0; } for (int i = startIndex; i < array.length; i++) { if (valueToFind == array[i]) { return i; } } return INDEX_NOT_FOUND; } /** *

Finds the last index of the given value within the array.

* *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

* * @param array the array to travers backwords looking for the object, may be null * @param valueToFind the object to find * @return the last index of the value within the array, * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input */ public static int lastIndexOf(long[] array, long valueToFind) { return lastIndexOf(array, valueToFind, Integer.MAX_VALUE); } /** *

Finds the last index of the given value in the array starting at the given index.

* *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

* *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the * array length will search from the end of the array.

* * @param array the array to traverse for looking for the object, may be null * @param valueToFind the value to find * @param startIndex the start index to travers backwards from * @return the last index of the value within the array, * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input */ public static int lastIndexOf(long[] array, long valueToFind, int startIndex) { if (array == null) { return INDEX_NOT_FOUND; } if (startIndex < 0) { return INDEX_NOT_FOUND; } else if (startIndex >= array.length) { startIndex = array.length - 1; } for (int i = startIndex; i >= 0; i--) { if (valueToFind == array[i]) { return i; } } return INDEX_NOT_FOUND; } /** *

Checks if the value is in the given array.

* *

The method returns false if a null array is passed in.

* * @param array the array to search through * @param valueToFind the value to find * @return true if the array contains the object */ public static boolean contains(long[] array, long valueToFind) { return indexOf(array, valueToFind) != INDEX_NOT_FOUND; } // int IndexOf //----------------------------------------------------------------------- /** *

Finds the index of the given value in the array.

* *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

* * @param array the array to search through for the object, may be null * @param valueToFind the value to find * @return the index of the value within the array, * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input */ public static int indexOf(int[] array, int valueToFind) { return indexOf(array, valueToFind, 0); } /** *

Finds the index of the given value in the array starting at the given index.

* *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

* *

A negative startIndex is treated as zero. A startIndex larger than the array * length will return {@link #INDEX_NOT_FOUND} (-1).

* * @param array the array to search through for the object, may be null * @param valueToFind the value to find * @param startIndex the index to start searching at * @return the index of the value within the array, * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input */ public static int indexOf(int[] array, int valueToFind, int startIndex) { if (array == null) { return INDEX_NOT_FOUND; } if (startIndex < 0) { startIndex = 0; } for (int i = startIndex; i < array.length; i++) { if (valueToFind == array[i]) { return i; } } return INDEX_NOT_FOUND; } /** *

Finds the last index of the given value within the array.

* *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

* * @param array the array to travers backwords looking for the object, may be null * @param valueToFind the object to find * @return the last index of the value within the array, * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input */ public static int lastIndexOf(int[] array, int valueToFind) { return lastIndexOf(array, valueToFind, Integer.MAX_VALUE); } /** *

Finds the last index of the given value in the array starting at the given index.

* *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

* *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the * array length will search from the end of the array.

* * @param array the array to traverse for looking for the object, may be null * @param valueToFind the value to find * @param startIndex the start index to travers backwards from * @return the last index of the value within the array, * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input */ public static int lastIndexOf(int[] array, int valueToFind, int startIndex) { if (array == null) { return INDEX_NOT_FOUND; } if (startIndex < 0) { return INDEX_NOT_FOUND; } else if (startIndex >= array.length) { startIndex = array.length - 1; } for (int i = startIndex; i >= 0; i--) { if (valueToFind == array[i]) { return i; } } return INDEX_NOT_FOUND; } /** *

Checks if the value is in the given array.

* *

The method returns false if a null array is passed in.

* * @param array the array to search through * @param valueToFind the value to find * @return true if the array contains the object */ public static boolean contains(int[] array, int valueToFind) { return indexOf(array, valueToFind) != INDEX_NOT_FOUND; } // short IndexOf //----------------------------------------------------------------------- /** *

Finds the index of the given value in the array.

* *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

* * @param array the array to search through for the object, may be null * @param valueToFind the value to find * @return the index of the value within the array, * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input */ public static int indexOf(short[] array, short valueToFind) { return indexOf(array, valueToFind, 0); } /** *

Finds the index of the given value in the array starting at the given index.

* *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

* *

A negative startIndex is treated as zero. A startIndex larger than the array * length will return {@link #INDEX_NOT_FOUND} (-1).

* * @param array the array to search through for the object, may be null * @param valueToFind the value to find * @param startIndex the index to start searching at * @return the index of the value within the array, * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input */ public static int indexOf(short[] array, short valueToFind, int startIndex) { if (array == null) { return INDEX_NOT_FOUND; } if (startIndex < 0) { startIndex = 0; } for (int i = startIndex; i < array.length; i++) { if (valueToFind == array[i]) { return i; } } return INDEX_NOT_FOUND; } /** *

Finds the last index of the given value within the array.

* *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

* * @param array the array to travers backwords looking for the object, may be null * @param valueToFind the object to find * @return the last index of the value within the array, * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input */ public static int lastIndexOf(short[] array, short valueToFind) { return lastIndexOf(array, valueToFind, Integer.MAX_VALUE); } /** *

Finds the last index of the given value in the array starting at the given index.

* *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

* *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the * array length will search from the end of the array.

* * @param array the array to traverse for looking for the object, may be null * @param valueToFind the value to find * @param startIndex the start index to travers backwards from * @return the last index of the value within the array, * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input */ public static int lastIndexOf(short[] array, short valueToFind, int startIndex) { if (array == null) { return INDEX_NOT_FOUND; } if (startIndex < 0) { return INDEX_NOT_FOUND; } else if (startIndex >= array.length) { startIndex = array.length - 1; } for (int i = startIndex; i >= 0; i--) { if (valueToFind == array[i]) { return i; } } return INDEX_NOT_FOUND; } /** *

Checks if the value is in the given array.

* *

The method returns false if a null array is passed in.

* * @param array the array to search through * @param valueToFind the value to find * @return true if the array contains the object */ public static boolean contains(short[] array, short valueToFind) { return indexOf(array, valueToFind) != INDEX_NOT_FOUND; } // char IndexOf //----------------------------------------------------------------------- /** *

Finds the index of the given value in the array.

* *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

* * @param array the array to search through for the object, may be null * @param valueToFind the value to find * @return the index of the value within the array, * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input * @since 2.1 */ public static int indexOf(char[] array, char valueToFind) { return indexOf(array, valueToFind, 0); } /** *

Finds the index of the given value in the array starting at the given index.

* *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

* *

A negative startIndex is treated as zero. A startIndex larger than the array * length will return {@link #INDEX_NOT_FOUND} (-1).

* * @param array the array to search through for the object, may be null * @param valueToFind the value to find * @param startIndex the index to start searching at * @return the index of the value within the array, * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input * @since 2.1 */ public static int indexOf(char[] array, char valueToFind, int startIndex) { if (array == null) { return INDEX_NOT_FOUND; } if (startIndex < 0) { startIndex = 0; } for (int i = startIndex; i < array.length; i++) { if (valueToFind == array[i]) { return i; } } return INDEX_NOT_FOUND; } /** *

Finds the last index of the given value within the array.

* *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

* * @param array the array to travers backwords looking for the object, may be null * @param valueToFind the object to find * @return the last index of the value within the array, * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input * @since 2.1 */ public static int lastIndexOf(char[] array, char valueToFind) { return lastIndexOf(array, valueToFind, Integer.MAX_VALUE); } /** *

Finds the last index of the given value in the array starting at the given index.

* *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

* *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the * array length will search from the end of the array.

* * @param array the array to traverse for looking for the object, may be null * @param valueToFind the value to find * @param startIndex the start index to travers backwards from * @return the last index of the value within the array, * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input * @since 2.1 */ public static int lastIndexOf(char[] array, char valueToFind, int startIndex) { if (array == null) { return INDEX_NOT_FOUND; } if (startIndex < 0) { return INDEX_NOT_FOUND; } else if (startIndex >= array.length) { startIndex = array.length - 1; } for (int i = startIndex; i >= 0; i--) { if (valueToFind == array[i]) { return i; } } return INDEX_NOT_FOUND; } /** *

Checks if the value is in the given array.

* *

The method returns false if a null array is passed in.

* * @param array the array to search through * @param valueToFind the value to find * @return true if the array contains the object * @since 2.1 */ public static boolean contains(char[] array, char valueToFind) { return indexOf(array, valueToFind) != INDEX_NOT_FOUND; } // byte IndexOf //----------------------------------------------------------------------- /** *

Finds the index of the given value in the array.

* *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

* * @param array the array to search through for the object, may be null * @param valueToFind the value to find * @return the index of the value within the array, * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input */ public static int indexOf(byte[] array, byte valueToFind) { return indexOf(array, valueToFind, 0); } /** *

Finds the index of the given value in the array starting at the given index.

* *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

* *

A negative startIndex is treated as zero. A startIndex larger than the array * length will return {@link #INDEX_NOT_FOUND} (-1).

* * @param array the array to search through for the object, may be null * @param valueToFind the value to find * @param startIndex the index to start searching at * @return the index of the value within the array, * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input */ public static int indexOf(byte[] array, byte valueToFind, int startIndex) { if (array == null) { return INDEX_NOT_FOUND; } if (startIndex < 0) { startIndex = 0; } for (int i = startIndex; i < array.length; i++) { if (valueToFind == array[i]) { return i; } } return INDEX_NOT_FOUND; } /** *

Finds the last index of the given value within the array.

* *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

* * @param array the array to travers backwords looking for the object, may be null * @param valueToFind the object to find * @return the last index of the value within the array, * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input */ public static int lastIndexOf(byte[] array, byte valueToFind) { return lastIndexOf(array, valueToFind, Integer.MAX_VALUE); } /** *

Finds the last index of the given value in the array starting at the given index.

* *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

* *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the * array length will search from the end of the array.

* * @param array the array to traverse for looking for the object, may be null * @param valueToFind the value to find * @param startIndex the start index to travers backwards from * @return the last index of the value within the array, * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input */ public static int lastIndexOf(byte[] array, byte valueToFind, int startIndex) { if (array == null) { return INDEX_NOT_FOUND; } if (startIndex < 0) { return INDEX_NOT_FOUND; } else if (startIndex >= array.length) { startIndex = array.length - 1; } for (int i = startIndex; i >= 0; i--) { if (valueToFind == array[i]) { return i; } } return INDEX_NOT_FOUND; } /** *

Checks if the value is in the given array.

* *

The method returns false if a null array is passed in.

* * @param array the array to search through * @param valueToFind the value to find * @return true if the array contains the object */ public static boolean contains(byte[] array, byte valueToFind) { return indexOf(array, valueToFind) != INDEX_NOT_FOUND; } // double IndexOf //----------------------------------------------------------------------- /** *

Finds the index of the given value in the array.

* *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

* * @param array the array to search through for the object, may be null * @param valueToFind the value to find * @return the index of the value within the array, * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input */ public static int indexOf(double[] array, double valueToFind) { return indexOf(array, valueToFind, 0); } /** *

Finds the index of the given value within a given tolerance in the array. * This method will return the index of the first value which falls between the region * defined by valueToFind - tolerance and valueToFind + tolerance.

* *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

* * @param array the array to search through for the object, may be null * @param valueToFind the value to find * @param tolerance tolerance of the search * @return the index of the value within the array, * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input */ public static int indexOf(double[] array, double valueToFind, double tolerance) { return indexOf(array, valueToFind, 0, tolerance); } /** *

Finds the index of the given value in the array starting at the given index.

* *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

* *

A negative startIndex is treated as zero. A startIndex larger than the array * length will return {@link #INDEX_NOT_FOUND} (-1).

* * @param array the array to search through for the object, may be null * @param valueToFind the value to find * @param startIndex the index to start searching at * @return the index of the value within the array, * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input */ public static int indexOf(double[] array, double valueToFind, int startIndex) { if (ArrayUtils.isEmpty(array)) { return INDEX_NOT_FOUND; } if (startIndex < 0) { startIndex = 0; } for (int i = startIndex; i < array.length; i++) { if (valueToFind == array[i]) { return i; } } return INDEX_NOT_FOUND; } /** *

Finds the index of the given value in the array starting at the given index. * This method will return the index of the first value which falls between the region * defined by valueToFind - tolerance and valueToFind + tolerance.

* *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

* *

A negative startIndex is treated as zero. A startIndex larger than the array * length will return {@link #INDEX_NOT_FOUND} (-1).

* * @param array the array to search through for the object, may be null * @param valueToFind the value to find * @param startIndex the index to start searching at * @param tolerance tolerance of the search * @return the index of the value within the array, * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input */ public static int indexOf(double[] array, double valueToFind, int startIndex, double tolerance) { if (ArrayUtils.isEmpty(array)) { return INDEX_NOT_FOUND; } if (startIndex < 0) { startIndex = 0; } double min = valueToFind - tolerance; double max = valueToFind + tolerance; for (int i = startIndex; i < array.length; i++) { if (array[i] >= min && array[i] <= max) { return i; } } return INDEX_NOT_FOUND; } /** *

Finds the last index of the given value within the array.

* *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

* * @param array the array to travers backwords looking for the object, may be null * @param valueToFind the object to find * @return the last index of the value within the array, * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input */ public static int lastIndexOf(double[] array, double valueToFind) { return lastIndexOf(array, valueToFind, Integer.MAX_VALUE); } /** *

Finds the last index of the given value within a given tolerance in the array. * This method will return the index of the last value which falls between the region * defined by valueToFind - tolerance and valueToFind + tolerance.

* *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

* * @param array the array to search through for the object, may be null * @param valueToFind the value to find * @param tolerance tolerance of the search * @return the index of the value within the array, * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input */ public static int lastIndexOf(double[] array, double valueToFind, double tolerance) { return lastIndexOf(array, valueToFind, Integer.MAX_VALUE, tolerance); } /** *

Finds the last index of the given value in the array starting at the given index.

* *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

* *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the * array length will search from the end of the array.

* * @param array the array to traverse for looking for the object, may be null * @param valueToFind the value to find * @param startIndex the start index to travers backwards from * @return the last index of the value within the array, * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input */ public static int lastIndexOf(double[] array, double valueToFind, int startIndex) { if (ArrayUtils.isEmpty(array)) { return INDEX_NOT_FOUND; } if (startIndex < 0) { return INDEX_NOT_FOUND; } else if (startIndex >= array.length) { startIndex = array.length - 1; } for (int i = startIndex; i >= 0; i--) { if (valueToFind == array[i]) { return i; } } return INDEX_NOT_FOUND; } /** *

Finds the last index of the given value in the array starting at the given index. * This method will return the index of the last value which falls between the region * defined by valueToFind - tolerance and valueToFind + tolerance.

* *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

* *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the * array length will search from the end of the array.

* * @param array the array to traverse for looking for the object, may be null * @param valueToFind the value to find * @param startIndex the start index to travers backwards from * @param tolerance search for value within plus/minus this amount * @return the last index of the value within the array, * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input */ public static int lastIndexOf(double[] array, double valueToFind, int startIndex, double tolerance) { if (ArrayUtils.isEmpty(array)) { return INDEX_NOT_FOUND; } if (startIndex < 0) { return INDEX_NOT_FOUND; } else if (startIndex >= array.length) { startIndex = array.length - 1; } double min = valueToFind - tolerance; double max = valueToFind + tolerance; for (int i = startIndex; i >= 0; i--) { if (array[i] >= min && array[i] <= max) { return i; } } return INDEX_NOT_FOUND; } /** *

Checks if the value is in the given array.

* *

The method returns false if a null array is passed in.

* * @param array the array to search through * @param valueToFind the value to find * @return true if the array contains the object */ public static boolean contains(double[] array, double valueToFind) { return indexOf(array, valueToFind) != INDEX_NOT_FOUND; } /** *

Checks if a value falling within the given tolerance is in the * given array. If the array contains a value within the inclusive range * defined by (value - tolerance) to (value + tolerance).

* *

The method returns false if a null array * is passed in.

* * @param array the array to search * @param valueToFind the value to find * @param tolerance the array contains the tolerance of the search * @return true if value falling within tolerance is in array */ public static boolean contains(double[] array, double valueToFind, double tolerance) { return indexOf(array, valueToFind, 0, tolerance) != INDEX_NOT_FOUND; } // float IndexOf //----------------------------------------------------------------------- /** *

Finds the index of the given value in the array.

* *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

* * @param array the array to search through for the object, may be null * @param valueToFind the value to find * @return the index of the value within the array, * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input */ public static int indexOf(float[] array, float valueToFind) { return indexOf(array, valueToFind, 0); } /** *

Finds the index of the given value in the array starting at the given index.

* *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

* *

A negative startIndex is treated as zero. A startIndex larger than the array * length will return {@link #INDEX_NOT_FOUND} (-1).

* * @param array the array to search through for the object, may be null * @param valueToFind the value to find * @param startIndex the index to start searching at * @return the index of the value within the array, * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input */ public static int indexOf(float[] array, float valueToFind, int startIndex) { if (ArrayUtils.isEmpty(array)) { return INDEX_NOT_FOUND; } if (startIndex < 0) { startIndex = 0; } for (int i = startIndex; i < array.length; i++) { if (valueToFind == array[i]) { return i; } } return INDEX_NOT_FOUND; } /** *

Finds the last index of the given value within the array.

* *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

* * @param array the array to travers backwords looking for the object, may be null * @param valueToFind the object to find * @return the last index of the value within the array, * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input */ public static int lastIndexOf(float[] array, float valueToFind) { return lastIndexOf(array, valueToFind, Integer.MAX_VALUE); } /** *

Finds the last index of the given value in the array starting at the given index.

* *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

* *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than the * array length will search from the end of the array.

* * @param array the array to traverse for looking for the object, may be null * @param valueToFind the value to find * @param startIndex the start index to travers backwards from * @return the last index of the value within the array, * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input */ public static int lastIndexOf(float[] array, float valueToFind, int startIndex) { if (ArrayUtils.isEmpty(array)) { return INDEX_NOT_FOUND; } if (startIndex < 0) { return INDEX_NOT_FOUND; } else if (startIndex >= array.length) { startIndex = array.length - 1; } for (int i = startIndex; i >= 0; i--) { if (valueToFind == array[i]) { return i; } } return INDEX_NOT_FOUND; } /** *

Checks if the value is in the given array.

* *

The method returns false if a null array is passed in.

* * @param array the array to search through * @param valueToFind the value to find * @return true if the array contains the object */ public static boolean contains(float[] array, float valueToFind) { return indexOf(array, valueToFind) != INDEX_NOT_FOUND; } // boolean IndexOf //----------------------------------------------------------------------- /** *

Finds the index of the given value in the array.

* *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

* * @param array the array to search through for the object, may be null * @param valueToFind the value to find * @return the index of the value within the array, * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input */ public static int indexOf(boolean[] array, boolean valueToFind) { return indexOf(array, valueToFind, 0); } /** *

Finds the index of the given value in the array starting at the given index.

* *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

* *

A negative startIndex is treated as zero. A startIndex larger than the array * length will return {@link #INDEX_NOT_FOUND} (-1).

* * @param array the array to search through for the object, may be null * @param valueToFind the value to find * @param startIndex the index to start searching at * @return the index of the value within the array, * {@link #INDEX_NOT_FOUND} (-1) if not found or null * array input */ public static int indexOf(boolean[] array, boolean valueToFind, int startIndex) { if (ArrayUtils.isEmpty(array)) { return INDEX_NOT_FOUND; } if (startIndex < 0) { startIndex = 0; } for (int i = startIndex; i < array.length; i++) { if (valueToFind == array[i]) { return i; } } return INDEX_NOT_FOUND; } /** *

Finds the last index of the given value within the array.

* *

This method returns {@link #INDEX_NOT_FOUND} (-1) if * null array input.

* * @param array the array to travers backwords looking for the object, may be null * @param valueToFind the object to find * @return the last index of the value within the array, * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input */ public static int lastIndexOf(boolean[] array, boolean valueToFind) { return lastIndexOf(array, valueToFind, Integer.MAX_VALUE); } /** *

Finds the last index of the given value in the array starting at the given index.

* *

This method returns {@link #INDEX_NOT_FOUND} (-1) for a null input array.

* *

A negative startIndex will return {@link #INDEX_NOT_FOUND} (-1). A startIndex larger than * the array length will search from the end of the array.

* * @param array the array to traverse for looking for the object, may be null * @param valueToFind the value to find * @param startIndex the start index to travers backwards from * @return the last index of the value within the array, * {@link #INDEX_NOT_FOUND} (-1) if not found or null array input */ public static int lastIndexOf(boolean[] array, boolean valueToFind, int startIndex) { if (ArrayUtils.isEmpty(array)) { return INDEX_NOT_FOUND; } if (startIndex < 0) { return INDEX_NOT_FOUND; } else if (startIndex >= array.length) { startIndex = array.length - 1; } for (int i = startIndex; i >= 0; i--) { if (valueToFind == array[i]) { return i; } } return INDEX_NOT_FOUND; } /** *

Checks if the value is in the given array.

* *

The method returns false if a null array is passed in.

* * @param array the array to search through * @param valueToFind the value to find * @return true if the array contains the object */ public static boolean contains(boolean[] array, boolean valueToFind) { return indexOf(array, valueToFind) != INDEX_NOT_FOUND; } // Primitive/Object array converters // ---------------------------------------------------------------------- // Character array converters // ---------------------------------------------------------------------- /** *

Converts an array of object Characters to primitives.

* *

This method returns null for a null input array.

* * @param array a Character array, may be null * @return a char array, null if null array input * @throws NullPointerException if array content is null */ public static char[] toPrimitive(Character[] array) { if (array == null) { return null; } else if (array.length == 0) { return EMPTY_CHAR_ARRAY; } final char[] result = new char[array.length]; for (int i = 0; i < array.length; i++) { result[i] = array[i].charValue(); } return result; } /** *

Converts an array of object Character to primitives handling null.

* *

This method returns null for a null input array.

* * @param array a Character array, may be null * @param valueForNull the value to insert if null found * @return a char array, null if null array input */ public static char[] toPrimitive(Character[] array, char valueForNull) { if (array == null) { return null; } else if (array.length == 0) { return EMPTY_CHAR_ARRAY; } final char[] result = new char[array.length]; for (int i = 0; i < array.length; i++) { Character b = array[i]; result[i] = (b == null ? valueForNull : b.charValue()); } return result; } /** *

Converts an array of primitive chars to objects.

* *

This method returns null for a null input array.

* * @param array a char array * @return a Character array, null if null array input */ public static Character[] toObject(char[] array) { if (array == null) { return null; } else if (array.length == 0) { return EMPTY_CHARACTER_OBJECT_ARRAY; } final Character[] result = new Character[array.length]; for (int i = 0; i < array.length; i++) { result[i] = new Character(array[i]); } return result; } // Long array converters // ---------------------------------------------------------------------- /** *

Converts an array of object Longs to primitives.

* *

This method returns null for a null input array.

* * @param array a Long array, may be null * @return a long array, null if null array input * @throws NullPointerException if array content is null */ public static long[] toPrimitive(Long[] array) { if (array == null) { return null; } else if (array.length == 0) { return EMPTY_LONG_ARRAY; } final long[] result = new long[array.length]; for (int i = 0; i < array.length; i++) { result[i] = array[i].longValue(); } return result; } /** *

Converts an array of object Long to primitives handling null.

* *

This method returns null for a null input array.

* * @param array a Long array, may be null * @param valueForNull the value to insert if null found * @return a long array, null if null array input */ public static long[] toPrimitive(Long[] array, long valueForNull) { if (array == null) { return null; } else if (array.length == 0) { return EMPTY_LONG_ARRAY; } final long[] result = new long[array.length]; for (int i = 0; i < array.length; i++) { Long b = array[i]; result[i] = (b == null ? valueForNull : b.longValue()); } return result; } /** *

Converts an array of primitive longs to objects.

* *

This method returns null for a null input array.

* * @param array a long array * @return a Long array, null if null array input */ public static Long[] toObject(long[] array) { if (array == null) { return null; } else if (array.length == 0) { return EMPTY_LONG_OBJECT_ARRAY; } final Long[] result = new Long[array.length]; for (int i = 0; i < array.length; i++) { result[i] = new Long(array[i]); } return result; } // Int array converters // ---------------------------------------------------------------------- /** *

Converts an array of object Integers to primitives.

* *

This method returns null for a null input array.

* * @param array a Integer array, may be null * @return an int array, null if null array input * @throws NullPointerException if array content is null */ public static int[] toPrimitive(Integer[] array) { if (array == null) { return null; } else if (array.length == 0) { return EMPTY_INT_ARRAY; } final int[] result = new int[array.length]; for (int i = 0; i < array.length; i++) { result[i] = array[i].intValue(); } return result; } /** *

Converts an array of object Integer to primitives handling null.

* *

This method returns null for a null input array.

* * @param array a Integer array, may be null * @param valueForNull the value to insert if null found * @return an int array, null if null array input */ public static int[] toPrimitive(Integer[] array, int valueForNull) { if (array == null) { return null; } else if (array.length == 0) { return EMPTY_INT_ARRAY; } final int[] result = new int[array.length]; for (int i = 0; i < array.length; i++) { Integer b = array[i]; result[i] = (b == null ? valueForNull : b.intValue()); } return result; } /** *

Converts an array of primitive ints to objects.

* *

This method returns null for a null input array.

* * @param array an int array * @return an Integer array, null if null array input */ public static Integer[] toObject(int[] array) { if (array == null) { return null; } else if (array.length == 0) { return EMPTY_INTEGER_OBJECT_ARRAY; } final Integer[] result = new Integer[array.length]; for (int i = 0; i < array.length; i++) { result[i] = new Integer(array[i]); } return result; } // Short array converters // ---------------------------------------------------------------------- /** *

Converts an array of object Shorts to primitives.

* *

This method returns null for a null input array.

* * @param array a Short array, may be null * @return a byte array, null if null array input * @throws NullPointerException if array content is null */ public static short[] toPrimitive(Short[] array) { if (array == null) { return null; } else if (array.length == 0) { return EMPTY_SHORT_ARRAY; } final short[] result = new short[array.length]; for (int i = 0; i < array.length; i++) { result[i] = array[i].shortValue(); } return result; } /** *

Converts an array of object Short to primitives handling null.

* *

This method returns null for a null input array.

* * @param array a Short array, may be null * @param valueForNull the value to insert if null found * @return a byte array, null if null array input */ public static short[] toPrimitive(Short[] array, short valueForNull) { if (array == null) { return null; } else if (array.length == 0) { return EMPTY_SHORT_ARRAY; } final short[] result = new short[array.length]; for (int i = 0; i < array.length; i++) { Short b = array[i]; result[i] = (b == null ? valueForNull : b.shortValue()); } return result; } /** *

Converts an array of primitive shorts to objects.

* *

This method returns null for a null input array.

* * @param array a short array * @return a Short array, null if null array input */ public static Short[] toObject(short[] array) { if (array == null) { return null; } else if (array.length == 0) { return EMPTY_SHORT_OBJECT_ARRAY; } final Short[] result = new Short[array.length]; for (int i = 0; i < array.length; i++) { result[i] = new Short(array[i]); } return result; } // Byte array converters // ---------------------------------------------------------------------- /** *

Converts an array of object Bytes to primitives.

* *

This method returns null for a null input array.

* * @param array a Byte array, may be null * @return a byte array, null if null array input * @throws NullPointerException if array content is null */ public static byte[] toPrimitive(Byte[] array) { if (array == null) { return null; } else if (array.length == 0) { return EMPTY_BYTE_ARRAY; } final byte[] result = new byte[array.length]; for (int i = 0; i < array.length; i++) { result[i] = array[i].byteValue(); } return result; } /** *

Converts an array of object Bytes to primitives handling null.

* *

This method returns null for a null input array.

* * @param array a Byte array, may be null * @param valueForNull the value to insert if null found * @return a byte array, null if null array input */ public static byte[] toPrimitive(Byte[] array, byte valueForNull) { if (array == null) { return null; } else if (array.length == 0) { return EMPTY_BYTE_ARRAY; } final byte[] result = new byte[array.length]; for (int i = 0; i < array.length; i++) { Byte b = array[i]; result[i] = (b == null ? valueForNull : b.byteValue()); } return result; } /** *

Converts an array of primitive bytes to objects.

* *

This method returns null for a null input array.

* * @param array a byte array * @return a Byte array, null if null array input */ public static Byte[] toObject(byte[] array) { if (array == null) { return null; } else if (array.length == 0) { return EMPTY_BYTE_OBJECT_ARRAY; } final Byte[] result = new Byte[array.length]; for (int i = 0; i < array.length; i++) { result[i] = new Byte(array[i]); } return result; } // Double array converters // ---------------------------------------------------------------------- /** *

Converts an array of object Doubles to primitives.

* *

This method returns null for a null input array.

* * @param array a Double array, may be null * @return a double array, null if null array input * @throws NullPointerException if array content is null */ public static double[] toPrimitive(Double[] array) { if (array == null) { return null; } else if (array.length == 0) { return EMPTY_DOUBLE_ARRAY; } final double[] result = new double[array.length]; for (int i = 0; i < array.length; i++) { result[i] = array[i].doubleValue(); } return result; } /** *

Converts an array of object Doubles to primitives handling null.

* *

This method returns null for a null input array.

* * @param array a Double array, may be null * @param valueForNull the value to insert if null found * @return a double array, null if null array input */ public static double[] toPrimitive(Double[] array, double valueForNull) { if (array == null) { return null; } else if (array.length == 0) { return EMPTY_DOUBLE_ARRAY; } final double[] result = new double[array.length]; for (int i = 0; i < array.length; i++) { Double b = array[i]; result[i] = (b == null ? valueForNull : b.doubleValue()); } return result; } /** *

Converts an array of primitive doubles to objects.

* *

This method returns null for a null input array.

* * @param array a double array * @return a Double array, null if null array input */ public static Double[] toObject(double[] array) { if (array == null) { return null; } else if (array.length == 0) { return EMPTY_DOUBLE_OBJECT_ARRAY; } final Double[] result = new Double[array.length]; for (int i = 0; i < array.length; i++) { result[i] = new Double(array[i]); } return result; } // Float array converters // ---------------------------------------------------------------------- /** *

Converts an array of object Floats to primitives.

* *

This method returns null for a null input array.

* * @param array a Float array, may be null * @return a float array, null if null array input * @throws NullPointerException if array content is null */ public static float[] toPrimitive(Float[] array) { if (array == null) { return null; } else if (array.length == 0) { return EMPTY_FLOAT_ARRAY; } final float[] result = new float[array.length]; for (int i = 0; i < array.length; i++) { result[i] = array[i].floatValue(); } return result; } /** *

Converts an array of object Floats to primitives handling null.

* *

This method returns null for a null input array.

* * @param array a Float array, may be null * @param valueForNull the value to insert if null found * @return a float array, null if null array input */ public static float[] toPrimitive(Float[] array, float valueForNull) { if (array == null) { return null; } else if (array.length == 0) { return EMPTY_FLOAT_ARRAY; } final float[] result = new float[array.length]; for (int i = 0; i < array.length; i++) { Float b = array[i]; result[i] = (b == null ? valueForNull : b.floatValue()); } return result; } /** *

Converts an array of primitive floats to objects.

* *

This method returns null for a null input array.

* * @param array a float array * @return a Float array, null if null array input */ public static Float[] toObject(float[] array) { if (array == null) { return null; } else if (array.length == 0) { return EMPTY_FLOAT_OBJECT_ARRAY; } final Float[] result = new Float[array.length]; for (int i = 0; i < array.length; i++) { result[i] = new Float(array[i]); } return result; } // Boolean array converters // ---------------------------------------------------------------------- /** *

Converts an array of object Booleans to primitives.

* *

This method returns null for a null input array.

* * @param array a Boolean array, may be null * @return a boolean array, null if null array input * @throws NullPointerException if array content is null */ public static boolean[] toPrimitive(Boolean[] array) { if (array == null) { return null; } else if (array.length == 0) { return EMPTY_BOOLEAN_ARRAY; } final boolean[] result = new boolean[array.length]; for (int i = 0; i < array.length; i++) { result[i] = array[i].booleanValue(); } return result; } /** *

Converts an array of object Booleans to primitives handling null.

* *

This method returns null for a null input array.

* * @param array a Boolean array, may be null * @param valueForNull the value to insert if null found * @return a boolean array, null if null array input */ public static boolean[] toPrimitive(Boolean[] array, boolean valueForNull) { if (array == null) { return null; } else if (array.length == 0) { return EMPTY_BOOLEAN_ARRAY; } final boolean[] result = new boolean[array.length]; for (int i = 0; i < array.length; i++) { Boolean b = array[i]; result[i] = (b == null ? valueForNull : b.booleanValue()); } return result; } /** *

Converts an array of primitive booleans to objects.

* *

This method returns null for a null input array.

* * @param array a boolean array * @return a Boolean array, null if null array input */ public static Boolean[] toObject(boolean[] array) { if (array == null) { return null; } else if (array.length == 0) { return EMPTY_BOOLEAN_OBJECT_ARRAY; } final Boolean[] result = new Boolean[array.length]; for (int i = 0; i < array.length; i++) { result[i] = (array[i] ? Boolean.TRUE : Boolean.FALSE); } return result; } // ---------------------------------------------------------------------- /** *

Checks if an array of Objects is empty or null.

* * @param array the array to test * @return true if the array is empty or null * @since 2.1 */ public static boolean isEmpty(Object[] array) { return array == null || array.length == 0; } /** *

Checks if an array of primitive longs is empty or null.

* * @param array the array to test * @return true if the array is empty or null * @since 2.1 */ public static boolean isEmpty(long[] array) { return array == null || array.length == 0; } /** *

Checks if an array of primitive ints is empty or null.

* * @param array the array to test * @return true if the array is empty or null * @since 2.1 */ public static boolean isEmpty(int[] array) { return array == null || array.length == 0; } /** *

Checks if an array of primitive shorts is empty or null.

* * @param array the array to test * @return true if the array is empty or null * @since 2.1 */ public static boolean isEmpty(short[] array) { return array == null || array.length == 0; } /** *

Checks if an array of primitive chars is empty or null.

* * @param array the array to test * @return true if the array is empty or null * @since 2.1 */ public static boolean isEmpty(char[] array) { return array == null || array.length == 0; } /** *

Checks if an array of primitive bytes is empty or null.

* * @param array the array to test * @return true if the array is empty or null * @since 2.1 */ public static boolean isEmpty(byte[] array) { return array == null || array.length == 0; } /** *

Checks if an array of primitive doubles is empty or null.

* * @param array the array to test * @return true if the array is empty or null * @since 2.1 */ public static boolean isEmpty(double[] array) { return array == null || array.length == 0; } /** *

Checks if an array of primitive floats is empty or null.

* * @param array the array to test * @return true if the array is empty or null * @since 2.1 */ public static boolean isEmpty(float[] array) { return array == null || array.length == 0; } /** *

Checks if an array of primitive booleans is empty or null.

* * @param array the array to test * @return true if the array is empty or null * @since 2.1 */ public static boolean isEmpty(boolean[] array) { return array == null || array.length == 0; } // ---------------------------------------------------------------------- /** *

Checks if an array of Objects is not empty or not null.

* * @param array the array to test * @return true if the array is not empty or not null * @since 2.5 */ public static boolean isNotEmpty(Object[] array) { return (array != null && array.length != 0); } /** *

Checks if an array of primitive longs is not empty or not null.

* * @param array the array to test * @return true if the array is not empty or not null * @since 2.5 */ public static boolean isNotEmpty(long[] array) { return (array != null && array.length != 0); } /** *

Checks if an array of primitive ints is not empty or not null.

* * @param array the array to test * @return true if the array is not empty or not null * @since 2.5 */ public static boolean isNotEmpty(int[] array) { return (array != null && array.length != 0); } /** *

Checks if an array of primitive shorts is not empty or not null.

* * @param array the array to test * @return true if the array is not empty or not null * @since 2.5 */ public static boolean isNotEmpty(short[] array) { return (array != null && array.length != 0); } /** *

Checks if an array of primitive chars is not empty or not null.

* * @param array the array to test * @return true if the array is not empty or not null * @since 2.5 */ public static boolean isNotEmpty(char[] array) { return (array != null && array.length != 0); } /** *

Checks if an array of primitive bytes is not empty or not null.

* * @param array the array to test * @return true if the array is not empty or not null * @since 2.5 */ public static boolean isNotEmpty(byte[] array) { return (array != null && array.length != 0); } /** *

Checks if an array of primitive doubles is not empty or not null.

* * @param array the array to test * @return true if the array is not empty or not null * @since 2.5 */ public static boolean isNotEmpty(double[] array) { return (array != null && array.length != 0); } /** *

Checks if an array of primitive floats is not empty or not null.

* * @param array the array to test * @return true if the array is not empty or not null * @since 2.5 */ public static boolean isNotEmpty(float[] array) { return (array != null && array.length != 0); } /** *

Checks if an array of primitive booleans is not empty or not null.

* * @param array the array to test * @return true if the array is not empty or not null * @since 2.5 */ public static boolean isNotEmpty(boolean[] array) { return (array != null && array.length != 0); } /** *

Adds all the elements of the given arrays into a new array.

*

The new array contains all of the element of array1 followed * by all of the elements array2. When an array is returned, it is always * a new array.

* *
     * ArrayUtils.addAll(null, null)     = null
     * ArrayUtils.addAll(array1, null)   = cloned copy of array1
     * ArrayUtils.addAll(null, array2)   = cloned copy of array2
     * ArrayUtils.addAll([], [])         = []
     * ArrayUtils.addAll([null], [null]) = [null, null]
     * ArrayUtils.addAll(["a", "b", "c"], ["1", "2", "3"]) = ["a", "b", "c", "1", "2", "3"]
     * 
* * @param array1 the first array whose elements are added to the new array, may be null * @param array2 the second array whose elements are added to the new array, may be null * @return The new array, null if both arrays are null. * The type of the new array is the type of the first array, * unless the first array is null, in which case the type is the same as the second array. * @since 2.1 * @throws IllegalArgumentException if the array types are incompatible */ public static Object[] addAll(Object[] array1, Object[] array2) { if (array1 == null) { return clone(array2); } else if (array2 == null) { return clone(array1); } Object[] joinedArray = (Object[]) Array.newInstance(array1.getClass().getComponentType(), array1.length + array2.length); System.arraycopy(array1, 0, joinedArray, 0, array1.length); try { System.arraycopy(array2, 0, joinedArray, array1.length, array2.length); } catch (ArrayStoreException ase) { // Check if problem was due to incompatible types /* * We do this here, rather than before the copy because: * - it would be a wasted check most of the time * - safer, in case check turns out to be too strict */ final Class type1 = array1.getClass().getComponentType(); final Class type2 = array2.getClass().getComponentType(); if (!type1.isAssignableFrom(type2)){ throw new IllegalArgumentException("Cannot store "+type2.getName()+" in an array of "+type1.getName()); } throw ase; // No, so rethrow original } return joinedArray; } /** *

Adds all the elements of the given arrays into a new array.

*

The new array contains all of the element of array1 followed * by all of the elements array2. When an array is returned, it is always * a new array.

* *
     * ArrayUtils.addAll(array1, null)   = cloned copy of array1
     * ArrayUtils.addAll(null, array2)   = cloned copy of array2
     * ArrayUtils.addAll([], [])         = []
     * 
* * @param array1 the first array whose elements are added to the new array. * @param array2 the second array whose elements are added to the new array. * @return The new boolean[] array. * @since 2.1 */ public static boolean[] addAll(boolean[] array1, boolean[] array2) { if (array1 == null) { return clone(array2); } else if (array2 == null) { return clone(array1); } boolean[] joinedArray = new boolean[array1.length + array2.length]; System.arraycopy(array1, 0, joinedArray, 0, array1.length); System.arraycopy(array2, 0, joinedArray, array1.length, array2.length); return joinedArray; } /** *

Adds all the elements of the given arrays into a new array.

*

The new array contains all of the element of array1 followed * by all of the elements array2. When an array is returned, it is always * a new array.

* *
     * ArrayUtils.addAll(array1, null)   = cloned copy of array1
     * ArrayUtils.addAll(null, array2)   = cloned copy of array2
     * ArrayUtils.addAll([], [])         = []
     * 
* * @param array1 the first array whose elements are added to the new array. * @param array2 the second array whose elements are added to the new array. * @return The new char[] array. * @since 2.1 */ public static char[] addAll(char[] array1, char[] array2) { if (array1 == null) { return clone(array2); } else if (array2 == null) { return clone(array1); } char[] joinedArray = new char[array1.length + array2.length]; System.arraycopy(array1, 0, joinedArray, 0, array1.length); System.arraycopy(array2, 0, joinedArray, array1.length, array2.length); return joinedArray; } /** *

Adds all the elements of the given arrays into a new array.

*

The new array contains all of the element of array1 followed * by all of the elements array2. When an array is returned, it is always * a new array.

* *
     * ArrayUtils.addAll(array1, null)   = cloned copy of array1
     * ArrayUtils.addAll(null, array2)   = cloned copy of array2
     * ArrayUtils.addAll([], [])         = []
     * 
* * @param array1 the first array whose elements are added to the new array. * @param array2 the second array whose elements are added to the new array. * @return The new byte[] array. * @since 2.1 */ public static byte[] addAll(byte[] array1, byte[] array2) { if (array1 == null) { return clone(array2); } else if (array2 == null) { return clone(array1); } byte[] joinedArray = new byte[array1.length + array2.length]; System.arraycopy(array1, 0, joinedArray, 0, array1.length); System.arraycopy(array2, 0, joinedArray, array1.length, array2.length); return joinedArray; } /** *

Adds all the elements of the given arrays into a new array.

*

The new array contains all of the element of array1 followed * by all of the elements array2. When an array is returned, it is always * a new array.

* *
     * ArrayUtils.addAll(array1, null)   = cloned copy of array1
     * ArrayUtils.addAll(null, array2)   = cloned copy of array2
     * ArrayUtils.addAll([], [])         = []
     * 
* * @param array1 the first array whose elements are added to the new array. * @param array2 the second array whose elements are added to the new array. * @return The new short[] array. * @since 2.1 */ public static short[] addAll(short[] array1, short[] array2) { if (array1 == null) { return clone(array2); } else if (array2 == null) { return clone(array1); } short[] joinedArray = new short[array1.length + array2.length]; System.arraycopy(array1, 0, joinedArray, 0, array1.length); System.arraycopy(array2, 0, joinedArray, array1.length, array2.length); return joinedArray; } /** *

Adds all the elements of the given arrays into a new array.

*

The new array contains all of the element of array1 followed * by all of the elements array2. When an array is returned, it is always * a new array.

* *
     * ArrayUtils.addAll(array1, null)   = cloned copy of array1
     * ArrayUtils.addAll(null, array2)   = cloned copy of array2
     * ArrayUtils.addAll([], [])         = []
     * 
* * @param array1 the first array whose elements are added to the new array. * @param array2 the second array whose elements are added to the new array. * @return The new int[] array. * @since 2.1 */ public static int[] addAll(int[] array1, int[] array2) { if (array1 == null) { return clone(array2); } else if (array2 == null) { return clone(array1); } int[] joinedArray = new int[array1.length + array2.length]; System.arraycopy(array1, 0, joinedArray, 0, array1.length); System.arraycopy(array2, 0, joinedArray, array1.length, array2.length); return joinedArray; } /** *

Adds all the elements of the given arrays into a new array.

*

The new array contains all of the element of array1 followed * by all of the elements array2. When an array is returned, it is always * a new array.

* *
     * ArrayUtils.addAll(array1, null)   = cloned copy of array1
     * ArrayUtils.addAll(null, array2)   = cloned copy of array2
     * ArrayUtils.addAll([], [])         = []
     * 
* * @param array1 the first array whose elements are added to the new array. * @param array2 the second array whose elements are added to the new array. * @return The new long[] array. * @since 2.1 */ public static long[] addAll(long[] array1, long[] array2) { if (array1 == null) { return clone(array2); } else if (array2 == null) { return clone(array1); } long[] joinedArray = new long[array1.length + array2.length]; System.arraycopy(array1, 0, joinedArray, 0, array1.length); System.arraycopy(array2, 0, joinedArray, array1.length, array2.length); return joinedArray; } /** *

Adds all the elements of the given arrays into a new array.

*

The new array contains all of the element of array1 followed * by all of the elements array2. When an array is returned, it is always * a new array.

* *
     * ArrayUtils.addAll(array1, null)   = cloned copy of array1
     * ArrayUtils.addAll(null, array2)   = cloned copy of array2
     * ArrayUtils.addAll([], [])         = []
     * 
* * @param array1 the first array whose elements are added to the new array. * @param array2 the second array whose elements are added to the new array. * @return The new float[] array. * @since 2.1 */ public static float[] addAll(float[] array1, float[] array2) { if (array1 == null) { return clone(array2); } else if (array2 == null) { return clone(array1); } float[] joinedArray = new float[array1.length + array2.length]; System.arraycopy(array1, 0, joinedArray, 0, array1.length); System.arraycopy(array2, 0, joinedArray, array1.length, array2.length); return joinedArray; } /** *

Adds all the elements of the given arrays into a new array.

*

The new array contains all of the element of array1 followed * by all of the elements array2. When an array is returned, it is always * a new array.

* *
     * ArrayUtils.addAll(array1, null)   = cloned copy of array1
     * ArrayUtils.addAll(null, array2)   = cloned copy of array2
     * ArrayUtils.addAll([], [])         = []
     * 
* * @param array1 the first array whose elements are added to the new array. * @param array2 the second array whose elements are added to the new array. * @return The new double[] array. * @since 2.1 */ public static double[] addAll(double[] array1, double[] array2) { if (array1 == null) { return clone(array2); } else if (array2 == null) { return clone(array1); } double[] joinedArray = new double[array1.length + array2.length]; System.arraycopy(array1, 0, joinedArray, 0, array1.length); System.arraycopy(array2, 0, joinedArray, array1.length, array2.length); return joinedArray; } /** *

Copies the given array and adds the given element at the end of the new array.

* *

The new array contains the same elements of the input * array plus the given element in the last position. The component type of * the new array is the same as that of the input array.

* *

If the input array is null, a new one element array is returned * whose component type is the same as the element, unless the element itself is null, * in which case the return type is Object[]

* *
     * ArrayUtils.add(null, null)      = [null]
     * ArrayUtils.add(null, "a")       = ["a"]
     * ArrayUtils.add(["a"], null)     = ["a", null]
     * ArrayUtils.add(["a"], "b")      = ["a", "b"]
     * ArrayUtils.add(["a", "b"], "c") = ["a", "b", "c"]
     * 
* * @param array the array to "add" the element to, may be null * @param element the object to add, may be null * @return A new array containing the existing elements plus the new element * The returned array type will be that of the input array (unless null), * in which case it will have the same type as the element. * @since 2.1 */ public static Object[] add(Object[] array, Object element) { Class type; if (array != null){ type = array.getClass(); } else if (element != null) { type = element.getClass(); } else { type = Object.class; } Object[] newArray = (Object[]) copyArrayGrow1(array, type); newArray[newArray.length - 1] = element; return newArray; } /** *

Copies the given array and adds the given element at the end of the new array.

* *

The new array contains the same elements of the input * array plus the given element in the last position. The component type of * the new array is the same as that of the input array.

* *

If the input array is null, a new one element array is returned * whose component type is the same as the element.

* *
     * ArrayUtils.add(null, true)          = [true]
     * ArrayUtils.add([true], false)       = [true, false]
     * ArrayUtils.add([true, false], true) = [true, false, true]
     * 
* * @param array the array to copy and add the element to, may be null * @param element the object to add at the last index of the new array * @return A new array containing the existing elements plus the new element * @since 2.1 */ public static boolean[] add(boolean[] array, boolean element) { boolean[] newArray = (boolean[])copyArrayGrow1(array, Boolean.TYPE); newArray[newArray.length - 1] = element; return newArray; } /** *

Copies the given array and adds the given element at the end of the new array.

* *

The new array contains the same elements of the input * array plus the given element in the last position. The component type of * the new array is the same as that of the input array.

* *

If the input array is null, a new one element array is returned * whose component type is the same as the element.

* *
     * ArrayUtils.add(null, 0)   = [0]
     * ArrayUtils.add([1], 0)    = [1, 0]
     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]
     * 
* * @param array the array to copy and add the element to, may be null * @param element the object to add at the last index of the new array * @return A new array containing the existing elements plus the new element * @since 2.1 */ public static byte[] add(byte[] array, byte element) { byte[] newArray = (byte[])copyArrayGrow1(array, Byte.TYPE); newArray[newArray.length - 1] = element; return newArray; } /** *

Copies the given array and adds the given element at the end of the new array.

* *

The new array contains the same elements of the input * array plus the given element in the last position. The component type of * the new array is the same as that of the input array.

* *

If the input array is null, a new one element array is returned * whose component type is the same as the element.

* *
     * ArrayUtils.add(null, '0')       = ['0']
     * ArrayUtils.add(['1'], '0')      = ['1', '0']
     * ArrayUtils.add(['1', '0'], '1') = ['1', '0', '1']
     * 
* * @param array the array to copy and add the element to, may be null * @param element the object to add at the last index of the new array * @return A new array containing the existing elements plus the new element * @since 2.1 */ public static char[] add(char[] array, char element) { char[] newArray = (char[])copyArrayGrow1(array, Character.TYPE); newArray[newArray.length - 1] = element; return newArray; } /** *

Copies the given array and adds the given element at the end of the new array.

* *

The new array contains the same elements of the input * array plus the given element in the last position. The component type of * the new array is the same as that of the input array.

* *

If the input array is null, a new one element array is returned * whose component type is the same as the element.

* *
     * ArrayUtils.add(null, 0)   = [0]
     * ArrayUtils.add([1], 0)    = [1, 0]
     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]
     * 
* * @param array the array to copy and add the element to, may be null * @param element the object to add at the last index of the new array * @return A new array containing the existing elements plus the new element * @since 2.1 */ public static double[] add(double[] array, double element) { double[] newArray = (double[])copyArrayGrow1(array, Double.TYPE); newArray[newArray.length - 1] = element; return newArray; } /** *

Copies the given array and adds the given element at the end of the new array.

* *

The new array contains the same elements of the input * array plus the given element in the last position. The component type of * the new array is the same as that of the input array.

* *

If the input array is null, a new one element array is returned * whose component type is the same as the element.

* *
     * ArrayUtils.add(null, 0)   = [0]
     * ArrayUtils.add([1], 0)    = [1, 0]
     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]
     * 
* * @param array the array to copy and add the element to, may be null * @param element the object to add at the last index of the new array * @return A new array containing the existing elements plus the new element * @since 2.1 */ public static float[] add(float[] array, float element) { float[] newArray = (float[])copyArrayGrow1(array, Float.TYPE); newArray[newArray.length - 1] = element; return newArray; } /** *

Copies the given array and adds the given element at the end of the new array.

* *

The new array contains the same elements of the input * array plus the given element in the last position. The component type of * the new array is the same as that of the input array.

* *

If the input array is null, a new one element array is returned * whose component type is the same as the element.

* *
     * ArrayUtils.add(null, 0)   = [0]
     * ArrayUtils.add([1], 0)    = [1, 0]
     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]
     * 
* * @param array the array to copy and add the element to, may be null * @param element the object to add at the last index of the new array * @return A new array containing the existing elements plus the new element * @since 2.1 */ public static int[] add(int[] array, int element) { int[] newArray = (int[])copyArrayGrow1(array, Integer.TYPE); newArray[newArray.length - 1] = element; return newArray; } /** *

Copies the given array and adds the given element at the end of the new array.

* *

The new array contains the same elements of the input * array plus the given element in the last position. The component type of * the new array is the same as that of the input array.

* *

If the input array is null, a new one element array is returned * whose component type is the same as the element.

* *
     * ArrayUtils.add(null, 0)   = [0]
     * ArrayUtils.add([1], 0)    = [1, 0]
     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]
     * 
* * @param array the array to copy and add the element to, may be null * @param element the object to add at the last index of the new array * @return A new array containing the existing elements plus the new element * @since 2.1 */ public static long[] add(long[] array, long element) { long[] newArray = (long[])copyArrayGrow1(array, Long.TYPE); newArray[newArray.length - 1] = element; return newArray; } /** *

Copies the given array and adds the given element at the end of the new array.

* *

The new array contains the same elements of the input * array plus the given element in the last position. The component type of * the new array is the same as that of the input array.

* *

If the input array is null, a new one element array is returned * whose component type is the same as the element.

* *
     * ArrayUtils.add(null, 0)   = [0]
     * ArrayUtils.add([1], 0)    = [1, 0]
     * ArrayUtils.add([1, 0], 1) = [1, 0, 1]
     * 
* * @param array the array to copy and add the element to, may be null * @param element the object to add at the last index of the new array * @return A new array containing the existing elements plus the new element * @since 2.1 */ public static short[] add(short[] array, short element) { short[] newArray = (short[])copyArrayGrow1(array, Short.TYPE); newArray[newArray.length - 1] = element; return newArray; } /** * Returns a copy of the given array of size 1 greater than the argument. * The last value of the array is left to the default value. * * @param array The array to copy, must not be null. * @param newArrayComponentType If array is null, create a * size 1 array of this type. * @return A new copy of the array of size 1 greater than the input. */ private static Object copyArrayGrow1(Object array, Class newArrayComponentType) { if (array != null) { int arrayLength = Array.getLength(array); Object newArray = Array.newInstance(array.getClass().getComponentType(), arrayLength + 1); System.arraycopy(array, 0, newArray, 0, arrayLength); return newArray; } return Array.newInstance(newArrayComponentType, 1); } /** *

Inserts the specified element at the specified position in the array. * Shifts the element currently at that position (if any) and any subsequent * elements to the right (adds one to their indices).

* *

This method returns a new array with the same elements of the input * array plus the given element on the specified position. The component * type of the returned array is always the same as that of the input * array.

* *

If the input array is null, a new one element array is returned * whose component type is the same as the element.

* *
     * ArrayUtils.add(null, 0, null)      = [null]
     * ArrayUtils.add(null, 0, "a")       = ["a"]
     * ArrayUtils.add(["a"], 1, null)     = ["a", null]
     * ArrayUtils.add(["a"], 1, "b")      = ["a", "b"]
     * ArrayUtils.add(["a", "b"], 3, "c") = ["a", "b", "c"]
     * 
* * @param array the array to add the element to, may be null * @param index the position of the new object * @param element the object to add * @return A new array containing the existing elements and the new element * @throws IndexOutOfBoundsException if the index is out of range * (index < 0 || index > array.length). */ public static Object[] add(Object[] array, int index, Object element) { Class clss = null; if (array != null) { clss = array.getClass().getComponentType(); } else if (element != null) { clss = element.getClass(); } else { return new Object[]{null}; } return (Object[]) add(array, index, element, clss); } /** *

Inserts the specified element at the specified position in the array. * Shifts the element currently at that position (if any) and any subsequent * elements to the right (adds one to their indices).

* *

This method returns a new array with the same elements of the input * array plus the given element on the specified position. The component * type of the returned array is always the same as that of the input * array.

* *

If the input array is null, a new one element array is returned * whose component type is the same as the element.

* *
     * ArrayUtils.add(null, 0, true)          = [true]
     * ArrayUtils.add([true], 0, false)       = [false, true]
     * ArrayUtils.add([false], 1, true)       = [false, true]
     * ArrayUtils.add([true, false], 1, true) = [true, true, false]
     * 
* * @param array the array to add the element to, may be null * @param index the position of the new object * @param element the object to add * @return A new array containing the existing elements and the new element * @throws IndexOutOfBoundsException if the index is out of range * (index < 0 || index > array.length). */ public static boolean[] add(boolean[] array, int index, boolean element) { return (boolean[]) add(array, index, BooleanUtils.toBooleanObject(element), Boolean.TYPE); } /** *

Inserts the specified element at the specified position in the array. * Shifts the element currently at that position (if any) and any subsequent * elements to the right (adds one to their indices).

* *

This method returns a new array with the same elements of the input * array plus the given element on the specified position. The component * type of the returned array is always the same as that of the input * array.

* *

If the input array is null, a new one element array is returned * whose component type is the same as the element.

* *
     * ArrayUtils.add(null, 0, 'a')            = ['a']
     * ArrayUtils.add(['a'], 0, 'b')           = ['b', 'a']
     * ArrayUtils.add(['a', 'b'], 0, 'c')      = ['c', 'a', 'b']
     * ArrayUtils.add(['a', 'b'], 1, 'k')      = ['a', 'k', 'b']
     * ArrayUtils.add(['a', 'b', 'c'], 1, 't') = ['a', 't', 'b', 'c']
     * 
* * @param array the array to add the element to, may be null * @param index the position of the new object * @param element the object to add * @return A new array containing the existing elements and the new element * @throws IndexOutOfBoundsException if the index is out of range * (index < 0 || index > array.length). */ public static char[] add(char[] array, int index, char element) { return (char[]) add(array, index, new Character(element), Character.TYPE); } /** *

Inserts the specified element at the specified position in the array. * Shifts the element currently at that position (if any) and any subsequent * elements to the right (adds one to their indices).

* *

This method returns a new array with the same elements of the input * array plus the given element on the specified position. The component * type of the returned array is always the same as that of the input * array.

* *

If the input array is null, a new one element array is returned * whose component type is the same as the element.

* *
     * ArrayUtils.add([1], 0, 2)         = [2, 1]
     * ArrayUtils.add([2, 6], 2, 3)      = [2, 6, 3]
     * ArrayUtils.add([2, 6], 0, 1)      = [1, 2, 6]
     * ArrayUtils.add([2, 6, 3], 2, 1)   = [2, 6, 1, 3]
     * 
* * @param array the array to add the element to, may be null * @param index the position of the new object * @param element the object to add * @return A new array containing the existing elements and the new element * @throws IndexOutOfBoundsException if the index is out of range * (index < 0 || index > array.length). */ public static byte[] add(byte[] array, int index, byte element) { return (byte[]) add(array, index, new Byte(element), Byte.TYPE); } /** *

Inserts the specified element at the specified position in the array. * Shifts the element currently at that position (if any) and any subsequent * elements to the right (adds one to their indices).

* *

This method returns a new array with the same elements of the input * array plus the given element on the specified position. The component * type of the returned array is always the same as that of the input * array.

* *

If the input array is null, a new one element array is returned * whose component type is the same as the element.

* *
     * ArrayUtils.add([1], 0, 2)         = [2, 1]
     * ArrayUtils.add([2, 6], 2, 10)     = [2, 6, 10]
     * ArrayUtils.add([2, 6], 0, -4)     = [-4, 2, 6]
     * ArrayUtils.add([2, 6, 3], 2, 1)   = [2, 6, 1, 3]
     * 
* * @param array the array to add the element to, may be null * @param index the position of the new object * @param element the object to add * @return A new array containing the existing elements and the new element * @throws IndexOutOfBoundsException if the index is out of range * (index < 0 || index > array.length). */ public static short[] add(short[] array, int index, short element) { return (short[]) add(array, index, new Short(element), Short.TYPE); } /** *

Inserts the specified element at the specified position in the array. * Shifts the element currently at that position (if any) and any subsequent * elements to the right (adds one to their indices).

* *

This method returns a new array with the same elements of the input * array plus the given element on the specified position. The component * type of the returned array is always the same as that of the input * array.

* *

If the input array is null, a new one element array is returned * whose component type is the same as the element.

* *
     * ArrayUtils.add([1], 0, 2)         = [2, 1]
     * ArrayUtils.add([2, 6], 2, 10)     = [2, 6, 10]
     * ArrayUtils.add([2, 6], 0, -4)     = [-4, 2, 6]
     * ArrayUtils.add([2, 6, 3], 2, 1)   = [2, 6, 1, 3]
     * 
* * @param array the array to add the element to, may be null * @param index the position of the new object * @param element the object to add * @return A new array containing the existing elements and the new element * @throws IndexOutOfBoundsException if the index is out of range * (index < 0 || index > array.length). */ public static int[] add(int[] array, int index, int element) { return (int[]) add(array, index, new Integer(element), Integer.TYPE); } /** *

Inserts the specified element at the specified position in the array. * Shifts the element currently at that position (if any) and any subsequent * elements to the right (adds one to their indices).

* *

This method returns a new array with the same elements of the input * array plus the given element on the specified position. The component * type of the returned array is always the same as that of the input * array.

* *

If the input array is null, a new one element array is returned * whose component type is the same as the element.

* *
     * ArrayUtils.add([1L], 0, 2L)           = [2L, 1L]
     * ArrayUtils.add([2L, 6L], 2, 10L)      = [2L, 6L, 10L]
     * ArrayUtils.add([2L, 6L], 0, -4L)      = [-4L, 2L, 6L]
     * ArrayUtils.add([2L, 6L, 3L], 2, 1L)   = [2L, 6L, 1L, 3L]
     * 
* * @param array the array to add the element to, may be null * @param index the position of the new object * @param element the object to add * @return A new array containing the existing elements and the new element * @throws IndexOutOfBoundsException if the index is out of range * (index < 0 || index > array.length). */ public static long[] add(long[] array, int index, long element) { return (long[]) add(array, index, new Long(element), Long.TYPE); } /** *

Inserts the specified element at the specified position in the array. * Shifts the element currently at that position (if any) and any subsequent * elements to the right (adds one to their indices).

* *

This method returns a new array with the same elements of the input * array plus the given element on the specified position. The component * type of the returned array is always the same as that of the input * array.

* *

If the input array is null, a new one element array is returned * whose component type is the same as the element.

* *
     * ArrayUtils.add([1.1f], 0, 2.2f)               = [2.2f, 1.1f]
     * ArrayUtils.add([2.3f, 6.4f], 2, 10.5f)        = [2.3f, 6.4f, 10.5f]
     * ArrayUtils.add([2.6f, 6.7f], 0, -4.8f)        = [-4.8f, 2.6f, 6.7f]
     * ArrayUtils.add([2.9f, 6.0f, 0.3f], 2, 1.0f)   = [2.9f, 6.0f, 1.0f, 0.3f]
     * 
* * @param array the array to add the element to, may be null * @param index the position of the new object * @param element the object to add * @return A new array containing the existing elements and the new element * @throws IndexOutOfBoundsException if the index is out of range * (index < 0 || index > array.length). */ public static float[] add(float[] array, int index, float element) { return (float[]) add(array, index, new Float(element), Float.TYPE); } /** *

Inserts the specified element at the specified position in the array. * Shifts the element currently at that position (if any) and any subsequent * elements to the right (adds one to their indices).

* *

This method returns a new array with the same elements of the input * array plus the given element on the specified position. The component * type of the returned array is always the same as that of the input * array.

* *

If the input array is null, a new one element array is returned * whose component type is the same as the element.

* *
     * ArrayUtils.add([1.1], 0, 2.2)              = [2.2, 1.1]
     * ArrayUtils.add([2.3, 6.4], 2, 10.5)        = [2.3, 6.4, 10.5]
     * ArrayUtils.add([2.6, 6.7], 0, -4.8)        = [-4.8, 2.6, 6.7]
     * ArrayUtils.add([2.9, 6.0, 0.3], 2, 1.0)    = [2.9, 6.0, 1.0, 0.3]
     * 
* * @param array the array to add the element to, may be null * @param index the position of the new object * @param element the object to add * @return A new array containing the existing elements and the new element * @throws IndexOutOfBoundsException if the index is out of range * (index < 0 || index > array.length). */ public static double[] add(double[] array, int index, double element) { return (double[]) add(array, index, new Double(element), Double.TYPE); } /** * Underlying implementation of add(array, index, element) methods. * The last parameter is the class, which may not equal element.getClass * for primitives. * * @param array the array to add the element to, may be null * @param index the position of the new object * @param element the object to add * @param clss the type of the element being added * @return A new array containing the existing elements and the new element */ private static Object add(Object array, int index, Object element, Class clss) { if (array == null) { if (index != 0) { throw new IndexOutOfBoundsException("Index: " + index + ", Length: 0"); } Object joinedArray = Array.newInstance(clss, 1); Array.set(joinedArray, 0, element); return joinedArray; } int length = Array.getLength(array); if (index > length || index < 0) { throw new IndexOutOfBoundsException("Index: " + index + ", Length: " + length); } Object result = Array.newInstance(clss, length + 1); System.arraycopy(array, 0, result, 0, index); Array.set(result, index, element); if (index < length) { System.arraycopy(array, index, result, index + 1, length - index); } return result; } /** *

Removes the element at the specified position from the specified array. * All subsequent elements are shifted to the left (substracts one from * their indices).

* *

This method returns a new array with the same elements of the input * array except the element on the specified position. The component * type of the returned array is always the same as that of the input * array.

* *

If the input array is null, an IndexOutOfBoundsException * will be thrown, because in that case no valid index can be specified.

* *
     * ArrayUtils.remove(["a"], 0)           = []
     * ArrayUtils.remove(["a", "b"], 0)      = ["b"]
     * ArrayUtils.remove(["a", "b"], 1)      = ["a"]
     * ArrayUtils.remove(["a", "b", "c"], 1) = ["a", "c"]
     * 
* * @param array the array to remove the element from, may not be null * @param index the position of the element to be removed * @return A new array containing the existing elements except the element * at the specified position. * @throws IndexOutOfBoundsException if the index is out of range * (index < 0 || index >= array.length), or if the array is null. * @since 2.1 */ public static Object[] remove(Object[] array, int index) { return (Object[]) remove((Object) array, index); } /** *

Removes the first occurrence of the specified element from the * specified array. All subsequent elements are shifted to the left * (substracts one from their indices). If the array doesn't contains * such an element, no elements are removed from the array.

* *

This method returns a new array with the same elements of the input * array except the first occurrence of the specified element. The component * type of the returned array is always the same as that of the input * array.

* *
     * ArrayUtils.removeElement(null, "a")            = null
     * ArrayUtils.removeElement([], "a")              = []
     * ArrayUtils.removeElement(["a"], "b")           = ["a"]
     * ArrayUtils.removeElement(["a", "b"], "a")      = ["b"]
     * ArrayUtils.removeElement(["a", "b", "a"], "a") = ["b", "a"]
     * 
* * @param array the array to remove the element from, may be null * @param element the element to be removed * @return A new array containing the existing elements except the first * occurrence of the specified element. * @since 2.1 */ public static Object[] removeElement(Object[] array, Object element) { int index = indexOf(array, element); if (index == INDEX_NOT_FOUND) { return clone(array); } return remove(array, index); } /** *

Removes the element at the specified position from the specified array. * All subsequent elements are shifted to the left (substracts one from * their indices).

* *

This method returns a new array with the same elements of the input * array except the element on the specified position. The component * type of the returned array is always the same as that of the input * array.

* *

If the input array is null, an IndexOutOfBoundsException * will be thrown, because in that case no valid index can be specified.

* *
     * ArrayUtils.remove([true], 0)              = []
     * ArrayUtils.remove([true, false], 0)       = [false]
     * ArrayUtils.remove([true, false], 1)       = [true]
     * ArrayUtils.remove([true, true, false], 1) = [true, false]
     * 
* * @param array the array to remove the element from, may not be null * @param index the position of the element to be removed * @return A new array containing the existing elements except the element * at the specified position. * @throws IndexOutOfBoundsException if the index is out of range * (index < 0 || index >= array.length), or if the array is null. * @since 2.1 */ public static boolean[] remove(boolean[] array, int index) { return (boolean[]) remove((Object) array, index); } /** *

Removes the first occurrence of the specified element from the * specified array. All subsequent elements are shifted to the left * (substracts one from their indices). If the array doesn't contains * such an element, no elements are removed from the array.

* *

This method returns a new array with the same elements of the input * array except the first occurrence of the specified element. The component * type of the returned array is always the same as that of the input * array.

* *
     * ArrayUtils.removeElement(null, true)                = null
     * ArrayUtils.removeElement([], true)                  = []
     * ArrayUtils.removeElement([true], false)             = [true]
     * ArrayUtils.removeElement([true, false], false)      = [true]
     * ArrayUtils.removeElement([true, false, true], true) = [false, true]
     * 
* * @param array the array to remove the element from, may be null * @param element the element to be removed * @return A new array containing the existing elements except the first * occurrence of the specified element. * @since 2.1 */ public static boolean[] removeElement(boolean[] array, boolean element) { int index = indexOf(array, element); if (index == INDEX_NOT_FOUND) { return clone(array); } return remove(array, index); } /** *

Removes the element at the specified position from the specified array. * All subsequent elements are shifted to the left (substracts one from * their indices).

* *

This method returns a new array with the same elements of the input * array except the element on the specified position. The component * type of the returned array is always the same as that of the input * array.

* *

If the input array is null, an IndexOutOfBoundsException * will be thrown, because in that case no valid index can be specified.

* *
     * ArrayUtils.remove([1], 0)          = []
     * ArrayUtils.remove([1, 0], 0)       = [0]
     * ArrayUtils.remove([1, 0], 1)       = [1]
     * ArrayUtils.remove([1, 0, 1], 1)    = [1, 1]
     * 
* * @param array the array to remove the element from, may not be null * @param index the position of the element to be removed * @return A new array containing the existing elements except the element * at the specified position. * @throws IndexOutOfBoundsException if the index is out of range * (index < 0 || index >= array.length), or if the array is null. * @since 2.1 */ public static byte[] remove(byte[] array, int index) { return (byte[]) remove((Object) array, index); } /** *

Removes the first occurrence of the specified element from the * specified array. All subsequent elements are shifted to the left * (substracts one from their indices). If the array doesn't contains * such an element, no elements are removed from the array.

* *

This method returns a new array with the same elements of the input * array except the first occurrence of the specified element. The component * type of the returned array is always the same as that of the input * array.

* *
     * ArrayUtils.removeElement(null, 1)        = null
     * ArrayUtils.removeElement([], 1)          = []
     * ArrayUtils.removeElement([1], 0)         = [1]
     * ArrayUtils.removeElement([1, 0], 0)      = [1]
     * ArrayUtils.removeElement([1, 0, 1], 1)   = [0, 1]
     * 
* * @param array the array to remove the element from, may be null * @param element the element to be removed * @return A new array containing the existing elements except the first * occurrence of the specified element. * @since 2.1 */ public static byte[] removeElement(byte[] array, byte element) { int index = indexOf(array, element); if (index == INDEX_NOT_FOUND) { return clone(array); } return remove(array, index); } /** *

Removes the element at the specified position from the specified array. * All subsequent elements are shifted to the left (substracts one from * their indices).

* *

This method returns a new array with the same elements of the input * array except the element on the specified position. The component * type of the returned array is always the same as that of the input * array.

* *

If the input array is null, an IndexOutOfBoundsException * will be thrown, because in that case no valid index can be specified.

* *
     * ArrayUtils.remove(['a'], 0)           = []
     * ArrayUtils.remove(['a', 'b'], 0)      = ['b']
     * ArrayUtils.remove(['a', 'b'], 1)      = ['a']
     * ArrayUtils.remove(['a', 'b', 'c'], 1) = ['a', 'c']
     * 
* * @param array the array to remove the element from, may not be null * @param index the position of the element to be removed * @return A new array containing the existing elements except the element * at the specified position. * @throws IndexOutOfBoundsException if the index is out of range * (index < 0 || index >= array.length), or if the array is null. * @since 2.1 */ public static char[] remove(char[] array, int index) { return (char[]) remove((Object) array, index); } /** *

Removes the first occurrence of the specified element from the * specified array. All subsequent elements are shifted to the left * (substracts one from their indices). If the array doesn't contains * such an element, no elements are removed from the array.

* *

This method returns a new array with the same elements of the input * array except the first occurrence of the specified element. The component * type of the returned array is always the same as that of the input * array.

* *
     * ArrayUtils.removeElement(null, 'a')            = null
     * ArrayUtils.removeElement([], 'a')              = []
     * ArrayUtils.removeElement(['a'], 'b')           = ['a']
     * ArrayUtils.removeElement(['a', 'b'], 'a')      = ['b']
     * ArrayUtils.removeElement(['a', 'b', 'a'], 'a') = ['b', 'a']
     * 
* * @param array the array to remove the element from, may be null * @param element the element to be removed * @return A new array containing the existing elements except the first * occurrence of the specified element. * @since 2.1 */ public static char[] removeElement(char[] array, char element) { int index = indexOf(array, element); if (index == INDEX_NOT_FOUND) { return clone(array); } return remove(array, index); } /** *

Removes the element at the specified position from the specified array. * All subsequent elements are shifted to the left (substracts one from * their indices).

* *

This method returns a new array with the same elements of the input * array except the element on the specified position. The component * type of the returned array is always the same as that of the input * array.

* *

If the input array is null, an IndexOutOfBoundsException * will be thrown, because in that case no valid index can be specified.

* *
     * ArrayUtils.remove([1.1], 0)           = []
     * ArrayUtils.remove([2.5, 6.0], 0)      = [6.0]
     * ArrayUtils.remove([2.5, 6.0], 1)      = [2.5]
     * ArrayUtils.remove([2.5, 6.0, 3.8], 1) = [2.5, 3.8]
     * 
* * @param array the array to remove the element from, may not be null * @param index the position of the element to be removed * @return A new array containing the existing elements except the element * at the specified position. * @throws IndexOutOfBoundsException if the index is out of range * (index < 0 || index >= array.length), or if the array is null. * @since 2.1 */ public static double[] remove(double[] array, int index) { return (double[]) remove((Object) array, index); } /** *

Removes the first occurrence of the specified element from the * specified array. All subsequent elements are shifted to the left * (substracts one from their indices). If the array doesn't contains * such an element, no elements are removed from the array.

* *

This method returns a new array with the same elements of the input * array except the first occurrence of the specified element. The component * type of the returned array is always the same as that of the input * array.

* *
     * ArrayUtils.removeElement(null, 1.1)            = null
     * ArrayUtils.removeElement([], 1.1)              = []
     * ArrayUtils.removeElement([1.1], 1.2)           = [1.1]
     * ArrayUtils.removeElement([1.1, 2.3], 1.1)      = [2.3]
     * ArrayUtils.removeElement([1.1, 2.3, 1.1], 1.1) = [2.3, 1.1]
     * 
* * @param array the array to remove the element from, may be null * @param element the element to be removed * @return A new array containing the existing elements except the first * occurrence of the specified element. * @since 2.1 */ public static double[] removeElement(double[] array, double element) { int index = indexOf(array, element); if (index == INDEX_NOT_FOUND) { return clone(array); } return remove(array, index); } /** *

Removes the element at the specified position from the specified array. * All subsequent elements are shifted to the left (substracts one from * their indices).

* *

This method returns a new array with the same elements of the input * array except the element on the specified position. The component * type of the returned array is always the same as that of the input * array.

* *

If the input array is null, an IndexOutOfBoundsException * will be thrown, because in that case no valid index can be specified.

* *
     * ArrayUtils.remove([1.1], 0)           = []
     * ArrayUtils.remove([2.5, 6.0], 0)      = [6.0]
     * ArrayUtils.remove([2.5, 6.0], 1)      = [2.5]
     * ArrayUtils.remove([2.5, 6.0, 3.8], 1) = [2.5, 3.8]
     * 
* * @param array the array to remove the element from, may not be null * @param index the position of the element to be removed * @return A new array containing the existing elements except the element * at the specified position. * @throws IndexOutOfBoundsException if the index is out of range * (index < 0 || index >= array.length), or if the array is null. * @since 2.1 */ public static float[] remove(float[] array, int index) { return (float[]) remove((Object) array, index); } /** *

Removes the first occurrence of the specified element from the * specified array. All subsequent elements are shifted to the left * (substracts one from their indices). If the array doesn't contains * such an element, no elements are removed from the array.

* *

This method returns a new array with the same elements of the input * array except the first occurrence of the specified element. The component * type of the returned array is always the same as that of the input * array.

* *
     * ArrayUtils.removeElement(null, 1.1)            = null
     * ArrayUtils.removeElement([], 1.1)              = []
     * ArrayUtils.removeElement([1.1], 1.2)           = [1.1]
     * ArrayUtils.removeElement([1.1, 2.3], 1.1)      = [2.3]
     * ArrayUtils.removeElement([1.1, 2.3, 1.1], 1.1) = [2.3, 1.1]
     * 
* * @param array the array to remove the element from, may be null * @param element the element to be removed * @return A new array containing the existing elements except the first * occurrence of the specified element. * @since 2.1 */ public static float[] removeElement(float[] array, float element) { int index = indexOf(array, element); if (index == INDEX_NOT_FOUND) { return clone(array); } return remove(array, index); } /** *

Removes the element at the specified position from the specified array. * All subsequent elements are shifted to the left (substracts one from * their indices).

* *

This method returns a new array with the same elements of the input * array except the element on the specified position. The component * type of the returned array is always the same as that of the input * array.

* *

If the input array is null, an IndexOutOfBoundsException * will be thrown, because in that case no valid index can be specified.

* *
     * ArrayUtils.remove([1], 0)         = []
     * ArrayUtils.remove([2, 6], 0)      = [6]
     * ArrayUtils.remove([2, 6], 1)      = [2]
     * ArrayUtils.remove([2, 6, 3], 1)   = [2, 3]
     * 
* * @param array the array to remove the element from, may not be null * @param index the position of the element to be removed * @return A new array containing the existing elements except the element * at the specified position. * @throws IndexOutOfBoundsException if the index is out of range * (index < 0 || index >= array.length), or if the array is null. * @since 2.1 */ public static int[] remove(int[] array, int index) { return (int[]) remove((Object) array, index); } /** *

Removes the first occurrence of the specified element from the * specified array. All subsequent elements are shifted to the left * (substracts one from their indices). If the array doesn't contains * such an element, no elements are removed from the array.

* *

This method returns a new array with the same elements of the input * array except the first occurrence of the specified element. The component * type of the returned array is always the same as that of the input * array.

* *
     * ArrayUtils.removeElement(null, 1)      = null
     * ArrayUtils.removeElement([], 1)        = []
     * ArrayUtils.removeElement([1], 2)       = [1]
     * ArrayUtils.removeElement([1, 3], 1)    = [3]
     * ArrayUtils.removeElement([1, 3, 1], 1) = [3, 1]
     * 
* * @param array the array to remove the element from, may be null * @param element the element to be removed * @return A new array containing the existing elements except the first * occurrence of the specified element. * @since 2.1 */ public static int[] removeElement(int[] array, int element) { int index = indexOf(array, element); if (index == INDEX_NOT_FOUND) { return clone(array); } return remove(array, index); } /** *

Removes the element at the specified position from the specified array. * All subsequent elements are shifted to the left (substracts one from * their indices).

* *

This method returns a new array with the same elements of the input * array except the element on the specified position. The component * type of the returned array is always the same as that of the input * array.

* *

If the input array is null, an IndexOutOfBoundsException * will be thrown, because in that case no valid index can be specified.

* *
     * ArrayUtils.remove([1], 0)         = []
     * ArrayUtils.remove([2, 6], 0)      = [6]
     * ArrayUtils.remove([2, 6], 1)      = [2]
     * ArrayUtils.remove([2, 6, 3], 1)   = [2, 3]
     * 
* * @param array the array to remove the element from, may not be null * @param index the position of the element to be removed * @return A new array containing the existing elements except the element * at the specified position. * @throws IndexOutOfBoundsException if the index is out of range * (index < 0 || index >= array.length), or if the array is null. * @since 2.1 */ public static long[] remove(long[] array, int index) { return (long[]) remove((Object) array, index); } /** *

Removes the first occurrence of the specified element from the * specified array. All subsequent elements are shifted to the left * (substracts one from their indices). If the array doesn't contains * such an element, no elements are removed from the array.

* *

This method returns a new array with the same elements of the input * array except the first occurrence of the specified element. The component * type of the returned array is always the same as that of the input * array.

* *
     * ArrayUtils.removeElement(null, 1)      = null
     * ArrayUtils.removeElement([], 1)        = []
     * ArrayUtils.removeElement([1], 2)       = [1]
     * ArrayUtils.removeElement([1, 3], 1)    = [3]
     * ArrayUtils.removeElement([1, 3, 1], 1) = [3, 1]
     * 
* * @param array the array to remove the element from, may be null * @param element the element to be removed * @return A new array containing the existing elements except the first * occurrence of the specified element. * @since 2.1 */ public static long[] removeElement(long[] array, long element) { int index = indexOf(array, element); if (index == INDEX_NOT_FOUND) { return clone(array); } return remove(array, index); } /** *

Removes the element at the specified position from the specified array. * All subsequent elements are shifted to the left (substracts one from * their indices).

* *

This method returns a new array with the same elements of the input * array except the element on the specified position. The component * type of the returned array is always the same as that of the input * array.

* *

If the input array is null, an IndexOutOfBoundsException * will be thrown, because in that case no valid index can be specified.

* *
     * ArrayUtils.remove([1], 0)         = []
     * ArrayUtils.remove([2, 6], 0)      = [6]
     * ArrayUtils.remove([2, 6], 1)      = [2]
     * ArrayUtils.remove([2, 6, 3], 1)   = [2, 3]
     * 
* * @param array the array to remove the element from, may not be null * @param index the position of the element to be removed * @return A new array containing the existing elements except the element * at the specified position. * @throws IndexOutOfBoundsException if the index is out of range * (index < 0 || index >= array.length), or if the array is null. * @since 2.1 */ public static short[] remove(short[] array, int index) { return (short[]) remove((Object) array, index); } /** *

Removes the first occurrence of the specified element from the * specified array. All subsequent elements are shifted to the left * (substracts one from their indices). If the array doesn't contains * such an element, no elements are removed from the array.

* *

This method returns a new array with the same elements of the input * array except the first occurrence of the specified element. The component * type of the returned array is always the same as that of the input * array.

* *
     * ArrayUtils.removeElement(null, 1)      = null
     * ArrayUtils.removeElement([], 1)        = []
     * ArrayUtils.removeElement([1], 2)       = [1]
     * ArrayUtils.removeElement([1, 3], 1)    = [3]
     * ArrayUtils.removeElement([1, 3, 1], 1) = [3, 1]
     * 
* * @param array the array to remove the element from, may be null * @param element the element to be removed * @return A new array containing the existing elements except the first * occurrence of the specified element. * @since 2.1 */ public static short[] removeElement(short[] array, short element) { int index = indexOf(array, element); if (index == INDEX_NOT_FOUND) { return clone(array); } return remove(array, index); } /** *

Removes the element at the specified position from the specified array. * All subsequent elements are shifted to the left (substracts one from * their indices).

* *

This method returns a new array with the same elements of the input * array except the element on the specified position. The component * type of the returned array is always the same as that of the input * array.

* *

If the input array is null, an IndexOutOfBoundsException * will be thrown, because in that case no valid index can be specified.

* * @param array the array to remove the element from, may not be null * @param index the position of the element to be removed * @return A new array containing the existing elements except the element * at the specified position. * @throws IndexOutOfBoundsException if the index is out of range * (index < 0 || index >= array.length), or if the array is null. * @since 2.1 */ private static Object remove(Object array, int index) { int length = getLength(array); if (index < 0 || index >= length) { throw new IndexOutOfBoundsException("Index: " + index + ", Length: " + length); } Object result = Array.newInstance(array.getClass().getComponentType(), length - 1); System.arraycopy(array, 0, result, 0, index); if (index < length - 1) { System.arraycopy(array, index + 1, result, index, length - index - 1); } return result; } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/BitField.java100644 0 0 21772 11513702445 23307 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang; /** *

Operations on bit-mapped fields.

* * @author Apache Software Foundation * @author Apache Jakarta POI * @author Scott Sanders (sanders at apache dot org) * @author Marc Johnson (mjohnson at apache dot org) * @author Andrew C. Oliver (acoliver at apache dot org) * @author Pete Gieser * @author Gary Gregory * @since 2.0 * @version $Id: BitField.java 905636 2010-02-02 14:03:32Z niallp $ */ public class BitField { private final int _mask; private final int _shift_count; /** *

Creates a BitField instance.

* * @param mask the mask specifying which bits apply to this * BitField. Bits that are set in this mask are the bits * that this BitField operates on */ public BitField(int mask) { _mask = mask; int count = 0; int bit_pattern = mask; if (bit_pattern != 0) { while ((bit_pattern & 1) == 0) { count++; bit_pattern >>= 1; } } _shift_count = count; } /** *

Obtains the value for the specified BitField, appropriately * shifted right.

* *

Many users of a BitField will want to treat the specified * bits as an int value, and will not want to be aware that the * value is stored as a BitField (and so shifted left so many * bits).

* * @see #setValue(int,int) * @param holder the int data containing the bits we're interested * in * @return the selected bits, shifted right appropriately */ public int getValue(int holder) { return getRawValue(holder) >> _shift_count; } /** *

Obtains the value for the specified BitField, appropriately * shifted right, as a short.

* *

Many users of a BitField will want to treat the specified * bits as an int value, and will not want to be aware that the * value is stored as a BitField (and so shifted left so many * bits).

* * @see #setShortValue(short,short) * @param holder the short data containing the bits we're * interested in * @return the selected bits, shifted right appropriately */ public short getShortValue(short holder) { return (short) getValue(holder); } /** *

Obtains the value for the specified BitField, unshifted.

* * @param holder the int data containing the bits we're * interested in * @return the selected bits */ public int getRawValue(int holder) { return holder & _mask; } /** *

Obtains the value for the specified BitField, unshifted.

* * @param holder the short data containing the bits we're * interested in * @return the selected bits */ public short getShortRawValue(short holder) { return (short) getRawValue(holder); } /** *

Returns whether the field is set or not.

* *

This is most commonly used for a single-bit field, which is * often used to represent a boolean value; the results of using * it for a multi-bit field is to determine whether *any* of its * bits are set.

* * @param holder the int data containing the bits we're interested * in * @return true if any of the bits are set, * else false */ public boolean isSet(int holder) { return (holder & _mask) != 0; } /** *

Returns whether all of the bits are set or not.

* *

This is a stricter test than {@link #isSet(int)}, * in that all of the bits in a multi-bit set must be set * for this method to return true.

* * @param holder the int data containing the bits we're * interested in * @return true if all of the bits are set, * else false */ public boolean isAllSet(int holder) { return (holder & _mask) == _mask; } /** *

Replaces the bits with new values.

* * @see #getValue(int) * @param holder the int data containing the bits we're * interested in * @param value the new value for the specified bits * @return the value of holder with the bits from the value * parameter replacing the old bits */ public int setValue(int holder, int value) { return (holder & ~_mask) | ((value << _shift_count) & _mask); } /** *

Replaces the bits with new values.

* * @see #getShortValue(short) * @param holder the short data containing the bits we're * interested in * @param value the new value for the specified bits * @return the value of holder with the bits from the value * parameter replacing the old bits */ public short setShortValue(short holder, short value) { return (short) setValue(holder, value); } /** *

Clears the bits.

* * @param holder the int data containing the bits we're * interested in * @return the value of holder with the specified bits cleared * (set to 0) */ public int clear(int holder) { return holder & ~_mask; } /** *

Clears the bits.

* * @param holder the short data containing the bits we're * interested in * @return the value of holder with the specified bits cleared * (set to 0) */ public short clearShort(short holder) { return (short) clear(holder); } /** *

Clears the bits.

* * @param holder the byte data containing the bits we're * interested in * * @return the value of holder with the specified bits cleared * (set to 0) */ public byte clearByte(byte holder) { return (byte) clear(holder); } /** *

Sets the bits.

* * @param holder the int data containing the bits we're * interested in * @return the value of holder with the specified bits set * to 1 */ public int set(int holder) { return holder | _mask; } /** *

Sets the bits.

* * @param holder the short data containing the bits we're * interested in * @return the value of holder with the specified bits set * to 1 */ public short setShort(short holder) { return (short) set(holder); } /** *

Sets the bits.

* * @param holder the byte data containing the bits we're * interested in * * @return the value of holder with the specified bits set * to 1 */ public byte setByte(byte holder) { return (byte) set(holder); } /** *

Sets a boolean BitField.

* * @param holder the int data containing the bits we're * interested in * @param flag indicating whether to set or clear the bits * @return the value of holder with the specified bits set or * cleared */ public int setBoolean(int holder, boolean flag) { return flag ? set(holder) : clear(holder); } /** *

Sets a boolean BitField.

* * @param holder the short data containing the bits we're * interested in * @param flag indicating whether to set or clear the bits * @return the value of holder with the specified bits set or * cleared */ public short setShortBoolean(short holder, boolean flag) { return flag ? setShort(holder) : clearShort(holder); } /** *

Sets a boolean BitField.

* * @param holder the byte data containing the bits we're * interested in * @param flag indicating whether to set or clear the bits * @return the value of holder with the specified bits set or * cleared */ public byte setByteBoolean(byte holder, boolean flag) { return flag ? setByte(holder) : clearByte(holder); } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/BooleanUtils.java100644 0 0 111744 11513702445 24244 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang; import org.apache.commons.lang.math.NumberUtils; /** *

Operations on boolean primitives and Boolean objects.

* *

This class tries to handle null input gracefully. * An exception will not be thrown for a null input. * Each method documents its behaviour in more detail.

* *

#ThreadSafe#

* @author Apache Software Foundation * @author Matthew Hawthorne * @author Gary Gregory * @since 2.0 * @version $Id: BooleanUtils.java 1057037 2011-01-09 21:35:32Z niallp $ */ public class BooleanUtils { /** *

BooleanUtils instances should NOT be constructed in standard programming. * Instead, the class should be used as BooleanUtils.toBooleanObject(true);.

* *

This constructor is public to permit tools that require a JavaBean instance * to operate.

*/ public BooleanUtils() { super(); } // Boolean utilities //-------------------------------------------------------------------------- /** *

Negates the specified boolean.

* *

If null is passed in, null will be returned.

* *
     *   BooleanUtils.negate(Boolean.TRUE)  = Boolean.FALSE;
     *   BooleanUtils.negate(Boolean.FALSE) = Boolean.TRUE;
     *   BooleanUtils.negate(null)          = null;
     * 
* * @param bool the Boolean to negate, may be null * @return the negated Boolean, or null if null input */ public static Boolean negate(Boolean bool) { if (bool == null) { return null; } return (bool.booleanValue() ? Boolean.FALSE : Boolean.TRUE); } // boolean Boolean methods //----------------------------------------------------------------------- /** *

Checks if a Boolean value is true, * handling null by returning false.

* *
     *   BooleanUtils.isTrue(Boolean.TRUE)  = true
     *   BooleanUtils.isTrue(Boolean.FALSE) = false
     *   BooleanUtils.isTrue(null)          = false
     * 
* * @param bool the boolean to check, null returns false * @return true only if the input is non-null and true * @since 2.1 */ public static boolean isTrue(Boolean bool) { if (bool == null) { return false; } return bool.booleanValue() ? true : false; } /** *

Checks if a Boolean value is not true, * handling null by returning true.

* *
     *   BooleanUtils.isNotTrue(Boolean.TRUE)  = false
     *   BooleanUtils.isNotTrue(Boolean.FALSE) = true
     *   BooleanUtils.isNotTrue(null)          = true
     * 
* * @param bool the boolean to check, null returns true * @return true if the input is null or false * @since 2.3 */ public static boolean isNotTrue(Boolean bool) { return !isTrue(bool); } /** *

Checks if a Boolean value is false, * handling null by returning false.

* *
     *   BooleanUtils.isFalse(Boolean.TRUE)  = false
     *   BooleanUtils.isFalse(Boolean.FALSE) = true
     *   BooleanUtils.isFalse(null)          = false
     * 
* * @param bool the boolean to check, null returns false * @return true only if the input is non-null and false * @since 2.1 */ public static boolean isFalse(Boolean bool) { if (bool == null) { return false; } return bool.booleanValue() ? false : true; } /** *

Checks if a Boolean value is not false, * handling null by returning true.

* *
     *   BooleanUtils.isNotFalse(Boolean.TRUE)  = true
     *   BooleanUtils.isNotFalse(Boolean.FALSE) = false
     *   BooleanUtils.isNotFalse(null)          = true
     * 
* * @param bool the boolean to check, null returns true * @return true if the input is null or true * @since 2.3 */ public static boolean isNotFalse(Boolean bool) { return !isFalse(bool); } //----------------------------------------------------------------------- /** *

Boolean factory that avoids creating new Boolean objecs all the time.

* *

This method was added to JDK1.4 but is available here for earlier JDKs.

* *
     *   BooleanUtils.toBooleanObject(false) = Boolean.FALSE
     *   BooleanUtils.toBooleanObject(true)  = Boolean.TRUE
     * 
* * @param bool the boolean to convert * @return Boolean.TRUE or Boolean.FALSE as appropriate */ public static Boolean toBooleanObject(boolean bool) { return bool ? Boolean.TRUE : Boolean.FALSE; } /** *

Converts a Boolean to a boolean handling null * by returning false.

* *
     *   BooleanUtils.toBoolean(Boolean.TRUE)  = true
     *   BooleanUtils.toBoolean(Boolean.FALSE) = false
     *   BooleanUtils.toBoolean(null)          = false
     * 
* * @param bool the boolean to convert * @return true or false, * null returns false */ public static boolean toBoolean(Boolean bool) { if (bool == null) { return false; } return bool.booleanValue() ? true : false; } /** *

Converts a Boolean to a boolean handling null.

* *
     *   BooleanUtils.toBooleanDefaultIfNull(Boolean.TRUE, false) = true
     *   BooleanUtils.toBooleanDefaultIfNull(Boolean.FALSE, true) = false
     *   BooleanUtils.toBooleanDefaultIfNull(null, true)          = true
     * 
* * @param bool the boolean to convert * @param valueIfNull the boolean value to return if null * @return true or false */ public static boolean toBooleanDefaultIfNull(Boolean bool, boolean valueIfNull) { if (bool == null) { return valueIfNull; } return bool.booleanValue() ? true : false; } // Integer to Boolean methods //----------------------------------------------------------------------- /** *

Converts an int to a boolean using the convention that zero * is false.

* *
     *   BooleanUtils.toBoolean(0) = false
     *   BooleanUtils.toBoolean(1) = true
     *   BooleanUtils.toBoolean(2) = true
     * 
* * @param value the int to convert * @return true if non-zero, false * if zero */ public static boolean toBoolean(int value) { return value == 0 ? false : true; } /** *

Converts an int to a Boolean using the convention that zero * is false.

* *
     *   BooleanUtils.toBoolean(0) = Boolean.FALSE
     *   BooleanUtils.toBoolean(1) = Boolean.TRUE
     *   BooleanUtils.toBoolean(2) = Boolean.TRUE
     * 
* * @param value the int to convert * @return Boolean.TRUE if non-zero, Boolean.FALSE if zero, * null if null */ public static Boolean toBooleanObject(int value) { return value == 0 ? Boolean.FALSE : Boolean.TRUE; } /** *

Converts an Integer to a Boolean using the convention that zero * is false.

* *

null will be converted to null.

* *
     *   BooleanUtils.toBoolean(new Integer(0))    = Boolean.FALSE
     *   BooleanUtils.toBoolean(new Integer(1))    = Boolean.TRUE
     *   BooleanUtils.toBoolean(new Integer(null)) = null
     * 
* * @param value the Integer to convert * @return Boolean.TRUE if non-zero, Boolean.FALSE if zero, * null if null input */ public static Boolean toBooleanObject(Integer value) { if (value == null) { return null; } return value.intValue() == 0 ? Boolean.FALSE : Boolean.TRUE; } /** *

Converts an int to a boolean specifying the conversion values.

* *
     *   BooleanUtils.toBoolean(0, 1, 0) = false
     *   BooleanUtils.toBoolean(1, 1, 0) = true
     *   BooleanUtils.toBoolean(2, 1, 2) = false
     *   BooleanUtils.toBoolean(2, 2, 0) = true
     * 
* * @param value the Integer to convert * @param trueValue the value to match for true * @param falseValue the value to match for false * @return true or false * @throws IllegalArgumentException if no match */ public static boolean toBoolean(int value, int trueValue, int falseValue) { if (value == trueValue) { return true; } else if (value == falseValue) { return false; } // no match throw new IllegalArgumentException("The Integer did not match either specified value"); } /** *

Converts an Integer to a boolean specifying the conversion values.

* *
     *   BooleanUtils.toBoolean(new Integer(0), new Integer(1), new Integer(0)) = false
     *   BooleanUtils.toBoolean(new Integer(1), new Integer(1), new Integer(0)) = true
     *   BooleanUtils.toBoolean(new Integer(2), new Integer(1), new Integer(2)) = false
     *   BooleanUtils.toBoolean(new Integer(2), new Integer(2), new Integer(0)) = true
     *   BooleanUtils.toBoolean(null, null, new Integer(0))                     = true
     * 
* * @param value the Integer to convert * @param trueValue the value to match for true, * may be null * @param falseValue the value to match for false, * may be null * @return true or false * @throws IllegalArgumentException if no match */ public static boolean toBoolean(Integer value, Integer trueValue, Integer falseValue) { if (value == null) { if (trueValue == null) { return true; } else if (falseValue == null) { return false; } } else if (value.equals(trueValue)) { return true; } else if (value.equals(falseValue)) { return false; } // no match throw new IllegalArgumentException("The Integer did not match either specified value"); } /** *

Converts an int to a Boolean specifying the conversion values.

* *
     *   BooleanUtils.toBooleanObject(0, 0, 2, 3) = Boolean.TRUE
     *   BooleanUtils.toBooleanObject(2, 1, 2, 3) = Boolean.FALSE
     *   BooleanUtils.toBooleanObject(3, 1, 2, 3) = null
     * 
* * @param value the Integer to convert * @param trueValue the value to match for true * @param falseValue the value to match for false * @param nullValue the value to to match for null * @return Boolean.TRUE, Boolean.FALSE, or null * @throws IllegalArgumentException if no match */ public static Boolean toBooleanObject(int value, int trueValue, int falseValue, int nullValue) { if (value == trueValue) { return Boolean.TRUE; } else if (value == falseValue) { return Boolean.FALSE; } else if (value == nullValue) { return null; } // no match throw new IllegalArgumentException("The Integer did not match any specified value"); } /** *

Converts an Integer to a Boolean specifying the conversion values.

* *
     *   BooleanUtils.toBooleanObject(new Integer(0), new Integer(0), new Integer(2), new Integer(3)) = Boolean.TRUE
     *   BooleanUtils.toBooleanObject(new Integer(2), new Integer(1), new Integer(2), new Integer(3)) = Boolean.FALSE
     *   BooleanUtils.toBooleanObject(new Integer(3), new Integer(1), new Integer(2), new Integer(3)) = null
     * 
* * @param value the Integer to convert * @param trueValue the value to match for true, * may be null * @param falseValue the value to match for false, * may be null * @param nullValue the value to to match for null, * may be null * @return Boolean.TRUE, Boolean.FALSE, or null * @throws IllegalArgumentException if no match */ public static Boolean toBooleanObject(Integer value, Integer trueValue, Integer falseValue, Integer nullValue) { if (value == null) { if (trueValue == null) { return Boolean.TRUE; } else if (falseValue == null) { return Boolean.FALSE; } else if (nullValue == null) { return null; } } else if (value.equals(trueValue)) { return Boolean.TRUE; } else if (value.equals(falseValue)) { return Boolean.FALSE; } else if (value.equals(nullValue)) { return null; } // no match throw new IllegalArgumentException("The Integer did not match any specified value"); } // Boolean to Integer methods //----------------------------------------------------------------------- /** *

Converts a boolean to an int using the convention that * zero is false.

* *
     *   BooleanUtils.toInteger(true)  = 1
     *   BooleanUtils.toInteger(false) = 0
     * 
* * @param bool the boolean to convert * @return one if true, zero if false */ public static int toInteger(boolean bool) { return bool ? 1 : 0; } /** *

Converts a boolean to an Integer using the convention that * zero is false.

* *
     *   BooleanUtils.toIntegerObject(true)  = new Integer(1)
     *   BooleanUtils.toIntegerObject(false) = new Integer(0)
     * 
* * @param bool the boolean to convert * @return one if true, zero if false */ public static Integer toIntegerObject(boolean bool) { return bool ? NumberUtils.INTEGER_ONE : NumberUtils.INTEGER_ZERO; } /** *

Converts a Boolean to a Integer using the convention that * zero is false.

* *

null will be converted to null.

* *
     *   BooleanUtils.toIntegerObject(Boolean.TRUE)  = new Integer(1)
     *   BooleanUtils.toIntegerObject(Boolean.FALSE) = new Integer(0)
     * 
* * @param bool the Boolean to convert * @return one if Boolean.TRUE, zero if Boolean.FALSE, null if null */ public static Integer toIntegerObject(Boolean bool) { if (bool == null) { return null; } return bool.booleanValue() ? NumberUtils.INTEGER_ONE : NumberUtils.INTEGER_ZERO; } /** *

Converts a boolean to an int specifying the conversion values.

* *
     *   BooleanUtils.toInteger(true, 1, 0)  = 1
     *   BooleanUtils.toInteger(false, 1, 0) = 0
     * 
* * @param bool the to convert * @param trueValue the value to return if true * @param falseValue the value to return if false * @return the appropriate value */ public static int toInteger(boolean bool, int trueValue, int falseValue) { return bool ? trueValue : falseValue; } /** *

Converts a Boolean to an int specifying the conversion values.

* *
     *   BooleanUtils.toInteger(Boolean.TRUE, 1, 0, 2)  = 1
     *   BooleanUtils.toInteger(Boolean.FALSE, 1, 0, 2) = 0
     *   BooleanUtils.toInteger(null, 1, 0, 2)          = 2
     * 
* * @param bool the Boolean to convert * @param trueValue the value to return if true * @param falseValue the value to return if false * @param nullValue the value to return if null * @return the appropriate value */ public static int toInteger(Boolean bool, int trueValue, int falseValue, int nullValue) { if (bool == null) { return nullValue; } return bool.booleanValue() ? trueValue : falseValue; } /** *

Converts a boolean to an Integer specifying the conversion values.

* *
     *   BooleanUtils.toIntegerObject(true, new Integer(1), new Integer(0))  = new Integer(1)
     *   BooleanUtils.toIntegerObject(false, new Integer(1), new Integer(0)) = new Integer(0)
     * 
* * @param bool the to convert * @param trueValue the value to return if true, * may be null * @param falseValue the value to return if false, * may be null * @return the appropriate value */ public static Integer toIntegerObject(boolean bool, Integer trueValue, Integer falseValue) { return bool ? trueValue : falseValue; } /** *

Converts a Boolean to an Integer specifying the conversion values.

* *
     *   BooleanUtils.toIntegerObject(Boolean.TRUE, new Integer(1), new Integer(0), new Integer(2))  = new Integer(1)
     *   BooleanUtils.toIntegerObject(Boolean.FALSE, new Integer(1), new Integer(0), new Integer(2)) = new Integer(0)
     *   BooleanUtils.toIntegerObject(null, new Integer(1), new Integer(0), new Integer(2))          = new Integer(2)
     * 
* * @param bool the Boolean to convert * @param trueValue the value to return if true, * may be null * @param falseValue the value to return if false, * may be null * @param nullValue the value to return if null, * may be null * @return the appropriate value */ public static Integer toIntegerObject(Boolean bool, Integer trueValue, Integer falseValue, Integer nullValue) { if (bool == null) { return nullValue; } return bool.booleanValue() ? trueValue : falseValue; } // String to Boolean methods //----------------------------------------------------------------------- /** *

Converts a String to a Boolean.

* *

'true', 'on' or 'yes' * (case insensitive) will return true. * 'false', 'off' or 'no' * (case insensitive) will return false. * Otherwise, null is returned.

* *
     *   BooleanUtils.toBooleanObject(null)    = null
     *   BooleanUtils.toBooleanObject("true")  = Boolean.TRUE
     *   BooleanUtils.toBooleanObject("false") = Boolean.FALSE
     *   BooleanUtils.toBooleanObject("on")    = Boolean.TRUE
     *   BooleanUtils.toBooleanObject("ON")    = Boolean.TRUE
     *   BooleanUtils.toBooleanObject("off")   = Boolean.FALSE
     *   BooleanUtils.toBooleanObject("oFf")   = Boolean.FALSE
     *   BooleanUtils.toBooleanObject("blue")  = null
     * 
* * @param str the String to check * @return the Boolean value of the string, * null if no match or null input */ public static Boolean toBooleanObject(String str) { // Previously used equalsIgnoreCase, which was fast for interned 'true'. // Non interned 'true' matched 15 times slower. // // Optimisation provides same performance as before for interned 'true'. // Similar performance for null, 'false', and other strings not length 2/3/4. // 'true'/'TRUE' match 4 times slower, 'tRUE'/'True' 7 times slower. if (str == "true") { return Boolean.TRUE; } if (str == null) { return null; } switch (str.length()) { case 1: { char ch0 = str.charAt(0); if ((ch0 == 'y' || ch0 == 'Y') || (ch0 == 't' || ch0 == 'T')) { return Boolean.TRUE; } if ((ch0 == 'n' || ch0 == 'N') || (ch0 == 'f' || ch0 == 'F')) { return Boolean.FALSE; } break; } case 2: { char ch0 = str.charAt(0); char ch1 = str.charAt(1); if ((ch0 == 'o' || ch0 == 'O') && (ch1 == 'n' || ch1 == 'N') ) { return Boolean.TRUE; } if ((ch0 == 'n' || ch0 == 'N') && (ch1 == 'o' || ch1 == 'O') ) { return Boolean.FALSE; } break; } case 3: { char ch0 = str.charAt(0); char ch1 = str.charAt(1); char ch2 = str.charAt(2); if ((ch0 == 'y' || ch0 == 'Y') && (ch1 == 'e' || ch1 == 'E') && (ch2 == 's' || ch2 == 'S') ) { return Boolean.TRUE; } if ((ch0 == 'o' || ch0 == 'O') && (ch1 == 'f' || ch1 == 'F') && (ch2 == 'f' || ch2 == 'F') ) { return Boolean.FALSE; } break; } case 4: { char ch0 = str.charAt(0); char ch1 = str.charAt(1); char ch2 = str.charAt(2); char ch3 = str.charAt(3); if ((ch0 == 't' || ch0 == 'T') && (ch1 == 'r' || ch1 == 'R') && (ch2 == 'u' || ch2 == 'U') && (ch3 == 'e' || ch3 == 'E') ) { return Boolean.TRUE; } break; } case 5: { char ch0 = str.charAt(0); char ch1 = str.charAt(1); char ch2 = str.charAt(2); char ch3 = str.charAt(3); char ch4 = str.charAt(4); if ((ch0 == 'f' || ch0 == 'F') && (ch1 == 'a' || ch1 == 'A') && (ch2 == 'l' || ch2 == 'L') && (ch3 == 's' || ch3 == 'S') && (ch4 == 'e' || ch4 == 'E') ) { return Boolean.FALSE; } break; } } return null; } /** *

Converts a String to a Boolean throwing an exception if no match.

* *
     *   BooleanUtils.toBooleanObject("true", "true", "false", "null")  = Boolean.TRUE
     *   BooleanUtils.toBooleanObject("false", "true", "false", "null") = Boolean.FALSE
     *   BooleanUtils.toBooleanObject("null", "true", "false", "null")  = null
     * 
* * @param str the String to check * @param trueString the String to match for true * (case sensitive), may be null * @param falseString the String to match for false * (case sensitive), may be null * @param nullString the String to match for null * (case sensitive), may be null * @return the Boolean value of the string, * null if either the String matches nullString * or if null input and nullString is * null * @throws IllegalArgumentException if the String doesn't match */ public static Boolean toBooleanObject(String str, String trueString, String falseString, String nullString) { if (str == null) { if (trueString == null) { return Boolean.TRUE; } else if (falseString == null) { return Boolean.FALSE; } else if (nullString == null) { return null; } } else if (str.equals(trueString)) { return Boolean.TRUE; } else if (str.equals(falseString)) { return Boolean.FALSE; } else if (str.equals(nullString)) { return null; } // no match throw new IllegalArgumentException("The String did not match any specified value"); } // String to boolean methods //----------------------------------------------------------------------- /** *

Converts a String to a boolean (optimised for performance).

* *

'true', 'on' or 'yes' * (case insensitive) will return true. Otherwise, * false is returned.

* *

This method performs 4 times faster (JDK1.4) than * Boolean.valueOf(String). However, this method accepts * 'on' and 'yes' as true values. * *

     *   BooleanUtils.toBoolean(null)    = false
     *   BooleanUtils.toBoolean("true")  = true
     *   BooleanUtils.toBoolean("TRUE")  = true
     *   BooleanUtils.toBoolean("tRUe")  = true
     *   BooleanUtils.toBoolean("on")    = true
     *   BooleanUtils.toBoolean("yes")   = true
     *   BooleanUtils.toBoolean("false") = false
     *   BooleanUtils.toBoolean("x gti") = false
     * 
* * @param str the String to check * @return the boolean value of the string, false if no match or the String is null */ public static boolean toBoolean(String str) { return toBoolean(toBooleanObject(str)); } /** *

Converts a String to a Boolean throwing an exception if no match found.

* *

null is returned if there is no match.

* *
     *   BooleanUtils.toBoolean("true", "true", "false")  = true
     *   BooleanUtils.toBoolean("false", "true", "false") = false
     * 
* * @param str the String to check * @param trueString the String to match for true * (case sensitive), may be null * @param falseString the String to match for false * (case sensitive), may be null * @return the boolean value of the string * @throws IllegalArgumentException if the String doesn't match */ public static boolean toBoolean(String str, String trueString, String falseString) { if (str == null) { if (trueString == null) { return true; } else if (falseString == null) { return false; } } else if (str.equals(trueString)) { return true; } else if (str.equals(falseString)) { return false; } // no match throw new IllegalArgumentException("The String did not match either specified value"); } // Boolean to String methods //----------------------------------------------------------------------- /** *

Converts a Boolean to a String returning 'true', * 'false', or null.

* *
     *   BooleanUtils.toStringTrueFalse(Boolean.TRUE)  = "true"
     *   BooleanUtils.toStringTrueFalse(Boolean.FALSE) = "false"
     *   BooleanUtils.toStringTrueFalse(null)          = null;
     * 
* * @param bool the Boolean to check * @return 'true', 'false', * or null */ public static String toStringTrueFalse(Boolean bool) { return toString(bool, "true", "false", null); } /** *

Converts a Boolean to a String returning 'on', * 'off', or null.

* *
     *   BooleanUtils.toStringOnOff(Boolean.TRUE)  = "on"
     *   BooleanUtils.toStringOnOff(Boolean.FALSE) = "off"
     *   BooleanUtils.toStringOnOff(null)          = null;
     * 
* * @param bool the Boolean to check * @return 'on', 'off', * or null */ public static String toStringOnOff(Boolean bool) { return toString(bool, "on", "off", null); } /** *

Converts a Boolean to a String returning 'yes', * 'no', or null.

* *
     *   BooleanUtils.toStringYesNo(Boolean.TRUE)  = "yes"
     *   BooleanUtils.toStringYesNo(Boolean.FALSE) = "no"
     *   BooleanUtils.toStringYesNo(null)          = null;
     * 
* * @param bool the Boolean to check * @return 'yes', 'no', * or null */ public static String toStringYesNo(Boolean bool) { return toString(bool, "yes", "no", null); } /** *

Converts a Boolean to a String returning one of the input Strings.

* *
     *   BooleanUtils.toString(Boolean.TRUE, "true", "false", null)   = "true"
     *   BooleanUtils.toString(Boolean.FALSE, "true", "false", null)  = "false"
     *   BooleanUtils.toString(null, "true", "false", null)           = null;
     * 
* * @param bool the Boolean to check * @param trueString the String to return if true, * may be null * @param falseString the String to return if false, * may be null * @param nullString the String to return if null, * may be null * @return one of the three input Strings */ public static String toString(Boolean bool, String trueString, String falseString, String nullString) { if (bool == null) { return nullString; } return bool.booleanValue() ? trueString : falseString; } // boolean to String methods //----------------------------------------------------------------------- /** *

Converts a boolean to a String returning 'true' * or 'false'.

* *
     *   BooleanUtils.toStringTrueFalse(true)   = "true"
     *   BooleanUtils.toStringTrueFalse(false)  = "false"
     * 
* * @param bool the Boolean to check * @return 'true', 'false', * or null */ public static String toStringTrueFalse(boolean bool) { return toString(bool, "true", "false"); } /** *

Converts a boolean to a String returning 'on' * or 'off'.

* *
     *   BooleanUtils.toStringOnOff(true)   = "on"
     *   BooleanUtils.toStringOnOff(false)  = "off"
     * 
* * @param bool the Boolean to check * @return 'on', 'off', * or null */ public static String toStringOnOff(boolean bool) { return toString(bool, "on", "off"); } /** *

Converts a boolean to a String returning 'yes' * or 'no'.

* *
     *   BooleanUtils.toStringYesNo(true)   = "yes"
     *   BooleanUtils.toStringYesNo(false)  = "no"
     * 
* * @param bool the Boolean to check * @return 'yes', 'no', * or null */ public static String toStringYesNo(boolean bool) { return toString(bool, "yes", "no"); } /** *

Converts a boolean to a String returning one of the input Strings.

* *
     *   BooleanUtils.toString(true, "true", "false")   = "true"
     *   BooleanUtils.toString(false, "true", "false")  = "false"
     * 
* * @param bool the Boolean to check * @param trueString the String to return if true, * may be null * @param falseString the String to return if false, * may be null * @return one of the two input Strings */ public static String toString(boolean bool, String trueString, String falseString) { return bool ? trueString : falseString; } // xor methods // ---------------------------------------------------------------------- /** *

Performs an xor on a set of booleans.

* *
     *   BooleanUtils.xor(new boolean[] { true, true })   = false
     *   BooleanUtils.xor(new boolean[] { false, false }) = false
     *   BooleanUtils.xor(new boolean[] { true, false })  = true
     * 
* * @param array an array of booleans * @return true if the xor is successful. * @throws IllegalArgumentException if array is null * @throws IllegalArgumentException if array is empty. */ public static boolean xor(boolean[] array) { // Validates input if (array == null) { throw new IllegalArgumentException("The Array must not be null"); } else if (array.length == 0) { throw new IllegalArgumentException("Array is empty"); } // Loops through array, comparing each item int trueCount = 0; for (int i = 0; i < array.length; i++) { // If item is true, and trueCount is < 1, increments count // Else, xor fails if (array[i]) { if (trueCount < 1) { trueCount++; } else { return false; } } } // Returns true if there was exactly 1 true item return trueCount == 1; } /** *

Performs an xor on an array of Booleans.

* *
     *   BooleanUtils.xor(new Boolean[] { Boolean.TRUE, Boolean.TRUE })   = Boolean.FALSE
     *   BooleanUtils.xor(new Boolean[] { Boolean.FALSE, Boolean.FALSE }) = Boolean.FALSE
     *   BooleanUtils.xor(new Boolean[] { Boolean.TRUE, Boolean.FALSE })  = Boolean.TRUE
     * 
* * @param array an array of Booleans * @return true if the xor is successful. * @throws IllegalArgumentException if array is null * @throws IllegalArgumentException if array is empty. * @throws IllegalArgumentException if array contains a null */ public static Boolean xor(Boolean[] array) { if (array == null) { throw new IllegalArgumentException("The Array must not be null"); } else if (array.length == 0) { throw new IllegalArgumentException("Array is empty"); } boolean[] primitive = null; try { primitive = ArrayUtils.toPrimitive(array); } catch (NullPointerException ex) { throw new IllegalArgumentException("The array must not contain any null elements"); } return xor(primitive) ? Boolean.TRUE : Boolean.FALSE; } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/builder/CompareToBuilder.java100644 0 0 114345 11513702444 26471 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.builder; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.Collection; import java.util.Comparator; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.math.NumberUtils; /** * Assists in implementing {@link java.lang.Comparable#compareTo(Object)} methods. * * It is consistent with equals(Object) and * hashcode() built with {@link EqualsBuilder} and * {@link HashCodeBuilder}.

* *

Two Objects that compare equal using equals(Object) should normally * also compare equal using compareTo(Object).

* *

All relevant fields should be included in the calculation of the * comparison. Derived fields may be ignored. The same fields, in the same * order, should be used in both compareTo(Object) and * equals(Object).

* *

To use this class write code as follows:

* *
 * public class MyClass {
 *   String field1;
 *   int field2;
 *   boolean field3;
 *
 *   ...
 *
 *   public int compareTo(Object o) {
 *     MyClass myClass = (MyClass) o;
 *     return new CompareToBuilder()
 *       .appendSuper(super.compareTo(o)
 *       .append(this.field1, myClass.field1)
 *       .append(this.field2, myClass.field2)
 *       .append(this.field3, myClass.field3)
 *       .toComparison();
 *   }
 * }
 * 
* *

Alternatively, there are {@link #reflectionCompare(Object, Object) reflectionCompare} methods that use * reflection to determine the fields to append. Because fields can be private, * reflectionCompare uses {@link java.lang.reflect.AccessibleObject#setAccessible(boolean)} to * bypass normal access control checks. This will fail under a security manager, * unless the appropriate permissions are set up correctly. It is also * slower than appending explicitly.

* *

A typical implementation of compareTo(Object) using * reflectionCompare looks like:

*
 * public int compareTo(Object o) {
 *   return CompareToBuilder.reflectionCompare(this, o);
 * }
 * 
* * @see java.lang.Comparable * @see java.lang.Object#equals(Object) * @see java.lang.Object#hashCode() * @see EqualsBuilder * @see HashCodeBuilder * @author Apache Software Foundation * @author Steve Downey * @author Gary Gregory * @author Pete Gieser * @since 1.0 * @version $Id: CompareToBuilder.java 1056843 2011-01-09 00:29:01Z niallp $ */ public class CompareToBuilder { /** * Current state of the comparison as appended fields are checked. */ private int comparison; /** *

Constructor for CompareToBuilder.

* *

Starts off assuming that the objects are equal. Multiple calls are * then made to the various append methods, followed by a call to * {@link #toComparison} to get the result.

*/ public CompareToBuilder() { super(); comparison = 0; } //----------------------------------------------------------------------- /** *

Compares two Objects via reflection.

* *

Fields can be private, thus AccessibleObject.setAccessible * is used to bypass normal access control checks. This will fail under a * security manager unless the appropriate permissions are set.

* *
    *
  • Static fields will not be compared
  • *
  • Transient members will be not be compared, as they are likely derived * fields
  • *
  • Superclass fields will be compared
  • *
* *

If both lhs and rhs are null, * they are considered equal.

* * @param lhs left-hand object * @param rhs right-hand object * @return a negative integer, zero, or a positive integer as lhs * is less than, equal to, or greater than rhs * @throws NullPointerException if either (but not both) parameters are * null * @throws ClassCastException if rhs is not assignment-compatible * with lhs */ public static int reflectionCompare(Object lhs, Object rhs) { return reflectionCompare(lhs, rhs, false, null, null); } /** *

Compares two Objects via reflection.

* *

Fields can be private, thus AccessibleObject.setAccessible * is used to bypass normal access control checks. This will fail under a * security manager unless the appropriate permissions are set.

* *
    *
  • Static fields will not be compared
  • *
  • If compareTransients is true, * compares transient members. Otherwise ignores them, as they * are likely derived fields.
  • *
  • Superclass fields will be compared
  • *
* *

If both lhs and rhs are null, * they are considered equal.

* * @param lhs left-hand object * @param rhs right-hand object * @param compareTransients whether to compare transient fields * @return a negative integer, zero, or a positive integer as lhs * is less than, equal to, or greater than rhs * @throws NullPointerException if either lhs or rhs * (but not both) is null * @throws ClassCastException if rhs is not assignment-compatible * with lhs */ public static int reflectionCompare(Object lhs, Object rhs, boolean compareTransients) { return reflectionCompare(lhs, rhs, compareTransients, null, null); } /** *

Compares two Objects via reflection.

* *

Fields can be private, thus AccessibleObject.setAccessible * is used to bypass normal access control checks. This will fail under a * security manager unless the appropriate permissions are set.

* *
    *
  • Static fields will not be compared
  • *
  • If compareTransients is true, * compares transient members. Otherwise ignores them, as they * are likely derived fields.
  • *
  • Superclass fields will be compared
  • *
* *

If both lhs and rhs are null, * they are considered equal.

* * @param lhs left-hand object * @param rhs right-hand object * @param excludeFields Collection of String fields to exclude * @return a negative integer, zero, or a positive integer as lhs * is less than, equal to, or greater than rhs * @throws NullPointerException if either lhs or rhs * (but not both) is null * @throws ClassCastException if rhs is not assignment-compatible * with lhs * @since 2.2 */ public static int reflectionCompare(Object lhs, Object rhs, Collection /*String*/ excludeFields) { return reflectionCompare(lhs, rhs, ReflectionToStringBuilder.toNoNullStringArray(excludeFields)); } /** *

Compares two Objects via reflection.

* *

Fields can be private, thus AccessibleObject.setAccessible * is used to bypass normal access control checks. This will fail under a * security manager unless the appropriate permissions are set.

* *
    *
  • Static fields will not be compared
  • *
  • If compareTransients is true, * compares transient members. Otherwise ignores them, as they * are likely derived fields.
  • *
  • Superclass fields will be compared
  • *
* *

If both lhs and rhs are null, * they are considered equal.

* * @param lhs left-hand object * @param rhs right-hand object * @param excludeFields array of fields to exclude * @return a negative integer, zero, or a positive integer as lhs * is less than, equal to, or greater than rhs * @throws NullPointerException if either lhs or rhs * (but not both) is null * @throws ClassCastException if rhs is not assignment-compatible * with lhs * @since 2.2 */ public static int reflectionCompare(Object lhs, Object rhs, String[] excludeFields) { return reflectionCompare(lhs, rhs, false, null, excludeFields); } /** *

Compares two Objects via reflection.

* *

Fields can be private, thus AccessibleObject.setAccessible * is used to bypass normal access control checks. This will fail under a * security manager unless the appropriate permissions are set.

* *
    *
  • Static fields will not be compared
  • *
  • If the compareTransients is true, * compares transient members. Otherwise ignores them, as they * are likely derived fields.
  • *
  • Compares superclass fields up to and including reflectUpToClass. * If reflectUpToClass is null, compares all superclass fields.
  • *
* *

If both lhs and rhs are null, * they are considered equal.

* * @param lhs left-hand object * @param rhs right-hand object * @param compareTransients whether to compare transient fields * @param reflectUpToClass last superclass for which fields are compared * @return a negative integer, zero, or a positive integer as lhs * is less than, equal to, or greater than rhs * @throws NullPointerException if either lhs or rhs * (but not both) is null * @throws ClassCastException if rhs is not assignment-compatible * with lhs * @since 2.0 */ public static int reflectionCompare(Object lhs, Object rhs, boolean compareTransients, Class reflectUpToClass) { return reflectionCompare(lhs, rhs, compareTransients, reflectUpToClass, null); } /** *

Compares two Objects via reflection.

* *

Fields can be private, thus AccessibleObject.setAccessible * is used to bypass normal access control checks. This will fail under a * security manager unless the appropriate permissions are set.

* *
    *
  • Static fields will not be compared
  • *
  • If the compareTransients is true, * compares transient members. Otherwise ignores them, as they * are likely derived fields.
  • *
  • Compares superclass fields up to and including reflectUpToClass. * If reflectUpToClass is null, compares all superclass fields.
  • *
* *

If both lhs and rhs are null, * they are considered equal.

* * @param lhs left-hand object * @param rhs right-hand object * @param compareTransients whether to compare transient fields * @param reflectUpToClass last superclass for which fields are compared * @param excludeFields fields to exclude * @return a negative integer, zero, or a positive integer as lhs * is less than, equal to, or greater than rhs * @throws NullPointerException if either lhs or rhs * (but not both) is null * @throws ClassCastException if rhs is not assignment-compatible * with lhs * @since 2.2 */ public static int reflectionCompare( Object lhs, Object rhs, boolean compareTransients, Class reflectUpToClass, String[] excludeFields) { if (lhs == rhs) { return 0; } if (lhs == null || rhs == null) { throw new NullPointerException(); } Class lhsClazz = lhs.getClass(); if (!lhsClazz.isInstance(rhs)) { throw new ClassCastException(); } CompareToBuilder compareToBuilder = new CompareToBuilder(); reflectionAppend(lhs, rhs, lhsClazz, compareToBuilder, compareTransients, excludeFields); while (lhsClazz.getSuperclass() != null && lhsClazz != reflectUpToClass) { lhsClazz = lhsClazz.getSuperclass(); reflectionAppend(lhs, rhs, lhsClazz, compareToBuilder, compareTransients, excludeFields); } return compareToBuilder.toComparison(); } /** *

Appends to builder the comparison of lhs * to rhs using the fields defined in clazz.

* * @param lhs left-hand object * @param rhs right-hand object * @param clazz Class that defines fields to be compared * @param builder CompareToBuilder to append to * @param useTransients whether to compare transient fields * @param excludeFields fields to exclude */ private static void reflectionAppend( Object lhs, Object rhs, Class clazz, CompareToBuilder builder, boolean useTransients, String[] excludeFields) { Field[] fields = clazz.getDeclaredFields(); AccessibleObject.setAccessible(fields, true); for (int i = 0; i < fields.length && builder.comparison == 0; i++) { Field f = fields[i]; if (!ArrayUtils.contains(excludeFields, f.getName()) && (f.getName().indexOf('$') == -1) && (useTransients || !Modifier.isTransient(f.getModifiers())) && (!Modifier.isStatic(f.getModifiers()))) { try { builder.append(f.get(lhs), f.get(rhs)); } catch (IllegalAccessException e) { // This can't happen. Would get a Security exception instead. // Throw a runtime exception in case the impossible happens. throw new InternalError("Unexpected IllegalAccessException"); } } } } //----------------------------------------------------------------------- /** *

Appends to the builder the compareTo(Object) * result of the superclass.

* * @param superCompareTo result of calling super.compareTo(Object) * @return this - used to chain append calls * @since 2.0 */ public CompareToBuilder appendSuper(int superCompareTo) { if (comparison != 0) { return this; } comparison = superCompareTo; return this; } //----------------------------------------------------------------------- /** *

Appends to the builder the comparison of * two Objects.

* *
    *
  1. Check if lhs == rhs
  2. *
  3. Check if either lhs or rhs is null, * a null object is less than a non-null object
  4. *
  5. Check the object contents
  6. *
* *

lhs must either be an array or implement {@link Comparable}.

* * @param lhs left-hand object * @param rhs right-hand object * @return this - used to chain append calls * @throws ClassCastException if rhs is not assignment-compatible * with lhs */ public CompareToBuilder append(Object lhs, Object rhs) { return append(lhs, rhs, null); } /** *

Appends to the builder the comparison of * two Objects.

* *
    *
  1. Check if lhs == rhs
  2. *
  3. Check if either lhs or rhs is null, * a null object is less than a non-null object
  4. *
  5. Check the object contents
  6. *
* *

If lhs is an array, array comparison methods will be used. * Otherwise comparator will be used to compare the objects. * If comparator is null, lhs must * implement {@link Comparable} instead.

* * @param lhs left-hand object * @param rhs right-hand object * @param comparator Comparator used to compare the objects, * null means treat lhs as Comparable * @return this - used to chain append calls * @throws ClassCastException if rhs is not assignment-compatible * with lhs * @since 2.0 */ public CompareToBuilder append(Object lhs, Object rhs, Comparator comparator) { if (comparison != 0) { return this; } if (lhs == rhs) { return this; } if (lhs == null) { comparison = -1; return this; } if (rhs == null) { comparison = +1; return this; } if (lhs.getClass().isArray()) { // switch on type of array, to dispatch to the correct handler // handles multi dimensional arrays // throws a ClassCastException if rhs is not the correct array type if (lhs instanceof long[]) { append((long[]) lhs, (long[]) rhs); } else if (lhs instanceof int[]) { append((int[]) lhs, (int[]) rhs); } else if (lhs instanceof short[]) { append((short[]) lhs, (short[]) rhs); } else if (lhs instanceof char[]) { append((char[]) lhs, (char[]) rhs); } else if (lhs instanceof byte[]) { append((byte[]) lhs, (byte[]) rhs); } else if (lhs instanceof double[]) { append((double[]) lhs, (double[]) rhs); } else if (lhs instanceof float[]) { append((float[]) lhs, (float[]) rhs); } else if (lhs instanceof boolean[]) { append((boolean[]) lhs, (boolean[]) rhs); } else { // not an array of primitives // throws a ClassCastException if rhs is not an array append((Object[]) lhs, (Object[]) rhs, comparator); } } else { // the simple case, not an array, just test the element if (comparator == null) { comparison = ((Comparable) lhs).compareTo(rhs); } else { comparison = comparator.compare(lhs, rhs); } } return this; } //------------------------------------------------------------------------- /** * Appends to the builder the comparison of * two longs. * * @param lhs left-hand value * @param rhs right-hand value * @return this - used to chain append calls */ public CompareToBuilder append(long lhs, long rhs) { if (comparison != 0) { return this; } comparison = ((lhs < rhs) ? -1 : ((lhs > rhs) ? 1 : 0)); return this; } /** * Appends to the builder the comparison of * two ints. * * @param lhs left-hand value * @param rhs right-hand value * @return this - used to chain append calls */ public CompareToBuilder append(int lhs, int rhs) { if (comparison != 0) { return this; } comparison = ((lhs < rhs) ? -1 : ((lhs > rhs) ? 1 : 0)); return this; } /** * Appends to the builder the comparison of * two shorts. * * @param lhs left-hand value * @param rhs right-hand value * @return this - used to chain append calls */ public CompareToBuilder append(short lhs, short rhs) { if (comparison != 0) { return this; } comparison = ((lhs < rhs) ? -1 : ((lhs > rhs) ? 1 : 0)); return this; } /** * Appends to the builder the comparison of * two chars. * * @param lhs left-hand value * @param rhs right-hand value * @return this - used to chain append calls */ public CompareToBuilder append(char lhs, char rhs) { if (comparison != 0) { return this; } comparison = ((lhs < rhs) ? -1 : ((lhs > rhs) ? 1 : 0)); return this; } /** * Appends to the builder the comparison of * two bytes. * * @param lhs left-hand value * @param rhs right-hand value * @return this - used to chain append calls */ public CompareToBuilder append(byte lhs, byte rhs) { if (comparison != 0) { return this; } comparison = ((lhs < rhs) ? -1 : ((lhs > rhs) ? 1 : 0)); return this; } /** *

Appends to the builder the comparison of * two doubles.

* *

This handles NaNs, Infinities, and -0.0.

* *

It is compatible with the hash code generated by * HashCodeBuilder.

* * @param lhs left-hand value * @param rhs right-hand value * @return this - used to chain append calls */ public CompareToBuilder append(double lhs, double rhs) { if (comparison != 0) { return this; } comparison = NumberUtils.compare(lhs, rhs); return this; } /** *

Appends to the builder the comparison of * two floats.

* *

This handles NaNs, Infinities, and -0.0.

* *

It is compatible with the hash code generated by * HashCodeBuilder.

* * @param lhs left-hand value * @param rhs right-hand value * @return this - used to chain append calls */ public CompareToBuilder append(float lhs, float rhs) { if (comparison != 0) { return this; } comparison = NumberUtils.compare(lhs, rhs); return this; } /** * Appends to the builder the comparison of * two booleanss. * * @param lhs left-hand value * @param rhs right-hand value * @return this - used to chain append calls */ public CompareToBuilder append(boolean lhs, boolean rhs) { if (comparison != 0) { return this; } if (lhs == rhs) { return this; } if (lhs == false) { comparison = -1; } else { comparison = +1; } return this; } //----------------------------------------------------------------------- /** *

Appends to the builder the deep comparison of * two Object arrays.

* *
    *
  1. Check if arrays are the same using ==
  2. *
  3. Check if for null, null is less than non-null
  4. *
  5. Check array length, a short length array is less than a long length array
  6. *
  7. Check array contents element by element using {@link #append(Object, Object, Comparator)}
  8. *
* *

This method will also will be called for the top level of multi-dimensional, * ragged, and multi-typed arrays.

* * @param lhs left-hand array * @param rhs right-hand array * @return this - used to chain append calls * @throws ClassCastException if rhs is not assignment-compatible * with lhs */ public CompareToBuilder append(Object[] lhs, Object[] rhs) { return append(lhs, rhs, null); } /** *

Appends to the builder the deep comparison of * two Object arrays.

* *
    *
  1. Check if arrays are the same using ==
  2. *
  3. Check if for null, null is less than non-null
  4. *
  5. Check array length, a short length array is less than a long length array
  6. *
  7. Check array contents element by element using {@link #append(Object, Object, Comparator)}
  8. *
* *

This method will also will be called for the top level of multi-dimensional, * ragged, and multi-typed arrays.

* * @param lhs left-hand array * @param rhs right-hand array * @param comparator Comparator to use to compare the array elements, * null means to treat lhs elements as Comparable. * @return this - used to chain append calls * @throws ClassCastException if rhs is not assignment-compatible * with lhs * @since 2.0 */ public CompareToBuilder append(Object[] lhs, Object[] rhs, Comparator comparator) { if (comparison != 0) { return this; } if (lhs == rhs) { return this; } if (lhs == null) { comparison = -1; return this; } if (rhs == null) { comparison = +1; return this; } if (lhs.length != rhs.length) { comparison = (lhs.length < rhs.length) ? -1 : +1; return this; } for (int i = 0; i < lhs.length && comparison == 0; i++) { append(lhs[i], rhs[i], comparator); } return this; } /** *

Appends to the builder the deep comparison of * two long arrays.

* *
    *
  1. Check if arrays are the same using ==
  2. *
  3. Check if for null, null is less than non-null
  4. *
  5. Check array length, a shorter length array is less than a longer length array
  6. *
  7. Check array contents element by element using {@link #append(long, long)}
  8. *
* * @param lhs left-hand array * @param rhs right-hand array * @return this - used to chain append calls */ public CompareToBuilder append(long[] lhs, long[] rhs) { if (comparison != 0) { return this; } if (lhs == rhs) { return this; } if (lhs == null) { comparison = -1; return this; } if (rhs == null) { comparison = +1; return this; } if (lhs.length != rhs.length) { comparison = (lhs.length < rhs.length) ? -1 : +1; return this; } for (int i = 0; i < lhs.length && comparison == 0; i++) { append(lhs[i], rhs[i]); } return this; } /** *

Appends to the builder the deep comparison of * two int arrays.

* *
    *
  1. Check if arrays are the same using ==
  2. *
  3. Check if for null, null is less than non-null
  4. *
  5. Check array length, a shorter length array is less than a longer length array
  6. *
  7. Check array contents element by element using {@link #append(int, int)}
  8. *
* * @param lhs left-hand array * @param rhs right-hand array * @return this - used to chain append calls */ public CompareToBuilder append(int[] lhs, int[] rhs) { if (comparison != 0) { return this; } if (lhs == rhs) { return this; } if (lhs == null) { comparison = -1; return this; } if (rhs == null) { comparison = +1; return this; } if (lhs.length != rhs.length) { comparison = (lhs.length < rhs.length) ? -1 : +1; return this; } for (int i = 0; i < lhs.length && comparison == 0; i++) { append(lhs[i], rhs[i]); } return this; } /** *

Appends to the builder the deep comparison of * two short arrays.

* *
    *
  1. Check if arrays are the same using ==
  2. *
  3. Check if for null, null is less than non-null
  4. *
  5. Check array length, a shorter length array is less than a longer length array
  6. *
  7. Check array contents element by element using {@link #append(short, short)}
  8. *
* * @param lhs left-hand array * @param rhs right-hand array * @return this - used to chain append calls */ public CompareToBuilder append(short[] lhs, short[] rhs) { if (comparison != 0) { return this; } if (lhs == rhs) { return this; } if (lhs == null) { comparison = -1; return this; } if (rhs == null) { comparison = +1; return this; } if (lhs.length != rhs.length) { comparison = (lhs.length < rhs.length) ? -1 : +1; return this; } for (int i = 0; i < lhs.length && comparison == 0; i++) { append(lhs[i], rhs[i]); } return this; } /** *

Appends to the builder the deep comparison of * two char arrays.

* *
    *
  1. Check if arrays are the same using ==
  2. *
  3. Check if for null, null is less than non-null
  4. *
  5. Check array length, a shorter length array is less than a longer length array
  6. *
  7. Check array contents element by element using {@link #append(char, char)}
  8. *
* * @param lhs left-hand array * @param rhs right-hand array * @return this - used to chain append calls */ public CompareToBuilder append(char[] lhs, char[] rhs) { if (comparison != 0) { return this; } if (lhs == rhs) { return this; } if (lhs == null) { comparison = -1; return this; } if (rhs == null) { comparison = +1; return this; } if (lhs.length != rhs.length) { comparison = (lhs.length < rhs.length) ? -1 : +1; return this; } for (int i = 0; i < lhs.length && comparison == 0; i++) { append(lhs[i], rhs[i]); } return this; } /** *

Appends to the builder the deep comparison of * two byte arrays.

* *
    *
  1. Check if arrays are the same using ==
  2. *
  3. Check if for null, null is less than non-null
  4. *
  5. Check array length, a shorter length array is less than a longer length array
  6. *
  7. Check array contents element by element using {@link #append(byte, byte)}
  8. *
* * @param lhs left-hand array * @param rhs right-hand array * @return this - used to chain append calls */ public CompareToBuilder append(byte[] lhs, byte[] rhs) { if (comparison != 0) { return this; } if (lhs == rhs) { return this; } if (lhs == null) { comparison = -1; return this; } if (rhs == null) { comparison = +1; return this; } if (lhs.length != rhs.length) { comparison = (lhs.length < rhs.length) ? -1 : +1; return this; } for (int i = 0; i < lhs.length && comparison == 0; i++) { append(lhs[i], rhs[i]); } return this; } /** *

Appends to the builder the deep comparison of * two double arrays.

* *
    *
  1. Check if arrays are the same using ==
  2. *
  3. Check if for null, null is less than non-null
  4. *
  5. Check array length, a shorter length array is less than a longer length array
  6. *
  7. Check array contents element by element using {@link #append(double, double)}
  8. *
* * @param lhs left-hand array * @param rhs right-hand array * @return this - used to chain append calls */ public CompareToBuilder append(double[] lhs, double[] rhs) { if (comparison != 0) { return this; } if (lhs == rhs) { return this; } if (lhs == null) { comparison = -1; return this; } if (rhs == null) { comparison = +1; return this; } if (lhs.length != rhs.length) { comparison = (lhs.length < rhs.length) ? -1 : +1; return this; } for (int i = 0; i < lhs.length && comparison == 0; i++) { append(lhs[i], rhs[i]); } return this; } /** *

Appends to the builder the deep comparison of * two float arrays.

* *
    *
  1. Check if arrays are the same using ==
  2. *
  3. Check if for null, null is less than non-null
  4. *
  5. Check array length, a shorter length array is less than a longer length array
  6. *
  7. Check array contents element by element using {@link #append(float, float)}
  8. *
* * @param lhs left-hand array * @param rhs right-hand array * @return this - used to chain append calls */ public CompareToBuilder append(float[] lhs, float[] rhs) { if (comparison != 0) { return this; } if (lhs == rhs) { return this; } if (lhs == null) { comparison = -1; return this; } if (rhs == null) { comparison = +1; return this; } if (lhs.length != rhs.length) { comparison = (lhs.length < rhs.length) ? -1 : +1; return this; } for (int i = 0; i < lhs.length && comparison == 0; i++) { append(lhs[i], rhs[i]); } return this; } /** *

Appends to the builder the deep comparison of * two boolean arrays.

* *
    *
  1. Check if arrays are the same using ==
  2. *
  3. Check if for null, null is less than non-null
  4. *
  5. Check array length, a shorter length array is less than a longer length array
  6. *
  7. Check array contents element by element using {@link #append(boolean, boolean)}
  8. *
* * @param lhs left-hand array * @param rhs right-hand array * @return this - used to chain append calls */ public CompareToBuilder append(boolean[] lhs, boolean[] rhs) { if (comparison != 0) { return this; } if (lhs == rhs) { return this; } if (lhs == null) { comparison = -1; return this; } if (rhs == null) { comparison = +1; return this; } if (lhs.length != rhs.length) { comparison = (lhs.length < rhs.length) ? -1 : +1; return this; } for (int i = 0; i < lhs.length && comparison == 0; i++) { append(lhs[i], rhs[i]); } return this; } //----------------------------------------------------------------------- /** * Returns a negative integer, a positive integer, or zero as * the builder has judged the "left-hand" side * as less than, greater than, or equal to the "right-hand" * side. * * @return final comparison result */ public int toComparison() { return comparison; } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/builder/EqualsBuilder.java100644 0 0 74113 11513702444 26010 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.builder; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.Collection; import org.apache.commons.lang.ArrayUtils; /** *

Assists in implementing {@link Object#equals(Object)} methods.

* *

This class provides methods to build a good equals method for any * class. It follows rules laid out in * Effective Java * , by Joshua Bloch. In particular the rule for comparing doubles, * floats, and arrays can be tricky. Also, making sure that * equals() and hashCode() are consistent can be * difficult.

* *

Two Objects that compare as equals must generate the same hash code, * but two Objects with the same hash code do not have to be equal.

* *

All relevant fields should be included in the calculation of equals. * Derived fields may be ignored. In particular, any field used in * generating a hash code must be used in the equals method, and vice * versa.

* *

Typical use for the code is as follows:

*
 * public boolean equals(Object obj) {
 *   if (obj == null) { return false; }
 *   if (obj == this) { return true; }
 *   if (obj.getClass() != getClass()) {
 *     return false;
 *   }
 *   MyClass rhs = (MyClass) obj;
 *   return new EqualsBuilder()
 *                 .appendSuper(super.equals(obj))
 *                 .append(field1, rhs.field1)
 *                 .append(field2, rhs.field2)
 *                 .append(field3, rhs.field3)
 *                 .isEquals();
 *  }
 * 
* *

Alternatively, there is a method that uses reflection to determine * the fields to test. Because these fields are usually private, the method, * reflectionEquals, uses AccessibleObject.setAccessible to * change the visibility of the fields. This will fail under a security * manager, unless the appropriate permissions are set up correctly. It is * also slower than testing explicitly.

* *

A typical invocation for this method would look like:

*
 * public boolean equals(Object obj) {
 *   return EqualsBuilder.reflectionEquals(this, obj);
 * }
 * 
* * @author Apache Software Foundation * @author Steve Downey * @author Gary Gregory * @author Pete Gieser * @author Arun Mammen Thomas * @since 1.0 * @version $Id: EqualsBuilder.java 905707 2010-02-02 16:59:59Z niallp $ */ public class EqualsBuilder { /** * If the fields tested are equals. * The default value is true. */ private boolean isEquals = true; /** *

Constructor for EqualsBuilder.

* *

Starts off assuming that equals is true.

* @see Object#equals(Object) */ public EqualsBuilder() { // do nothing for now. } //------------------------------------------------------------------------- /** *

This method uses reflection to determine if the two Objects * are equal.

* *

It uses AccessibleObject.setAccessible to gain access to private * fields. This means that it will throw a security exception if run under * a security manager, if the permissions are not set up correctly. It is also * not as efficient as testing explicitly.

* *

Transient members will be not be tested, as they are likely derived * fields, and not part of the value of the Object.

* *

Static fields will not be tested. Superclass fields will be included.

* * @param lhs this object * @param rhs the other object * @return true if the two Objects have tested equals. */ public static boolean reflectionEquals(Object lhs, Object rhs) { return reflectionEquals(lhs, rhs, false, null, null); } /** *

This method uses reflection to determine if the two Objects * are equal.

* *

It uses AccessibleObject.setAccessible to gain access to private * fields. This means that it will throw a security exception if run under * a security manager, if the permissions are not set up correctly. It is also * not as efficient as testing explicitly.

* *

Transient members will be not be tested, as they are likely derived * fields, and not part of the value of the Object.

* *

Static fields will not be tested. Superclass fields will be included.

* * @param lhs this object * @param rhs the other object * @param excludeFields Collection of String field names to exclude from testing * @return true if the two Objects have tested equals. */ public static boolean reflectionEquals(Object lhs, Object rhs, Collection /*String*/ excludeFields) { return reflectionEquals(lhs, rhs, ReflectionToStringBuilder.toNoNullStringArray(excludeFields)); } /** *

This method uses reflection to determine if the two Objects * are equal.

* *

It uses AccessibleObject.setAccessible to gain access to private * fields. This means that it will throw a security exception if run under * a security manager, if the permissions are not set up correctly. It is also * not as efficient as testing explicitly.

* *

Transient members will be not be tested, as they are likely derived * fields, and not part of the value of the Object.

* *

Static fields will not be tested. Superclass fields will be included.

* * @param lhs this object * @param rhs the other object * @param excludeFields array of field names to exclude from testing * @return true if the two Objects have tested equals. */ public static boolean reflectionEquals(Object lhs, Object rhs, String[] excludeFields) { return reflectionEquals(lhs, rhs, false, null, excludeFields); } /** *

This method uses reflection to determine if the two Objects * are equal.

* *

It uses AccessibleObject.setAccessible to gain access to private * fields. This means that it will throw a security exception if run under * a security manager, if the permissions are not set up correctly. It is also * not as efficient as testing explicitly.

* *

If the TestTransients parameter is set to true, transient * members will be tested, otherwise they are ignored, as they are likely * derived fields, and not part of the value of the Object.

* *

Static fields will not be tested. Superclass fields will be included.

* * @param lhs this object * @param rhs the other object * @param testTransients whether to include transient fields * @return true if the two Objects have tested equals. */ public static boolean reflectionEquals(Object lhs, Object rhs, boolean testTransients) { return reflectionEquals(lhs, rhs, testTransients, null, null); } /** *

This method uses reflection to determine if the two Objects * are equal.

* *

It uses AccessibleObject.setAccessible to gain access to private * fields. This means that it will throw a security exception if run under * a security manager, if the permissions are not set up correctly. It is also * not as efficient as testing explicitly.

* *

If the testTransients parameter is set to true, transient * members will be tested, otherwise they are ignored, as they are likely * derived fields, and not part of the value of the Object.

* *

Static fields will not be included. Superclass fields will be appended * up to and including the specified superclass. A null superclass is treated * as java.lang.Object.

* * @param lhs this object * @param rhs the other object * @param testTransients whether to include transient fields * @param reflectUpToClass the superclass to reflect up to (inclusive), * may be null * @return true if the two Objects have tested equals. * @since 2.0 */ public static boolean reflectionEquals(Object lhs, Object rhs, boolean testTransients, Class reflectUpToClass) { return reflectionEquals(lhs, rhs, testTransients, reflectUpToClass, null); } /** *

This method uses reflection to determine if the two Objects * are equal.

* *

It uses AccessibleObject.setAccessible to gain access to private * fields. This means that it will throw a security exception if run under * a security manager, if the permissions are not set up correctly. It is also * not as efficient as testing explicitly.

* *

If the testTransients parameter is set to true, transient * members will be tested, otherwise they are ignored, as they are likely * derived fields, and not part of the value of the Object.

* *

Static fields will not be included. Superclass fields will be appended * up to and including the specified superclass. A null superclass is treated * as java.lang.Object.

* * @param lhs this object * @param rhs the other object * @param testTransients whether to include transient fields * @param reflectUpToClass the superclass to reflect up to (inclusive), * may be null * @param excludeFields array of field names to exclude from testing * @return true if the two Objects have tested equals. * @since 2.0 */ public static boolean reflectionEquals(Object lhs, Object rhs, boolean testTransients, Class reflectUpToClass, String[] excludeFields) { if (lhs == rhs) { return true; } if (lhs == null || rhs == null) { return false; } // Find the leaf class since there may be transients in the leaf // class or in classes between the leaf and root. // If we are not testing transients or a subclass has no ivars, // then a subclass can test equals to a superclass. Class lhsClass = lhs.getClass(); Class rhsClass = rhs.getClass(); Class testClass; if (lhsClass.isInstance(rhs)) { testClass = lhsClass; if (!rhsClass.isInstance(lhs)) { // rhsClass is a subclass of lhsClass testClass = rhsClass; } } else if (rhsClass.isInstance(lhs)) { testClass = rhsClass; if (!lhsClass.isInstance(rhs)) { // lhsClass is a subclass of rhsClass testClass = lhsClass; } } else { // The two classes are not related. return false; } EqualsBuilder equalsBuilder = new EqualsBuilder(); try { reflectionAppend(lhs, rhs, testClass, equalsBuilder, testTransients, excludeFields); while (testClass.getSuperclass() != null && testClass != reflectUpToClass) { testClass = testClass.getSuperclass(); reflectionAppend(lhs, rhs, testClass, equalsBuilder, testTransients, excludeFields); } } catch (IllegalArgumentException e) { // In this case, we tried to test a subclass vs. a superclass and // the subclass has ivars or the ivars are transient and // we are testing transients. // If a subclass has ivars that we are trying to test them, we get an // exception and we know that the objects are not equal. return false; } return equalsBuilder.isEquals(); } /** *

Appends the fields and values defined by the given object of the * given Class.

* * @param lhs the left hand object * @param rhs the right hand object * @param clazz the class to append details of * @param builder the builder to append to * @param useTransients whether to test transient fields * @param excludeFields array of field names to exclude from testing */ private static void reflectionAppend( Object lhs, Object rhs, Class clazz, EqualsBuilder builder, boolean useTransients, String[] excludeFields) { Field[] fields = clazz.getDeclaredFields(); AccessibleObject.setAccessible(fields, true); for (int i = 0; i < fields.length && builder.isEquals; i++) { Field f = fields[i]; if (!ArrayUtils.contains(excludeFields, f.getName()) && (f.getName().indexOf('$') == -1) && (useTransients || !Modifier.isTransient(f.getModifiers())) && (!Modifier.isStatic(f.getModifiers()))) { try { builder.append(f.get(lhs), f.get(rhs)); } catch (IllegalAccessException e) { //this can't happen. Would get a Security exception instead //throw a runtime exception in case the impossible happens. throw new InternalError("Unexpected IllegalAccessException"); } } } } //------------------------------------------------------------------------- /** *

Adds the result of super.equals() to this builder.

* * @param superEquals the result of calling super.equals() * @return EqualsBuilder - used to chain calls. * @since 2.0 */ public EqualsBuilder appendSuper(boolean superEquals) { if (isEquals == false) { return this; } isEquals = superEquals; return this; } //------------------------------------------------------------------------- /** *

Test if two Objects are equal using their * equals method.

* * @param lhs the left hand object * @param rhs the right hand object * @return EqualsBuilder - used to chain calls. */ public EqualsBuilder append(Object lhs, Object rhs) { if (isEquals == false) { return this; } if (lhs == rhs) { return this; } if (lhs == null || rhs == null) { this.setEquals(false); return this; } Class lhsClass = lhs.getClass(); if (!lhsClass.isArray()) { // The simple case, not an array, just test the element isEquals = lhs.equals(rhs); } else if (lhs.getClass() != rhs.getClass()) { // Here when we compare different dimensions, for example: a boolean[][] to a boolean[] this.setEquals(false); } // 'Switch' on type of array, to dispatch to the correct handler // This handles multi dimensional arrays of the same depth else if (lhs instanceof long[]) { append((long[]) lhs, (long[]) rhs); } else if (lhs instanceof int[]) { append((int[]) lhs, (int[]) rhs); } else if (lhs instanceof short[]) { append((short[]) lhs, (short[]) rhs); } else if (lhs instanceof char[]) { append((char[]) lhs, (char[]) rhs); } else if (lhs instanceof byte[]) { append((byte[]) lhs, (byte[]) rhs); } else if (lhs instanceof double[]) { append((double[]) lhs, (double[]) rhs); } else if (lhs instanceof float[]) { append((float[]) lhs, (float[]) rhs); } else if (lhs instanceof boolean[]) { append((boolean[]) lhs, (boolean[]) rhs); } else { // Not an array of primitives append((Object[]) lhs, (Object[]) rhs); } return this; } /** *

* Test if two long s are equal. *

* * @param lhs * the left hand long * @param rhs * the right hand long * @return EqualsBuilder - used to chain calls. */ public EqualsBuilder append(long lhs, long rhs) { if (isEquals == false) { return this; } isEquals = (lhs == rhs); return this; } /** *

Test if two ints are equal.

* * @param lhs the left hand int * @param rhs the right hand int * @return EqualsBuilder - used to chain calls. */ public EqualsBuilder append(int lhs, int rhs) { if (isEquals == false) { return this; } isEquals = (lhs == rhs); return this; } /** *

Test if two shorts are equal.

* * @param lhs the left hand short * @param rhs the right hand short * @return EqualsBuilder - used to chain calls. */ public EqualsBuilder append(short lhs, short rhs) { if (isEquals == false) { return this; } isEquals = (lhs == rhs); return this; } /** *

Test if two chars are equal.

* * @param lhs the left hand char * @param rhs the right hand char * @return EqualsBuilder - used to chain calls. */ public EqualsBuilder append(char lhs, char rhs) { if (isEquals == false) { return this; } isEquals = (lhs == rhs); return this; } /** *

Test if two bytes are equal.

* * @param lhs the left hand byte * @param rhs the right hand byte * @return EqualsBuilder - used to chain calls. */ public EqualsBuilder append(byte lhs, byte rhs) { if (isEquals == false) { return this; } isEquals = (lhs == rhs); return this; } /** *

Test if two doubles are equal by testing that the * pattern of bits returned by doubleToLong are equal.

* *

This handles NaNs, Infinities, and -0.0.

* *

It is compatible with the hash code generated by * HashCodeBuilder.

* * @param lhs the left hand double * @param rhs the right hand double * @return EqualsBuilder - used to chain calls. */ public EqualsBuilder append(double lhs, double rhs) { if (isEquals == false) { return this; } return append(Double.doubleToLongBits(lhs), Double.doubleToLongBits(rhs)); } /** *

Test if two floats are equal byt testing that the * pattern of bits returned by doubleToLong are equal.

* *

This handles NaNs, Infinities, and -0.0.

* *

It is compatible with the hash code generated by * HashCodeBuilder.

* * @param lhs the left hand float * @param rhs the right hand float * @return EqualsBuilder - used to chain calls. */ public EqualsBuilder append(float lhs, float rhs) { if (isEquals == false) { return this; } return append(Float.floatToIntBits(lhs), Float.floatToIntBits(rhs)); } /** *

Test if two booleanss are equal.

* * @param lhs the left hand boolean * @param rhs the right hand boolean * @return EqualsBuilder - used to chain calls. */ public EqualsBuilder append(boolean lhs, boolean rhs) { if (isEquals == false) { return this; } isEquals = (lhs == rhs); return this; } /** *

Performs a deep comparison of two Object arrays.

* *

This also will be called for the top level of * multi-dimensional, ragged, and multi-typed arrays.

* * @param lhs the left hand Object[] * @param rhs the right hand Object[] * @return EqualsBuilder - used to chain calls. */ public EqualsBuilder append(Object[] lhs, Object[] rhs) { if (isEquals == false) { return this; } if (lhs == rhs) { return this; } if (lhs == null || rhs == null) { this.setEquals(false); return this; } if (lhs.length != rhs.length) { this.setEquals(false); return this; } for (int i = 0; i < lhs.length && isEquals; ++i) { append(lhs[i], rhs[i]); } return this; } /** *

Deep comparison of array of long. Length and all * values are compared.

* *

The method {@link #append(long, long)} is used.

* * @param lhs the left hand long[] * @param rhs the right hand long[] * @return EqualsBuilder - used to chain calls. */ public EqualsBuilder append(long[] lhs, long[] rhs) { if (isEquals == false) { return this; } if (lhs == rhs) { return this; } if (lhs == null || rhs == null) { this.setEquals(false); return this; } if (lhs.length != rhs.length) { this.setEquals(false); return this; } for (int i = 0; i < lhs.length && isEquals; ++i) { append(lhs[i], rhs[i]); } return this; } /** *

Deep comparison of array of int. Length and all * values are compared.

* *

The method {@link #append(int, int)} is used.

* * @param lhs the left hand int[] * @param rhs the right hand int[] * @return EqualsBuilder - used to chain calls. */ public EqualsBuilder append(int[] lhs, int[] rhs) { if (isEquals == false) { return this; } if (lhs == rhs) { return this; } if (lhs == null || rhs == null) { this.setEquals(false); return this; } if (lhs.length != rhs.length) { this.setEquals(false); return this; } for (int i = 0; i < lhs.length && isEquals; ++i) { append(lhs[i], rhs[i]); } return this; } /** *

Deep comparison of array of short. Length and all * values are compared.

* *

The method {@link #append(short, short)} is used.

* * @param lhs the left hand short[] * @param rhs the right hand short[] * @return EqualsBuilder - used to chain calls. */ public EqualsBuilder append(short[] lhs, short[] rhs) { if (isEquals == false) { return this; } if (lhs == rhs) { return this; } if (lhs == null || rhs == null) { this.setEquals(false); return this; } if (lhs.length != rhs.length) { this.setEquals(false); return this; } for (int i = 0; i < lhs.length && isEquals; ++i) { append(lhs[i], rhs[i]); } return this; } /** *

Deep comparison of array of char. Length and all * values are compared.

* *

The method {@link #append(char, char)} is used.

* * @param lhs the left hand char[] * @param rhs the right hand char[] * @return EqualsBuilder - used to chain calls. */ public EqualsBuilder append(char[] lhs, char[] rhs) { if (isEquals == false) { return this; } if (lhs == rhs) { return this; } if (lhs == null || rhs == null) { this.setEquals(false); return this; } if (lhs.length != rhs.length) { this.setEquals(false); return this; } for (int i = 0; i < lhs.length && isEquals; ++i) { append(lhs[i], rhs[i]); } return this; } /** *

Deep comparison of array of byte. Length and all * values are compared.

* *

The method {@link #append(byte, byte)} is used.

* * @param lhs the left hand byte[] * @param rhs the right hand byte[] * @return EqualsBuilder - used to chain calls. */ public EqualsBuilder append(byte[] lhs, byte[] rhs) { if (isEquals == false) { return this; } if (lhs == rhs) { return this; } if (lhs == null || rhs == null) { this.setEquals(false); return this; } if (lhs.length != rhs.length) { this.setEquals(false); return this; } for (int i = 0; i < lhs.length && isEquals; ++i) { append(lhs[i], rhs[i]); } return this; } /** *

Deep comparison of array of double. Length and all * values are compared.

* *

The method {@link #append(double, double)} is used.

* * @param lhs the left hand double[] * @param rhs the right hand double[] * @return EqualsBuilder - used to chain calls. */ public EqualsBuilder append(double[] lhs, double[] rhs) { if (isEquals == false) { return this; } if (lhs == rhs) { return this; } if (lhs == null || rhs == null) { this.setEquals(false); return this; } if (lhs.length != rhs.length) { this.setEquals(false); return this; } for (int i = 0; i < lhs.length && isEquals; ++i) { append(lhs[i], rhs[i]); } return this; } /** *

Deep comparison of array of float. Length and all * values are compared.

* *

The method {@link #append(float, float)} is used.

* * @param lhs the left hand float[] * @param rhs the right hand float[] * @return EqualsBuilder - used to chain calls. */ public EqualsBuilder append(float[] lhs, float[] rhs) { if (isEquals == false) { return this; } if (lhs == rhs) { return this; } if (lhs == null || rhs == null) { this.setEquals(false); return this; } if (lhs.length != rhs.length) { this.setEquals(false); return this; } for (int i = 0; i < lhs.length && isEquals; ++i) { append(lhs[i], rhs[i]); } return this; } /** *

Deep comparison of array of boolean. Length and all * values are compared.

* *

The method {@link #append(boolean, boolean)} is used.

* * @param lhs the left hand boolean[] * @param rhs the right hand boolean[] * @return EqualsBuilder - used to chain calls. */ public EqualsBuilder append(boolean[] lhs, boolean[] rhs) { if (isEquals == false) { return this; } if (lhs == rhs) { return this; } if (lhs == null || rhs == null) { this.setEquals(false); return this; } if (lhs.length != rhs.length) { this.setEquals(false); return this; } for (int i = 0; i < lhs.length && isEquals; ++i) { append(lhs[i], rhs[i]); } return this; } /** *

Returns true if the fields that have been checked * are all equal.

* * @return boolean */ public boolean isEquals() { return this.isEquals; } /** * Sets the isEquals value. * * @param isEquals The value to set. * @since 2.1 */ protected void setEquals(boolean isEquals) { this.isEquals = isEquals; } /** * Reset the EqualsBuilder so you can use the same object again * @since 2.5 */ public void reset() { this.isEquals = true; } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/builder/HashCodeBuilder.java100644 0 0 104421 11513702444 26250 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.builder; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.Collection; import java.util.HashSet; import java.util.Set; import org.apache.commons.lang.ArrayUtils; /** *

* Assists in implementing {@link Object#hashCode()} methods. *

* *

* This class enables a good hashCode method to be built for any class. It follows the rules laid out in * the book Effective Java by Joshua Bloch. Writing a * good hashCode method is actually quite difficult. This class aims to simplify the process. *

* *

* The following is the approach taken. When appending a data field, the current total is multiplied by the * multiplier then a relevant value * for that data type is added. For example, if the current hashCode is 17, and the multiplier is 37, then * appending the integer 45 will create a hashcode of 674, namely 17 * 37 + 45. *

* *

* All relevant fields from the object should be included in the hashCode method. Derived fields may be * excluded. In general, any field used in the equals method must be used in the hashCode * method. *

* *

* To use this class write code as follows: *

* *
 * public class Person {
 *   String name;
 *   int age;
 *   boolean smoker;
 *   ...
 *
 *   public int hashCode() {
 *     // you pick a hard-coded, randomly chosen, non-zero, odd number
 *     // ideally different for each class
 *     return new HashCodeBuilder(17, 37).
 *       append(name).
 *       append(age).
 *       append(smoker).
 *       toHashCode();
 *   }
 * }
 * 
* *

* If required, the superclass hashCode() can be added using {@link #appendSuper}. *

* *

* Alternatively, there is a method that uses reflection to determine the fields to test. Because these fields are * usually private, the method, reflectionHashCode, uses AccessibleObject.setAccessible * to change the visibility of the fields. This will fail under a security manager, unless the appropriate permissions * are set up correctly. It is also slower than testing explicitly. *

* *

* A typical invocation for this method would look like: *

* *
 * public int hashCode() {
 *   return HashCodeBuilder.reflectionHashCode(this);
 * }
 * 
* * @author Apache Software Foundation * @author Gary Gregory * @author Pete Gieser * @since 1.0 * @version $Id: HashCodeBuilder.java 1057009 2011-01-09 19:48:06Z niallp $ */ public class HashCodeBuilder { /** *

* A registry of objects used by reflection methods to detect cyclical object references and avoid infinite loops. *

* * @since 2.3 */ private static final ThreadLocal REGISTRY = new ThreadLocal(); /* * N.B. we cannot store the actual objects in a HashSet, as that would use the very hashCode() * we are in the process of calculating. * * So we generate a one-to-one mapping from the original object to a new object. * * Now HashSet uses equals() to determine if two elements with the same hashcode really * are equal, so we also need to ensure that the replacement objects are only equal * if the original objects are identical. * * The original implementation (2.4 and before) used the System.indentityHashCode() * method - however this is not guaranteed to generate unique ids (e.g. LANG-459) * * We now use the IDKey helper class (adapted from org.apache.axis.utils.IDKey) * to disambiguate the duplicate ids. */ /** *

* Returns the registry of objects being traversed by the reflection methods in the current thread. *

* * @return Set the registry of objects being traversed * @since 2.3 */ static Set getRegistry() { return (Set) REGISTRY.get(); } /** *

* Returns true if the registry contains the given object. Used by the reflection methods to avoid * infinite loops. *

* * @param value * The object to lookup in the registry. * @return boolean true if the registry contains the given object. * @since 2.3 */ static boolean isRegistered(Object value) { Set registry = getRegistry(); return registry != null && registry.contains(new IDKey(value)); } /** *

* Appends the fields and values defined by the given object of the given Class. *

* * @param object * the object to append details of * @param clazz * the class to append details of * @param builder * the builder to append to * @param useTransients * whether to use transient fields * @param excludeFields * Collection of String field names to exclude from use in calculation of hash code */ private static void reflectionAppend(Object object, Class clazz, HashCodeBuilder builder, boolean useTransients, String[] excludeFields) { if (isRegistered(object)) { return; } try { register(object); Field[] fields = clazz.getDeclaredFields(); AccessibleObject.setAccessible(fields, true); for (int i = 0; i < fields.length; i++) { Field field = fields[i]; if (!ArrayUtils.contains(excludeFields, field.getName()) && (field.getName().indexOf('$') == -1) && (useTransients || !Modifier.isTransient(field.getModifiers())) && (!Modifier.isStatic(field.getModifiers()))) { try { Object fieldValue = field.get(object); builder.append(fieldValue); } catch (IllegalAccessException e) { // this can't happen. Would get a Security exception instead // throw a runtime exception in case the impossible happens. throw new InternalError("Unexpected IllegalAccessException"); } } } } finally { unregister(object); } } /** *

* This method uses reflection to build a valid hash code. *

* *

* It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is * also not as efficient as testing explicitly. *

* *

* Transient members will be not be used, as they are likely derived fields, and not part of the value of the * Object. *

* *

* Static fields will not be tested. Superclass fields will be included. *

* *

* Two randomly chosen, non-zero, odd numbers must be passed in. Ideally these should be different for each class, * however this is not vital. Prime numbers are preferred, especially for the multiplier. *

* * @param initialNonZeroOddNumber * a non-zero, odd number used as the initial value * @param multiplierNonZeroOddNumber * a non-zero, odd number used as the multiplier * @param object * the Object to create a hashCode for * @return int hash code * @throws IllegalArgumentException * if the Object is null * @throws IllegalArgumentException * if the number is zero or even */ public static int reflectionHashCode(int initialNonZeroOddNumber, int multiplierNonZeroOddNumber, Object object) { return reflectionHashCode(initialNonZeroOddNumber, multiplierNonZeroOddNumber, object, false, null, null); } /** *

* This method uses reflection to build a valid hash code. *

* *

* It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is * also not as efficient as testing explicitly. *

* *

* If the TestTransients parameter is set to true, transient members will be tested, otherwise they * are ignored, as they are likely derived fields, and not part of the value of the Object. *

* *

* Static fields will not be tested. Superclass fields will be included. *

* *

* Two randomly chosen, non-zero, odd numbers must be passed in. Ideally these should be different for each class, * however this is not vital. Prime numbers are preferred, especially for the multiplier. *

* * @param initialNonZeroOddNumber * a non-zero, odd number used as the initial value * @param multiplierNonZeroOddNumber * a non-zero, odd number used as the multiplier * @param object * the Object to create a hashCode for * @param testTransients * whether to include transient fields * @return int hash code * @throws IllegalArgumentException * if the Object is null * @throws IllegalArgumentException * if the number is zero or even */ public static int reflectionHashCode(int initialNonZeroOddNumber, int multiplierNonZeroOddNumber, Object object, boolean testTransients) { return reflectionHashCode(initialNonZeroOddNumber, multiplierNonZeroOddNumber, object, testTransients, null, null); } /** * Calls {@link #reflectionHashCode(int, int, Object, boolean, Class, String[])} with excludeFields set to * null. * * @param initialNonZeroOddNumber * a non-zero, odd number used as the initial value * @param multiplierNonZeroOddNumber * a non-zero, odd number used as the multiplier * @param object * the Object to create a hashCode for * @param testTransients * whether to include transient fields * @param reflectUpToClass * the superclass to reflect up to (inclusive), may be null * @return int hash code */ public static int reflectionHashCode(int initialNonZeroOddNumber, int multiplierNonZeroOddNumber, Object object, boolean testTransients, Class reflectUpToClass) { return reflectionHashCode(initialNonZeroOddNumber, multiplierNonZeroOddNumber, object, testTransients, reflectUpToClass, null); } /** *

* This method uses reflection to build a valid hash code. *

* *

* It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is * also not as efficient as testing explicitly. *

* *

* If the TestTransients parameter is set to true, transient members will be tested, otherwise they * are ignored, as they are likely derived fields, and not part of the value of the Object. *

* *

* Static fields will not be included. Superclass fields will be included up to and including the specified * superclass. A null superclass is treated as java.lang.Object. *

* *

* Two randomly chosen, non-zero, odd numbers must be passed in. Ideally these should be different for each class, * however this is not vital. Prime numbers are preferred, especially for the multiplier. *

* * @param initialNonZeroOddNumber * a non-zero, odd number used as the initial value * @param multiplierNonZeroOddNumber * a non-zero, odd number used as the multiplier * @param object * the Object to create a hashCode for * @param testTransients * whether to include transient fields * @param reflectUpToClass * the superclass to reflect up to (inclusive), may be null * @param excludeFields * array of field names to exclude from use in calculation of hash code * @return int hash code * @throws IllegalArgumentException * if the Object is null * @throws IllegalArgumentException * if the number is zero or even * @since 2.0 */ public static int reflectionHashCode(int initialNonZeroOddNumber, int multiplierNonZeroOddNumber, Object object, boolean testTransients, Class reflectUpToClass, String[] excludeFields) { if (object == null) { throw new IllegalArgumentException("The object to build a hash code for must not be null"); } HashCodeBuilder builder = new HashCodeBuilder(initialNonZeroOddNumber, multiplierNonZeroOddNumber); Class clazz = object.getClass(); reflectionAppend(object, clazz, builder, testTransients, excludeFields); while (clazz.getSuperclass() != null && clazz != reflectUpToClass) { clazz = clazz.getSuperclass(); reflectionAppend(object, clazz, builder, testTransients, excludeFields); } return builder.toHashCode(); } /** *

* This method uses reflection to build a valid hash code. *

* *

* This constructor uses two hard coded choices for the constants needed to build a hash code. *

* *

* It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is * also not as efficient as testing explicitly. *

* *

* Transient members will be not be used, as they are likely derived fields, and not part of the value of the * Object. *

* *

* Static fields will not be tested. Superclass fields will be included. *

* * @param object * the Object to create a hashCode for * @return int hash code * @throws IllegalArgumentException * if the object is null */ public static int reflectionHashCode(Object object) { return reflectionHashCode(17, 37, object, false, null, null); } /** *

* This method uses reflection to build a valid hash code. *

* *

* This constructor uses two hard coded choices for the constants needed to build a hash code. *

* *

* It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is * also not as efficient as testing explicitly. *

* *

* If the TestTransients parameter is set to true, transient members will be tested, otherwise they * are ignored, as they are likely derived fields, and not part of the value of the Object. *

* *

* Static fields will not be tested. Superclass fields will be included. *

* * @param object * the Object to create a hashCode for * @param testTransients * whether to include transient fields * @return int hash code * @throws IllegalArgumentException * if the object is null */ public static int reflectionHashCode(Object object, boolean testTransients) { return reflectionHashCode(17, 37, object, testTransients, null, null); } /** *

* This method uses reflection to build a valid hash code. *

* *

* This constructor uses two hard coded choices for the constants needed to build a hash code. *

* *

* It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is * also not as efficient as testing explicitly. *

* *

* Transient members will be not be used, as they are likely derived fields, and not part of the value of the * Object. *

* *

* Static fields will not be tested. Superclass fields will be included. *

* * @param object * the Object to create a hashCode for * @param excludeFields * Collection of String field names to exclude from use in calculation of hash code * @return int hash code * @throws IllegalArgumentException * if the object is null */ public static int reflectionHashCode(Object object, Collection /* String */excludeFields) { return reflectionHashCode(object, ReflectionToStringBuilder.toNoNullStringArray(excludeFields)); } // ------------------------------------------------------------------------- /** *

* This method uses reflection to build a valid hash code. *

* *

* This constructor uses two hard coded choices for the constants needed to build a hash code. *

* *

* It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is * also not as efficient as testing explicitly. *

* *

* Transient members will be not be used, as they are likely derived fields, and not part of the value of the * Object. *

* *

* Static fields will not be tested. Superclass fields will be included. *

* * @param object * the Object to create a hashCode for * @param excludeFields * array of field names to exclude from use in calculation of hash code * @return int hash code * @throws IllegalArgumentException * if the object is null */ public static int reflectionHashCode(Object object, String[] excludeFields) { return reflectionHashCode(17, 37, object, false, null, excludeFields); } /** *

* Registers the given object. Used by the reflection methods to avoid infinite loops. *

* * @param value * The object to register. */ static void register(Object value) { synchronized (HashCodeBuilder.class) { if (getRegistry() == null) { REGISTRY.set(new HashSet()); } } getRegistry().add(new IDKey(value)); } /** *

* Unregisters the given object. *

* *

* Used by the reflection methods to avoid infinite loops. * * @param value * The object to unregister. * @since 2.3 */ static void unregister(Object value) { Set registry = getRegistry(); if (registry != null) { registry.remove(new IDKey(value)); synchronized (HashCodeBuilder.class) { //read again registry = getRegistry(); if (registry != null && registry.isEmpty()) { REGISTRY.set(null); } } } } /** * Constant to use in building the hashCode. */ private final int iConstant; /** * Running total of the hashCode. */ private int iTotal = 0; /** *

* Uses two hard coded choices for the constants needed to build a hashCode. *

*/ public HashCodeBuilder() { iConstant = 37; iTotal = 17; } /** *

* Two randomly chosen, non-zero, odd numbers must be passed in. Ideally these should be different for each class, * however this is not vital. *

* *

* Prime numbers are preferred, especially for the multiplier. *

* * @param initialNonZeroOddNumber * a non-zero, odd number used as the initial value * @param multiplierNonZeroOddNumber * a non-zero, odd number used as the multiplier * @throws IllegalArgumentException * if the number is zero or even */ public HashCodeBuilder(int initialNonZeroOddNumber, int multiplierNonZeroOddNumber) { if (initialNonZeroOddNumber == 0) { throw new IllegalArgumentException("HashCodeBuilder requires a non zero initial value"); } if (initialNonZeroOddNumber % 2 == 0) { throw new IllegalArgumentException("HashCodeBuilder requires an odd initial value"); } if (multiplierNonZeroOddNumber == 0) { throw new IllegalArgumentException("HashCodeBuilder requires a non zero multiplier"); } if (multiplierNonZeroOddNumber % 2 == 0) { throw new IllegalArgumentException("HashCodeBuilder requires an odd multiplier"); } iConstant = multiplierNonZeroOddNumber; iTotal = initialNonZeroOddNumber; } /** *

* Append a hashCode for a boolean. *

*

* This adds 1 when true, and 0 when false to the hashCode. *

*

* This is in contrast to the standard java.lang.Boolean.hashCode handling, which computes * a hashCode value of 1231 for java.lang.Boolean instances * that represent true or 1237 for java.lang.Boolean instances * that represent false. *

*

* This is in accordance with the Effective Java design. *

* * @param value * the boolean to add to the hashCode * @return this */ public HashCodeBuilder append(boolean value) { iTotal = iTotal * iConstant + (value ? 0 : 1); return this; } /** *

* Append a hashCode for a boolean array. *

* * @param array * the array to add to the hashCode * @return this */ public HashCodeBuilder append(boolean[] array) { if (array == null) { iTotal = iTotal * iConstant; } else { for (int i = 0; i < array.length; i++) { append(array[i]); } } return this; } // ------------------------------------------------------------------------- /** *

* Append a hashCode for a byte. *

* * @param value * the byte to add to the hashCode * @return this */ public HashCodeBuilder append(byte value) { iTotal = iTotal * iConstant + value; return this; } // ------------------------------------------------------------------------- /** *

* Append a hashCode for a byte array. *

* * @param array * the array to add to the hashCode * @return this */ public HashCodeBuilder append(byte[] array) { if (array == null) { iTotal = iTotal * iConstant; } else { for (int i = 0; i < array.length; i++) { append(array[i]); } } return this; } /** *

* Append a hashCode for a char. *

* * @param value * the char to add to the hashCode * @return this */ public HashCodeBuilder append(char value) { iTotal = iTotal * iConstant + value; return this; } /** *

* Append a hashCode for a char array. *

* * @param array * the array to add to the hashCode * @return this */ public HashCodeBuilder append(char[] array) { if (array == null) { iTotal = iTotal * iConstant; } else { for (int i = 0; i < array.length; i++) { append(array[i]); } } return this; } /** *

* Append a hashCode for a double. *

* * @param value * the double to add to the hashCode * @return this */ public HashCodeBuilder append(double value) { return append(Double.doubleToLongBits(value)); } /** *

* Append a hashCode for a double array. *

* * @param array * the array to add to the hashCode * @return this */ public HashCodeBuilder append(double[] array) { if (array == null) { iTotal = iTotal * iConstant; } else { for (int i = 0; i < array.length; i++) { append(array[i]); } } return this; } /** *

* Append a hashCode for a float. *

* * @param value * the float to add to the hashCode * @return this */ public HashCodeBuilder append(float value) { iTotal = iTotal * iConstant + Float.floatToIntBits(value); return this; } /** *

* Append a hashCode for a float array. *

* * @param array * the array to add to the hashCode * @return this */ public HashCodeBuilder append(float[] array) { if (array == null) { iTotal = iTotal * iConstant; } else { for (int i = 0; i < array.length; i++) { append(array[i]); } } return this; } /** *

* Append a hashCode for an int. *

* * @param value * the int to add to the hashCode * @return this */ public HashCodeBuilder append(int value) { iTotal = iTotal * iConstant + value; return this; } /** *

* Append a hashCode for an int array. *

* * @param array * the array to add to the hashCode * @return this */ public HashCodeBuilder append(int[] array) { if (array == null) { iTotal = iTotal * iConstant; } else { for (int i = 0; i < array.length; i++) { append(array[i]); } } return this; } /** *

* Append a hashCode for a long. *

* * @param value * the long to add to the hashCode * @return this */ // NOTE: This method uses >> and not >>> as Effective Java and // Long.hashCode do. Ideally we should switch to >>> at // some stage. There are backwards compat issues, so // that will have to wait for the time being. cf LANG-342. public HashCodeBuilder append(long value) { iTotal = iTotal * iConstant + ((int) (value ^ (value >> 32))); return this; } /** *

* Append a hashCode for a long array. *

* * @param array * the array to add to the hashCode * @return this */ public HashCodeBuilder append(long[] array) { if (array == null) { iTotal = iTotal * iConstant; } else { for (int i = 0; i < array.length; i++) { append(array[i]); } } return this; } /** *

* Append a hashCode for an Object. *

* * @param object * the Object to add to the hashCode * @return this */ public HashCodeBuilder append(Object object) { if (object == null) { iTotal = iTotal * iConstant; } else { if(object.getClass().isArray()) { // 'Switch' on type of array, to dispatch to the correct handler // This handles multi dimensional arrays if (object instanceof long[]) { append((long[]) object); } else if (object instanceof int[]) { append((int[]) object); } else if (object instanceof short[]) { append((short[]) object); } else if (object instanceof char[]) { append((char[]) object); } else if (object instanceof byte[]) { append((byte[]) object); } else if (object instanceof double[]) { append((double[]) object); } else if (object instanceof float[]) { append((float[]) object); } else if (object instanceof boolean[]) { append((boolean[]) object); } else { // Not an array of primitives append((Object[]) object); } } else { iTotal = iTotal * iConstant + object.hashCode(); } } return this; } /** *

* Append a hashCode for an Object array. *

* * @param array * the array to add to the hashCode * @return this */ public HashCodeBuilder append(Object[] array) { if (array == null) { iTotal = iTotal * iConstant; } else { for (int i = 0; i < array.length; i++) { append(array[i]); } } return this; } /** *

* Append a hashCode for a short. *

* * @param value * the short to add to the hashCode * @return this */ public HashCodeBuilder append(short value) { iTotal = iTotal * iConstant + value; return this; } /** *

* Append a hashCode for a short array. *

* * @param array * the array to add to the hashCode * @return this */ public HashCodeBuilder append(short[] array) { if (array == null) { iTotal = iTotal * iConstant; } else { for (int i = 0; i < array.length; i++) { append(array[i]); } } return this; } /** *

* Adds the result of super.hashCode() to this builder. *

* * @param superHashCode * the result of calling super.hashCode() * @return this HashCodeBuilder, used to chain calls. * @since 2.0 */ public HashCodeBuilder appendSuper(int superHashCode) { iTotal = iTotal * iConstant + superHashCode; return this; } /** *

* Return the computed hashCode. *

* * @return hashCode based on the fields appended */ public int toHashCode() { return iTotal; } /** *

* The computed hashCode from toHashCode() is returned due to the likelyhood * of bugs in mis-calling toHashCode() and the unlikelyness of it mattering what the hashCode for * HashCodeBuilder itself is. * * @return hashCode based on the fields appended * @since 2.5 */ public int hashCode() { return toHashCode(); } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/builder/IDKey.java100644 0 0 4714 11513702444 24174 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.commons.lang.builder; // adapted from org.apache.axis.utils.IDKey /** * Wrap an identity key (System.identityHashCode()) * so that an object can only be equal() to itself. * * This is necessary to disambiguate the occasional duplicate * identityHashCodes that can occur. * * @author Apache Software Foundation */ final class IDKey { private final Object value; private final int id; /** * Constructor for IDKey * @param _value The value */ public IDKey(Object _value) { // This is the Object hashcode id = System.identityHashCode(_value); // There have been some cases (LANG-459) that return the // same identity hash code for different objects. So // the value is also added to disambiguate these cases. value = _value; } /** * returns hashcode - i.e. the system identity hashcode. * @return the hashcode */ public int hashCode() { return id; } /** * checks if instances are equal * @param other The other object to compare to * @return if the instances are for the same object */ public boolean equals(Object other) { if (!(other instanceof IDKey)) { return false; } IDKey idKey = (IDKey) other; if (id != idKey.id) { return false; } // Note that identity equals is used. return value == idKey.value; } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/builder/package.html100644 0 0 2231 11513702444 24635 0ustar 0 0 Assists in creating consistent equals(Object), toString(), hashCode(), and compareTo(Object) methods. @see java.lang.Object#equals(Object) @see java.lang.Object#toString() @see java.lang.Object#hashCode() @see java.lang.Comparable#compareTo(Object) @since 1.0

These classes are not thread-safe.

commons-lang-2.6-src/src/main/java/org/apache/commons/lang/builder/ReflectionToStringBuilder.java100644 0 0 65601 11513702444 30344 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.builder; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.ClassUtils; /** *

* Assists in implementing {@link Object#toString()} methods using reflection. *

* *

* This class uses reflection to determine the fields to append. Because these fields are usually private, the class * uses {@link java.lang.reflect.AccessibleObject#setAccessible(java.lang.reflect.AccessibleObject[], boolean)} to * change the visibility of the fields. This will fail under a security manager, unless the appropriate permissions are * set up correctly. *

* *

* A typical invocation for this method would look like: *

* *
 * public String toString() {
 *   return ReflectionToStringBuilder.toString(this);
 * }
* * * *

* You can also use the builder to debug 3rd party objects: *

* *
 * System.out.println("An object: " + ReflectionToStringBuilder.toString(anObject));
* * * *

* A subclass can control field output by overriding the methods: *

    *
  • {@link #accept(java.lang.reflect.Field)}
  • *
  • {@link #getValue(java.lang.reflect.Field)}
  • *
*

*

* For example, this method does not include the password field in the returned * String: *

* *
 * public String toString() {
 *     return (new ReflectionToStringBuilder(this) {
 *         protected boolean accept(Field f) {
 *             return super.accept(f) && !f.getName().equals("password");
 *         }
 *     }).toString();
 * }
* * * *

* The exact format of the toString is determined by the {@link ToStringStyle} passed into the * constructor. *

* * @author Apache Software Foundation * @author Gary Gregory * @author Pete Gieser * @since 2.0 * @version $Id: ReflectionToStringBuilder.java 905636 2010-02-02 14:03:32Z niallp $ */ public class ReflectionToStringBuilder extends ToStringBuilder { /** *

* Builds a toString value using the default ToStringStyle through reflection. *

* *

* It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is * also not as efficient as testing explicitly. *

* *

* Transient members will be not be included, as they are likely derived. Static fields will not be included. * Superclass fields will be appended. *

* * @param object * the Object to be output * @return the String result * @throws IllegalArgumentException * if the Object is null */ public static String toString(Object object) { return toString(object, null, false, false, null); } /** *

* Builds a toString value through reflection. *

* *

* It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is * also not as efficient as testing explicitly. *

* *

* Transient members will be not be included, as they are likely derived. Static fields will not be included. * Superclass fields will be appended. *

* *

* If the style is null, the default ToStringStyle is used. *

* * @param object * the Object to be output * @param style * the style of the toString to create, may be null * @return the String result * @throws IllegalArgumentException * if the Object or ToStringStyle is null */ public static String toString(Object object, ToStringStyle style) { return toString(object, style, false, false, null); } /** *

* Builds a toString value through reflection. *

* *

* It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is * also not as efficient as testing explicitly. *

* *

* If the outputTransients is true, transient members will be output, otherwise they * are ignored, as they are likely derived fields, and not part of the value of the Object. *

* *

* Static fields will not be included. Superclass fields will be appended. *

* *

* If the style is null, the default ToStringStyle is used. *

* * @param object * the Object to be output * @param style * the style of the toString to create, may be null * @param outputTransients * whether to include transient fields * @return the String result * @throws IllegalArgumentException * if the Object is null */ public static String toString(Object object, ToStringStyle style, boolean outputTransients) { return toString(object, style, outputTransients, false, null); } /** *

* Builds a toString value through reflection. *

* *

* It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is * also not as efficient as testing explicitly. *

* *

* If the outputTransients is true, transient fields will be output, otherwise they * are ignored, as they are likely derived fields, and not part of the value of the Object. *

* *

* If the outputStatics is true, static fields will be output, otherwise they are * ignored. *

* *

* Static fields will not be included. Superclass fields will be appended. *

* *

* If the style is null, the default ToStringStyle is used. *

* * @param object * the Object to be output * @param style * the style of the toString to create, may be null * @param outputTransients * whether to include transient fields * @param outputStatics * whether to include transient fields * @return the String result * @throws IllegalArgumentException * if the Object is null * @since 2.1 */ public static String toString(Object object, ToStringStyle style, boolean outputTransients, boolean outputStatics) { return toString(object, style, outputTransients, outputStatics, null); } /** *

* Builds a toString value through reflection. *

* *

* It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is * also not as efficient as testing explicitly. *

* *

* If the outputTransients is true, transient fields will be output, otherwise they * are ignored, as they are likely derived fields, and not part of the value of the Object. *

* *

* If the outputStatics is true, static fields will be output, otherwise they are * ignored. *

* *

* Superclass fields will be appended up to and including the specified superclass. A null superclass is treated as * java.lang.Object. *

* *

* If the style is null, the default ToStringStyle is used. *

* * @param object * the Object to be output * @param style * the style of the toString to create, may be null * @param outputTransients * whether to include transient fields * @param outputStatics * whether to include static fields * @param reflectUpToClass * the superclass to reflect up to (inclusive), may be null * @return the String result * @throws IllegalArgumentException * if the Object is null * @since 2.1 */ public static String toString(Object object, ToStringStyle style, boolean outputTransients, boolean outputStatics, Class reflectUpToClass) { return new ReflectionToStringBuilder(object, style, null, reflectUpToClass, outputTransients, outputStatics) .toString(); } /** *

* Builds a toString value through reflection. *

* *

* It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will * throw a security exception if run under a security manager, if the permissions are not set up correctly. It is * also not as efficient as testing explicitly. *

* *

* If the outputTransients is true, transient members will be output, otherwise they * are ignored, as they are likely derived fields, and not part of the value of the Object. *

* *

* Static fields will not be included. Superclass fields will be appended up to and including the specified * superclass. A null superclass is treated as java.lang.Object. *

* *

* If the style is null, the default ToStringStyle is used. *

* * @deprecated Use {@link #toString(Object,ToStringStyle,boolean,boolean,Class)} * * @param object * the Object to be output * @param style * the style of the toString to create, may be null * @param outputTransients * whether to include transient fields * @param reflectUpToClass * the superclass to reflect up to (inclusive), may be null * @return the String result * @throws IllegalArgumentException * if the Object is null * @since 2.0 */ public static String toString(Object object, ToStringStyle style, boolean outputTransients, Class reflectUpToClass) { return new ReflectionToStringBuilder(object, style, null, reflectUpToClass, outputTransients).toString(); } /** * Builds a String for a toString method excluding the given field name. * * @param object * The object to "toString". * @param excludeFieldName * The field name to exclude * @return The toString value. */ public static String toStringExclude(Object object, final String excludeFieldName) { return toStringExclude(object, new String[]{excludeFieldName}); } /** * Builds a String for a toString method excluding the given field names. * * @param object * The object to "toString". * @param excludeFieldNames * The field names to exclude. Null excludes nothing. * @return The toString value. */ public static String toStringExclude(Object object, Collection /*String*/ excludeFieldNames) { return toStringExclude(object, toNoNullStringArray(excludeFieldNames)); } /** * Converts the given Collection into an array of Strings. The returned array does not contain null * entries. Note that {@link Arrays#sort(Object[])} will throw an {@link NullPointerException} if an array element * is null. * * @param collection * The collection to convert * @return A new array of Strings. */ static String[] toNoNullStringArray(Collection collection) { if (collection == null) { return ArrayUtils.EMPTY_STRING_ARRAY; } return toNoNullStringArray(collection.toArray()); } /** * Returns a new array of Strings without null elements. Internal method used to normalize exclude lists * (arrays and collections). Note that {@link Arrays#sort(Object[])} will throw an {@link NullPointerException} * if an array element is null. * * @param array * The array to check * @return The given array or a new array without null. */ static String[] toNoNullStringArray(Object[] array) { ArrayList list = new ArrayList(array.length); for (int i = 0; i < array.length; i++) { Object e = array[i]; if (e != null) { list.add(e.toString()); } } return (String[]) list.toArray(ArrayUtils.EMPTY_STRING_ARRAY); } /** * Builds a String for a toString method excluding the given field names. * * @param object * The object to "toString". * @param excludeFieldNames * The field names to exclude * @return The toString value. */ public static String toStringExclude(Object object, String[] excludeFieldNames) { return new ReflectionToStringBuilder(object).setExcludeFieldNames(excludeFieldNames).toString(); } /** * Whether or not to append static fields. */ private boolean appendStatics = false; /** * Whether or not to append transient fields. */ private boolean appendTransients = false; /** * Which field names to exclude from output. Intended for fields like "password". */ private String[] excludeFieldNames; /** * The last super class to stop appending fields for. */ private Class upToClass = null; /** *

* Constructor. *

* *

* This constructor outputs using the default style set with setDefaultStyle. *

* * @param object * the Object to build a toString for, must not be null * @throws IllegalArgumentException * if the Object passed in is null */ public ReflectionToStringBuilder(Object object) { super(object); } /** *

* Constructor. *

* *

* If the style is null, the default style is used. *

* * @param object * the Object to build a toString for, must not be null * @param style * the style of the toString to create, may be null * @throws IllegalArgumentException * if the Object passed in is null */ public ReflectionToStringBuilder(Object object, ToStringStyle style) { super(object, style); } /** *

* Constructor. *

* *

* If the style is null, the default style is used. *

* *

* If the buffer is null, a new one is created. *

* * @param object * the Object to build a toString for * @param style * the style of the toString to create, may be null * @param buffer * the StringBuffer to populate, may be null * @throws IllegalArgumentException * if the Object passed in is null */ public ReflectionToStringBuilder(Object object, ToStringStyle style, StringBuffer buffer) { super(object, style, buffer); } /** * Constructor. * * @deprecated Use {@link #ReflectionToStringBuilder(Object,ToStringStyle,StringBuffer,Class,boolean,boolean)}. * * @param object * the Object to build a toString for * @param style * the style of the toString to create, may be null * @param buffer * the StringBuffer to populate, may be null * @param reflectUpToClass * the superclass to reflect up to (inclusive), may be null * @param outputTransients * whether to include transient fields */ public ReflectionToStringBuilder(Object object, ToStringStyle style, StringBuffer buffer, Class reflectUpToClass, boolean outputTransients) { super(object, style, buffer); this.setUpToClass(reflectUpToClass); this.setAppendTransients(outputTransients); } /** * Constructor. * * @param object * the Object to build a toString for * @param style * the style of the toString to create, may be null * @param buffer * the StringBuffer to populate, may be null * @param reflectUpToClass * the superclass to reflect up to (inclusive), may be null * @param outputTransients * whether to include transient fields * @param outputStatics * whether to include static fields * @since 2.1 */ public ReflectionToStringBuilder(Object object, ToStringStyle style, StringBuffer buffer, Class reflectUpToClass, boolean outputTransients, boolean outputStatics) { super(object, style, buffer); this.setUpToClass(reflectUpToClass); this.setAppendTransients(outputTransients); this.setAppendStatics(outputStatics); } /** * Returns whether or not to append the given Field. *
    *
  • Transient fields are appended only if {@link #isAppendTransients()} returns true. *
  • Static fields are appended only if {@link #isAppendStatics()} returns true. *
  • Inner class fields are not appened.
  • *
* * @param field * The Field to test. * @return Whether or not to append the given Field. */ protected boolean accept(Field field) { if (field.getName().indexOf(ClassUtils.INNER_CLASS_SEPARATOR_CHAR) != -1) { // Reject field from inner class. return false; } if (Modifier.isTransient(field.getModifiers()) && !this.isAppendTransients()) { // Reject transient fields. return false; } if (Modifier.isStatic(field.getModifiers()) && !this.isAppendStatics()) { // Reject static fields. return false; } if (this.getExcludeFieldNames() != null && Arrays.binarySearch(this.getExcludeFieldNames(), field.getName()) >= 0) { // Reject fields from the getExcludeFieldNames list. return false; } return true; } /** *

* Appends the fields and values defined by the given object of the given Class. *

* *

* If a cycle is detected as an object is "toString()'ed", such an object is rendered as if * Object.toString() had been called and not implemented by the object. *

* * @param clazz * The class of object parameter */ protected void appendFieldsIn(Class clazz) { if (clazz.isArray()) { this.reflectionAppendArray(this.getObject()); return; } Field[] fields = clazz.getDeclaredFields(); AccessibleObject.setAccessible(fields, true); for (int i = 0; i < fields.length; i++) { Field field = fields[i]; String fieldName = field.getName(); if (this.accept(field)) { try { // Warning: Field.get(Object) creates wrappers objects // for primitive types. Object fieldValue = this.getValue(field); this.append(fieldName, fieldValue); } catch (IllegalAccessException ex) { //this can't happen. Would get a Security exception // instead //throw a runtime exception in case the impossible // happens. throw new InternalError("Unexpected IllegalAccessException: " + ex.getMessage()); } } } } /** * @return Returns the excludeFieldNames. */ public String[] getExcludeFieldNames() { return this.excludeFieldNames; } /** *

* Gets the last super class to stop appending fields for. *

* * @return The last super class to stop appending fields for. */ public Class getUpToClass() { return this.upToClass; } /** *

* Calls java.lang.reflect.Field.get(Object). *

* * @param field * The Field to query. * @return The Object from the given Field. * * @throws IllegalArgumentException * see {@link java.lang.reflect.Field#get(Object)} * @throws IllegalAccessException * see {@link java.lang.reflect.Field#get(Object)} * * @see java.lang.reflect.Field#get(Object) */ protected Object getValue(Field field) throws IllegalArgumentException, IllegalAccessException { return field.get(this.getObject()); } /** *

* Gets whether or not to append static fields. *

* * @return Whether or not to append static fields. * @since 2.1 */ public boolean isAppendStatics() { return this.appendStatics; } /** *

* Gets whether or not to append transient fields. *

* * @return Whether or not to append transient fields. */ public boolean isAppendTransients() { return this.appendTransients; } /** *

* Append to the toString an Object array. *

* * @param array * the array to add to the toString * @return this */ public ToStringBuilder reflectionAppendArray(Object array) { this.getStyle().reflectionAppendArrayDetail(this.getStringBuffer(), null, array); return this; } /** *

* Sets whether or not to append static fields. *

* * @param appendStatics * Whether or not to append static fields. * @since 2.1 */ public void setAppendStatics(boolean appendStatics) { this.appendStatics = appendStatics; } /** *

* Sets whether or not to append transient fields. *

* * @param appendTransients * Whether or not to append transient fields. */ public void setAppendTransients(boolean appendTransients) { this.appendTransients = appendTransients; } /** * Sets the field names to exclude. * * @param excludeFieldNamesParam * The excludeFieldNames to excluding from toString or null. * @return this */ public ReflectionToStringBuilder setExcludeFieldNames(String[] excludeFieldNamesParam) { if (excludeFieldNamesParam == null) { this.excludeFieldNames = null; } else { this.excludeFieldNames = toNoNullStringArray(excludeFieldNamesParam); Arrays.sort(this.excludeFieldNames); } return this; } /** *

* Sets the last super class to stop appending fields for. *

* * @param clazz * The last super class to stop appending fields for. */ public void setUpToClass(Class clazz) { if (clazz != null) { Object object = getObject(); if (object != null && clazz.isInstance(object) == false) { throw new IllegalArgumentException("Specified class is not a superclass of the object"); } } this.upToClass = clazz; } /** *

* Gets the String built by this builder. *

* * @return the built string */ public String toString() { if (this.getObject() == null) { return this.getStyle().getNullText(); } Class clazz = this.getObject().getClass(); this.appendFieldsIn(clazz); while (clazz.getSuperclass() != null && clazz != this.getUpToClass()) { clazz = clazz.getSuperclass(); this.appendFieldsIn(clazz); } return super.toString(); } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/builder/StandardToStringStyle.java100644 0 0 40464 11513702444 27524 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.builder; /** *

Works with {@link ToStringBuilder} to create a toString.

* *

This class is intended to be used as a singleton. * There is no need to instantiate a new style each time. * Simply instantiate the class once, customize the values as required, and * store the result in a public static final variable for the rest of the * program to access.

* * @author Apache Software Foundation * @author Pete Gieser * @author Gary Gregory * @since 1.0 * @version $Id: StandardToStringStyle.java 905636 2010-02-02 14:03:32Z niallp $ */ public class StandardToStringStyle extends ToStringStyle { /** * Required for serialization support. * * @see java.io.Serializable */ private static final long serialVersionUID = 1L; /** *

Constructor.

*/ public StandardToStringStyle() { super(); } //--------------------------------------------------------------------- /** *

Gets whether to use the class name.

* * @return the current useClassName flag */ public boolean isUseClassName() { return super.isUseClassName(); } /** *

Sets whether to use the class name.

* * @param useClassName the new useClassName flag */ public void setUseClassName(boolean useClassName) { super.setUseClassName(useClassName); } //--------------------------------------------------------------------- /** *

Gets whether to output short or long class names.

* * @return the current useShortClassName flag * @since 2.0 */ public boolean isUseShortClassName() { return super.isUseShortClassName(); } /** *

Gets whether to output short or long class names.

* * @return the current shortClassName flag * @deprecated Use {@link #isUseShortClassName()} * Method will be removed in Commons Lang 3.0. */ public boolean isShortClassName() { return super.isUseShortClassName(); } /** *

Sets whether to output short or long class names.

* * @param useShortClassName the new useShortClassName flag * @since 2.0 */ public void setUseShortClassName(boolean useShortClassName) { super.setUseShortClassName(useShortClassName); } /** *

Sets whether to output short or long class names.

* * @param shortClassName the new shortClassName flag * @deprecated Use {@link #setUseShortClassName(boolean)} * Method will be removed in Commons Lang 3.0. */ public void setShortClassName(boolean shortClassName) { super.setUseShortClassName(shortClassName); } //--------------------------------------------------------------------- /** *

Gets whether to use the identity hash code.

* @return the current useIdentityHashCode flag */ public boolean isUseIdentityHashCode() { return super.isUseIdentityHashCode(); } /** *

Sets whether to use the identity hash code.

* * @param useIdentityHashCode the new useIdentityHashCode flag */ public void setUseIdentityHashCode(boolean useIdentityHashCode) { super.setUseIdentityHashCode(useIdentityHashCode); } //--------------------------------------------------------------------- /** *

Gets whether to use the field names passed in.

* * @return the current useFieldNames flag */ public boolean isUseFieldNames() { return super.isUseFieldNames(); } /** *

Sets whether to use the field names passed in.

* * @param useFieldNames the new useFieldNames flag */ public void setUseFieldNames(boolean useFieldNames) { super.setUseFieldNames(useFieldNames); } //--------------------------------------------------------------------- /** *

Gets whether to use full detail when the caller doesn't * specify.

* * @return the current defaultFullDetail flag */ public boolean isDefaultFullDetail() { return super.isDefaultFullDetail(); } /** *

Sets whether to use full detail when the caller doesn't * specify.

* * @param defaultFullDetail the new defaultFullDetail flag */ public void setDefaultFullDetail(boolean defaultFullDetail) { super.setDefaultFullDetail(defaultFullDetail); } //--------------------------------------------------------------------- /** *

Gets whether to output array content detail.

* * @return the current array content detail setting */ public boolean isArrayContentDetail() { return super.isArrayContentDetail(); } /** *

Sets whether to output array content detail.

* * @param arrayContentDetail the new arrayContentDetail flag */ public void setArrayContentDetail(boolean arrayContentDetail) { super.setArrayContentDetail(arrayContentDetail); } //--------------------------------------------------------------------- /** *

Gets the array start text.

* * @return the current array start text */ public String getArrayStart() { return super.getArrayStart(); } /** *

Sets the array start text.

* *

null is accepted, but will be converted * to an empty String.

* * @param arrayStart the new array start text */ public void setArrayStart(String arrayStart) { super.setArrayStart(arrayStart); } //--------------------------------------------------------------------- /** *

Gets the array end text.

* * @return the current array end text */ public String getArrayEnd() { return super.getArrayEnd(); } /** *

Sets the array end text.

* *

null is accepted, but will be converted * to an empty String.

* * @param arrayEnd the new array end text */ public void setArrayEnd(String arrayEnd) { super.setArrayEnd(arrayEnd); } //--------------------------------------------------------------------- /** *

Gets the array separator text.

* * @return the current array separator text */ public String getArraySeparator() { return super.getArraySeparator(); } /** *

Sets the array separator text.

* *

null is accepted, but will be converted * to an empty String.

* * @param arraySeparator the new array separator text */ public void setArraySeparator(String arraySeparator) { super.setArraySeparator(arraySeparator); } //--------------------------------------------------------------------- /** *

Gets the content start text.

* * @return the current content start text */ public String getContentStart() { return super.getContentStart(); } /** *

Sets the content start text.

* *

null is accepted, but will be converted * to an empty String.

* * @param contentStart the new content start text */ public void setContentStart(String contentStart) { super.setContentStart(contentStart); } //--------------------------------------------------------------------- /** *

Gets the content end text.

* * @return the current content end text */ public String getContentEnd() { return super.getContentEnd(); } /** *

Sets the content end text.

* *

null is accepted, but will be converted * to an empty String.

* * @param contentEnd the new content end text */ public void setContentEnd(String contentEnd) { super.setContentEnd(contentEnd); } //--------------------------------------------------------------------- /** *

Gets the field name value separator text.

* * @return the current field name value separator text */ public String getFieldNameValueSeparator() { return super.getFieldNameValueSeparator(); } /** *

Sets the field name value separator text.

* *

null is accepted, but will be converted * to an empty String.

* * @param fieldNameValueSeparator the new field name value separator text */ public void setFieldNameValueSeparator(String fieldNameValueSeparator) { super.setFieldNameValueSeparator(fieldNameValueSeparator); } //--------------------------------------------------------------------- /** *

Gets the field separator text.

* * @return the current field separator text */ public String getFieldSeparator() { return super.getFieldSeparator(); } /** *

Sets the field separator text.

* *

null is accepted, but will be converted * to an empty String.

* * @param fieldSeparator the new field separator text */ public void setFieldSeparator(String fieldSeparator) { super.setFieldSeparator(fieldSeparator); } //--------------------------------------------------------------------- /** *

Gets whether the field separator should be added at the start * of each buffer.

* * @return the fieldSeparatorAtStart flag * @since 2.0 */ public boolean isFieldSeparatorAtStart() { return super.isFieldSeparatorAtStart(); } /** *

Sets whether the field separator should be added at the start * of each buffer.

* * @param fieldSeparatorAtStart the fieldSeparatorAtStart flag * @since 2.0 */ public void setFieldSeparatorAtStart(boolean fieldSeparatorAtStart) { super.setFieldSeparatorAtStart(fieldSeparatorAtStart); } //--------------------------------------------------------------------- /** *

Gets whether the field separator should be added at the end * of each buffer.

* * @return fieldSeparatorAtEnd flag * @since 2.0 */ public boolean isFieldSeparatorAtEnd() { return super.isFieldSeparatorAtEnd(); } /** *

Sets whether the field separator should be added at the end * of each buffer.

* * @param fieldSeparatorAtEnd the fieldSeparatorAtEnd flag * @since 2.0 */ public void setFieldSeparatorAtEnd(boolean fieldSeparatorAtEnd) { super.setFieldSeparatorAtEnd(fieldSeparatorAtEnd); } //--------------------------------------------------------------------- /** *

Gets the text to output when null found.

* * @return the current text to output when null found */ public String getNullText() { return super.getNullText(); } /** *

Sets the text to output when null found.

* *

null is accepted, but will be converted * to an empty String.

* * @param nullText the new text to output when null found */ public void setNullText(String nullText) { super.setNullText(nullText); } //--------------------------------------------------------------------- /** *

Gets the text to output when a Collection, * Map or Array size is output.

* *

This is output before the size value.

* * @return the current start of size text */ public String getSizeStartText() { return super.getSizeStartText(); } /** *

Sets the start text to output when a Collection, * Map or Array size is output.

* *

This is output before the size value.

* *

null is accepted, but will be converted to * an empty String.

* * @param sizeStartText the new start of size text */ public void setSizeStartText(String sizeStartText) { super.setSizeStartText(sizeStartText); } //--------------------------------------------------------------------- /** * Gets the end text to output when a Collection, * Map or Array size is output.

* *

This is output after the size value.

* * @return the current end of size text */ public String getSizeEndText() { return super.getSizeEndText(); } /** *

Sets the end text to output when a Collection, * Map or Array size is output.

* *

This is output after the size value.

* *

null is accepted, but will be converted * to an empty String.

* * @param sizeEndText the new end of size text */ public void setSizeEndText(String sizeEndText) { super.setSizeEndText(sizeEndText); } //--------------------------------------------------------------------- /** *

Gets the start text to output when an Object is * output in summary mode.

* *

This is output before the size value.

* * @return the current start of summary text */ public String getSummaryObjectStartText() { return super.getSummaryObjectStartText(); } /** *

Sets the start text to output when an Object is * output in summary mode.

* *

This is output before the size value.

* *

null is accepted, but will be converted to * an empty String.

* * @param summaryObjectStartText the new start of summary text */ public void setSummaryObjectStartText(String summaryObjectStartText) { super.setSummaryObjectStartText(summaryObjectStartText); } //--------------------------------------------------------------------- /** *

Gets the end text to output when an Object is * output in summary mode.

* *

This is output after the size value.

* * @return the current end of summary text */ public String getSummaryObjectEndText() { return super.getSummaryObjectEndText(); } /** *

Sets the end text to output when an Object is * output in summary mode.

* *

This is output after the size value.

* *

null is accepted, but will be converted to * an empty String.

* * @param summaryObjectEndText the new end of summary text */ public void setSummaryObjectEndText(String summaryObjectEndText) { super.setSummaryObjectEndText(summaryObjectEndText); } //--------------------------------------------------------------------- } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/builder/ToStringBuilder.java100644 0 0 110171 11513702444 26342 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.builder; import org.apache.commons.lang.BooleanUtils; import org.apache.commons.lang.ObjectUtils; /** *

Assists in implementing {@link Object#toString()} methods.

* *

This class enables a good and consistent toString() to be built for any * class or object. This class aims to simplify the process by:

*
    *
  • allowing field names
  • *
  • handling all types consistently
  • *
  • handling nulls consistently
  • *
  • outputting arrays and multi-dimensional arrays
  • *
  • enabling the detail level to be controlled for Objects and Collections
  • *
  • handling class hierarchies
  • *
* *

To use this class write code as follows:

* *
 * public class Person {
 *   String name;
 *   int age;
 *   boolean smoker;
 * 
 *   ...
 * 
 *   public String toString() {
 *     return new ToStringBuilder(this).
 *       append("name", name).
 *       append("age", age).
 *       append("smoker", smoker).
 *       toString();
 *   }
 * }
 * 
* *

This will produce a toString of the format: * Person@7f54[name=Stephen,age=29,smoker=false]

* *

To add the superclass toString, use {@link #appendSuper}. * To append the toString from an object that is delegated * to (or any other object), use {@link #appendToString}.

* *

Alternatively, there is a method that uses reflection to determine * the fields to test. Because these fields are usually private, the method, * reflectionToString, uses AccessibleObject.setAccessible to * change the visibility of the fields. This will fail under a security manager, * unless the appropriate permissions are set up correctly. It is also * slower than testing explicitly.

* *

A typical invocation for this method would look like:

* *
 * public String toString() {
 *   return ToStringBuilder.reflectionToString(this);
 * }
 * 
* *

You can also use the builder to debug 3rd party objects:

* *
 * System.out.println("An object: " + ToStringBuilder.reflectionToString(anObject));
 * 
* *

The exact format of the toString is determined by * the {@link ToStringStyle} passed into the constructor.

* * @author Apache Software Foundation * @author Gary Gregory * @author Pete Gieser * @since 1.0 * @version $Id: ToStringBuilder.java 905636 2010-02-02 14:03:32Z niallp $ */ public class ToStringBuilder { /** * The default style of output to use, not null. */ private static volatile ToStringStyle defaultStyle = ToStringStyle.DEFAULT_STYLE; //---------------------------------------------------------------------------- /** *

Gets the default ToStringStyle to use.

* *

This method gets a singleton default value, typically for the whole JVM. * Changing this default should generally only be done during application startup. * It is recommended to pass a ToStringStyle to the constructor instead * of using this global default.

* *

This method can be used from multiple threads. * Internally, a volatile variable is used to provide the guarantee * that the latest value set using {@link #setDefaultStyle} is the value returned. * It is strongly recommended that the default style is only changed during application startup.

* *

One reason for changing the default could be to have a verbose style during * development and a compact style in production.

* * @return the default ToStringStyle, never null */ public static ToStringStyle getDefaultStyle() { return defaultStyle; } /** *

Sets the default ToStringStyle to use.

* *

This method sets a singleton default value, typically for the whole JVM. * Changing this default should generally only be done during application startup. * It is recommended to pass a ToStringStyle to the constructor instead * of changing this global default.

* *

This method is not intended for use from multiple threads. * Internally, a volatile variable is used to provide the guarantee * that the latest value set is the value returned from {@link #getDefaultStyle}.

* * @param style the default ToStringStyle * @throws IllegalArgumentException if the style is null */ public static void setDefaultStyle(ToStringStyle style) { if (style == null) { throw new IllegalArgumentException("The style must not be null"); } defaultStyle = style; } //---------------------------------------------------------------------------- /** *

Uses ReflectionToStringBuilder to generate a * toString for the specified object.

* * @param object the Object to be output * @return the String result * @see ReflectionToStringBuilder#toString(Object) */ public static String reflectionToString(Object object) { return ReflectionToStringBuilder.toString(object); } /** *

Uses ReflectionToStringBuilder to generate a * toString for the specified object.

* * @param object the Object to be output * @param style the style of the toString to create, may be null * @return the String result * @see ReflectionToStringBuilder#toString(Object,ToStringStyle) */ public static String reflectionToString(Object object, ToStringStyle style) { return ReflectionToStringBuilder.toString(object, style); } /** *

Uses ReflectionToStringBuilder to generate a * toString for the specified object.

* * @param object the Object to be output * @param style the style of the toString to create, may be null * @param outputTransients whether to include transient fields * @return the String result * @see ReflectionToStringBuilder#toString(Object,ToStringStyle,boolean) */ public static String reflectionToString(Object object, ToStringStyle style, boolean outputTransients) { return ReflectionToStringBuilder.toString(object, style, outputTransients, false, null); } /** *

Uses ReflectionToStringBuilder to generate a * toString for the specified object.

* * @param object the Object to be output * @param style the style of the toString to create, may be null * @param outputTransients whether to include transient fields * @param reflectUpToClass the superclass to reflect up to (inclusive), may be null * @return the String result * @see ReflectionToStringBuilder#toString(Object,ToStringStyle,boolean,boolean,Class) * @since 2.0 */ public static String reflectionToString( Object object, ToStringStyle style, boolean outputTransients, Class reflectUpToClass) { return ReflectionToStringBuilder.toString(object, style, outputTransients, false, reflectUpToClass); } //---------------------------------------------------------------------------- /** * Current toString buffer, not null. */ private final StringBuffer buffer; /** * The object being output, may be null. */ private final Object object; /** * The style of output to use, not null. */ private final ToStringStyle style; /** *

Constructs a builder for the specified object using the default output style.

* *

This default style is obtained from {@link #getDefaultStyle()}.

* * @param object the Object to build a toString for, not recommended to be null */ public ToStringBuilder(Object object) { this(object, null, null); } /** *

Constructs a builder for the specified object using the a defined output style.

* *

If the style is null, the default style is used.

* * @param object the Object to build a toString for, not recommended to be null * @param style the style of the toString to create, null uses the default style */ public ToStringBuilder(Object object, ToStringStyle style) { this(object, style, null); } /** *

Constructs a builder for the specified object.

* *

If the style is null, the default style is used.

* *

If the buffer is null, a new one is created.

* * @param object the Object to build a toString for, not recommended to be null * @param style the style of the toString to create, null uses the default style * @param buffer the StringBuffer to populate, may be null */ public ToStringBuilder(Object object, ToStringStyle style, StringBuffer buffer) { if (style == null) { style = getDefaultStyle(); } if (buffer == null) { buffer = new StringBuffer(512); } this.buffer = buffer; this.style = style; this.object = object; style.appendStart(buffer, object); } //---------------------------------------------------------------------------- /** *

Append to the toString a boolean * value.

* * @param value the value to add to the toString * @return this */ public ToStringBuilder append(boolean value) { style.append(buffer, null, value); return this; } //---------------------------------------------------------------------------- /** *

Append to the toString a boolean * array.

* * @param array the array to add to the toString * @return this */ public ToStringBuilder append(boolean[] array) { style.append(buffer, null, array, null); return this; } //---------------------------------------------------------------------------- /** *

Append to the toString a byte * value.

* * @param value the value to add to the toString * @return this */ public ToStringBuilder append(byte value) { style.append(buffer, null, value); return this; } //---------------------------------------------------------------------------- /** *

Append to the toString a byte * array.

* * @param array the array to add to the toString * @return this */ public ToStringBuilder append(byte[] array) { style.append(buffer, null, array, null); return this; } //---------------------------------------------------------------------------- /** *

Append to the toString a char * value.

* * @param value the value to add to the toString * @return this */ public ToStringBuilder append(char value) { style.append(buffer, null, value); return this; } //---------------------------------------------------------------------------- /** *

Append to the toString a char * array.

* * @param array the array to add to the toString * @return this */ public ToStringBuilder append(char[] array) { style.append(buffer, null, array, null); return this; } //---------------------------------------------------------------------------- /** *

Append to the toString a double * value.

* * @param value the value to add to the toString * @return this */ public ToStringBuilder append(double value) { style.append(buffer, null, value); return this; } //---------------------------------------------------------------------------- /** *

Append to the toString a double * array.

* * @param array the array to add to the toString * @return this */ public ToStringBuilder append(double[] array) { style.append(buffer, null, array, null); return this; } //---------------------------------------------------------------------------- /** *

Append to the toString a float * value.

* * @param value the value to add to the toString * @return this */ public ToStringBuilder append(float value) { style.append(buffer, null, value); return this; } //---------------------------------------------------------------------------- /** *

Append to the toString a float * array.

* * @param array the array to add to the toString * @return this */ public ToStringBuilder append(float[] array) { style.append(buffer, null, array, null); return this; } //---------------------------------------------------------------------------- /** *

Append to the toString an int * value.

* * @param value the value to add to the toString * @return this */ public ToStringBuilder append(int value) { style.append(buffer, null, value); return this; } //---------------------------------------------------------------------------- /** *

Append to the toString an int * array.

* * @param array the array to add to the toString * @return this */ public ToStringBuilder append(int[] array) { style.append(buffer, null, array, null); return this; } //---------------------------------------------------------------------------- /** *

Append to the toString a long * value.

* * @param value the value to add to the toString * @return this */ public ToStringBuilder append(long value) { style.append(buffer, null, value); return this; } //---------------------------------------------------------------------------- /** *

Append to the toString a long * array.

* * @param array the array to add to the toString * @return this */ public ToStringBuilder append(long[] array) { style.append(buffer, null, array, null); return this; } //---------------------------------------------------------------------------- /** *

Append to the toString an Object * value.

* * @param obj the value to add to the toString * @return this */ public ToStringBuilder append(Object obj) { style.append(buffer, null, obj, null); return this; } //---------------------------------------------------------------------------- /** *

Append to the toString an Object * array.

* * @param array the array to add to the toString * @return this */ public ToStringBuilder append(Object[] array) { style.append(buffer, null, array, null); return this; } //---------------------------------------------------------------------------- /** *

Append to the toString a short * value.

* * @param value the value to add to the toString * @return this */ public ToStringBuilder append(short value) { style.append(buffer, null, value); return this; } //---------------------------------------------------------------------------- /** *

Append to the toString a short * array.

* * @param array the array to add to the toString * @return this */ public ToStringBuilder append(short[] array) { style.append(buffer, null, array, null); return this; } /** *

Append to the toString a boolean * value.

* * @param fieldName the field name * @param value the value to add to the toString * @return this */ public ToStringBuilder append(String fieldName, boolean value) { style.append(buffer, fieldName, value); return this; } /** *

Append to the toString a boolean * array.

* * @param fieldName the field name * @param array the array to add to the hashCode * @return this */ public ToStringBuilder append(String fieldName, boolean[] array) { style.append(buffer, fieldName, array, null); return this; } /** *

Append to the toString a boolean * array.

* *

A boolean parameter controls the level of detail to show. * Setting true will output the array in full. Setting * false will output a summary, typically the size of * the array.

* * @param fieldName the field name * @param array the array to add to the toString * @param fullDetail true for detail, false * for summary info * @return this */ public ToStringBuilder append(String fieldName, boolean[] array, boolean fullDetail) { style.append(buffer, fieldName, array, BooleanUtils.toBooleanObject(fullDetail)); return this; } /** *

Append to the toString an byte * value.

* * @param fieldName the field name * @param value the value to add to the toString * @return this */ public ToStringBuilder append(String fieldName, byte value) { style.append(buffer, fieldName, value); return this; } /** *

Append to the toString a byte array.

* * @param fieldName the field name * @param array the array to add to the toString * @return this */ public ToStringBuilder append(String fieldName, byte[] array) { style.append(buffer, fieldName, array, null); return this; } /** *

Append to the toString a byte * array.

* *

A boolean parameter controls the level of detail to show. * Setting true will output the array in full. Setting * false will output a summary, typically the size of * the array. * * @param fieldName the field name * @param array the array to add to the toString * @param fullDetail true for detail, false * for summary info * @return this */ public ToStringBuilder append(String fieldName, byte[] array, boolean fullDetail) { style.append(buffer, fieldName, array, BooleanUtils.toBooleanObject(fullDetail)); return this; } /** *

Append to the toString a char * value.

* * @param fieldName the field name * @param value the value to add to the toString * @return this */ public ToStringBuilder append(String fieldName, char value) { style.append(buffer, fieldName, value); return this; } /** *

Append to the toString a char * array.

* * @param fieldName the field name * @param array the array to add to the toString * @return this */ public ToStringBuilder append(String fieldName, char[] array) { style.append(buffer, fieldName, array, null); return this; } /** *

Append to the toString a char * array.

* *

A boolean parameter controls the level of detail to show. * Setting true will output the array in full. Setting * false will output a summary, typically the size of * the array.

* * @param fieldName the field name * @param array the array to add to the toString * @param fullDetail true for detail, false * for summary info * @return this */ public ToStringBuilder append(String fieldName, char[] array, boolean fullDetail) { style.append(buffer, fieldName, array, BooleanUtils.toBooleanObject(fullDetail)); return this; } /** *

Append to the toString a double * value.

* * @param fieldName the field name * @param value the value to add to the toString * @return this */ public ToStringBuilder append(String fieldName, double value) { style.append(buffer, fieldName, value); return this; } /** *

Append to the toString a double * array.

* * @param fieldName the field name * @param array the array to add to the toString * @return this */ public ToStringBuilder append(String fieldName, double[] array) { style.append(buffer, fieldName, array, null); return this; } /** *

Append to the toString a double * array.

* *

A boolean parameter controls the level of detail to show. * Setting true will output the array in full. Setting * false will output a summary, typically the size of * the array.

* * @param fieldName the field name * @param array the array to add to the toString * @param fullDetail true for detail, false * for summary info * @return this */ public ToStringBuilder append(String fieldName, double[] array, boolean fullDetail) { style.append(buffer, fieldName, array, BooleanUtils.toBooleanObject(fullDetail)); return this; } /** *

Append to the toString an float * value.

* * @param fieldName the field name * @param value the value to add to the toString * @return this */ public ToStringBuilder append(String fieldName, float value) { style.append(buffer, fieldName, value); return this; } /** *

Append to the toString a float * array.

* * @param fieldName the field name * @param array the array to add to the toString * @return this */ public ToStringBuilder append(String fieldName, float[] array) { style.append(buffer, fieldName, array, null); return this; } /** *

Append to the toString a float * array.

* *

A boolean parameter controls the level of detail to show. * Setting true will output the array in full. Setting * false will output a summary, typically the size of * the array.

* * @param fieldName the field name * @param array the array to add to the toString * @param fullDetail true for detail, false * for summary info * @return this */ public ToStringBuilder append(String fieldName, float[] array, boolean fullDetail) { style.append(buffer, fieldName, array, BooleanUtils.toBooleanObject(fullDetail)); return this; } /** *

Append to the toString an int * value.

* * @param fieldName the field name * @param value the value to add to the toString * @return this */ public ToStringBuilder append(String fieldName, int value) { style.append(buffer, fieldName, value); return this; } /** *

Append to the toString an int * array.

* * @param fieldName the field name * @param array the array to add to the toString * @return this */ public ToStringBuilder append(String fieldName, int[] array) { style.append(buffer, fieldName, array, null); return this; } /** *

Append to the toString an int * array.

* *

A boolean parameter controls the level of detail to show. * Setting true will output the array in full. Setting * false will output a summary, typically the size of * the array.

* * @param fieldName the field name * @param array the array to add to the toString * @param fullDetail true for detail, false * for summary info * @return this */ public ToStringBuilder append(String fieldName, int[] array, boolean fullDetail) { style.append(buffer, fieldName, array, BooleanUtils.toBooleanObject(fullDetail)); return this; } /** *

Append to the toString a long * value.

* * @param fieldName the field name * @param value the value to add to the toString * @return this */ public ToStringBuilder append(String fieldName, long value) { style.append(buffer, fieldName, value); return this; } /** *

Append to the toString a long * array.

* * @param fieldName the field name * @param array the array to add to the toString * @return this */ public ToStringBuilder append(String fieldName, long[] array) { style.append(buffer, fieldName, array, null); return this; } /** *

Append to the toString a long * array.

* *

A boolean parameter controls the level of detail to show. * Setting true will output the array in full. Setting * false will output a summary, typically the size of * the array.

* * @param fieldName the field name * @param array the array to add to the toString * @param fullDetail true for detail, false * for summary info * @return this */ public ToStringBuilder append(String fieldName, long[] array, boolean fullDetail) { style.append(buffer, fieldName, array, BooleanUtils.toBooleanObject(fullDetail)); return this; } /** *

Append to the toString an Object * value.

* * @param fieldName the field name * @param obj the value to add to the toString * @return this */ public ToStringBuilder append(String fieldName, Object obj) { style.append(buffer, fieldName, obj, null); return this; } /** *

Append to the toString an Object * value.

* * @param fieldName the field name * @param obj the value to add to the toString * @param fullDetail true for detail, * false for summary info * @return this */ public ToStringBuilder append(String fieldName, Object obj, boolean fullDetail) { style.append(buffer, fieldName, obj, BooleanUtils.toBooleanObject(fullDetail)); return this; } /** *

Append to the toString an Object * array.

* * @param fieldName the field name * @param array the array to add to the toString * @return this */ public ToStringBuilder append(String fieldName, Object[] array) { style.append(buffer, fieldName, array, null); return this; } /** *

Append to the toString an Object * array.

* *

A boolean parameter controls the level of detail to show. * Setting true will output the array in full. Setting * false will output a summary, typically the size of * the array.

* * @param fieldName the field name * @param array the array to add to the toString * @param fullDetail true for detail, false * for summary info * @return this */ public ToStringBuilder append(String fieldName, Object[] array, boolean fullDetail) { style.append(buffer, fieldName, array, BooleanUtils.toBooleanObject(fullDetail)); return this; } /** *

Append to the toString an short * value.

* * @param fieldName the field name * @param value the value to add to the toString * @return this */ public ToStringBuilder append(String fieldName, short value) { style.append(buffer, fieldName, value); return this; } /** *

Append to the toString a short * array.

* * @param fieldName the field name * @param array the array to add to the toString * @return this */ public ToStringBuilder append(String fieldName, short[] array) { style.append(buffer, fieldName, array, null); return this; } /** *

Append to the toString a short * array.

* *

A boolean parameter controls the level of detail to show. * Setting true will output the array in full. Setting * false will output a summary, typically the size of * the array. * * @param fieldName the field name * @param array the array to add to the toString * @param fullDetail true for detail, false * for summary info * @return this */ public ToStringBuilder append(String fieldName, short[] array, boolean fullDetail) { style.append(buffer, fieldName, array, BooleanUtils.toBooleanObject(fullDetail)); return this; } /** *

Appends with the same format as the default Object toString() * method. Appends the class name followed by * {@link System#identityHashCode(java.lang.Object)}.

* * @param object the Object whose class name and id to output * @return this * @since 2.0 */ public ToStringBuilder appendAsObjectToString(Object object) { ObjectUtils.identityToString(this.getStringBuffer(), object); return this; } //---------------------------------------------------------------------------- /** *

Append the toString from the superclass.

* *

This method assumes that the superclass uses the same ToStringStyle * as this one.

* *

If superToString is null, no change is made.

* * @param superToString the result of super.toString() * @return this * @since 2.0 */ public ToStringBuilder appendSuper(String superToString) { if (superToString != null) { style.appendSuper(buffer, superToString); } return this; } /** *

Append the toString from another object.

* *

This method is useful where a class delegates most of the implementation of * its properties to another class. You can then call toString() on * the other class and pass the result into this method.

* *
     *   private AnotherObject delegate;
     *   private String fieldInThisClass;
     * 
     *   public String toString() {
     *     return new ToStringBuilder(this).
     *       appendToString(delegate.toString()).
     *       append(fieldInThisClass).
     *       toString();
     *   }
* *

This method assumes that the other object uses the same ToStringStyle * as this one.

* *

If the toString is null, no change is made.

* * @param toString the result of toString() on another object * @return this * @since 2.0 */ public ToStringBuilder appendToString(String toString) { if (toString != null) { style.appendToString(buffer, toString); } return this; } /** *

Returns the Object being output.

* * @return The object being output. * @since 2.0 */ public Object getObject() { return object; } /** *

Gets the StringBuffer being populated.

* * @return the StringBuffer being populated */ public StringBuffer getStringBuffer() { return buffer; } //---------------------------------------------------------------------------- /** *

Gets the ToStringStyle being used.

* * @return the ToStringStyle being used * @since 2.0 */ public ToStringStyle getStyle() { return style; } /** *

Returns the built toString.

* *

This method appends the end of data indicator, and can only be called once. * Use {@link #getStringBuffer} to get the current string state.

* *

If the object is null, return the style's nullText

* * @return the String toString */ public String toString() { if (this.getObject() == null) { this.getStringBuffer().append(this.getStyle().getNullText()); } else { style.appendEnd(this.getStringBuffer(), this.getObject()); } return this.getStringBuffer().toString(); } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/builder/ToStringStyle.java100644 0 0 227674 11513702444 26075 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.builder; import java.io.Serializable; import java.lang.reflect.Array; import java.util.Collection; import java.util.Map; import java.util.WeakHashMap; import org.apache.commons.lang.ClassUtils; import org.apache.commons.lang.ObjectUtils; import org.apache.commons.lang.SystemUtils; /** *

Controls String formatting for {@link ToStringBuilder}. * The main public interface is always via ToStringBuilder.

* *

These classes are intended to be used as Singletons. * There is no need to instantiate a new style each time. A program * will generally use one of the predefined constants on this class. * Alternatively, the {@link StandardToStringStyle} class can be used * to set the individual settings. Thus most styles can be achieved * without subclassing.

* *

If required, a subclass can override as many or as few of the * methods as it requires. Each object type (from boolean * to long to Object to int[]) has * its own methods to output it. Most have two versions, detail and summary. * *

For example, the detail version of the array based methods will * output the whole array, whereas the summary method will just output * the array length.

* *

If you want to format the output of certain objects, such as dates, you * must create a subclass and override a method. *

 * public class MyStyle extends ToStringStyle {
 *   protected void appendDetail(StringBuffer buffer, String fieldName, Object value) {
 *     if (value instanceof Date) {
 *       value = new SimpleDateFormat("yyyy-MM-dd").format(value);
 *     }
 *     buffer.append(value);
 *   }
 * }
 * 
*

* * @author Apache Software Foundation * @author Gary Gregory * @author Pete Gieser * @author Masato Tezuka * @since 1.0 * @version $Id: ToStringStyle.java 907168 2010-02-06 03:33:50Z mbenson $ */ public abstract class ToStringStyle implements Serializable { /** * The default toString style. Using the Using the Person * example from {@link ToStringBuilder}, the output would look like this: * *
     * Person@182f0db[name=John Doe,age=33,smoker=false]
     * 
*/ public static final ToStringStyle DEFAULT_STYLE = new DefaultToStringStyle(); /** * The multi line toString style. Using the Using the Person * example from {@link ToStringBuilder}, the output would look like this: * *
     * Person@182f0db[
     *   name=John Doe
     *   age=33
     *   smoker=false
     * ]
     * 
*/ public static final ToStringStyle MULTI_LINE_STYLE = new MultiLineToStringStyle(); /** * The no field names toString style. Using the Using the * Person example from {@link ToStringBuilder}, the output * would look like this: * *
     * Person@182f0db[John Doe,33,false]
     * 
*/ public static final ToStringStyle NO_FIELD_NAMES_STYLE = new NoFieldNameToStringStyle(); /** * The short prefix toString style. Using the Person example * from {@link ToStringBuilder}, the output would look like this: * *
     * Person[name=John Doe,age=33,smoker=false]
     * 
* * @since 2.1 */ public static final ToStringStyle SHORT_PREFIX_STYLE = new ShortPrefixToStringStyle(); /** * The simple toString style. Using the Using the Person * example from {@link ToStringBuilder}, the output would look like this: * *
     * John Doe,33,false
     * 
*/ public static final ToStringStyle SIMPLE_STYLE = new SimpleToStringStyle(); /** *

* A registry of objects used by reflectionToString methods * to detect cyclical object references and avoid infinite loops. *

*/ private static final ThreadLocal REGISTRY = new ThreadLocal(); /** *

* Returns the registry of objects being traversed by the reflectionToString * methods in the current thread. *

* * @return Set the registry of objects being traversed */ static Map getRegistry() { return (Map) REGISTRY.get(); } /** *

* Returns true if the registry contains the given object. * Used by the reflection methods to avoid infinite loops. *

* * @param value * The object to lookup in the registry. * @return boolean true if the registry contains the given * object. */ static boolean isRegistered(Object value) { Map m = getRegistry(); return m != null && m.containsKey(value); } /** *

* Registers the given object. Used by the reflection methods to avoid * infinite loops. *

* * @param value * The object to register. */ static void register(Object value) { if (value != null) { Map m = getRegistry(); if (m == null) { m = new WeakHashMap(); REGISTRY.set(m); } m.put(value, null); } } /** *

* Unregisters the given object. *

* *

* Used by the reflection methods to avoid infinite loops. *

* * @param value * The object to unregister. */ static void unregister(Object value) { if (value != null) { Map m = getRegistry(); if (m != null) { m.remove(value); if (m.isEmpty()) { REGISTRY.set(null); } } } } /** * Whether to use the field names, the default is true. */ private boolean useFieldNames = true; /** * Whether to use the class name, the default is true. */ private boolean useClassName = true; /** * Whether to use short class names, the default is false. */ private boolean useShortClassName = false; /** * Whether to use the identity hash code, the default is true. */ private boolean useIdentityHashCode = true; /** * The content start '['. */ private String contentStart = "["; /** * The content end ']'. */ private String contentEnd = "]"; /** * The field name value separator '='. */ private String fieldNameValueSeparator = "="; /** * Whether the field separator should be added before any other fields. */ private boolean fieldSeparatorAtStart = false; /** * Whether the field separator should be added after any other fields. */ private boolean fieldSeparatorAtEnd = false; /** * The field separator ','. */ private String fieldSeparator = ","; /** * The array start '{'. */ private String arrayStart = "{"; /** * The array separator ','. */ private String arraySeparator = ","; /** * The detail for array content. */ private boolean arrayContentDetail = true; /** * The array end '}'. */ private String arrayEnd = "}"; /** * The value to use when fullDetail is null, * the default value is true. */ private boolean defaultFullDetail = true; /** * The null text '<null>'. */ private String nullText = ""; /** * The summary size text start '. */ private String sizeStartText = "'>'. */ private String sizeEndText = ">"; /** * The summary object text start '<'. */ private String summaryObjectStartText = "<"; /** * The summary object text start '>'. */ private String summaryObjectEndText = ">"; //---------------------------------------------------------------------------- /** *

Constructor.

*/ protected ToStringStyle() { super(); } //---------------------------------------------------------------------------- /** *

Append to the toString the superclass toString.

*

NOTE: It assumes that the toString has been created from the same ToStringStyle.

* *

A null superToString is ignored.

* * @param buffer the StringBuffer to populate * @param superToString the super.toString() * @since 2.0 */ public void appendSuper(StringBuffer buffer, String superToString) { appendToString(buffer, superToString); } /** *

Append to the toString another toString.

*

NOTE: It assumes that the toString has been created from the same ToStringStyle.

* *

A null toString is ignored.

* * @param buffer the StringBuffer to populate * @param toString the additional toString * @since 2.0 */ public void appendToString(StringBuffer buffer, String toString) { if (toString != null) { int pos1 = toString.indexOf(contentStart) + contentStart.length(); int pos2 = toString.lastIndexOf(contentEnd); if (pos1 != pos2 && pos1 >= 0 && pos2 >= 0) { String data = toString.substring(pos1, pos2); if (fieldSeparatorAtStart) { removeLastFieldSeparator(buffer); } buffer.append(data); appendFieldSeparator(buffer); } } } /** *

Append to the toString the start of data indicator.

* * @param buffer the StringBuffer to populate * @param object the Object to build a toString for */ public void appendStart(StringBuffer buffer, Object object) { if (object != null) { appendClassName(buffer, object); appendIdentityHashCode(buffer, object); appendContentStart(buffer); if (fieldSeparatorAtStart) { appendFieldSeparator(buffer); } } } /** *

Append to the toString the end of data indicator.

* * @param buffer the StringBuffer to populate * @param object the Object to build a * toString for. */ public void appendEnd(StringBuffer buffer, Object object) { if (this.fieldSeparatorAtEnd == false) { removeLastFieldSeparator(buffer); } appendContentEnd(buffer); unregister(object); } /** *

Remove the last field separator from the buffer.

* * @param buffer the StringBuffer to populate * @since 2.0 */ protected void removeLastFieldSeparator(StringBuffer buffer) { int len = buffer.length(); int sepLen = fieldSeparator.length(); if (len > 0 && sepLen > 0 && len >= sepLen) { boolean match = true; for (int i = 0; i < sepLen; i++) { if (buffer.charAt(len - 1 - i) != fieldSeparator.charAt(sepLen - 1 - i)) { match = false; break; } } if (match) { buffer.setLength(len - sepLen); } } } //---------------------------------------------------------------------------- /** *

Append to the toString an Object * value, printing the full toString of the * Object passed in.

* * @param buffer the StringBuffer to populate * @param fieldName the field name * @param value the value to add to the toString * @param fullDetail true for detail, false * for summary info, null for style decides */ public void append(StringBuffer buffer, String fieldName, Object value, Boolean fullDetail) { appendFieldStart(buffer, fieldName); if (value == null) { appendNullText(buffer, fieldName); } else { appendInternal(buffer, fieldName, value, isFullDetail(fullDetail)); } appendFieldEnd(buffer, fieldName); } /** *

Append to the toString an Object, * correctly interpreting its type.

* *

This method performs the main lookup by Class type to correctly * route arrays, Collections, Maps and * Objects to the appropriate method.

* *

Either detail or summary views can be specified.

* *

If a cycle is detected, an object will be appended with the * Object.toString() format.

* * @param buffer the StringBuffer to populate * @param fieldName the field name, typically not used as already appended * @param value the value to add to the toString, * not null * @param detail output detail or not */ protected void appendInternal(StringBuffer buffer, String fieldName, Object value, boolean detail) { if (isRegistered(value) && !(value instanceof Number || value instanceof Boolean || value instanceof Character)) { appendCyclicObject(buffer, fieldName, value); return; } register(value); try { if (value instanceof Collection) { if (detail) { appendDetail(buffer, fieldName, (Collection) value); } else { appendSummarySize(buffer, fieldName, ((Collection) value).size()); } } else if (value instanceof Map) { if (detail) { appendDetail(buffer, fieldName, (Map) value); } else { appendSummarySize(buffer, fieldName, ((Map) value).size()); } } else if (value instanceof long[]) { if (detail) { appendDetail(buffer, fieldName, (long[]) value); } else { appendSummary(buffer, fieldName, (long[]) value); } } else if (value instanceof int[]) { if (detail) { appendDetail(buffer, fieldName, (int[]) value); } else { appendSummary(buffer, fieldName, (int[]) value); } } else if (value instanceof short[]) { if (detail) { appendDetail(buffer, fieldName, (short[]) value); } else { appendSummary(buffer, fieldName, (short[]) value); } } else if (value instanceof byte[]) { if (detail) { appendDetail(buffer, fieldName, (byte[]) value); } else { appendSummary(buffer, fieldName, (byte[]) value); } } else if (value instanceof char[]) { if (detail) { appendDetail(buffer, fieldName, (char[]) value); } else { appendSummary(buffer, fieldName, (char[]) value); } } else if (value instanceof double[]) { if (detail) { appendDetail(buffer, fieldName, (double[]) value); } else { appendSummary(buffer, fieldName, (double[]) value); } } else if (value instanceof float[]) { if (detail) { appendDetail(buffer, fieldName, (float[]) value); } else { appendSummary(buffer, fieldName, (float[]) value); } } else if (value instanceof boolean[]) { if (detail) { appendDetail(buffer, fieldName, (boolean[]) value); } else { appendSummary(buffer, fieldName, (boolean[]) value); } } else if (value.getClass().isArray()) { if (detail) { appendDetail(buffer, fieldName, (Object[]) value); } else { appendSummary(buffer, fieldName, (Object[]) value); } } else { if (detail) { appendDetail(buffer, fieldName, value); } else { appendSummary(buffer, fieldName, value); } } } finally { unregister(value); } } /** *

Append to the toString an Object * value that has been detected to participate in a cycle. This * implementation will print the standard string value of the value.

* * @param buffer the StringBuffer to populate * @param fieldName the field name, typically not used as already appended * @param value the value to add to the toString, * not null * * @since 2.2 */ protected void appendCyclicObject(StringBuffer buffer, String fieldName, Object value) { ObjectUtils.identityToString(buffer, value); } /** *

Append to the toString an Object * value, printing the full detail of the Object.

* * @param buffer the StringBuffer to populate * @param fieldName the field name, typically not used as already appended * @param value the value to add to the toString, * not null */ protected void appendDetail(StringBuffer buffer, String fieldName, Object value) { buffer.append(value); } /** *

Append to the toString a Collection.

* * @param buffer the StringBuffer to populate * @param fieldName the field name, typically not used as already appended * @param coll the Collection to add to the * toString, not null */ protected void appendDetail(StringBuffer buffer, String fieldName, Collection coll) { buffer.append(coll); } /** *

Append to the toString a Map.

* * @param buffer the StringBuffer to populate * @param fieldName the field name, typically not used as already appended * @param map the Map to add to the toString, * not null */ protected void appendDetail(StringBuffer buffer, String fieldName, Map map) { buffer.append(map); } /** *

Append to the toString an Object * value, printing a summary of the Object.

* * @param buffer the StringBuffer to populate * @param fieldName the field name, typically not used as already appended * @param value the value to add to the toString, * not null */ protected void appendSummary(StringBuffer buffer, String fieldName, Object value) { buffer.append(summaryObjectStartText); buffer.append(getShortClassName(value.getClass())); buffer.append(summaryObjectEndText); } //---------------------------------------------------------------------------- /** *

Append to the toString a long * value.

* * @param buffer the StringBuffer to populate * @param fieldName the field name * @param value the value to add to the toString */ public void append(StringBuffer buffer, String fieldName, long value) { appendFieldStart(buffer, fieldName); appendDetail(buffer, fieldName, value); appendFieldEnd(buffer, fieldName); } /** *

Append to the toString a long * value.

* * @param buffer the StringBuffer to populate * @param fieldName the field name, typically not used as already appended * @param value the value to add to the toString */ protected void appendDetail(StringBuffer buffer, String fieldName, long value) { buffer.append(value); } //---------------------------------------------------------------------------- /** *

Append to the toString an int * value.

* * @param buffer the StringBuffer to populate * @param fieldName the field name * @param value the value to add to the toString */ public void append(StringBuffer buffer, String fieldName, int value) { appendFieldStart(buffer, fieldName); appendDetail(buffer, fieldName, value); appendFieldEnd(buffer, fieldName); } /** *

Append to the toString an int * value.

* * @param buffer the StringBuffer to populate * @param fieldName the field name, typically not used as already appended * @param value the value to add to the toString */ protected void appendDetail(StringBuffer buffer, String fieldName, int value) { buffer.append(value); } //---------------------------------------------------------------------------- /** *

Append to the toString a short * value.

* * @param buffer the StringBuffer to populate * @param fieldName the field name * @param value the value to add to the toString */ public void append(StringBuffer buffer, String fieldName, short value) { appendFieldStart(buffer, fieldName); appendDetail(buffer, fieldName, value); appendFieldEnd(buffer, fieldName); } /** *

Append to the toString a short * value.

* * @param buffer the StringBuffer to populate * @param fieldName the field name, typically not used as already appended * @param value the value to add to the toString */ protected void appendDetail(StringBuffer buffer, String fieldName, short value) { buffer.append(value); } //---------------------------------------------------------------------------- /** *

Append to the toString a byte * value.

* * @param buffer the StringBuffer to populate * @param fieldName the field name * @param value the value to add to the toString */ public void append(StringBuffer buffer, String fieldName, byte value) { appendFieldStart(buffer, fieldName); appendDetail(buffer, fieldName, value); appendFieldEnd(buffer, fieldName); } /** *

Append to the toString a byte * value.

* * @param buffer the StringBuffer to populate * @param fieldName the field name, typically not used as already appended * @param value the value to add to the toString */ protected void appendDetail(StringBuffer buffer, String fieldName, byte value) { buffer.append(value); } //---------------------------------------------------------------------------- /** *

Append to the toString a char * value.

* * @param buffer the StringBuffer to populate * @param fieldName the field name * @param value the value to add to the toString */ public void append(StringBuffer buffer, String fieldName, char value) { appendFieldStart(buffer, fieldName); appendDetail(buffer, fieldName, value); appendFieldEnd(buffer, fieldName); } /** *

Append to the toString a char * value.

* * @param buffer the StringBuffer to populate * @param fieldName the field name, typically not used as already appended * @param value the value to add to the toString */ protected void appendDetail(StringBuffer buffer, String fieldName, char value) { buffer.append(value); } //---------------------------------------------------------------------------- /** *

Append to the toString a double * value.

* * @param buffer the StringBuffer to populate * @param fieldName the field name * @param value the value to add to the toString */ public void append(StringBuffer buffer, String fieldName, double value) { appendFieldStart(buffer, fieldName); appendDetail(buffer, fieldName, value); appendFieldEnd(buffer, fieldName); } /** *

Append to the toString a double * value.

* * @param buffer the StringBuffer to populate * @param fieldName the field name, typically not used as already appended * @param value the value to add to the toString */ protected void appendDetail(StringBuffer buffer, String fieldName, double value) { buffer.append(value); } //---------------------------------------------------------------------------- /** *

Append to the toString a float * value.

* * @param buffer the StringBuffer to populate * @param fieldName the field name * @param value the value to add to the toString */ public void append(StringBuffer buffer, String fieldName, float value) { appendFieldStart(buffer, fieldName); appendDetail(buffer, fieldName, value); appendFieldEnd(buffer, fieldName); } /** *

Append to the toString a float * value.

* * @param buffer the StringBuffer to populate * @param fieldName the field name, typically not used as already appended * @param value the value to add to the toString */ protected void appendDetail(StringBuffer buffer, String fieldName, float value) { buffer.append(value); } //---------------------------------------------------------------------------- /** *

Append to the toString a boolean * value.

* * @param buffer the StringBuffer to populate * @param fieldName the field name * @param value the value to add to the toString */ public void append(StringBuffer buffer, String fieldName, boolean value) { appendFieldStart(buffer, fieldName); appendDetail(buffer, fieldName, value); appendFieldEnd(buffer, fieldName); } /** *

Append to the toString a boolean * value.

* * @param buffer the StringBuffer to populate * @param fieldName the field name, typically not used as already appended * @param value the value to add to the toString */ protected void appendDetail(StringBuffer buffer, String fieldName, boolean value) { buffer.append(value); } /** *

Append to the toString an Object * array.

* * @param buffer the StringBuffer to populate * @param fieldName the field name * @param array the array to add to the toString * @param fullDetail true for detail, false * for summary info, null for style decides */ public void append(StringBuffer buffer, String fieldName, Object[] array, Boolean fullDetail) { appendFieldStart(buffer, fieldName); if (array == null) { appendNullText(buffer, fieldName); } else if (isFullDetail(fullDetail)) { appendDetail(buffer, fieldName, array); } else { appendSummary(buffer, fieldName, array); } appendFieldEnd(buffer, fieldName); } //---------------------------------------------------------------------------- /** *

Append to the toString the detail of an * Object array.

* * @param buffer the StringBuffer to populate * @param fieldName the field name, typically not used as already appended * @param array the array to add to the toString, * not null */ protected void appendDetail(StringBuffer buffer, String fieldName, Object[] array) { buffer.append(arrayStart); for (int i = 0; i < array.length; i++) { Object item = array[i]; if (i > 0) { buffer.append(arraySeparator); } if (item == null) { appendNullText(buffer, fieldName); } else { appendInternal(buffer, fieldName, item, arrayContentDetail); } } buffer.append(arrayEnd); } /** *

Append to the toString the detail of an array type.

* * @param buffer the StringBuffer to populate * @param fieldName the field name, typically not used as already appended * @param array the array to add to the toString, * not null * @since 2.0 */ protected void reflectionAppendArrayDetail(StringBuffer buffer, String fieldName, Object array) { buffer.append(arrayStart); int length = Array.getLength(array); for (int i = 0; i < length; i++) { Object item = Array.get(array, i); if (i > 0) { buffer.append(arraySeparator); } if (item == null) { appendNullText(buffer, fieldName); } else { appendInternal(buffer, fieldName, item, arrayContentDetail); } } buffer.append(arrayEnd); } /** *

Append to the toString a summary of an * Object array.

* * @param buffer the StringBuffer to populate * @param fieldName the field name, typically not used as already appended * @param array the array to add to the toString, * not null */ protected void appendSummary(StringBuffer buffer, String fieldName, Object[] array) { appendSummarySize(buffer, fieldName, array.length); } //---------------------------------------------------------------------------- /** *

Append to the toString a long * array.

* * @param buffer the StringBuffer to populate * @param fieldName the field name * @param array the array to add to the toString * @param fullDetail true for detail, false * for summary info, null for style decides */ public void append(StringBuffer buffer, String fieldName, long[] array, Boolean fullDetail) { appendFieldStart(buffer, fieldName); if (array == null) { appendNullText(buffer, fieldName); } else if (isFullDetail(fullDetail)) { appendDetail(buffer, fieldName, array); } else { appendSummary(buffer, fieldName, array); } appendFieldEnd(buffer, fieldName); } /** *

Append to the toString the detail of a * long array.

* * @param buffer the StringBuffer to populate * @param fieldName the field name, typically not used as already appended * @param array the array to add to the toString, * not null */ protected void appendDetail(StringBuffer buffer, String fieldName, long[] array) { buffer.append(arrayStart); for (int i = 0; i < array.length; i++) { if (i > 0) { buffer.append(arraySeparator); } appendDetail(buffer, fieldName, array[i]); } buffer.append(arrayEnd); } /** *

Append to the toString a summary of a * long array.

* * @param buffer the StringBuffer to populate * @param fieldName the field name, typically not used as already appended * @param array the array to add to the toString, * not null */ protected void appendSummary(StringBuffer buffer, String fieldName, long[] array) { appendSummarySize(buffer, fieldName, array.length); } //---------------------------------------------------------------------------- /** *

Append to the toString an int * array.

* * @param buffer the StringBuffer to populate * @param fieldName the field name * @param array the array to add to the toString * @param fullDetail true for detail, false * for summary info, null for style decides */ public void append(StringBuffer buffer, String fieldName, int[] array, Boolean fullDetail) { appendFieldStart(buffer, fieldName); if (array == null) { appendNullText(buffer, fieldName); } else if (isFullDetail(fullDetail)) { appendDetail(buffer, fieldName, array); } else { appendSummary(buffer, fieldName, array); } appendFieldEnd(buffer, fieldName); } /** *

Append to the toString the detail of an * int array.

* * @param buffer the StringBuffer to populate * @param fieldName the field name, typically not used as already appended * @param array the array to add to the toString, * not null */ protected void appendDetail(StringBuffer buffer, String fieldName, int[] array) { buffer.append(arrayStart); for (int i = 0; i < array.length; i++) { if (i > 0) { buffer.append(arraySeparator); } appendDetail(buffer, fieldName, array[i]); } buffer.append(arrayEnd); } /** *

Append to the toString a summary of an * int array.

* * @param buffer the StringBuffer to populate * @param fieldName the field name, typically not used as already appended * @param array the array to add to the toString, * not null */ protected void appendSummary(StringBuffer buffer, String fieldName, int[] array) { appendSummarySize(buffer, fieldName, array.length); } //---------------------------------------------------------------------------- /** *

Append to the toString a short * array.

* * @param buffer the StringBuffer to populate * @param fieldName the field name * @param array the array to add to the toString * @param fullDetail true for detail, false * for summary info, null for style decides */ public void append(StringBuffer buffer, String fieldName, short[] array, Boolean fullDetail) { appendFieldStart(buffer, fieldName); if (array == null) { appendNullText(buffer, fieldName); } else if (isFullDetail(fullDetail)) { appendDetail(buffer, fieldName, array); } else { appendSummary(buffer, fieldName, array); } appendFieldEnd(buffer, fieldName); } /** *

Append to the toString the detail of a * short array.

* * @param buffer the StringBuffer to populate * @param fieldName the field name, typically not used as already appended * @param array the array to add to the toString, * not null */ protected void appendDetail(StringBuffer buffer, String fieldName, short[] array) { buffer.append(arrayStart); for (int i = 0; i < array.length; i++) { if (i > 0) { buffer.append(arraySeparator); } appendDetail(buffer, fieldName, array[i]); } buffer.append(arrayEnd); } /** *

Append to the toString a summary of a * short array.

* * @param buffer the StringBuffer to populate * @param fieldName the field name, typically not used as already appended * @param array the array to add to the toString, * not null */ protected void appendSummary(StringBuffer buffer, String fieldName, short[] array) { appendSummarySize(buffer, fieldName, array.length); } //---------------------------------------------------------------------------- /** *

Append to the toString a byte * array.

* * @param buffer the StringBuffer to populate * @param fieldName the field name * @param array the array to add to the toString * @param fullDetail true for detail, false * for summary info, null for style decides */ public void append(StringBuffer buffer, String fieldName, byte[] array, Boolean fullDetail) { appendFieldStart(buffer, fieldName); if (array == null) { appendNullText(buffer, fieldName); } else if (isFullDetail(fullDetail)) { appendDetail(buffer, fieldName, array); } else { appendSummary(buffer, fieldName, array); } appendFieldEnd(buffer, fieldName); } /** *

Append to the toString the detail of a * byte array.

* * @param buffer the StringBuffer to populate * @param fieldName the field name, typically not used as already appended * @param array the array to add to the toString, * not null */ protected void appendDetail(StringBuffer buffer, String fieldName, byte[] array) { buffer.append(arrayStart); for (int i = 0; i < array.length; i++) { if (i > 0) { buffer.append(arraySeparator); } appendDetail(buffer, fieldName, array[i]); } buffer.append(arrayEnd); } /** *

Append to the toString a summary of a * byte array.

* * @param buffer the StringBuffer to populate * @param fieldName the field name, typically not used as already appended * @param array the array to add to the toString, * not null */ protected void appendSummary(StringBuffer buffer, String fieldName, byte[] array) { appendSummarySize(buffer, fieldName, array.length); } //---------------------------------------------------------------------------- /** *

Append to the toString a char * array.

* * @param buffer the StringBuffer to populate * @param fieldName the field name * @param array the array to add to the toString * @param fullDetail true for detail, false * for summary info, null for style decides */ public void append(StringBuffer buffer, String fieldName, char[] array, Boolean fullDetail) { appendFieldStart(buffer, fieldName); if (array == null) { appendNullText(buffer, fieldName); } else if (isFullDetail(fullDetail)) { appendDetail(buffer, fieldName, array); } else { appendSummary(buffer, fieldName, array); } appendFieldEnd(buffer, fieldName); } /** *

Append to the toString the detail of a * char array.

* * @param buffer the StringBuffer to populate * @param fieldName the field name, typically not used as already appended * @param array the array to add to the toString, * not null */ protected void appendDetail(StringBuffer buffer, String fieldName, char[] array) { buffer.append(arrayStart); for (int i = 0; i < array.length; i++) { if (i > 0) { buffer.append(arraySeparator); } appendDetail(buffer, fieldName, array[i]); } buffer.append(arrayEnd); } /** *

Append to the toString a summary of a * char array.

* * @param buffer the StringBuffer to populate * @param fieldName the field name, typically not used as already appended * @param array the array to add to the toString, * not null */ protected void appendSummary(StringBuffer buffer, String fieldName, char[] array) { appendSummarySize(buffer, fieldName, array.length); } //---------------------------------------------------------------------------- /** *

Append to the toString a double * array.

* * @param buffer the StringBuffer to populate * @param fieldName the field name * @param array the array to add to the toString * @param fullDetail true for detail, false * for summary info, null for style decides */ public void append(StringBuffer buffer, String fieldName, double[] array, Boolean fullDetail) { appendFieldStart(buffer, fieldName); if (array == null) { appendNullText(buffer, fieldName); } else if (isFullDetail(fullDetail)) { appendDetail(buffer, fieldName, array); } else { appendSummary(buffer, fieldName, array); } appendFieldEnd(buffer, fieldName); } /** *

Append to the toString the detail of a * double array.

* * @param buffer the StringBuffer to populate * @param fieldName the field name, typically not used as already appended * @param array the array to add to the toString, * not null */ protected void appendDetail(StringBuffer buffer, String fieldName, double[] array) { buffer.append(arrayStart); for (int i = 0; i < array.length; i++) { if (i > 0) { buffer.append(arraySeparator); } appendDetail(buffer, fieldName, array[i]); } buffer.append(arrayEnd); } /** *

Append to the toString a summary of a * double array.

* * @param buffer the StringBuffer to populate * @param fieldName the field name, typically not used as already appended * @param array the array to add to the toString, * not null */ protected void appendSummary(StringBuffer buffer, String fieldName, double[] array) { appendSummarySize(buffer, fieldName, array.length); } //---------------------------------------------------------------------------- /** *

Append to the toString a float * array.

* * @param buffer the StringBuffer to populate * @param fieldName the field name * @param array the array to add to the toString * @param fullDetail true for detail, false * for summary info, null for style decides */ public void append(StringBuffer buffer, String fieldName, float[] array, Boolean fullDetail) { appendFieldStart(buffer, fieldName); if (array == null) { appendNullText(buffer, fieldName); } else if (isFullDetail(fullDetail)) { appendDetail(buffer, fieldName, array); } else { appendSummary(buffer, fieldName, array); } appendFieldEnd(buffer, fieldName); } /** *

Append to the toString the detail of a * float array.

* * @param buffer the StringBuffer to populate * @param fieldName the field name, typically not used as already appended * @param array the array to add to the toString, * not null */ protected void appendDetail(StringBuffer buffer, String fieldName, float[] array) { buffer.append(arrayStart); for (int i = 0; i < array.length; i++) { if (i > 0) { buffer.append(arraySeparator); } appendDetail(buffer, fieldName, array[i]); } buffer.append(arrayEnd); } /** *

Append to the toString a summary of a * float array.

* * @param buffer the StringBuffer to populate * @param fieldName the field name, typically not used as already appended * @param array the array to add to the toString, * not null */ protected void appendSummary(StringBuffer buffer, String fieldName, float[] array) { appendSummarySize(buffer, fieldName, array.length); } //---------------------------------------------------------------------------- /** *

Append to the toString a boolean * array.

* * @param buffer the StringBuffer to populate * @param fieldName the field name * @param array the array to add to the toString * @param fullDetail true for detail, false * for summary info, null for style decides */ public void append(StringBuffer buffer, String fieldName, boolean[] array, Boolean fullDetail) { appendFieldStart(buffer, fieldName); if (array == null) { appendNullText(buffer, fieldName); } else if (isFullDetail(fullDetail)) { appendDetail(buffer, fieldName, array); } else { appendSummary(buffer, fieldName, array); } appendFieldEnd(buffer, fieldName); } /** *

Append to the toString the detail of a * boolean array.

* * @param buffer the StringBuffer to populate * @param fieldName the field name, typically not used as already appended * @param array the array to add to the toString, * not null */ protected void appendDetail(StringBuffer buffer, String fieldName, boolean[] array) { buffer.append(arrayStart); for (int i = 0; i < array.length; i++) { if (i > 0) { buffer.append(arraySeparator); } appendDetail(buffer, fieldName, array[i]); } buffer.append(arrayEnd); } /** *

Append to the toString a summary of a * boolean array.

* * @param buffer the StringBuffer to populate * @param fieldName the field name, typically not used as already appended * @param array the array to add to the toString, * not null */ protected void appendSummary(StringBuffer buffer, String fieldName, boolean[] array) { appendSummarySize(buffer, fieldName, array.length); } //---------------------------------------------------------------------------- /** *

Append to the toString the class name.

* * @param buffer the StringBuffer to populate * @param object the Object whose name to output */ protected void appendClassName(StringBuffer buffer, Object object) { if (useClassName && object != null) { register(object); if (useShortClassName) { buffer.append(getShortClassName(object.getClass())); } else { buffer.append(object.getClass().getName()); } } } /** *

Append the {@link System#identityHashCode(java.lang.Object)}.

* * @param buffer the StringBuffer to populate * @param object the Object whose id to output */ protected void appendIdentityHashCode(StringBuffer buffer, Object object) { if (this.isUseIdentityHashCode() && object!=null) { register(object); buffer.append('@'); buffer.append(Integer.toHexString(System.identityHashCode(object))); } } /** *

Append to the toString the content start.

* * @param buffer the StringBuffer to populate */ protected void appendContentStart(StringBuffer buffer) { buffer.append(contentStart); } /** *

Append to the toString the content end.

* * @param buffer the StringBuffer to populate */ protected void appendContentEnd(StringBuffer buffer) { buffer.append(contentEnd); } /** *

Append to the toString an indicator for null.

* *

The default indicator is '<null>'.

* * @param buffer the StringBuffer to populate * @param fieldName the field name, typically not used as already appended */ protected void appendNullText(StringBuffer buffer, String fieldName) { buffer.append(nullText); } /** *

Append to the toString the field separator.

* * @param buffer the StringBuffer to populate */ protected void appendFieldSeparator(StringBuffer buffer) { buffer.append(fieldSeparator); } /** *

Append to the toString the field start.

* * @param buffer the StringBuffer to populate * @param fieldName the field name */ protected void appendFieldStart(StringBuffer buffer, String fieldName) { if (useFieldNames && fieldName != null) { buffer.append(fieldName); buffer.append(fieldNameValueSeparator); } } /** *

Append to the toString the field end.

* * @param buffer the StringBuffer to populate * @param fieldName the field name, typically not used as already appended */ protected void appendFieldEnd(StringBuffer buffer, String fieldName) { appendFieldSeparator(buffer); } /** *

Append to the toString a size summary.

* *

The size summary is used to summarize the contents of * Collections, Maps and arrays.

* *

The output consists of a prefix, the passed in size * and a suffix.

* *

The default format is '<size=n>'.

* * @param buffer the StringBuffer to populate * @param fieldName the field name, typically not used as already appended * @param size the size to append */ protected void appendSummarySize(StringBuffer buffer, String fieldName, int size) { buffer.append(sizeStartText); buffer.append(size); buffer.append(sizeEndText); } /** *

Is this field to be output in full detail.

* *

This method converts a detail request into a detail level. * The calling code may request full detail (true), * but a subclass might ignore that and always return * false. The calling code may pass in * null indicating that it doesn't care about * the detail level. In this case the default detail level is * used.

* * @param fullDetailRequest the detail level requested * @return whether full detail is to be shown */ protected boolean isFullDetail(Boolean fullDetailRequest) { if (fullDetailRequest == null) { return defaultFullDetail; } return fullDetailRequest.booleanValue(); } /** *

Gets the short class name for a class.

* *

The short class name is the classname excluding * the package name.

* * @param cls the Class to get the short name of * @return the short name */ protected String getShortClassName(Class cls) { return ClassUtils.getShortClassName(cls); } // Setters and getters for the customizable parts of the style // These methods are not expected to be overridden, except to make public // (They are not public so that immutable subclasses can be written) //--------------------------------------------------------------------- /** *

Gets whether to use the class name.

* * @return the current useClassName flag */ protected boolean isUseClassName() { return useClassName; } /** *

Sets whether to use the class name.

* * @param useClassName the new useClassName flag */ protected void setUseClassName(boolean useClassName) { this.useClassName = useClassName; } //--------------------------------------------------------------------- /** *

Gets whether to output short or long class names.

* * @return the current useShortClassName flag * @since 2.0 */ protected boolean isUseShortClassName() { return useShortClassName; } /** *

Gets whether to output short or long class names.

* * @return the current shortClassName flag * @deprecated Use {@link #isUseShortClassName()} * Method will be removed in Commons Lang 3.0. */ protected boolean isShortClassName() { return useShortClassName; } /** *

Sets whether to output short or long class names.

* * @param useShortClassName the new useShortClassName flag * @since 2.0 */ protected void setUseShortClassName(boolean useShortClassName) { this.useShortClassName = useShortClassName; } /** *

Sets whether to output short or long class names.

* * @param shortClassName the new shortClassName flag * @deprecated Use {@link #setUseShortClassName(boolean)} * Method will be removed in Commons Lang 3.0. */ protected void setShortClassName(boolean shortClassName) { this.useShortClassName = shortClassName; } //--------------------------------------------------------------------- /** *

Gets whether to use the identity hash code.

* * @return the current useIdentityHashCode flag */ protected boolean isUseIdentityHashCode() { return useIdentityHashCode; } /** *

Sets whether to use the identity hash code.

* * @param useIdentityHashCode the new useIdentityHashCode flag */ protected void setUseIdentityHashCode(boolean useIdentityHashCode) { this.useIdentityHashCode = useIdentityHashCode; } //--------------------------------------------------------------------- /** *

Gets whether to use the field names passed in.

* * @return the current useFieldNames flag */ protected boolean isUseFieldNames() { return useFieldNames; } /** *

Sets whether to use the field names passed in.

* * @param useFieldNames the new useFieldNames flag */ protected void setUseFieldNames(boolean useFieldNames) { this.useFieldNames = useFieldNames; } //--------------------------------------------------------------------- /** *

Gets whether to use full detail when the caller doesn't * specify.

* * @return the current defaultFullDetail flag */ protected boolean isDefaultFullDetail() { return defaultFullDetail; } /** *

Sets whether to use full detail when the caller doesn't * specify.

* * @param defaultFullDetail the new defaultFullDetail flag */ protected void setDefaultFullDetail(boolean defaultFullDetail) { this.defaultFullDetail = defaultFullDetail; } //--------------------------------------------------------------------- /** *

Gets whether to output array content detail.

* * @return the current array content detail setting */ protected boolean isArrayContentDetail() { return arrayContentDetail; } /** *

Sets whether to output array content detail.

* * @param arrayContentDetail the new arrayContentDetail flag */ protected void setArrayContentDetail(boolean arrayContentDetail) { this.arrayContentDetail = arrayContentDetail; } //--------------------------------------------------------------------- /** *

Gets the array start text.

* * @return the current array start text */ protected String getArrayStart() { return arrayStart; } /** *

Sets the array start text.

* *

null is accepted, but will be converted to * an empty String.

* * @param arrayStart the new array start text */ protected void setArrayStart(String arrayStart) { if (arrayStart == null) { arrayStart = ""; } this.arrayStart = arrayStart; } //--------------------------------------------------------------------- /** *

Gets the array end text.

* * @return the current array end text */ protected String getArrayEnd() { return arrayEnd; } /** *

Sets the array end text.

* *

null is accepted, but will be converted to * an empty String.

* * @param arrayEnd the new array end text */ protected void setArrayEnd(String arrayEnd) { if (arrayEnd == null) { arrayEnd = ""; } this.arrayEnd = arrayEnd; } //--------------------------------------------------------------------- /** *

Gets the array separator text.

* * @return the current array separator text */ protected String getArraySeparator() { return arraySeparator; } /** *

Sets the array separator text.

* *

null is accepted, but will be converted to * an empty String.

* * @param arraySeparator the new array separator text */ protected void setArraySeparator(String arraySeparator) { if (arraySeparator == null) { arraySeparator = ""; } this.arraySeparator = arraySeparator; } //--------------------------------------------------------------------- /** *

Gets the content start text.

* * @return the current content start text */ protected String getContentStart() { return contentStart; } /** *

Sets the content start text.

* *

null is accepted, but will be converted to * an empty String.

* * @param contentStart the new content start text */ protected void setContentStart(String contentStart) { if (contentStart == null) { contentStart = ""; } this.contentStart = contentStart; } //--------------------------------------------------------------------- /** *

Gets the content end text.

* * @return the current content end text */ protected String getContentEnd() { return contentEnd; } /** *

Sets the content end text.

* *

null is accepted, but will be converted to * an empty String.

* * @param contentEnd the new content end text */ protected void setContentEnd(String contentEnd) { if (contentEnd == null) { contentEnd = ""; } this.contentEnd = contentEnd; } //--------------------------------------------------------------------- /** *

Gets the field name value separator text.

* * @return the current field name value separator text */ protected String getFieldNameValueSeparator() { return fieldNameValueSeparator; } /** *

Sets the field name value separator text.

* *

null is accepted, but will be converted to * an empty String.

* * @param fieldNameValueSeparator the new field name value separator text */ protected void setFieldNameValueSeparator(String fieldNameValueSeparator) { if (fieldNameValueSeparator == null) { fieldNameValueSeparator = ""; } this.fieldNameValueSeparator = fieldNameValueSeparator; } //--------------------------------------------------------------------- /** *

Gets the field separator text.

* * @return the current field separator text */ protected String getFieldSeparator() { return fieldSeparator; } /** *

Sets the field separator text.

* *

null is accepted, but will be converted to * an empty String.

* * @param fieldSeparator the new field separator text */ protected void setFieldSeparator(String fieldSeparator) { if (fieldSeparator == null) { fieldSeparator = ""; } this.fieldSeparator = fieldSeparator; } //--------------------------------------------------------------------- /** *

Gets whether the field separator should be added at the start * of each buffer.

* * @return the fieldSeparatorAtStart flag * @since 2.0 */ protected boolean isFieldSeparatorAtStart() { return fieldSeparatorAtStart; } /** *

Sets whether the field separator should be added at the start * of each buffer.

* * @param fieldSeparatorAtStart the fieldSeparatorAtStart flag * @since 2.0 */ protected void setFieldSeparatorAtStart(boolean fieldSeparatorAtStart) { this.fieldSeparatorAtStart = fieldSeparatorAtStart; } //--------------------------------------------------------------------- /** *

Gets whether the field separator should be added at the end * of each buffer.

* * @return fieldSeparatorAtEnd flag * @since 2.0 */ protected boolean isFieldSeparatorAtEnd() { return fieldSeparatorAtEnd; } /** *

Sets whether the field separator should be added at the end * of each buffer.

* * @param fieldSeparatorAtEnd the fieldSeparatorAtEnd flag * @since 2.0 */ protected void setFieldSeparatorAtEnd(boolean fieldSeparatorAtEnd) { this.fieldSeparatorAtEnd = fieldSeparatorAtEnd; } //--------------------------------------------------------------------- /** *

Gets the text to output when null found.

* * @return the current text to output when null found */ protected String getNullText() { return nullText; } /** *

Sets the text to output when null found.

* *

null is accepted, but will be converted to * an empty String.

* * @param nullText the new text to output when null found */ protected void setNullText(String nullText) { if (nullText == null) { nullText = ""; } this.nullText = nullText; } //--------------------------------------------------------------------- /** *

Gets the start text to output when a Collection, * Map or array size is output.

* *

This is output before the size value.

* * @return the current start of size text */ protected String getSizeStartText() { return sizeStartText; } /** *

Sets the start text to output when a Collection, * Map or array size is output.

* *

This is output before the size value.

* *

null is accepted, but will be converted to * an empty String.

* * @param sizeStartText the new start of size text */ protected void setSizeStartText(String sizeStartText) { if (sizeStartText == null) { sizeStartText = ""; } this.sizeStartText = sizeStartText; } //--------------------------------------------------------------------- /** *

Gets the end text to output when a Collection, * Map or array size is output.

* *

This is output after the size value.

* * @return the current end of size text */ protected String getSizeEndText() { return sizeEndText; } /** *

Sets the end text to output when a Collection, * Map or array size is output.

* *

This is output after the size value.

* *

null is accepted, but will be converted to * an empty String.

* * @param sizeEndText the new end of size text */ protected void setSizeEndText(String sizeEndText) { if (sizeEndText == null) { sizeEndText = ""; } this.sizeEndText = sizeEndText; } //--------------------------------------------------------------------- /** *

Gets the start text to output when an Object is * output in summary mode.

* *

This is output before the size value.

* * @return the current start of summary text */ protected String getSummaryObjectStartText() { return summaryObjectStartText; } /** *

Sets the start text to output when an Object is * output in summary mode.

* *

This is output before the size value.

* *

null is accepted, but will be converted to * an empty String.

* * @param summaryObjectStartText the new start of summary text */ protected void setSummaryObjectStartText(String summaryObjectStartText) { if (summaryObjectStartText == null) { summaryObjectStartText = ""; } this.summaryObjectStartText = summaryObjectStartText; } //--------------------------------------------------------------------- /** *

Gets the end text to output when an Object is * output in summary mode.

* *

This is output after the size value.

* * @return the current end of summary text */ protected String getSummaryObjectEndText() { return summaryObjectEndText; } /** *

Sets the end text to output when an Object is * output in summary mode.

* *

This is output after the size value.

* *

null is accepted, but will be converted to * an empty String.

* * @param summaryObjectEndText the new end of summary text */ protected void setSummaryObjectEndText(String summaryObjectEndText) { if (summaryObjectEndText == null) { summaryObjectEndText = ""; } this.summaryObjectEndText = summaryObjectEndText; } //---------------------------------------------------------------------------- /** *

Default ToStringStyle.

* *

This is an inner class rather than using * StandardToStringStyle to ensure its immutability.

*/ private static final class DefaultToStringStyle extends ToStringStyle { /** * Required for serialization support. * * @see java.io.Serializable */ private static final long serialVersionUID = 1L; /** *

Constructor.

* *

Use the static constant rather than instantiating.

*/ DefaultToStringStyle() { super(); } /** *

Ensure Singleton after serialization.

* * @return the singleton */ private Object readResolve() { return ToStringStyle.DEFAULT_STYLE; } } //---------------------------------------------------------------------------- /** *

ToStringStyle that does not print out * the field names.

* *

This is an inner class rather than using * StandardToStringStyle to ensure its immutability. */ private static final class NoFieldNameToStringStyle extends ToStringStyle { private static final long serialVersionUID = 1L; /** *

Constructor.

* *

Use the static constant rather than instantiating.

*/ NoFieldNameToStringStyle() { super(); this.setUseFieldNames(false); } /** *

Ensure Singleton after serialization.

* * @return the singleton */ private Object readResolve() { return ToStringStyle.NO_FIELD_NAMES_STYLE; } } //---------------------------------------------------------------------------- /** *

ToStringStyle that prints out the short * class name and no identity hashcode.

* *

This is an inner class rather than using * StandardToStringStyle to ensure its immutability.

*/ private static final class ShortPrefixToStringStyle extends ToStringStyle { private static final long serialVersionUID = 1L; /** *

Constructor.

* *

Use the static constant rather than instantiating.

*/ ShortPrefixToStringStyle() { super(); this.setUseShortClassName(true); this.setUseIdentityHashCode(false); } /** *

Ensure Singleton after serialization.

* @return the singleton */ private Object readResolve() { return ToStringStyle.SHORT_PREFIX_STYLE; } } /** *

ToStringStyle that does not print out the * classname, identity hashcode, content start or field name.

* *

This is an inner class rather than using * StandardToStringStyle to ensure its immutability.

*/ private static final class SimpleToStringStyle extends ToStringStyle { private static final long serialVersionUID = 1L; /** *

Constructor.

* *

Use the static constant rather than instantiating.

*/ SimpleToStringStyle() { super(); this.setUseClassName(false); this.setUseIdentityHashCode(false); this.setUseFieldNames(false); this.setContentStart(""); this.setContentEnd(""); } /** *

Ensure Singleton after serialization.

* @return the singleton */ private Object readResolve() { return ToStringStyle.SIMPLE_STYLE; } } //---------------------------------------------------------------------------- /** *

ToStringStyle that outputs on multiple lines.

* *

This is an inner class rather than using * StandardToStringStyle to ensure its immutability.

*/ private static final class MultiLineToStringStyle extends ToStringStyle { private static final long serialVersionUID = 1L; /** *

Constructor.

* *

Use the static constant rather than instantiating.

*/ MultiLineToStringStyle() { super(); this.setContentStart("["); this.setFieldSeparator(SystemUtils.LINE_SEPARATOR + " "); this.setFieldSeparatorAtStart(true); this.setContentEnd(SystemUtils.LINE_SEPARATOR + "]"); } /** *

Ensure Singleton after serialization.

* * @return the singleton */ private Object readResolve() { return ToStringStyle.MULTI_LINE_STYLE; } } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/CharEncoding.java100644 0 0 12756 11513702445 24153 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang; import java.io.UnsupportedEncodingException; /** *

* Character encoding names required of every implementation of the Java platform. *

* *

* According to JRE character * encoding names: *

* Every implementation of the Java platform is required to support the following character encodings. Consult the * release documentation for your implementation to see if any other encodings are supported. *

*

* * @see JRE character encoding * names * @author Apache Software Foundation * @since 2.1 * @version $Id: CharEncoding.java 437554 2006-08-28 06:21:41Z bayard $ */ public class CharEncoding { /** *

* ISO Latin Alphabet #1, also known as ISO-LATIN-1. *

*

* Every implementation of the Java platform is required to support this character encoding. *

* * @see JRE character * encoding names */ public static final String ISO_8859_1 = "ISO-8859-1"; /** *

* Seven-bit ASCII, also known as ISO646-US, also known as the Basic Latin block of the Unicode character set. *

*

* Every implementation of the Java platform is required to support this character encoding. *

* * @see JRE character * encoding names */ public static final String US_ASCII = "US-ASCII"; /** *

* Sixteen-bit Unicode Transformation Format, byte order specified by a mandatory initial byte-order mark (either * order accepted on input, big-endian used on output). *

*

* Every implementation of the Java platform is required to support this character encoding. *

* * @see JRE character * encoding names */ public static final String UTF_16 = "UTF-16"; /** *

* Sixteen-bit Unicode Transformation Format, big-endian byte order. *

*

* Every implementation of the Java platform is required to support this character encoding. *

* * @see JRE character * encoding names */ public static final String UTF_16BE = "UTF-16BE"; /** *

* Sixteen-bit Unicode Transformation Format, little-endian byte order. *

*

* Every implementation of the Java platform is required to support this character encoding. *

* * @see JRE character * encoding names */ public static final String UTF_16LE = "UTF-16LE"; /** *

* Eight-bit Unicode Transformation Format. *

*

* Every implementation of the Java platform is required to support this character encoding. *

* * @see JRE character * encoding names */ public static final String UTF_8 = "UTF-8"; /** *

* Returns whether the named charset is supported. *

*

* This is similar to * java.nio.charset.Charset.isSupported(String) *

* * @param name * the name of the requested charset; may be either a canonical name or an alias * @return true if, and only if, support for the named charset is available in the current Java * virtual machine * * @see JRE character * encoding names */ public static boolean isSupported(String name) { if (name == null) { return false; } try { new String(ArrayUtils.EMPTY_BYTE_ARRAY, name); } catch (UnsupportedEncodingException e) { return false; } return true; } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/CharRange.java100644 0 0 30413 11513702445 23447 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang; import java.io.Serializable; import java.util.Iterator; import java.util.NoSuchElementException; import org.apache.commons.lang.text.StrBuilder; /** *

A contiguous range of characters, optionally negated.

* *

Instances are immutable.

* *

#ThreadSafe#

* @author Apache Software Foundation * @author Chris Feldhacker * @author Gary Gregory * @since 1.0 * @version $Id: CharRange.java 1057072 2011-01-10 01:55:57Z niallp $ */ public final class CharRange implements Serializable { /** * Required for serialization support. Lang version 2.0. * * @see java.io.Serializable */ private static final long serialVersionUID = 8270183163158333422L; /** The first character, inclusive, in the range. */ private final char start; /** The last character, inclusive, in the range. */ private final char end; /** True if the range is everything except the characters specified. */ private final boolean negated; /** Cached toString. */ private transient String iToString; // Static //----------------------------------------------------------------------- /** *

Constructs a CharRange over a single character.

* * @param ch only character in this range * @return the new CharRange object * @see CharRange#CharRange(char, char, boolean) * @since 2.5 */ public static CharRange is(char ch) { return new CharRange(ch, ch, false); } /** *

Constructs a negated CharRange over a single character.

* * @param ch only character in this range * @return the new CharRange object * @see CharRange#CharRange(char, char, boolean) * @since 2.5 */ public static CharRange isNot(char ch) { return new CharRange(ch, ch, true); } /** *

Constructs a CharRange over a set of characters.

* * @param start first character, inclusive, in this range * @param end last character, inclusive, in this range * @return the new CharRange object * @see CharRange#CharRange(char, char, boolean) * @since 2.5 */ public static CharRange isIn(char start, char end) { return new CharRange(start, end, false); } /** *

Constructs a negated CharRange over a set of characters.

* * @param start first character, inclusive, in this range * @param end last character, inclusive, in this range * @return the new CharRange object * @see CharRange#CharRange(char, char, boolean) * @since 2.5 */ public static CharRange isNotIn(char start, char end) { return new CharRange(start, end, true); } //----------------------------------------------------------------------- /** *

Constructs a CharRange over a single character.

* * @param ch only character in this range */ public CharRange(char ch) { this(ch, ch, false); } /** *

Constructs a CharRange over a single character, * optionally negating the range.

* *

A negated range includes everything except the specified char.

* * @param ch only character in this range * @param negated true to express everything except the range */ public CharRange(char ch, boolean negated) { this(ch, ch, negated); } /** *

Constructs a CharRange over a set of characters.

* * @param start first character, inclusive, in this range * @param end last character, inclusive, in this range */ public CharRange(char start, char end) { this(start, end, false); } /** *

Constructs a CharRange over a set of characters, * optionally negating the range.

* *

A negated range includes everything except that defined by the * start and end characters.

* *

If start and end are in the wrong order, they are reversed. * Thus a-e is the same as e-a.

* * @param start first character, inclusive, in this range * @param end last character, inclusive, in this range * @param negated true to express everything except the range */ public CharRange(char start, char end, boolean negated) { super(); if (start > end) { char temp = start; start = end; end = temp; } this.start = start; this.end = end; this.negated = negated; } // Accessors //----------------------------------------------------------------------- /** *

Gets the start character for this character range.

* * @return the start char (inclusive) */ public char getStart() { return this.start; } /** *

Gets the end character for this character range.

* * @return the end char (inclusive) */ public char getEnd() { return this.end; } /** *

Is this CharRange negated.

* *

A negated range includes everything except that defined by the * start and end characters.

* * @return true is negated */ public boolean isNegated() { return negated; } // Contains //----------------------------------------------------------------------- /** *

Is the character specified contained in this range.

* * @param ch the character to check * @return true if this range contains the input character */ public boolean contains(char ch) { return (ch >= start && ch <= end) != negated; } /** *

Are all the characters of the passed in range contained in * this range.

* * @param range the range to check against * @return true if this range entirely contains the input range * @throws IllegalArgumentException if null input */ public boolean contains(CharRange range) { if (range == null) { throw new IllegalArgumentException("The Range must not be null"); } if (negated) { if (range.negated) { return start >= range.start && end <= range.end; } return range.end < start || range.start > end; } if (range.negated) { return start == 0 && end == Character.MAX_VALUE; } return start <= range.start && end >= range.end; } // Basics //----------------------------------------------------------------------- /** *

Compares two CharRange objects, returning true if they represent * exactly the same range of characters defined in the same way.

* * @param obj the object to compare to * @return true if equal */ public boolean equals(Object obj) { if (obj == this) { return true; } if (obj instanceof CharRange == false) { return false; } CharRange other = (CharRange) obj; return start == other.start && end == other.end && negated == other.negated; } /** *

Gets a hashCode compatible with the equals method.

* * @return a suitable hashCode */ public int hashCode() { return 83 + start + 7 * end + (negated ? 1 : 0); } /** *

Gets a string representation of the character range.

* * @return string representation of this range */ public String toString() { if (iToString == null) { StrBuilder buf = new StrBuilder(4); if (isNegated()) { buf.append('^'); } buf.append(start); if (start != end) { buf.append('-'); buf.append(end); } iToString = buf.toString(); } return iToString; } // Expansions //----------------------------------------------------------------------- /** *

Returns an iterator which can be used to walk through the characters described by this range.

* *

#NotThreadSafe# the iterator is not threadsafe

* @return an iterator to the chars represented by this range * @since 2.5 */ public Iterator iterator() { return new CharacterIterator(this); } /** * Character {@link Iterator}. *

#NotThreadSafe#

*/ private static class CharacterIterator implements Iterator { /** The current character */ private char current; private final CharRange range; private boolean hasNext; /** * Construct a new iterator for the character range. * * @param r The character range */ private CharacterIterator(CharRange r) { range = r; hasNext = true; if (range.negated) { if (range.start == 0) { if (range.end == Character.MAX_VALUE) { // This range is an empty set hasNext = false; } else { current = (char) (range.end + 1); } } else { current = 0; } } else { current = range.start; } } /** * Prepare the next character in the range. */ private void prepareNext() { if (range.negated) { if (current == Character.MAX_VALUE) { hasNext = false; } else if (current + 1 == range.start) { if (range.end == Character.MAX_VALUE) { hasNext = false; } else { current = (char) (range.end + 1); } } else { current = (char) (current + 1); } } else if (current < range.end) { current = (char) (current + 1); } else { hasNext = false; } } /** * Has the iterator not reached the end character yet? * * @return true if the iterator has yet to reach the character date */ public boolean hasNext() { return hasNext; } /** * Return the next character in the iteration * * @return Character for the next character */ public Object next() { if (hasNext == false) { throw new NoSuchElementException(); } char cur = current; prepareNext(); return new Character(cur); } /** * Always throws UnsupportedOperationException. * * @throws UnsupportedOperationException * @see java.util.Iterator#remove() */ public void remove() { throw new UnsupportedOperationException(); } } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/CharSet.java100644 0 0 23263 11513702445 23153 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang; import java.io.Serializable; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; /** *

A set of characters.

* *

Instances are immutable, but instances of subclasses may not be.

* *

#ThreadSafe#

* @author Apache Software Foundation * @author Phil Steitz * @author Pete Gieser * @author Gary Gregory * @since 1.0 * @version $Id: CharSet.java 1056988 2011-01-09 17:58:53Z niallp $ */ public class CharSet implements Serializable { /** * Required for serialization support. Lang version 2.0. * * @see java.io.Serializable */ private static final long serialVersionUID = 5947847346149275958L; /** * A CharSet defining no characters. * @since 2.0 */ public static final CharSet EMPTY = new CharSet((String) null); /** * A CharSet defining ASCII alphabetic characters "a-zA-Z". * @since 2.0 */ public static final CharSet ASCII_ALPHA = new CharSet("a-zA-Z"); /** * A CharSet defining ASCII alphabetic characters "a-z". * @since 2.0 */ public static final CharSet ASCII_ALPHA_LOWER = new CharSet("a-z"); /** * A CharSet defining ASCII alphabetic characters "A-Z". * @since 2.0 */ public static final CharSet ASCII_ALPHA_UPPER = new CharSet("A-Z"); /** * A CharSet defining ASCII alphabetic characters "0-9". * @since 2.0 */ public static final CharSet ASCII_NUMERIC = new CharSet("0-9"); /** * A Map of the common cases used in the factory. * Subclasses can add more common patterns if desired * @since 2.0 */ protected static final Map COMMON = Collections.synchronizedMap(new HashMap()); static { COMMON.put(null, EMPTY); COMMON.put("", EMPTY); COMMON.put("a-zA-Z", ASCII_ALPHA); COMMON.put("A-Za-z", ASCII_ALPHA); COMMON.put("a-z", ASCII_ALPHA_LOWER); COMMON.put("A-Z", ASCII_ALPHA_UPPER); COMMON.put("0-9", ASCII_NUMERIC); } /** The set of CharRange objects. */ private final Set set = Collections.synchronizedSet(new HashSet()); //----------------------------------------------------------------------- /** *

Factory method to create a new CharSet using a special syntax.

* *
    *
  • null or empty string ("") * - set containing no characters
  • *
  • Single character, such as "a" * - set containing just that character
  • *
  • Multi character, such as "a-e" * - set containing characters from one character to the other
  • *
  • Negated, such as "^a" or "^a-e" * - set containing all characters except those defined
  • *
  • Combinations, such as "abe-g" * - set containing all the characters from the individual sets
  • *
* *

The matching order is:

*
    *
  1. Negated multi character range, such as "^a-e" *
  2. Ordinary multi character range, such as "a-e" *
  3. Negated single character, such as "^a" *
  4. Ordinary single character, such as "a" *
*

Matching works left to right. Once a match is found the * search starts again from the next character.

* *

If the same range is defined twice using the same syntax, only * one range will be kept. * Thus, "a-ca-c" creates only one range of "a-c".

* *

If the start and end of a range are in the wrong order, * they are reversed. Thus "a-e" is the same as "e-a". * As a result, "a-ee-a" would create only one range, * as the "a-e" and "e-a" are the same.

* *

The set of characters represented is the union of the specified ranges.

* *

All CharSet objects returned by this method will be immutable.

* * @param setStr the String describing the set, may be null * @return a CharSet instance * @since 2.0 */ public static CharSet getInstance(String setStr) { Object set = COMMON.get(setStr); if (set != null) { return (CharSet) set; } return new CharSet(setStr); } /** *

Constructs a new CharSet using the set syntax. * Each string is merged in with the set.

* * @param setStrs Strings to merge into the initial set, may be null * @return a CharSet instance * @since 2.4 */ public static CharSet getInstance(String[] setStrs) { if (setStrs == null) { return null; } return new CharSet(setStrs); } //----------------------------------------------------------------------- /** *

Constructs a new CharSet using the set syntax.

* * @param setStr the String describing the set, may be null * @since 2.0 */ protected CharSet(String setStr) { super(); add(setStr); } /** *

Constructs a new CharSet using the set syntax. * Each string is merged in with the set.

* * @param set Strings to merge into the initial set * @throws NullPointerException if set is null */ protected CharSet(String[] set) { super(); int sz = set.length; for (int i = 0; i < sz; i++) { add(set[i]); } } //----------------------------------------------------------------------- /** *

Add a set definition string to the CharSet.

* * @param str set definition string */ protected void add(String str) { if (str == null) { return; } int len = str.length(); int pos = 0; while (pos < len) { int remainder = (len - pos); if (remainder >= 4 && str.charAt(pos) == '^' && str.charAt(pos + 2) == '-') { // negated range set.add(CharRange.isNotIn(str.charAt(pos + 1), str.charAt(pos + 3))); pos += 4; } else if (remainder >= 3 && str.charAt(pos + 1) == '-') { // range set.add(CharRange.isIn(str.charAt(pos), str.charAt(pos + 2))); pos += 3; } else if (remainder >= 2 && str.charAt(pos) == '^') { // negated char set.add(CharRange.isNot(str.charAt(pos + 1))); pos += 2; } else { // char set.add(CharRange.is(str.charAt(pos))); pos += 1; } } } //----------------------------------------------------------------------- /** *

Gets the internal set as an array of CharRange objects.

* * @return an array of immutable CharRange objects * @since 2.0 */ public CharRange[] getCharRanges() { return (CharRange[]) set.toArray(new CharRange[set.size()]); } //----------------------------------------------------------------------- /** *

Does the CharSet contain the specified * character ch.

* * @param ch the character to check for * @return true if the set contains the characters */ public boolean contains(char ch) { for (Iterator it = set.iterator(); it.hasNext();) { CharRange range = (CharRange) it.next(); if (range.contains(ch)) { return true; } } return false; } // Basics //----------------------------------------------------------------------- /** *

Compares two CharSet objects, returning true if they represent * exactly the same set of characters defined in the same way.

* *

The two sets abc and a-c are not * equal according to this method.

* * @param obj the object to compare to * @return true if equal * @since 2.0 */ public boolean equals(Object obj) { if (obj == this) { return true; } if (obj instanceof CharSet == false) { return false; } CharSet other = (CharSet) obj; return set.equals(other.set); } /** *

Gets a hashCode compatible with the equals method.

* * @return a suitable hashCode * @since 2.0 */ public int hashCode() { return 89 + set.hashCode(); } /** *

Gets a string representation of the set.

* * @return string representation of the set */ public String toString() { return set.toString(); } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/CharSetUtils.java100644 0 0 34664 11513702445 24203 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang; import org.apache.commons.lang.text.StrBuilder; /** *

Operations on CharSets.

* *

This class handles null input gracefully. * An exception will not be thrown for a null input. * Each method documents its behaviour in more detail.

* *

#ThreadSafe#

* @see CharSet * @author Apache Software Foundation * @author Phil Steitz * @author Gary Gregory * @since 1.0 * @version $Id: CharSetUtils.java 1057072 2011-01-10 01:55:57Z niallp $ */ public class CharSetUtils { /** *

CharSetUtils instances should NOT be constructed in standard programming. * Instead, the class should be used as CharSetUtils.evaluateSet(null);.

* *

This constructor is public to permit tools that require a JavaBean instance * to operate.

*/ public CharSetUtils() { super(); } // Factory //----------------------------------------------------------------------- /** *

Creates a CharSet instance which allows a certain amount of * set logic to be performed.

*

The syntax is:

*
    *
  • "aeio" which implies 'a','e',..
  • *
  • "^e" implies not e.
  • *
  • "ej-m" implies e,j->m. e,j,k,l,m.
  • *
* *
     * CharSetUtils.evaluateSet(null)    = null
     * CharSetUtils.evaluateSet([])      = CharSet matching nothing
     * CharSetUtils.evaluateSet(["a-e"]) = CharSet matching a,b,c,d,e
     * 
* * @param set the set, may be null * @return a CharSet instance, null if null input * @deprecated Use {@link CharSet#getInstance(String[])}. * Method will be removed in Commons Lang 3.0. */ public static CharSet evaluateSet(String[] set) { if (set == null) { return null; } return new CharSet(set); } // Squeeze //----------------------------------------------------------------------- /** *

Squeezes any repetitions of a character that is mentioned in the * supplied set.

* *
     * CharSetUtils.squeeze(null, *)        = null
     * CharSetUtils.squeeze("", *)          = ""
     * CharSetUtils.squeeze(*, null)        = *
     * CharSetUtils.squeeze(*, "")          = *
     * CharSetUtils.squeeze("hello", "k-p") = "helo"
     * CharSetUtils.squeeze("hello", "a-e") = "hello"
     * 
* * @see CharSet#getInstance(java.lang.String) for set-syntax. * @param str the string to squeeze, may be null * @param set the character set to use for manipulation, may be null * @return modified String, null if null string input */ public static String squeeze(String str, String set) { if (StringUtils.isEmpty(str) || StringUtils.isEmpty(set)) { return str; } String[] strs = new String[1]; strs[0] = set; return squeeze(str, strs); } /** *

Squeezes any repetitions of a character that is mentioned in the * supplied set.

* *

An example is:

*
    *
  • squeeze("hello", {"el"}) => "helo"
  • *
* * @see CharSet#getInstance(java.lang.String) for set-syntax. * @param str the string to squeeze, may be null * @param set the character set to use for manipulation, may be null * @return modified String, null if null string input */ public static String squeeze(String str, String[] set) { if (StringUtils.isEmpty(str) || ArrayUtils.isEmpty(set)) { return str; } CharSet chars = CharSet.getInstance(set); StrBuilder buffer = new StrBuilder(str.length()); char[] chrs = str.toCharArray(); int sz = chrs.length; char lastChar = ' '; char ch = ' '; for (int i = 0; i < sz; i++) { ch = chrs[i]; if (chars.contains(ch)) { if ((ch == lastChar) && (i != 0)) { continue; } } buffer.append(ch); lastChar = ch; } return buffer.toString(); } // Count //----------------------------------------------------------------------- /** *

Takes an argument in set-syntax, see evaluateSet, * and returns the number of characters present in the specified string.

* *
     * CharSetUtils.count(null, *)        = 0
     * CharSetUtils.count("", *)          = 0
     * CharSetUtils.count(*, null)        = 0
     * CharSetUtils.count(*, "")          = 0
     * CharSetUtils.count("hello", "k-p") = 3
     * CharSetUtils.count("hello", "a-e") = 1
     * 
* * @see CharSet#getInstance(java.lang.String) for set-syntax. * @param str String to count characters in, may be null * @param set String set of characters to count, may be null * @return character count, zero if null string input */ public static int count(String str, String set) { if (StringUtils.isEmpty(str) || StringUtils.isEmpty(set)) { return 0; } String[] strs = new String[1]; strs[0] = set; return count(str, strs); } /** *

Takes an argument in set-syntax, see evaluateSet, * and returns the number of characters present in the specified string.

* *

An example would be:

*
    *
  • count("hello", {"c-f", "o"}) returns 2.
  • *
* * @see CharSet#getInstance(java.lang.String) for set-syntax. * @param str String to count characters in, may be null * @param set String[] set of characters to count, may be null * @return character count, zero if null string input */ public static int count(String str, String[] set) { if (StringUtils.isEmpty(str) || ArrayUtils.isEmpty(set)) { return 0; } CharSet chars = CharSet.getInstance(set); int count = 0; char[] chrs = str.toCharArray(); int sz = chrs.length; for(int i=0; iTakes an argument in set-syntax, see evaluateSet, * and keeps any of characters present in the specified string.

* *
     * CharSetUtils.keep(null, *)        = null
     * CharSetUtils.keep("", *)          = ""
     * CharSetUtils.keep(*, null)        = ""
     * CharSetUtils.keep(*, "")          = ""
     * CharSetUtils.keep("hello", "hl")  = "hll"
     * CharSetUtils.keep("hello", "le")  = "ell"
     * 
* * @see CharSet#getInstance(java.lang.String) for set-syntax. * @param str String to keep characters from, may be null * @param set String set of characters to keep, may be null * @return modified String, null if null string input * @since 2.0 */ public static String keep(String str, String set) { if (str == null) { return null; } if (str.length() == 0 || StringUtils.isEmpty(set)) { return ""; } String[] strs = new String[1]; strs[0] = set; return keep(str, strs); } /** *

Takes an argument in set-syntax, see evaluateSet, * and keeps any of characters present in the specified string.

* *

An example would be:

*
    *
  • keep("hello", {"c-f", "o"}) * returns "eo"
  • *
* * @see CharSet#getInstance(java.lang.String) for set-syntax. * @param str String to keep characters from, may be null * @param set String[] set of characters to keep, may be null * @return modified String, null if null string input * @since 2.0 */ public static String keep(String str, String[] set) { if (str == null) { return null; } if (str.length() == 0 || ArrayUtils.isEmpty(set)) { return ""; } return modify(str, set, true); } // Delete //----------------------------------------------------------------------- /** *

Takes an argument in set-syntax, see evaluateSet, * and deletes any of characters present in the specified string.

* *
     * CharSetUtils.delete(null, *)        = null
     * CharSetUtils.delete("", *)          = ""
     * CharSetUtils.delete(*, null)        = *
     * CharSetUtils.delete(*, "")          = *
     * CharSetUtils.delete("hello", "hl")  = "eo"
     * CharSetUtils.delete("hello", "le")  = "ho"
     * 
* * @see CharSet#getInstance(java.lang.String) for set-syntax. * @param str String to delete characters from, may be null * @param set String set of characters to delete, may be null * @return modified String, null if null string input */ public static String delete(String str, String set) { if (StringUtils.isEmpty(str) || StringUtils.isEmpty(set)) { return str; } String[] strs = new String[1]; strs[0] = set; return delete(str, strs); } /** *

Takes an argument in set-syntax, see evaluateSet, * and deletes any of characters present in the specified string.

* *

An example would be:

*
    *
  • delete("hello", {"c-f", "o"}) returns * "hll"
  • *
* * @see CharSet#getInstance(java.lang.String) for set-syntax. * @param str String to delete characters from, may be null * @param set String[] set of characters to delete, may be null * @return modified String, null if null string input */ public static String delete(String str, String[] set) { if (StringUtils.isEmpty(str) || ArrayUtils.isEmpty(set)) { return str; } return modify(str, set, false); } //----------------------------------------------------------------------- /** * Implementation of delete and keep * * @param str String to modify characters within * @param set String[] set of characters to modify * @param expect whether to evaluate on match, or non-match * @return modified String */ private static String modify(String str, String[] set, boolean expect) { CharSet chars = CharSet.getInstance(set); StrBuilder buffer = new StrBuilder(str.length()); char[] chrs = str.toCharArray(); int sz = chrs.length; for(int i=0; iTranslate characters in a String. * This is a multi character search and replace routine.

* *

An example is:

*
    *
  • translate("hello", "ho", "jy") * => jelly
  • *
* *

If the length of characters to search for is greater than the * length of characters to replace, then the last character is * used.

* *
     * CharSetUtils.translate(null, *, *) = null
     * CharSetUtils.translate("", *, *)   = ""
     * 
* * @param str String to replace characters in, may be null * @param searchChars a set of characters to search for, must not be null * @param replaceChars a set of characters to replace, must not be null or empty ("") * @return translated String, null if null string input * @throws NullPointerException if searchChars or replaceChars * is null * @throws ArrayIndexOutOfBoundsException if replaceChars is empty ("") * @deprecated Use {@link StringUtils#replaceChars(String, String, String)}. * Method will be removed in Commons Lang 3.0. * NOTE: StringUtils#replaceChars behaves differently when 'searchChars' is longer * than 'replaceChars'. CharSetUtils#translate will use the last char of the replacement * string whereas StringUtils#replaceChars will delete */ public static String translate(String str, String searchChars, String replaceChars) { if (StringUtils.isEmpty(str)) { return str; } StrBuilder buffer = new StrBuilder(str.length()); char[] chrs = str.toCharArray(); char[] withChrs = replaceChars.toCharArray(); int sz = chrs.length; int withMax = replaceChars.length() - 1; for(int i=0; i withMax) { idx = withMax; } buffer.append(withChrs[idx]); } else { buffer.append(chrs[i]); } } return buffer.toString(); } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/CharUtils.java100644 0 0 47722 11513702446 23527 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang; /** *

Operations on char primitives and Character objects.

* *

This class tries to handle null input gracefully. * An exception will not be thrown for a null input. * Each method documents its behaviour in more detail.

* *

#ThreadSafe#

* @author Apache Software Foundation * @since 2.1 * @version $Id: CharUtils.java 1056988 2011-01-09 17:58:53Z niallp $ */ public class CharUtils { private static final String CHAR_STRING = "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007" + "\b\t\n\u000b\f\r\u000e\u000f" + "\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017" + "\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f" + "\u0020\u0021\"\u0023\u0024\u0025\u0026\u0027" + "\u0028\u0029\u002a\u002b\u002c\u002d\u002e\u002f" + "\u0030\u0031\u0032\u0033\u0034\u0035\u0036\u0037" + "\u0038\u0039\u003a\u003b\u003c\u003d\u003e\u003f" + "\u0040\u0041\u0042\u0043\u0044\u0045\u0046\u0047" + "\u0048\u0049\u004a\u004b\u004c\u004d\u004e\u004f" + "\u0050\u0051\u0052\u0053\u0054\u0055\u0056\u0057" + "\u0058\u0059\u005a\u005b\\\u005d\u005e\u005f" + "\u0060\u0061\u0062\u0063\u0064\u0065\u0066\u0067" + "\u0068\u0069\u006a\u006b\u006c\u006d\u006e\u006f" + "\u0070\u0071\u0072\u0073\u0074\u0075\u0076\u0077" + "\u0078\u0079\u007a\u007b\u007c\u007d\u007e\u007f"; private static final String[] CHAR_STRING_ARRAY = new String[128]; private static final Character[] CHAR_ARRAY = new Character[128]; /** * \u000a linefeed LF ('\n'). * * @see JLF: Escape Sequences * for Character and String Literals * @since 2.2 */ public static final char LF = '\n'; /** * \u000d carriage return CR ('\r'). * * @see JLF: Escape Sequences * for Character and String Literals * @since 2.2 */ public static final char CR = '\r'; static { for (int i = 127; i >= 0; i--) { CHAR_STRING_ARRAY[i] = CHAR_STRING.substring(i, i + 1); CHAR_ARRAY[i] = new Character((char) i); } } /** *

CharUtils instances should NOT be constructed in standard programming. * Instead, the class should be used as CharUtils.toString('c');.

* *

This constructor is public to permit tools that require a JavaBean instance * to operate.

*/ public CharUtils() { super(); } //----------------------------------------------------------------------- /** *

Converts the character to a Character.

* *

For ASCII 7 bit characters, this uses a cache that will return the * same Character object each time.

* *
     *   CharUtils.toCharacterObject(' ')  = ' '
     *   CharUtils.toCharacterObject('A')  = 'A'
     * 
* * @param ch the character to convert * @return a Character of the specified character */ public static Character toCharacterObject(char ch) { if (ch < CHAR_ARRAY.length) { return CHAR_ARRAY[ch]; } return new Character(ch); } /** *

Converts the String to a Character using the first character, returning * null for empty Strings.

* *

For ASCII 7 bit characters, this uses a cache that will return the * same Character object each time.

* *
     *   CharUtils.toCharacterObject(null) = null
     *   CharUtils.toCharacterObject("")   = null
     *   CharUtils.toCharacterObject("A")  = 'A'
     *   CharUtils.toCharacterObject("BA") = 'B'
     * 
* * @param str the character to convert * @return the Character value of the first letter of the String */ public static Character toCharacterObject(String str) { if (StringUtils.isEmpty(str)) { return null; } return toCharacterObject(str.charAt(0)); } //----------------------------------------------------------------------- /** *

Converts the Character to a char throwing an exception for null.

* *
     *   CharUtils.toChar(null) = IllegalArgumentException
     *   CharUtils.toChar(' ')  = ' '
     *   CharUtils.toChar('A')  = 'A'
     * 
* * @param ch the character to convert * @return the char value of the Character * @throws IllegalArgumentException if the Character is null */ public static char toChar(Character ch) { if (ch == null) { throw new IllegalArgumentException("The Character must not be null"); } return ch.charValue(); } /** *

Converts the Character to a char handling null.

* *
     *   CharUtils.toChar(null, 'X') = 'X'
     *   CharUtils.toChar(' ', 'X')  = ' '
     *   CharUtils.toChar('A', 'X')  = 'A'
     * 
* * @param ch the character to convert * @param defaultValue the value to use if the Character is null * @return the char value of the Character or the default if null */ public static char toChar(Character ch, char defaultValue) { if (ch == null) { return defaultValue; } return ch.charValue(); } //----------------------------------------------------------------------- /** *

Converts the String to a char using the first character, throwing * an exception on empty Strings.

* *
     *   CharUtils.toChar(null) = IllegalArgumentException
     *   CharUtils.toChar("")   = IllegalArgumentException
     *   CharUtils.toChar("A")  = 'A'
     *   CharUtils.toChar("BA") = 'B'
     * 
* * @param str the character to convert * @return the char value of the first letter of the String * @throws IllegalArgumentException if the String is empty */ public static char toChar(String str) { if (StringUtils.isEmpty(str)) { throw new IllegalArgumentException("The String must not be empty"); } return str.charAt(0); } /** *

Converts the String to a char using the first character, defaulting * the value on empty Strings.

* *
     *   CharUtils.toChar(null, 'X') = 'X'
     *   CharUtils.toChar("", 'X')   = 'X'
     *   CharUtils.toChar("A", 'X')  = 'A'
     *   CharUtils.toChar("BA", 'X') = 'B'
     * 
* * @param str the character to convert * @param defaultValue the value to use if the Character is null * @return the char value of the first letter of the String or the default if null */ public static char toChar(String str, char defaultValue) { if (StringUtils.isEmpty(str)) { return defaultValue; } return str.charAt(0); } //----------------------------------------------------------------------- /** *

Converts the character to the Integer it represents, throwing an * exception if the character is not numeric.

* *

This method coverts the char '1' to the int 1 and so on.

* *
     *   CharUtils.toIntValue('3')  = 3
     *   CharUtils.toIntValue('A')  = IllegalArgumentException
     * 
* * @param ch the character to convert * @return the int value of the character * @throws IllegalArgumentException if the character is not ASCII numeric */ public static int toIntValue(char ch) { if (isAsciiNumeric(ch) == false) { throw new IllegalArgumentException("The character " + ch + " is not in the range '0' - '9'"); } return ch - 48; } /** *

Converts the character to the Integer it represents, throwing an * exception if the character is not numeric.

* *

This method coverts the char '1' to the int 1 and so on.

* *
     *   CharUtils.toIntValue('3', -1)  = 3
     *   CharUtils.toIntValue('A', -1)  = -1
     * 
* * @param ch the character to convert * @param defaultValue the default value to use if the character is not numeric * @return the int value of the character */ public static int toIntValue(char ch, int defaultValue) { if (isAsciiNumeric(ch) == false) { return defaultValue; } return ch - 48; } /** *

Converts the character to the Integer it represents, throwing an * exception if the character is not numeric.

* *

This method coverts the char '1' to the int 1 and so on.

* *
     *   CharUtils.toIntValue(null) = IllegalArgumentException
     *   CharUtils.toIntValue('3')  = 3
     *   CharUtils.toIntValue('A')  = IllegalArgumentException
     * 
* * @param ch the character to convert, not null * @return the int value of the character * @throws IllegalArgumentException if the Character is not ASCII numeric or is null */ public static int toIntValue(Character ch) { if (ch == null) { throw new IllegalArgumentException("The character must not be null"); } return toIntValue(ch.charValue()); } /** *

Converts the character to the Integer it represents, throwing an * exception if the character is not numeric.

* *

This method coverts the char '1' to the int 1 and so on.

* *
     *   CharUtils.toIntValue(null, -1) = -1
     *   CharUtils.toIntValue('3', -1)  = 3
     *   CharUtils.toIntValue('A', -1)  = -1
     * 
* * @param ch the character to convert * @param defaultValue the default value to use if the character is not numeric * @return the int value of the character */ public static int toIntValue(Character ch, int defaultValue) { if (ch == null) { return defaultValue; } return toIntValue(ch.charValue(), defaultValue); } //----------------------------------------------------------------------- /** *

Converts the character to a String that contains the one character.

* *

For ASCII 7 bit characters, this uses a cache that will return the * same String object each time.

* *
     *   CharUtils.toString(' ')  = " "
     *   CharUtils.toString('A')  = "A"
     * 
* * @param ch the character to convert * @return a String containing the one specified character */ public static String toString(char ch) { if (ch < 128) { return CHAR_STRING_ARRAY[ch]; } return new String(new char[] {ch}); } /** *

Converts the character to a String that contains the one character.

* *

For ASCII 7 bit characters, this uses a cache that will return the * same String object each time.

* *

If null is passed in, null will be returned.

* *
     *   CharUtils.toString(null) = null
     *   CharUtils.toString(' ')  = " "
     *   CharUtils.toString('A')  = "A"
     * 
* * @param ch the character to convert * @return a String containing the one specified character */ public static String toString(Character ch) { if (ch == null) { return null; } return toString(ch.charValue()); } //-------------------------------------------------------------------------- /** *

Converts the string to the unicode format '\u0020'.

* *

This format is the Java source code format.

* *
     *   CharUtils.unicodeEscaped(' ') = "\u0020"
     *   CharUtils.unicodeEscaped('A') = "\u0041"
     * 
* * @param ch the character to convert * @return the escaped unicode string */ public static String unicodeEscaped(char ch) { if (ch < 0x10) { return "\\u000" + Integer.toHexString(ch); } else if (ch < 0x100) { return "\\u00" + Integer.toHexString(ch); } else if (ch < 0x1000) { return "\\u0" + Integer.toHexString(ch); } return "\\u" + Integer.toHexString(ch); } /** *

Converts the string to the unicode format '\u0020'.

* *

This format is the Java source code format.

* *

If null is passed in, null will be returned.

* *
     *   CharUtils.unicodeEscaped(null) = null
     *   CharUtils.unicodeEscaped(' ')  = "\u0020"
     *   CharUtils.unicodeEscaped('A')  = "\u0041"
     * 
* * @param ch the character to convert, may be null * @return the escaped unicode string, null if null input */ public static String unicodeEscaped(Character ch) { if (ch == null) { return null; } return unicodeEscaped(ch.charValue()); } //-------------------------------------------------------------------------- /** *

Checks whether the character is ASCII 7 bit.

* *
     *   CharUtils.isAscii('a')  = true
     *   CharUtils.isAscii('A')  = true
     *   CharUtils.isAscii('3')  = true
     *   CharUtils.isAscii('-')  = true
     *   CharUtils.isAscii('\n') = true
     *   CharUtils.isAscii('©') = false
     * 
* * @param ch the character to check * @return true if less than 128 */ public static boolean isAscii(char ch) { return ch < 128; } /** *

Checks whether the character is ASCII 7 bit printable.

* *
     *   CharUtils.isAsciiPrintable('a')  = true
     *   CharUtils.isAsciiPrintable('A')  = true
     *   CharUtils.isAsciiPrintable('3')  = true
     *   CharUtils.isAsciiPrintable('-')  = true
     *   CharUtils.isAsciiPrintable('\n') = false
     *   CharUtils.isAsciiPrintable('©') = false
     * 
* * @param ch the character to check * @return true if between 32 and 126 inclusive */ public static boolean isAsciiPrintable(char ch) { return ch >= 32 && ch < 127; } /** *

Checks whether the character is ASCII 7 bit control.

* *
     *   CharUtils.isAsciiControl('a')  = false
     *   CharUtils.isAsciiControl('A')  = false
     *   CharUtils.isAsciiControl('3')  = false
     *   CharUtils.isAsciiControl('-')  = false
     *   CharUtils.isAsciiControl('\n') = true
     *   CharUtils.isAsciiControl('©') = false
     * 
* * @param ch the character to check * @return true if less than 32 or equals 127 */ public static boolean isAsciiControl(char ch) { return ch < 32 || ch == 127; } /** *

Checks whether the character is ASCII 7 bit alphabetic.

* *
     *   CharUtils.isAsciiAlpha('a')  = true
     *   CharUtils.isAsciiAlpha('A')  = true
     *   CharUtils.isAsciiAlpha('3')  = false
     *   CharUtils.isAsciiAlpha('-')  = false
     *   CharUtils.isAsciiAlpha('\n') = false
     *   CharUtils.isAsciiAlpha('©') = false
     * 
* * @param ch the character to check * @return true if between 65 and 90 or 97 and 122 inclusive */ public static boolean isAsciiAlpha(char ch) { return (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z'); } /** *

Checks whether the character is ASCII 7 bit alphabetic upper case.

* *
     *   CharUtils.isAsciiAlphaUpper('a')  = false
     *   CharUtils.isAsciiAlphaUpper('A')  = true
     *   CharUtils.isAsciiAlphaUpper('3')  = false
     *   CharUtils.isAsciiAlphaUpper('-')  = false
     *   CharUtils.isAsciiAlphaUpper('\n') = false
     *   CharUtils.isAsciiAlphaUpper('©') = false
     * 
* * @param ch the character to check * @return true if between 65 and 90 inclusive */ public static boolean isAsciiAlphaUpper(char ch) { return ch >= 'A' && ch <= 'Z'; } /** *

Checks whether the character is ASCII 7 bit alphabetic lower case.

* *
     *   CharUtils.isAsciiAlphaLower('a')  = true
     *   CharUtils.isAsciiAlphaLower('A')  = false
     *   CharUtils.isAsciiAlphaLower('3')  = false
     *   CharUtils.isAsciiAlphaLower('-')  = false
     *   CharUtils.isAsciiAlphaLower('\n') = false
     *   CharUtils.isAsciiAlphaLower('©') = false
     * 
* * @param ch the character to check * @return true if between 97 and 122 inclusive */ public static boolean isAsciiAlphaLower(char ch) { return ch >= 'a' && ch <= 'z'; } /** *

Checks whether the character is ASCII 7 bit numeric.

* *
     *   CharUtils.isAsciiNumeric('a')  = false
     *   CharUtils.isAsciiNumeric('A')  = false
     *   CharUtils.isAsciiNumeric('3')  = true
     *   CharUtils.isAsciiNumeric('-')  = false
     *   CharUtils.isAsciiNumeric('\n') = false
     *   CharUtils.isAsciiNumeric('©') = false
     * 
* * @param ch the character to check * @return true if between 48 and 57 inclusive */ public static boolean isAsciiNumeric(char ch) { return ch >= '0' && ch <= '9'; } /** *

Checks whether the character is ASCII 7 bit numeric.

* *
     *   CharUtils.isAsciiAlphanumeric('a')  = true
     *   CharUtils.isAsciiAlphanumeric('A')  = true
     *   CharUtils.isAsciiAlphanumeric('3')  = true
     *   CharUtils.isAsciiAlphanumeric('-')  = false
     *   CharUtils.isAsciiAlphanumeric('\n') = false
     *   CharUtils.isAsciiAlphanumeric('©') = false
     * 
* * @param ch the character to check * @return true if between 48 and 57 or 65 and 90 or 97 and 122 inclusive */ public static boolean isAsciiAlphanumeric(char ch) { return (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9'); } // ----------------- Following code copied from Apache Harmony (Character class) /** * Indicates whether {@code ch} is a high- (or leading-) surrogate code unit * that is used for representing supplementary characters in UTF-16 * encoding. * * @param ch * the character to test. * @return {@code true} if {@code ch} is a high-surrogate code unit; * {@code false} otherwise. */ static boolean isHighSurrogate(char ch) { return ('\uD800' <= ch && '\uDBFF' >= ch); } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/ClassUtils.java100644 0 0 125602 11513702445 23730 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.commons.lang.text.StrBuilder; /** *

Operates on classes without using reflection.

* *

This class handles invalid null inputs as best it can. * Each method documents its behaviour in more detail.

* *

The notion of a canonical name includes the human * readable name for the type, for example int[]. The * non-canonical method variants work with the JVM names, such as * [I.

* * @author Apache Software Foundation * @author Gary Gregory * @author Norm Deane * @author Alban Peignier * @author Tomasz Blachowicz * @since 2.0 * @version $Id: ClassUtils.java 1057072 2011-01-10 01:55:57Z niallp $ */ public class ClassUtils { /** *

The package separator character: '.' == {@value}.

*/ public static final char PACKAGE_SEPARATOR_CHAR = '.'; /** *

The package separator String: ".".

*/ public static final String PACKAGE_SEPARATOR = String.valueOf(PACKAGE_SEPARATOR_CHAR); /** *

The inner class separator character: '$' == {@value}.

*/ public static final char INNER_CLASS_SEPARATOR_CHAR = '$'; /** *

The inner class separator String: "$".

*/ public static final String INNER_CLASS_SEPARATOR = String.valueOf(INNER_CLASS_SEPARATOR_CHAR); /** * Maps primitive Classes to their corresponding wrapper Class. */ private static final Map primitiveWrapperMap = new HashMap(); static { primitiveWrapperMap.put(Boolean.TYPE, Boolean.class); primitiveWrapperMap.put(Byte.TYPE, Byte.class); primitiveWrapperMap.put(Character.TYPE, Character.class); primitiveWrapperMap.put(Short.TYPE, Short.class); primitiveWrapperMap.put(Integer.TYPE, Integer.class); primitiveWrapperMap.put(Long.TYPE, Long.class); primitiveWrapperMap.put(Double.TYPE, Double.class); primitiveWrapperMap.put(Float.TYPE, Float.class); primitiveWrapperMap.put(Void.TYPE, Void.TYPE); } /** * Maps wrapper Classes to their corresponding primitive types. */ private static final Map wrapperPrimitiveMap = new HashMap(); static { for (Iterator it = primitiveWrapperMap.keySet().iterator(); it.hasNext();) { Class primitiveClass = (Class) it.next(); Class wrapperClass = (Class) primitiveWrapperMap.get(primitiveClass); if (!primitiveClass.equals(wrapperClass)) { wrapperPrimitiveMap.put(wrapperClass, primitiveClass); } } } /** * Maps a primitive class name to its corresponding abbreviation used in array class names. */ private static final Map abbreviationMap = new HashMap(); /** * Maps an abbreviation used in array class names to corresponding primitive class name. */ private static final Map reverseAbbreviationMap = new HashMap(); /** * Add primitive type abbreviation to maps of abbreviations. * * @param primitive Canonical name of primitive type * @param abbreviation Corresponding abbreviation of primitive type */ private static void addAbbreviation(String primitive, String abbreviation) { abbreviationMap.put(primitive, abbreviation); reverseAbbreviationMap.put(abbreviation, primitive); } /** * Feed abbreviation maps */ static { addAbbreviation("int", "I"); addAbbreviation("boolean", "Z"); addAbbreviation("float", "F"); addAbbreviation("long", "J"); addAbbreviation("short", "S"); addAbbreviation("byte", "B"); addAbbreviation("double", "D"); addAbbreviation("char", "C"); } /** *

ClassUtils instances should NOT be constructed in standard programming. * Instead, the class should be used as * ClassUtils.getShortClassName(cls).

* *

This constructor is public to permit tools that require a JavaBean * instance to operate.

*/ public ClassUtils() { super(); } // Short class name // ---------------------------------------------------------------------- /** *

Gets the class name minus the package name for an Object.

* * @param object the class to get the short name for, may be null * @param valueIfNull the value to return if null * @return the class name of the object without the package name, or the null value */ public static String getShortClassName(Object object, String valueIfNull) { if (object == null) { return valueIfNull; } return getShortClassName(object.getClass()); } /** *

Gets the class name minus the package name from a Class.

* * @param cls the class to get the short name for. * @return the class name without the package name or an empty string */ public static String getShortClassName(Class cls) { if (cls == null) { return StringUtils.EMPTY; } return getShortClassName(cls.getName()); } /** *

Gets the class name minus the package name from a String.

* *

The string passed in is assumed to be a class name - it is not checked.

* * @param className the className to get the short name for * @return the class name of the class without the package name or an empty string */ public static String getShortClassName(String className) { if (className == null) { return StringUtils.EMPTY; } if (className.length() == 0) { return StringUtils.EMPTY; } StrBuilder arrayPrefix = new StrBuilder(); // Handle array encoding if (className.startsWith("[")) { while (className.charAt(0) == '[') { className = className.substring(1); arrayPrefix.append("[]"); } // Strip Object type encoding if (className.charAt(0) == 'L' && className.charAt(className.length() - 1) == ';') { className = className.substring(1, className.length() - 1); } } if (reverseAbbreviationMap.containsKey(className)) { className = (String)reverseAbbreviationMap.get(className); } int lastDotIdx = className.lastIndexOf(PACKAGE_SEPARATOR_CHAR); int innerIdx = className.indexOf( INNER_CLASS_SEPARATOR_CHAR, lastDotIdx == -1 ? 0 : lastDotIdx + 1); String out = className.substring(lastDotIdx + 1); if (innerIdx != -1) { out = out.replace(INNER_CLASS_SEPARATOR_CHAR, PACKAGE_SEPARATOR_CHAR); } return out + arrayPrefix; } // Package name // ---------------------------------------------------------------------- /** *

Gets the package name of an Object.

* * @param object the class to get the package name for, may be null * @param valueIfNull the value to return if null * @return the package name of the object, or the null value */ public static String getPackageName(Object object, String valueIfNull) { if (object == null) { return valueIfNull; } return getPackageName(object.getClass()); } /** *

Gets the package name of a Class.

* * @param cls the class to get the package name for, may be null. * @return the package name or an empty string */ public static String getPackageName(Class cls) { if (cls == null) { return StringUtils.EMPTY; } return getPackageName(cls.getName()); } /** *

Gets the package name from a String.

* *

The string passed in is assumed to be a class name - it is not checked.

*

If the class is unpackaged, return an empty string.

* * @param className the className to get the package name for, may be null * @return the package name or an empty string */ public static String getPackageName(String className) { if (className == null || className.length() == 0) { return StringUtils.EMPTY; } // Strip array encoding while (className.charAt(0) == '[') { className = className.substring(1); } // Strip Object type encoding if (className.charAt(0) == 'L' && className.charAt(className.length() - 1) == ';') { className = className.substring(1); } int i = className.lastIndexOf(PACKAGE_SEPARATOR_CHAR); if (i == -1) { return StringUtils.EMPTY; } return className.substring(0, i); } // Superclasses/Superinterfaces // ---------------------------------------------------------------------- /** *

Gets a List of superclasses for the given class.

* * @param cls the class to look up, may be null * @return the List of superclasses in order going up from this one * null if null input */ public static List getAllSuperclasses(Class cls) { if (cls == null) { return null; } List classes = new ArrayList(); Class superclass = cls.getSuperclass(); while (superclass != null) { classes.add(superclass); superclass = superclass.getSuperclass(); } return classes; } /** *

Gets a List of all interfaces implemented by the given * class and its superclasses.

* *

The order is determined by looking through each interface in turn as * declared in the source file and following its hierarchy up. Then each * superclass is considered in the same way. Later duplicates are ignored, * so the order is maintained.

* * @param cls the class to look up, may be null * @return the List of interfaces in order, * null if null input */ public static List getAllInterfaces(Class cls) { if (cls == null) { return null; } List interfacesFound = new ArrayList(); getAllInterfaces(cls, interfacesFound); return interfacesFound; } /** * Get the interfaces for the specified class. * * @param cls the class to look up, may be null * @param interfacesFound the Set of interfaces for the class */ private static void getAllInterfaces(Class cls, List interfacesFound) { while (cls != null) { Class[] interfaces = cls.getInterfaces(); for (int i = 0; i < interfaces.length; i++) { if (!interfacesFound.contains(interfaces[i])) { interfacesFound.add(interfaces[i]); getAllInterfaces(interfaces[i], interfacesFound); } } cls = cls.getSuperclass(); } } // Convert list // ---------------------------------------------------------------------- /** *

Given a List of class names, this method converts them into classes.

* *

A new List is returned. If the class name cannot be found, null * is stored in the List. If the class name in the List is * null, null is stored in the output List.

* * @param classNames the classNames to change * @return a List of Class objects corresponding to the class names, * null if null input * @throws ClassCastException if classNames contains a non String entry */ public static List convertClassNamesToClasses(List classNames) { if (classNames == null) { return null; } List classes = new ArrayList(classNames.size()); for (Iterator it = classNames.iterator(); it.hasNext();) { String className = (String) it.next(); try { classes.add(Class.forName(className)); } catch (Exception ex) { classes.add(null); } } return classes; } /** *

Given a List of Class objects, this method converts * them into class names.

* *

A new List is returned. null objects will be copied into * the returned list as null.

* * @param classes the classes to change * @return a List of class names corresponding to the Class objects, * null if null input * @throws ClassCastException if classes contains a non-Class entry */ public static List convertClassesToClassNames(List classes) { if (classes == null) { return null; } List classNames = new ArrayList(classes.size()); for (Iterator it = classes.iterator(); it.hasNext();) { Class cls = (Class) it.next(); if (cls == null) { classNames.add(null); } else { classNames.add(cls.getName()); } } return classNames; } // Is assignable // ---------------------------------------------------------------------- /** *

Checks if an array of Classes can be assigned to another array of Classes.

* *

This method calls {@link #isAssignable(Class, Class) isAssignable} for each * Class pair in the input arrays. It can be used to check if a set of arguments * (the first parameter) are suitably compatible with a set of method parameter types * (the second parameter).

* *

Unlike the {@link Class#isAssignableFrom(java.lang.Class)} method, this * method takes into account widenings of primitive classes and * nulls.

* *

Primitive widenings allow an int to be assigned to a long, * float or double. This method returns the correct * result for these cases.

* *

Null may be assigned to any reference type. This method will * return true if null is passed in and the toClass is * non-primitive.

* *

Specifically, this method tests whether the type represented by the * specified Class parameter can be converted to the type * represented by this Class object via an identity conversion * widening primitive or widening reference conversion. See * The Java Language Specification, * sections 5.1.1, 5.1.2 and 5.1.4 for details.

* * @param classArray the array of Classes to check, may be null * @param toClassArray the array of Classes to try to assign into, may be null * @return true if assignment possible */ public static boolean isAssignable(Class[] classArray, Class[] toClassArray) { return isAssignable(classArray, toClassArray, false); } /** *

Checks if an array of Classes can be assigned to another array of Classes.

* *

This method calls {@link #isAssignable(Class, Class) isAssignable} for each * Class pair in the input arrays. It can be used to check if a set of arguments * (the first parameter) are suitably compatible with a set of method parameter types * (the second parameter).

* *

Unlike the {@link Class#isAssignableFrom(java.lang.Class)} method, this * method takes into account widenings of primitive classes and * nulls.

* *

Primitive widenings allow an int to be assigned to a long, * float or double. This method returns the correct * result for these cases.

* *

Null may be assigned to any reference type. This method will * return true if null is passed in and the toClass is * non-primitive.

* *

Specifically, this method tests whether the type represented by the * specified Class parameter can be converted to the type * represented by this Class object via an identity conversion * widening primitive or widening reference conversion. See * The Java Language Specification, * sections 5.1.1, 5.1.2 and 5.1.4 for details.

* * @param classArray the array of Classes to check, may be null * @param toClassArray the array of Classes to try to assign into, may be null * @param autoboxing whether to use implicit autoboxing/unboxing between primitives and wrappers * @return true if assignment possible * @since 2.5 */ public static boolean isAssignable(Class[] classArray, Class[] toClassArray, boolean autoboxing) { if (ArrayUtils.isSameLength(classArray, toClassArray) == false) { return false; } if (classArray == null) { classArray = ArrayUtils.EMPTY_CLASS_ARRAY; } if (toClassArray == null) { toClassArray = ArrayUtils.EMPTY_CLASS_ARRAY; } for (int i = 0; i < classArray.length; i++) { if (isAssignable(classArray[i], toClassArray[i], autoboxing) == false) { return false; } } return true; } /** *

Checks if one Class can be assigned to a variable of * another Class.

* *

Unlike the {@link Class#isAssignableFrom(java.lang.Class)} method, * this method takes into account widenings of primitive classes and * nulls.

* *

Primitive widenings allow an int to be assigned to a long, float or * double. This method returns the correct result for these cases.

* *

Null may be assigned to any reference type. This method * will return true if null is passed in and the * toClass is non-primitive.

* *

Specifically, this method tests whether the type represented by the * specified Class parameter can be converted to the type * represented by this Class object via an identity conversion * widening primitive or widening reference conversion. See * The Java Language Specification, * sections 5.1.1, 5.1.2 and 5.1.4 for details.

* * @param cls the Class to check, may be null * @param toClass the Class to try to assign into, returns false if null * @return true if assignment possible */ public static boolean isAssignable(Class cls, Class toClass) { return isAssignable(cls, toClass, false); } /** *

Checks if one Class can be assigned to a variable of * another Class.

* *

Unlike the {@link Class#isAssignableFrom(java.lang.Class)} method, * this method takes into account widenings of primitive classes and * nulls.

* *

Primitive widenings allow an int to be assigned to a long, float or * double. This method returns the correct result for these cases.

* *

Null may be assigned to any reference type. This method * will return true if null is passed in and the * toClass is non-primitive.

* *

Specifically, this method tests whether the type represented by the * specified Class parameter can be converted to the type * represented by this Class object via an identity conversion * widening primitive or widening reference conversion. See * The Java Language Specification, * sections 5.1.1, 5.1.2 and 5.1.4 for details.

* * @param cls the Class to check, may be null * @param toClass the Class to try to assign into, returns false if null * @param autoboxing whether to use implicit autoboxing/unboxing between primitives and wrappers * @return true if assignment possible * @since 2.5 */ public static boolean isAssignable(Class cls, Class toClass, boolean autoboxing) { if (toClass == null) { return false; } // have to check for null, as isAssignableFrom doesn't if (cls == null) { return !(toClass.isPrimitive()); } //autoboxing: if (autoboxing) { if (cls.isPrimitive() && !toClass.isPrimitive()) { cls = primitiveToWrapper(cls); if (cls == null) { return false; } } if (toClass.isPrimitive() && !cls.isPrimitive()) { cls = wrapperToPrimitive(cls); if (cls == null) { return false; } } } if (cls.equals(toClass)) { return true; } if (cls.isPrimitive()) { if (toClass.isPrimitive() == false) { return false; } if (Integer.TYPE.equals(cls)) { return Long.TYPE.equals(toClass) || Float.TYPE.equals(toClass) || Double.TYPE.equals(toClass); } if (Long.TYPE.equals(cls)) { return Float.TYPE.equals(toClass) || Double.TYPE.equals(toClass); } if (Boolean.TYPE.equals(cls)) { return false; } if (Double.TYPE.equals(cls)) { return false; } if (Float.TYPE.equals(cls)) { return Double.TYPE.equals(toClass); } if (Character.TYPE.equals(cls)) { return Integer.TYPE.equals(toClass) || Long.TYPE.equals(toClass) || Float.TYPE.equals(toClass) || Double.TYPE.equals(toClass); } if (Short.TYPE.equals(cls)) { return Integer.TYPE.equals(toClass) || Long.TYPE.equals(toClass) || Float.TYPE.equals(toClass) || Double.TYPE.equals(toClass); } if (Byte.TYPE.equals(cls)) { return Short.TYPE.equals(toClass) || Integer.TYPE.equals(toClass) || Long.TYPE.equals(toClass) || Float.TYPE.equals(toClass) || Double.TYPE.equals(toClass); } // should never get here return false; } return toClass.isAssignableFrom(cls); } /** *

Converts the specified primitive Class object to its corresponding * wrapper Class object.

* *

NOTE: From v2.2, this method handles Void.TYPE, * returning Void.TYPE.

* * @param cls the class to convert, may be null * @return the wrapper class for cls or cls if * cls is not a primitive. null if null input. * @since 2.1 */ public static Class primitiveToWrapper(Class cls) { Class convertedClass = cls; if (cls != null && cls.isPrimitive()) { convertedClass = (Class) primitiveWrapperMap.get(cls); } return convertedClass; } /** *

Converts the specified array of primitive Class objects to an array of * its corresponding wrapper Class objects.

* * @param classes the class array to convert, may be null or empty * @return an array which contains for each given class, the wrapper class or * the original class if class is not a primitive. null if null input. * Empty array if an empty array passed in. * @since 2.1 */ public static Class[] primitivesToWrappers(Class[] classes) { if (classes == null) { return null; } if (classes.length == 0) { return classes; } Class[] convertedClasses = new Class[classes.length]; for (int i = 0; i < classes.length; i++) { convertedClasses[i] = primitiveToWrapper(classes[i]); } return convertedClasses; } /** *

Converts the specified wrapper class to its corresponding primitive * class.

* *

This method is the counter part of primitiveToWrapper(). * If the passed in class is a wrapper class for a primitive type, this * primitive type will be returned (e.g. Integer.TYPE for * Integer.class). For other classes, or if the parameter is * null, the return value is null.

* * @param cls the class to convert, may be null * @return the corresponding primitive type if cls is a * wrapper class, null otherwise * @see #primitiveToWrapper(Class) * @since 2.4 */ public static Class wrapperToPrimitive(Class cls) { return (Class) wrapperPrimitiveMap.get(cls); } /** *

Converts the specified array of wrapper Class objects to an array of * its corresponding primitive Class objects.

* *

This method invokes wrapperToPrimitive() for each element * of the passed in array.

* * @param classes the class array to convert, may be null or empty * @return an array which contains for each given class, the primitive class or * null if the original class is not a wrapper class. null if null input. * Empty array if an empty array passed in. * @see #wrapperToPrimitive(Class) * @since 2.4 */ public static Class[] wrappersToPrimitives(Class[] classes) { if (classes == null) { return null; } if (classes.length == 0) { return classes; } Class[] convertedClasses = new Class[classes.length]; for (int i = 0; i < classes.length; i++) { convertedClasses[i] = wrapperToPrimitive(classes[i]); } return convertedClasses; } // Inner class // ---------------------------------------------------------------------- /** *

Is the specified class an inner class or static nested class.

* * @param cls the class to check, may be null * @return true if the class is an inner or static nested class, * false if not or null */ public static boolean isInnerClass(Class cls) { if (cls == null) { return false; } return cls.getName().indexOf(INNER_CLASS_SEPARATOR_CHAR) >= 0; } // Class loading // ---------------------------------------------------------------------- /** * Returns the class represented by className using the * classLoader. This implementation supports the syntaxes * "java.util.Map.Entry[]", "java.util.Map$Entry[]", * "[Ljava.util.Map.Entry;", and "[Ljava.util.Map$Entry;". * * @param classLoader the class loader to use to load the class * @param className the class name * @param initialize whether the class must be initialized * @return the class represented by className using the classLoader * @throws ClassNotFoundException if the class is not found */ public static Class getClass( ClassLoader classLoader, String className, boolean initialize) throws ClassNotFoundException { try { Class clazz; if (abbreviationMap.containsKey(className)) { String clsName = "[" + abbreviationMap.get(className); clazz = Class.forName(clsName, initialize, classLoader).getComponentType(); } else { clazz = Class.forName(toCanonicalName(className), initialize, classLoader); } return clazz; } catch (ClassNotFoundException ex) { // allow path separators (.) as inner class name separators int lastDotIndex = className.lastIndexOf(PACKAGE_SEPARATOR_CHAR); if (lastDotIndex != -1) { try { return getClass(classLoader, className.substring(0, lastDotIndex) + INNER_CLASS_SEPARATOR_CHAR + className.substring(lastDotIndex + 1), initialize); } catch (ClassNotFoundException ex2) { } } throw ex; } } /** * Returns the (initialized) class represented by className * using the classLoader. This implementation supports * the syntaxes "java.util.Map.Entry[]", * "java.util.Map$Entry[]", "[Ljava.util.Map.Entry;", * and "[Ljava.util.Map$Entry;". * * @param classLoader the class loader to use to load the class * @param className the class name * @return the class represented by className using the classLoader * @throws ClassNotFoundException if the class is not found */ public static Class getClass(ClassLoader classLoader, String className) throws ClassNotFoundException { return getClass(classLoader, className, true); } /** * Returns the (initialized) class represented by className * using the current thread's context class loader. This implementation * supports the syntaxes "java.util.Map.Entry[]", * "java.util.Map$Entry[]", "[Ljava.util.Map.Entry;", * and "[Ljava.util.Map$Entry;". * * @param className the class name * @return the class represented by className using the current thread's context class loader * @throws ClassNotFoundException if the class is not found */ public static Class getClass(String className) throws ClassNotFoundException { return getClass(className, true); } /** * Returns the class represented by className using the * current thread's context class loader. This implementation supports the * syntaxes "java.util.Map.Entry[]", "java.util.Map$Entry[]", * "[Ljava.util.Map.Entry;", and "[Ljava.util.Map$Entry;". * * @param className the class name * @param initialize whether the class must be initialized * @return the class represented by className using the current thread's context class loader * @throws ClassNotFoundException if the class is not found */ public static Class getClass(String className, boolean initialize) throws ClassNotFoundException { ClassLoader contextCL = Thread.currentThread().getContextClassLoader(); ClassLoader loader = contextCL == null ? ClassUtils.class.getClassLoader() : contextCL; return getClass(loader, className, initialize ); } // Public method // ---------------------------------------------------------------------- /** *

Returns the desired Method much like Class.getMethod, however * it ensures that the returned Method is from a public class or interface and not * from an anonymous inner class. This means that the Method is invokable and * doesn't fall foul of Java bug * 4071957). * *

Set set = Collections.unmodifiableSet(...);
     *  Method method = ClassUtils.getPublicMethod(set.getClass(), "isEmpty",  new Class[0]);
     *  Object result = method.invoke(set, new Object[]);
*

* * @param cls the class to check, not null * @param methodName the name of the method * @param parameterTypes the list of parameters * @return the method * @throws NullPointerException if the class is null * @throws SecurityException if a a security violation occured * @throws NoSuchMethodException if the method is not found in the given class * or if the metothod doen't conform with the requirements */ public static Method getPublicMethod(Class cls, String methodName, Class parameterTypes[]) throws SecurityException, NoSuchMethodException { Method declaredMethod = cls.getMethod(methodName, parameterTypes); if (Modifier.isPublic(declaredMethod.getDeclaringClass().getModifiers())) { return declaredMethod; } List candidateClasses = new ArrayList(); candidateClasses.addAll(getAllInterfaces(cls)); candidateClasses.addAll(getAllSuperclasses(cls)); for (Iterator it = candidateClasses.iterator(); it.hasNext(); ) { Class candidateClass = (Class) it.next(); if (!Modifier.isPublic(candidateClass.getModifiers())) { continue; } Method candidateMethod; try { candidateMethod = candidateClass.getMethod(methodName, parameterTypes); } catch (NoSuchMethodException ex) { continue; } if (Modifier.isPublic(candidateMethod.getDeclaringClass().getModifiers())) { return candidateMethod; } } throw new NoSuchMethodException("Can't find a public method for " + methodName + " " + ArrayUtils.toString(parameterTypes)); } // ---------------------------------------------------------------------- /** * Converts a class name to a JLS style class name. * * @param className the class name * @return the converted name */ private static String toCanonicalName(String className) { className = StringUtils.deleteWhitespace(className); if (className == null) { throw new NullArgumentException("className"); } else if (className.endsWith("[]")) { StrBuilder classNameBuffer = new StrBuilder(); while (className.endsWith("[]")) { className = className.substring(0, className.length() - 2); classNameBuffer.append("["); } String abbreviation = (String) abbreviationMap.get(className); if (abbreviation != null) { classNameBuffer.append(abbreviation); } else { classNameBuffer.append("L").append(className).append(";"); } className = classNameBuffer.toString(); } return className; } /** *

Converts an array of Object in to an array of Class objects. * If any of these objects is null, a null element will be inserted into the array.

* *

This method returns null for a null input array.

* * @param array an Object array * @return a Class array, null if null array input * @since 2.4 */ public static Class[] toClass(Object[] array) { if (array == null) { return null; } else if (array.length == 0) { return ArrayUtils.EMPTY_CLASS_ARRAY; } Class[] classes = new Class[array.length]; for (int i = 0; i < array.length; i++) { classes[i] = array[i] == null ? null : array[i].getClass(); } return classes; } // Short canonical name // ---------------------------------------------------------------------- /** *

Gets the canonical name minus the package name for an Object.

* * @param object the class to get the short name for, may be null * @param valueIfNull the value to return if null * @return the canonical name of the object without the package name, or the null value * @since 2.4 */ public static String getShortCanonicalName(Object object, String valueIfNull) { if (object == null) { return valueIfNull; } return getShortCanonicalName(object.getClass().getName()); } /** *

Gets the canonical name minus the package name from a Class.

* * @param cls the class to get the short name for. * @return the canonical name without the package name or an empty string * @since 2.4 */ public static String getShortCanonicalName(Class cls) { if (cls == null) { return StringUtils.EMPTY; } return getShortCanonicalName(cls.getName()); } /** *

Gets the canonical name minus the package name from a String.

* *

The string passed in is assumed to be a canonical name - it is not checked.

* * @param canonicalName the class name to get the short name for * @return the canonical name of the class without the package name or an empty string * @since 2.4 */ public static String getShortCanonicalName(String canonicalName) { return ClassUtils.getShortClassName(getCanonicalName(canonicalName)); } // Package name // ---------------------------------------------------------------------- /** *

Gets the package name from the canonical name of an Object.

* * @param object the class to get the package name for, may be null * @param valueIfNull the value to return if null * @return the package name of the object, or the null value * @since 2.4 */ public static String getPackageCanonicalName(Object object, String valueIfNull) { if (object == null) { return valueIfNull; } return getPackageCanonicalName(object.getClass().getName()); } /** *

Gets the package name from the canonical name of a Class.

* * @param cls the class to get the package name for, may be null. * @return the package name or an empty string * @since 2.4 */ public static String getPackageCanonicalName(Class cls) { if (cls == null) { return StringUtils.EMPTY; } return getPackageCanonicalName(cls.getName()); } /** *

Gets the package name from the canonical name.

* *

The string passed in is assumed to be a canonical name - it is not checked.

*

If the class is unpackaged, return an empty string.

* * @param canonicalName the canonical name to get the package name for, may be null * @return the package name or an empty string * @since 2.4 */ public static String getPackageCanonicalName(String canonicalName) { return ClassUtils.getPackageName(getCanonicalName(canonicalName)); } /** *

Converts a given name of class into canonical format. * If name of class is not a name of array class it returns * unchanged name.

*

Example: *

    *
  • getCanonicalName("[I") = "int[]"
  • *
  • getCanonicalName("[Ljava.lang.String;") = "java.lang.String[]"
  • *
  • getCanonicalName("java.lang.String") = "java.lang.String"
  • *
*

* * @param className the name of class * @return canonical form of class name * @since 2.4 */ private static String getCanonicalName(String className) { className = StringUtils.deleteWhitespace(className); if (className == null) { return null; } else { int dim = 0; while (className.startsWith("[")) { dim++; className = className.substring(1); } if (dim < 1) { return className; } else { if (className.startsWith("L")) { className = className.substring( 1, className.endsWith(";") ? className.length() - 1 : className.length()); } else { if (className.length() > 0) { className = (String) reverseAbbreviationMap.get( className.substring(0, 1)); } } StrBuilder canonicalClassNameBuffer = new StrBuilder(className); for (int i = 0; i < dim; i++) { canonicalClassNameBuffer.append("[]"); } return canonicalClassNameBuffer.toString(); } } } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/Entities.java100644 0 0 123266 11513702446 23433 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang; import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import java.util.HashMap; import java.util.Map; import java.util.TreeMap; /** *

* Provides HTML and XML entity utilities. *

* * @see ISO Entities * @see HTML 3.2 Character Entities for ISO Latin-1 * @see HTML 4.0 Character entity references * @see HTML 4.01 Character References * @see HTML 4.01 Code positions * * @author Alexander Day Chaffee * @author Gary Gregory * @since 2.0 * @version $Id: Entities.java 1057037 2011-01-09 21:35:32Z niallp $ */ class Entities { private static final String[][] BASIC_ARRAY = {{"quot", "34"}, // " - double-quote {"amp", "38"}, // & - ampersand {"lt", "60"}, // < - less-than {"gt", "62"}, // > - greater-than }; private static final String[][] APOS_ARRAY = {{"apos", "39"}, // XML apostrophe }; // package scoped for testing static final String[][] ISO8859_1_ARRAY = {{"nbsp", "160"}, // non-breaking space {"iexcl", "161"}, // inverted exclamation mark {"cent", "162"}, // cent sign {"pound", "163"}, // pound sign {"curren", "164"}, // currency sign {"yen", "165"}, // yen sign = yuan sign {"brvbar", "166"}, // broken bar = broken vertical bar {"sect", "167"}, // section sign {"uml", "168"}, // diaeresis = spacing diaeresis {"copy", "169"}, // © - copyright sign {"ordf", "170"}, // feminine ordinal indicator {"laquo", "171"}, // left-pointing double angle quotation mark = left pointing guillemet {"not", "172"}, // not sign {"shy", "173"}, // soft hyphen = discretionary hyphen {"reg", "174"}, // ® - registered trademark sign {"macr", "175"}, // macron = spacing macron = overline = APL overbar {"deg", "176"}, // degree sign {"plusmn", "177"}, // plus-minus sign = plus-or-minus sign {"sup2", "178"}, // superscript two = superscript digit two = squared {"sup3", "179"}, // superscript three = superscript digit three = cubed {"acute", "180"}, // acute accent = spacing acute {"micro", "181"}, // micro sign {"para", "182"}, // pilcrow sign = paragraph sign {"middot", "183"}, // middle dot = Georgian comma = Greek middle dot {"cedil", "184"}, // cedilla = spacing cedilla {"sup1", "185"}, // superscript one = superscript digit one {"ordm", "186"}, // masculine ordinal indicator {"raquo", "187"}, // right-pointing double angle quotation mark = right pointing guillemet {"frac14", "188"}, // vulgar fraction one quarter = fraction one quarter {"frac12", "189"}, // vulgar fraction one half = fraction one half {"frac34", "190"}, // vulgar fraction three quarters = fraction three quarters {"iquest", "191"}, // inverted question mark = turned question mark {"Agrave", "192"}, // À - uppercase A, grave accent {"Aacute", "193"}, // Á - uppercase A, acute accent {"Acirc", "194"}, // Â - uppercase A, circumflex accent {"Atilde", "195"}, // Ã - uppercase A, tilde {"Auml", "196"}, // Ä - uppercase A, umlaut {"Aring", "197"}, // Å - uppercase A, ring {"AElig", "198"}, // Æ - uppercase AE {"Ccedil", "199"}, // Ç - uppercase C, cedilla {"Egrave", "200"}, // È - uppercase E, grave accent {"Eacute", "201"}, // É - uppercase E, acute accent {"Ecirc", "202"}, // Ê - uppercase E, circumflex accent {"Euml", "203"}, // Ë - uppercase E, umlaut {"Igrave", "204"}, // Ì - uppercase I, grave accent {"Iacute", "205"}, // Í - uppercase I, acute accent {"Icirc", "206"}, // Î - uppercase I, circumflex accent {"Iuml", "207"}, // Ï - uppercase I, umlaut {"ETH", "208"}, // Ð - uppercase Eth, Icelandic {"Ntilde", "209"}, // Ñ - uppercase N, tilde {"Ograve", "210"}, // Ò - uppercase O, grave accent {"Oacute", "211"}, // Ó - uppercase O, acute accent {"Ocirc", "212"}, // Ô - uppercase O, circumflex accent {"Otilde", "213"}, // Õ - uppercase O, tilde {"Ouml", "214"}, // Ö - uppercase O, umlaut {"times", "215"}, // multiplication sign {"Oslash", "216"}, // Ø - uppercase O, slash {"Ugrave", "217"}, // Ù - uppercase U, grave accent {"Uacute", "218"}, // Ú - uppercase U, acute accent {"Ucirc", "219"}, // Û - uppercase U, circumflex accent {"Uuml", "220"}, // Ü - uppercase U, umlaut {"Yacute", "221"}, // Ý - uppercase Y, acute accent {"THORN", "222"}, // Þ - uppercase THORN, Icelandic {"szlig", "223"}, // ß - lowercase sharps, German {"agrave", "224"}, // à - lowercase a, grave accent {"aacute", "225"}, // á - lowercase a, acute accent {"acirc", "226"}, // â - lowercase a, circumflex accent {"atilde", "227"}, // ã - lowercase a, tilde {"auml", "228"}, // ä - lowercase a, umlaut {"aring", "229"}, // å - lowercase a, ring {"aelig", "230"}, // æ - lowercase ae {"ccedil", "231"}, // ç - lowercase c, cedilla {"egrave", "232"}, // è - lowercase e, grave accent {"eacute", "233"}, // é - lowercase e, acute accent {"ecirc", "234"}, // ê - lowercase e, circumflex accent {"euml", "235"}, // ë - lowercase e, umlaut {"igrave", "236"}, // ì - lowercase i, grave accent {"iacute", "237"}, // í - lowercase i, acute accent {"icirc", "238"}, // î - lowercase i, circumflex accent {"iuml", "239"}, // ï - lowercase i, umlaut {"eth", "240"}, // ð - lowercase eth, Icelandic {"ntilde", "241"}, // ñ - lowercase n, tilde {"ograve", "242"}, // ò - lowercase o, grave accent {"oacute", "243"}, // ó - lowercase o, acute accent {"ocirc", "244"}, // ô - lowercase o, circumflex accent {"otilde", "245"}, // õ - lowercase o, tilde {"ouml", "246"}, // ö - lowercase o, umlaut {"divide", "247"}, // division sign {"oslash", "248"}, // ø - lowercase o, slash {"ugrave", "249"}, // ù - lowercase u, grave accent {"uacute", "250"}, // ú - lowercase u, acute accent {"ucirc", "251"}, // û - lowercase u, circumflex accent {"uuml", "252"}, // ü - lowercase u, umlaut {"yacute", "253"}, // ý - lowercase y, acute accent {"thorn", "254"}, // þ - lowercase thorn, Icelandic {"yuml", "255"}, // ÿ - lowercase y, umlaut }; // http://www.w3.org/TR/REC-html40/sgml/entities.html // package scoped for testing static final String[][] HTML40_ARRAY = { // {"fnof", "402"}, // latin small f with hook = function= florin, U+0192 ISOtech --> // {"Alpha", "913"}, // greek capital letter alpha, U+0391 --> {"Beta", "914"}, // greek capital letter beta, U+0392 --> {"Gamma", "915"}, // greek capital letter gamma,U+0393 ISOgrk3 --> {"Delta", "916"}, // greek capital letter delta,U+0394 ISOgrk3 --> {"Epsilon", "917"}, // greek capital letter epsilon, U+0395 --> {"Zeta", "918"}, // greek capital letter zeta, U+0396 --> {"Eta", "919"}, // greek capital letter eta, U+0397 --> {"Theta", "920"}, // greek capital letter theta,U+0398 ISOgrk3 --> {"Iota", "921"}, // greek capital letter iota, U+0399 --> {"Kappa", "922"}, // greek capital letter kappa, U+039A --> {"Lambda", "923"}, // greek capital letter lambda,U+039B ISOgrk3 --> {"Mu", "924"}, // greek capital letter mu, U+039C --> {"Nu", "925"}, // greek capital letter nu, U+039D --> {"Xi", "926"}, // greek capital letter xi, U+039E ISOgrk3 --> {"Omicron", "927"}, // greek capital letter omicron, U+039F --> {"Pi", "928"}, // greek capital letter pi, U+03A0 ISOgrk3 --> {"Rho", "929"}, // greek capital letter rho, U+03A1 --> // {"Sigma", "931"}, // greek capital letter sigma,U+03A3 ISOgrk3 --> {"Tau", "932"}, // greek capital letter tau, U+03A4 --> {"Upsilon", "933"}, // greek capital letter upsilon,U+03A5 ISOgrk3 --> {"Phi", "934"}, // greek capital letter phi,U+03A6 ISOgrk3 --> {"Chi", "935"}, // greek capital letter chi, U+03A7 --> {"Psi", "936"}, // greek capital letter psi,U+03A8 ISOgrk3 --> {"Omega", "937"}, // greek capital letter omega,U+03A9 ISOgrk3 --> {"alpha", "945"}, // greek small letter alpha,U+03B1 ISOgrk3 --> {"beta", "946"}, // greek small letter beta, U+03B2 ISOgrk3 --> {"gamma", "947"}, // greek small letter gamma,U+03B3 ISOgrk3 --> {"delta", "948"}, // greek small letter delta,U+03B4 ISOgrk3 --> {"epsilon", "949"}, // greek small letter epsilon,U+03B5 ISOgrk3 --> {"zeta", "950"}, // greek small letter zeta, U+03B6 ISOgrk3 --> {"eta", "951"}, // greek small letter eta, U+03B7 ISOgrk3 --> {"theta", "952"}, // greek small letter theta,U+03B8 ISOgrk3 --> {"iota", "953"}, // greek small letter iota, U+03B9 ISOgrk3 --> {"kappa", "954"}, // greek small letter kappa,U+03BA ISOgrk3 --> {"lambda", "955"}, // greek small letter lambda,U+03BB ISOgrk3 --> {"mu", "956"}, // greek small letter mu, U+03BC ISOgrk3 --> {"nu", "957"}, // greek small letter nu, U+03BD ISOgrk3 --> {"xi", "958"}, // greek small letter xi, U+03BE ISOgrk3 --> {"omicron", "959"}, // greek small letter omicron, U+03BF NEW --> {"pi", "960"}, // greek small letter pi, U+03C0 ISOgrk3 --> {"rho", "961"}, // greek small letter rho, U+03C1 ISOgrk3 --> {"sigmaf", "962"}, // greek small letter final sigma,U+03C2 ISOgrk3 --> {"sigma", "963"}, // greek small letter sigma,U+03C3 ISOgrk3 --> {"tau", "964"}, // greek small letter tau, U+03C4 ISOgrk3 --> {"upsilon", "965"}, // greek small letter upsilon,U+03C5 ISOgrk3 --> {"phi", "966"}, // greek small letter phi, U+03C6 ISOgrk3 --> {"chi", "967"}, // greek small letter chi, U+03C7 ISOgrk3 --> {"psi", "968"}, // greek small letter psi, U+03C8 ISOgrk3 --> {"omega", "969"}, // greek small letter omega,U+03C9 ISOgrk3 --> {"thetasym", "977"}, // greek small letter theta symbol,U+03D1 NEW --> {"upsih", "978"}, // greek upsilon with hook symbol,U+03D2 NEW --> {"piv", "982"}, // greek pi symbol, U+03D6 ISOgrk3 --> // {"bull", "8226"}, // bullet = black small circle,U+2022 ISOpub --> // {"hellip", "8230"}, // horizontal ellipsis = three dot leader,U+2026 ISOpub --> {"prime", "8242"}, // prime = minutes = feet, U+2032 ISOtech --> {"Prime", "8243"}, // double prime = seconds = inches,U+2033 ISOtech --> {"oline", "8254"}, // overline = spacing overscore,U+203E NEW --> {"frasl", "8260"}, // fraction slash, U+2044 NEW --> // {"weierp", "8472"}, // script capital P = power set= Weierstrass p, U+2118 ISOamso --> {"image", "8465"}, // blackletter capital I = imaginary part,U+2111 ISOamso --> {"real", "8476"}, // blackletter capital R = real part symbol,U+211C ISOamso --> {"trade", "8482"}, // trade mark sign, U+2122 ISOnum --> {"alefsym", "8501"}, // alef symbol = first transfinite cardinal,U+2135 NEW --> // // {"larr", "8592"}, // leftwards arrow, U+2190 ISOnum --> {"uarr", "8593"}, // upwards arrow, U+2191 ISOnum--> {"rarr", "8594"}, // rightwards arrow, U+2192 ISOnum --> {"darr", "8595"}, // downwards arrow, U+2193 ISOnum --> {"harr", "8596"}, // left right arrow, U+2194 ISOamsa --> {"crarr", "8629"}, // downwards arrow with corner leftwards= carriage return, U+21B5 NEW --> {"lArr", "8656"}, // leftwards double arrow, U+21D0 ISOtech --> // {"uArr", "8657"}, // upwards double arrow, U+21D1 ISOamsa --> {"rArr", "8658"}, // rightwards double arrow,U+21D2 ISOtech --> // {"dArr", "8659"}, // downwards double arrow, U+21D3 ISOamsa --> {"hArr", "8660"}, // left right double arrow,U+21D4 ISOamsa --> // {"forall", "8704"}, // for all, U+2200 ISOtech --> {"part", "8706"}, // partial differential, U+2202 ISOtech --> {"exist", "8707"}, // there exists, U+2203 ISOtech --> {"empty", "8709"}, // empty set = null set = diameter,U+2205 ISOamso --> {"nabla", "8711"}, // nabla = backward difference,U+2207 ISOtech --> {"isin", "8712"}, // element of, U+2208 ISOtech --> {"notin", "8713"}, // not an element of, U+2209 ISOtech --> {"ni", "8715"}, // contains as member, U+220B ISOtech --> // {"prod", "8719"}, // n-ary product = product sign,U+220F ISOamsb --> // {"sum", "8721"}, // n-ary summation, U+2211 ISOamsb --> // {"minus", "8722"}, // minus sign, U+2212 ISOtech --> {"lowast", "8727"}, // asterisk operator, U+2217 ISOtech --> {"radic", "8730"}, // square root = radical sign,U+221A ISOtech --> {"prop", "8733"}, // proportional to, U+221D ISOtech --> {"infin", "8734"}, // infinity, U+221E ISOtech --> {"ang", "8736"}, // angle, U+2220 ISOamso --> {"and", "8743"}, // logical and = wedge, U+2227 ISOtech --> {"or", "8744"}, // logical or = vee, U+2228 ISOtech --> {"cap", "8745"}, // intersection = cap, U+2229 ISOtech --> {"cup", "8746"}, // union = cup, U+222A ISOtech --> {"int", "8747"}, // integral, U+222B ISOtech --> {"there4", "8756"}, // therefore, U+2234 ISOtech --> {"sim", "8764"}, // tilde operator = varies with = similar to,U+223C ISOtech --> // {"cong", "8773"}, // approximately equal to, U+2245 ISOtech --> {"asymp", "8776"}, // almost equal to = asymptotic to,U+2248 ISOamsr --> {"ne", "8800"}, // not equal to, U+2260 ISOtech --> {"equiv", "8801"}, // identical to, U+2261 ISOtech --> {"le", "8804"}, // less-than or equal to, U+2264 ISOtech --> {"ge", "8805"}, // greater-than or equal to,U+2265 ISOtech --> {"sub", "8834"}, // subset of, U+2282 ISOtech --> {"sup", "8835"}, // superset of, U+2283 ISOtech --> // {"sube", "8838"}, // subset of or equal to, U+2286 ISOtech --> {"supe", "8839"}, // superset of or equal to,U+2287 ISOtech --> {"oplus", "8853"}, // circled plus = direct sum,U+2295 ISOamsb --> {"otimes", "8855"}, // circled times = vector product,U+2297 ISOamsb --> {"perp", "8869"}, // up tack = orthogonal to = perpendicular,U+22A5 ISOtech --> {"sdot", "8901"}, // dot operator, U+22C5 ISOamsb --> // // {"lceil", "8968"}, // left ceiling = apl upstile,U+2308 ISOamsc --> {"rceil", "8969"}, // right ceiling, U+2309 ISOamsc --> {"lfloor", "8970"}, // left floor = apl downstile,U+230A ISOamsc --> {"rfloor", "8971"}, // right floor, U+230B ISOamsc --> {"lang", "9001"}, // left-pointing angle bracket = bra,U+2329 ISOtech --> // {"rang", "9002"}, // right-pointing angle bracket = ket,U+232A ISOtech --> // // {"loz", "9674"}, // lozenge, U+25CA ISOpub --> // {"spades", "9824"}, // black spade suit, U+2660 ISOpub --> // {"clubs", "9827"}, // black club suit = shamrock,U+2663 ISOpub --> {"hearts", "9829"}, // black heart suit = valentine,U+2665 ISOpub --> {"diams", "9830"}, // black diamond suit, U+2666 ISOpub --> // {"OElig", "338"}, // -- latin capital ligature OE,U+0152 ISOlat2 --> {"oelig", "339"}, // -- latin small ligature oe, U+0153 ISOlat2 --> // {"Scaron", "352"}, // -- latin capital letter S with caron,U+0160 ISOlat2 --> {"scaron", "353"}, // -- latin small letter s with caron,U+0161 ISOlat2 --> {"Yuml", "376"}, // -- latin capital letter Y with diaeresis,U+0178 ISOlat2 --> // {"circ", "710"}, // -- modifier letter circumflex accent,U+02C6 ISOpub --> {"tilde", "732"}, // small tilde, U+02DC ISOdia --> // {"ensp", "8194"}, // en space, U+2002 ISOpub --> {"emsp", "8195"}, // em space, U+2003 ISOpub --> {"thinsp", "8201"}, // thin space, U+2009 ISOpub --> {"zwnj", "8204"}, // zero width non-joiner,U+200C NEW RFC 2070 --> {"zwj", "8205"}, // zero width joiner, U+200D NEW RFC 2070 --> {"lrm", "8206"}, // left-to-right mark, U+200E NEW RFC 2070 --> {"rlm", "8207"}, // right-to-left mark, U+200F NEW RFC 2070 --> {"ndash", "8211"}, // en dash, U+2013 ISOpub --> {"mdash", "8212"}, // em dash, U+2014 ISOpub --> {"lsquo", "8216"}, // left single quotation mark,U+2018 ISOnum --> {"rsquo", "8217"}, // right single quotation mark,U+2019 ISOnum --> {"sbquo", "8218"}, // single low-9 quotation mark, U+201A NEW --> {"ldquo", "8220"}, // left double quotation mark,U+201C ISOnum --> {"rdquo", "8221"}, // right double quotation mark,U+201D ISOnum --> {"bdquo", "8222"}, // double low-9 quotation mark, U+201E NEW --> {"dagger", "8224"}, // dagger, U+2020 ISOpub --> {"Dagger", "8225"}, // double dagger, U+2021 ISOpub --> {"permil", "8240"}, // per mille sign, U+2030 ISOtech --> {"lsaquo", "8249"}, // single left-pointing angle quotation mark,U+2039 ISO proposed --> // {"rsaquo", "8250"}, // single right-pointing angle quotation mark,U+203A ISO proposed --> // {"euro", "8364"}, // -- euro sign, U+20AC NEW --> }; /** *

* The set of entities supported by standard XML. *

*/ public static final Entities XML; /** *

* The set of entities supported by HTML 3.2. *

*/ public static final Entities HTML32; /** *

* The set of entities supported by HTML 4.0. *

*/ public static final Entities HTML40; static { Entities xml = new Entities(); xml.addEntities(BASIC_ARRAY); xml.addEntities(APOS_ARRAY); XML = xml; } static { Entities html32 = new Entities(); html32.addEntities(BASIC_ARRAY); html32.addEntities(ISO8859_1_ARRAY); HTML32 = html32; } static { Entities html40 = new Entities(); fillWithHtml40Entities(html40); HTML40 = html40; } /** *

* Fills the specified entities instance with HTML 40 entities. *

* * @param entities * the instance to be filled. */ static void fillWithHtml40Entities(Entities entities) { entities.addEntities(BASIC_ARRAY); entities.addEntities(ISO8859_1_ARRAY); entities.addEntities(HTML40_ARRAY); } static interface EntityMap { /** *

* Add an entry to this entity map. *

* * @param name * the entity name * @param value * the entity value */ void add(String name, int value); /** *

* Returns the name of the entity identified by the specified value. *

* * @param value * the value to locate * @return entity name associated with the specified value */ String name(int value); /** *

* Returns the value of the entity identified by the specified name. *

* * @param name * the name to locate * @return entity value associated with the specified name */ int value(String name); } static class PrimitiveEntityMap implements EntityMap { private final Map mapNameToValue = new HashMap(); private final IntHashMap mapValueToName = new IntHashMap(); /** * {@inheritDoc} */ // TODO not thread-safe as there is a window between changing the two maps public void add(String name, int value) { mapNameToValue.put(name, new Integer(value)); mapValueToName.put(value, name); } /** * {@inheritDoc} */ public String name(int value) { return (String) mapValueToName.get(value); } /** * {@inheritDoc} */ public int value(String name) { Object value = mapNameToValue.get(name); if (value == null) { return -1; } return ((Integer) value).intValue(); } } static abstract class MapIntMap implements Entities.EntityMap { protected final Map mapNameToValue; protected final Map mapValueToName; /** * Construct a new instance with specified maps. * * @param nameToValue name to value map * @param valueToName value to namee map */ MapIntMap(Map nameToValue, Map valueToName){ mapNameToValue = nameToValue; mapValueToName = valueToName; } /** * {@inheritDoc} */ public void add(String name, int value) { mapNameToValue.put(name, new Integer(value)); mapValueToName.put(new Integer(value), name); } /** * {@inheritDoc} */ public String name(int value) { return (String) mapValueToName.get(new Integer(value)); } /** * {@inheritDoc} */ public int value(String name) { Object value = mapNameToValue.get(name); if (value == null) { return -1; } return ((Integer) value).intValue(); } } static class HashEntityMap extends MapIntMap { /** * Constructs a new instance of HashEntityMap. */ public HashEntityMap() { super(new HashMap(), new HashMap()); } } static class TreeEntityMap extends MapIntMap { /** * Constructs a new instance of TreeEntityMap. */ public TreeEntityMap() { super(new TreeMap(), new TreeMap()); } } static class LookupEntityMap extends PrimitiveEntityMap { // TODO this class is not thread-safe private String[] lookupTable; private static final int LOOKUP_TABLE_SIZE = 256; /** * {@inheritDoc} */ public String name(int value) { if (value < LOOKUP_TABLE_SIZE) { return lookupTable()[value]; } return super.name(value); } /** *

* Returns the lookup table for this entity map. The lookup table is created if it has not been previously. *

* * @return the lookup table */ private String[] lookupTable() { if (lookupTable == null) { createLookupTable(); } return lookupTable; } /** *

* Creates an entity lookup table of LOOKUP_TABLE_SIZE elements, initialized with entity names. *

*/ private void createLookupTable() { lookupTable = new String[LOOKUP_TABLE_SIZE]; for (int i = 0; i < LOOKUP_TABLE_SIZE; ++i) { lookupTable[i] = super.name(i); } } } static class ArrayEntityMap implements EntityMap { // TODO this class is not thread-safe protected final int growBy; protected int size = 0; protected String[] names; protected int[] values; /** * Constructs a new instance of ArrayEntityMap. */ public ArrayEntityMap() { this.growBy = 100; names = new String[growBy]; values = new int[growBy]; } /** * Constructs a new instance of ArrayEntityMap specifying the size by which the array should * grow. * * @param growBy * array will be initialized to and will grow by this amount */ public ArrayEntityMap(int growBy) { this.growBy = growBy; names = new String[growBy]; values = new int[growBy]; } /** * {@inheritDoc} */ public void add(String name, int value) { ensureCapacity(size + 1); names[size] = name; values[size] = value; size++; } /** * Verifies the capacity of the entity array, adjusting the size if necessary. * * @param capacity * size the array should be */ protected void ensureCapacity(int capacity) { if (capacity > names.length) { int newSize = Math.max(capacity, size + growBy); String[] newNames = new String[newSize]; System.arraycopy(names, 0, newNames, 0, size); names = newNames; int[] newValues = new int[newSize]; System.arraycopy(values, 0, newValues, 0, size); values = newValues; } } /** * {@inheritDoc} */ public String name(int value) { for (int i = 0; i < size; ++i) { if (values[i] == value) { return names[i]; } } return null; } /** * {@inheritDoc} */ public int value(String name) { for (int i = 0; i < size; ++i) { if (names[i].equals(name)) { return values[i]; } } return -1; } } static class BinaryEntityMap extends ArrayEntityMap { // TODO - not thread-safe, because parent is not. Also references size. /** * Constructs a new instance of BinaryEntityMap. */ public BinaryEntityMap() { super(); } /** * Constructs a new instance of ArrayEntityMap specifying the size by which the underlying array * should grow. * * @param growBy * array will be initialized to and will grow by this amount */ public BinaryEntityMap(int growBy) { super(growBy); } /** * Performs a binary search of the entity array for the specified key. This method is based on code in * {@link java.util.Arrays}. * * @param key * the key to be found * @return the index of the entity array matching the specified key */ private int binarySearch(int key) { int low = 0; int high = size - 1; while (low <= high) { int mid = (low + high) >>> 1; int midVal = values[mid]; if (midVal < key) { low = mid + 1; } else if (midVal > key) { high = mid - 1; } else { return mid; // key found } } return -(low + 1); // key not found. } /** * {@inheritDoc} */ public void add(String name, int value) { ensureCapacity(size + 1); int insertAt = binarySearch(value); if (insertAt > 0) { return; // note: this means you can't insert the same value twice } insertAt = -(insertAt + 1); // binarySearch returns it negative and off-by-one System.arraycopy(values, insertAt, values, insertAt + 1, size - insertAt); values[insertAt] = value; System.arraycopy(names, insertAt, names, insertAt + 1, size - insertAt); names[insertAt] = name; size++; } /** * {@inheritDoc} */ public String name(int value) { int index = binarySearch(value); if (index < 0) { return null; } return names[index]; } } private final EntityMap map; /** * Default constructor. */ public Entities(){ map = new Entities.LookupEntityMap(); } /** * package scoped constructor for testing. * * @param emap entity map. */ Entities(EntityMap emap){ map = emap; } /** *

* Adds entities to this entity. *

* * @param entityArray * array of entities to be added */ public void addEntities(String[][] entityArray) { for (int i = 0; i < entityArray.length; ++i) { addEntity(entityArray[i][0], Integer.parseInt(entityArray[i][1])); } } /** *

* Add an entity to this entity. *

* * @param name * name of the entity * @param value * vale of the entity */ public void addEntity(String name, int value) { map.add(name, value); } /** *

* Returns the name of the entity identified by the specified value. *

* * @param value * the value to locate * @return entity name associated with the specified value */ public String entityName(int value) { return map.name(value); } /** *

* Returns the value of the entity identified by the specified name. *

* * @param name * the name to locate * @return entity value associated with the specified name */ public int entityValue(String name) { return map.value(name); } /** *

* Escapes the characters in a String. *

* *

* For example, if you have called addEntity("foo", 0xA1), escape("\u00A1") will return * "&foo;" *

* * @param str * The String to escape. * @return A new escaped String. */ public String escape(String str) { StringWriter stringWriter = createStringWriter(str); try { this.escape(stringWriter, str); } catch (IOException e) { // This should never happen because ALL the StringWriter methods called by #escape(Writer, String) do not // throw IOExceptions. throw new UnhandledException(e); } return stringWriter.toString(); } /** *

* Escapes the characters in the String passed and writes the result to the Writer * passed. *

* * @param writer * The Writer to write the results of the escaping to. Assumed to be a non-null value. * @param str * The String to escape. Assumed to be a non-null value. * @throws IOException * when Writer passed throws the exception from calls to the {@link Writer#write(int)} * methods. * * @see #escape(String) * @see Writer */ public void escape(Writer writer, String str) throws IOException { int len = str.length(); for (int i = 0; i < len; i++) { char c = str.charAt(i); String entityName = this.entityName(c); if (entityName == null) { if (c > 0x7F) { writer.write("&#"); writer.write(Integer.toString(c, 10)); writer.write(';'); } else { writer.write(c); } } else { writer.write('&'); writer.write(entityName); writer.write(';'); } } } /** *

* Unescapes the entities in a String. *

* *

* For example, if you have called addEntity("foo", 0xA1), unescape("&foo;") will return * "\u00A1" *

* * @param str * The String to escape. * @return A new escaped String. */ public String unescape(String str) { int firstAmp = str.indexOf('&'); if (firstAmp < 0) { return str; } else { StringWriter stringWriter = createStringWriter(str); try { this.doUnescape(stringWriter, str, firstAmp); } catch (IOException e) { // This should never happen because ALL the StringWriter methods called by #escape(Writer, String) // do not throw IOExceptions. throw new UnhandledException(e); } return stringWriter.toString(); } } /** * Make the StringWriter 10% larger than the source String to avoid growing the writer * * @param str The source string * @return A newly created StringWriter */ private StringWriter createStringWriter(String str) { return new StringWriter((int) (str.length() + (str.length() * 0.1))); } /** *

* Unescapes the escaped entities in the String passed and writes the result to the * Writer passed. *

* * @param writer * The Writer to write the results to; assumed to be non-null. * @param str * The source String to unescape; assumed to be non-null. * @throws IOException * when Writer passed throws the exception from calls to the {@link Writer#write(int)} * methods. * * @see #escape(String) * @see Writer */ public void unescape(Writer writer, String str) throws IOException { int firstAmp = str.indexOf('&'); if (firstAmp < 0) { writer.write(str); return; } else { doUnescape(writer, str, firstAmp); } } /** * Underlying unescape method that allows the optimisation of not starting from the 0 index again. * * @param writer * The Writer to write the results to; assumed to be non-null. * @param str * The source String to unescape; assumed to be non-null. * @param firstAmp * The int index of the first ampersand in the source String. * @throws IOException * when Writer passed throws the exception from calls to the {@link Writer#write(int)} * methods. */ private void doUnescape(Writer writer, String str, int firstAmp) throws IOException { writer.write(str, 0, firstAmp); int len = str.length(); for (int i = firstAmp; i < len; i++) { char c = str.charAt(i); if (c == '&') { int nextIdx = i + 1; int semiColonIdx = str.indexOf(';', nextIdx); if (semiColonIdx == -1) { writer.write(c); continue; } int amphersandIdx = str.indexOf('&', i + 1); if (amphersandIdx != -1 && amphersandIdx < semiColonIdx) { // Then the text looks like &...&...; writer.write(c); continue; } String entityContent = str.substring(nextIdx, semiColonIdx); int entityValue = -1; int entityContentLen = entityContent.length(); if (entityContentLen > 0) { if (entityContent.charAt(0) == '#') { // escaped value content is an integer (decimal or // hexidecimal) if (entityContentLen > 1) { char isHexChar = entityContent.charAt(1); try { switch (isHexChar) { case 'X' : case 'x' : { entityValue = Integer.parseInt(entityContent.substring(2), 16); break; } default : { entityValue = Integer.parseInt(entityContent.substring(1), 10); } } if (entityValue > 0xFFFF) { entityValue = -1; } } catch (NumberFormatException e) { entityValue = -1; } } } else { // escaped value content is an entity name entityValue = this.entityValue(entityContent); } } if (entityValue == -1) { writer.write('&'); writer.write(entityContent); writer.write(';'); } else { writer.write(entityValue); } i = semiColonIdx; // move index up to the semi-colon } else { writer.write(c); } } } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/enum/Enum.java100644 0 0 56130 11513702445 23471 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.enum; import java.io.Serializable; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.WeakHashMap; import org.apache.commons.lang.ClassUtils; import org.apache.commons.lang.StringUtils; /** *

Abstract superclass for type-safe enums.

* *

One feature of the C programming language lacking in Java is enumerations. The * C implementation based on ints was poor and open to abuse. The original Java * recommendation and most of the JDK also uses int constants. It has been recognised * however that a more robust type-safe class-based solution can be designed. This * class follows the basic Java type-safe enumeration pattern.

* *

NOTE:Due to the way in which Java ClassLoaders work, comparing * Enum objects should always be done using equals(), not ==. * The equals() method will try == first so in most cases the effect is the same.

* *

Of course, if you actually want (or don't mind) Enums in different class * loaders being non-equal, then you can use ==.

* *

Simple Enums

* *

To use this class, it must be subclassed. For example:

* *
 * public final class ColorEnum extends Enum {
 *   public static final ColorEnum RED = new ColorEnum("Red");
 *   public static final ColorEnum GREEN = new ColorEnum("Green");
 *   public static final ColorEnum BLUE = new ColorEnum("Blue");
 *
 *   private ColorEnum(String color) {
 *     super(color);
 *   }
 * 
 *   public static ColorEnum getEnum(String color) {
 *     return (ColorEnum) getEnum(ColorEnum.class, color);
 *   }
 * 
 *   public static Map getEnumMap() {
 *     return getEnumMap(ColorEnum.class);
 *   }
 * 
 *   public static List getEnumList() {
 *     return getEnumList(ColorEnum.class);
 *   }
 * 
 *   public static Iterator iterator() {
 *     return iterator(ColorEnum.class);
 *   }
 * }
 * 
* *

As shown, each enum has a name. This can be accessed using getName.

* *

The getEnum and iterator methods are recommended. * Unfortunately, Java restrictions require these to be coded as shown in each subclass. * An alternative choice is to use the {@link EnumUtils} class.

* *

Subclassed Enums

*

A hierarchy of Enum classes can be built. In this case, the superclass is * unaffected by the addition of subclasses (as per normal Java). The subclasses * may add additional Enum constants of the type of the superclass. The * query methods on the subclass will return all of the Enum constants from the * superclass and subclass.

* *
 * public final class ExtraColorEnum extends ColorEnum {
 *   // NOTE: Color enum declared above is final, change that to get this
 *   // example to compile.
 *   public static final ColorEnum YELLOW = new ExtraColorEnum("Yellow");
 *
 *   private ExtraColorEnum(String color) {
 *     super(color);
 *   }
 * 
 *   public static ColorEnum getEnum(String color) {
 *     return (ColorEnum) getEnum(ExtraColorEnum.class, color);
 *   }
 * 
 *   public static Map getEnumMap() {
 *     return getEnumMap(ExtraColorEnum.class);
 *   }
 * 
 *   public static List getEnumList() {
 *     return getEnumList(ExtraColorEnum.class);
 *   }
 * 
 *   public static Iterator iterator() {
 *     return iterator(ExtraColorEnum.class);
 *   }
 * }
 * 
* *

This example will return RED, GREEN, BLUE, YELLOW from the List and iterator * methods in that order. The RED, GREEN and BLUE instances will be the same (==) * as those from the superclass ColorEnum. Note that YELLOW is declared as a * ColorEnum and not an ExtraColorEnum.

* *

Functional Enums

* *

The enums can have functionality by defining subclasses and * overriding the getEnumClass() method:

* *
 *   public static final OperationEnum PLUS = new PlusOperation();
 *   private static final class PlusOperation extends OperationEnum {
 *     private PlusOperation() {
 *       super("Plus");
 *     }
 *     public int eval(int a, int b) {
 *       return a + b;
 *     }
 *   }
 *   public static final OperationEnum MINUS = new MinusOperation();
 *   private static final class MinusOperation extends OperationEnum {
 *     private MinusOperation() {
 *       super("Minus");
 *     }
 *     public int eval(int a, int b) {
 *       return a - b;
 *     }
 *   }
 *
 *   private OperationEnum(String color) {
 *     super(color);
 *   }
 * 
 *   public final Class getEnumClass() {     // NOTE: new method!
 *     return OperationEnum.class;
 *   }
 *
 *   public abstract double eval(double a, double b);
 * 
 *   public static OperationEnum getEnum(String name) {
 *     return (OperationEnum) getEnum(OperationEnum.class, name);
 *   }
 * 
 *   public static Map getEnumMap() {
 *     return getEnumMap(OperationEnum.class);
 *   }
 * 
 *   public static List getEnumList() {
 *     return getEnumList(OperationEnum.class);
 *   }
 * 
 *   public static Iterator iterator() {
 *     return iterator(OperationEnum.class);
 *   }
 * }
 * 
*

The code above will work on JDK 1.2. If JDK1.3 and later is used, * the subclasses may be defined as anonymous.

* *

Nested class Enums

* *

Care must be taken with class loading when defining a static nested class * for enums. The static nested class can be loaded without the surrounding outer * class being loaded. This can result in an empty list/map/iterator being returned. * One solution is to define a static block that references the outer class where * the constants are defined. For example:

* *
 * public final class Outer {
 *   public static final BWEnum BLACK = new BWEnum("Black");
 *   public static final BWEnum WHITE = new BWEnum("White");
 *
 *   // static nested enum class
 *   public static final class BWEnum extends Enum {
 * 
 *     static {
 *       // explicitly reference BWEnum class to force constants to load
 *       Object obj = Outer.BLACK;
 *     }
 * 
 *     // ... other methods omitted
 *   }
 * }
 * 
* *

Although the above solves the problem, it is not recommended. The best solution * is to define the constants in the enum class, and hold references in the outer class: * *

 * public final class Outer {
 *   public static final BWEnum BLACK = BWEnum.BLACK;
 *   public static final BWEnum WHITE = BWEnum.WHITE;
 *
 *   // static nested enum class
 *   public static final class BWEnum extends Enum {
 *     // only define constants in enum classes - private if desired
 *     private static final BWEnum BLACK = new BWEnum("Black");
 *     private static final BWEnum WHITE = new BWEnum("White");
 * 
 *     // ... other methods omitted
 *   }
 * }
 * 
* *

For more details, see the 'Nested' test cases. * * @deprecated Replaced by {@link org.apache.commons.lang.enums.Enum org.apache.commons.lang.enums.Enum} * and will be removed in version 3.0. All classes in this package are deprecated and repackaged to * {@link org.apache.commons.lang.enums} since enum is a Java 1.5 keyword. * @see org.apache.commons.lang.enums.Enum * @author Apache Avalon project * @author Apache Software Foundation * @author Chris Webb * @author Mike Bowler * @since 1.0 * @version $Id: Enum.java 912394 2010-02-21 20:16:22Z niallp $ */ public abstract class Enum implements Comparable, Serializable { /** * Required for serialization support. Lang version 1.0.1 serial compatibility. * * @see java.io.Serializable */ private static final long serialVersionUID = -487045951170455942L; // After discussion, the default size for HashMaps is used, as the // sizing algorithm changes across the JDK versions /** * An empty Map, as JDK1.2 didn't have an empty map. */ private static final Map EMPTY_MAP = Collections.unmodifiableMap(new HashMap(0)); /** * Map, key of class name, value of Entry. */ private static Map cEnumClasses // LANG-334: To avoid exposing a mutating map, // we copy it each time we add to it. This is cheaper than // using a synchronized map since we are almost entirely reads = new WeakHashMap(); /** * The string representation of the Enum. */ private final String iName; /** * The hashcode representation of the Enum. */ private transient final int iHashCode; /** * The toString representation of the Enum. * @since 2.0 */ protected transient String iToString = null; /** *

Enable the iterator to retain the source code order.

*/ private static class Entry { /** * Map of Enum name to Enum. */ final Map map = new HashMap(); /** * Map of Enum name to Enum. */ final Map unmodifiableMap = Collections.unmodifiableMap(map); /** * List of Enums in source code order. */ final List list = new ArrayList(25); /** * Map of Enum name to Enum. */ final List unmodifiableList = Collections.unmodifiableList(list); /** *

Restrictive constructor.

*/ protected Entry() { super(); } } /** *

Constructor to add a new named item to the enumeration.

* * @param name the name of the enum object, * must not be empty or null * @throws IllegalArgumentException if the name is null * or an empty string * @throws IllegalArgumentException if the getEnumClass() method returns * a null or invalid Class */ protected Enum(String name) { super(); init(name); iName = name; iHashCode = 7 + getEnumClass().hashCode() + 3 * name.hashCode(); // cannot create toString here as subclasses may want to include other data } /** * Initializes the enumeration. * * @param name the enum name * @throws IllegalArgumentException if the name is null or empty or duplicate * @throws IllegalArgumentException if the enumClass is null or invalid */ private void init(String name) { if (StringUtils.isEmpty(name)) { throw new IllegalArgumentException("The Enum name must not be empty or null"); } Class enumClass = getEnumClass(); if (enumClass == null) { throw new IllegalArgumentException("getEnumClass() must not be null"); } Class cls = getClass(); boolean ok = false; while (cls != null && cls != Enum.class && cls != ValuedEnum.class) { if (cls == enumClass) { ok = true; break; } cls = cls.getSuperclass(); } if (ok == false) { throw new IllegalArgumentException("getEnumClass() must return a superclass of this class"); } Entry entry; synchronized( Enum.class ) { // LANG-334 // create entry entry = (Entry) cEnumClasses.get(enumClass); if (entry == null) { entry = createEntry(enumClass); Map myMap = new WeakHashMap( ); // we avoid the (Map) constructor to achieve JDK 1.2 support myMap.putAll( cEnumClasses ); myMap.put(enumClass, entry); cEnumClasses = myMap; } } if (entry.map.containsKey(name)) { throw new IllegalArgumentException("The Enum name must be unique, '" + name + "' has already been added"); } entry.map.put(name, this); entry.list.add(this); } /** *

Handle the deserialization of the class to ensure that multiple * copies are not wastefully created, or illegal enum types created.

* * @return the resolved object */ protected Object readResolve() { Entry entry = (Entry) cEnumClasses.get(getEnumClass()); if (entry == null) { return null; } return entry.map.get(getName()); } //-------------------------------------------------------------------------------- /** *

Gets an Enum object by class and name.

* * @param enumClass the class of the Enum to get, must not * be null * @param name the name of the Enum to get, * may be null * @return the enum object, or null if the enum does not exist * @throws IllegalArgumentException if the enum class * is null */ protected static Enum getEnum(Class enumClass, String name) { Entry entry = getEntry(enumClass); if (entry == null) { return null; } return (Enum) entry.map.get(name); } /** *

Gets the Map of Enum objects by * name using the Enum class.

* *

If the requested class has no enum objects an empty * Map is returned.

* * @param enumClass the class of the Enum to get, * must not be null * @return the enum object Map * @throws IllegalArgumentException if the enum class is null * @throws IllegalArgumentException if the enum class is not a subclass of Enum */ protected static Map getEnumMap(Class enumClass) { Entry entry = getEntry(enumClass); if (entry == null) { return EMPTY_MAP; } return entry.unmodifiableMap; } /** *

Gets the List of Enum objects using the * Enum class.

* *

The list is in the order that the objects were created (source code order). * If the requested class has no enum objects an empty List is * returned.

* * @param enumClass the class of the Enum to get, * must not be null * @return the enum object Map * @throws IllegalArgumentException if the enum class is null * @throws IllegalArgumentException if the enum class is not a subclass of Enum */ protected static List getEnumList(Class enumClass) { Entry entry = getEntry(enumClass); if (entry == null) { return Collections.EMPTY_LIST; } return entry.unmodifiableList; } /** *

Gets an Iterator over the Enum objects in * an Enum class.

* *

The Iterator is in the order that the objects were * created (source code order). If the requested class has no enum * objects an empty Iterator is returned.

* * @param enumClass the class of the Enum to get, * must not be null * @return an iterator of the Enum objects * @throws IllegalArgumentException if the enum class is null * @throws IllegalArgumentException if the enum class is not a subclass of Enum */ protected static Iterator iterator(Class enumClass) { return Enum.getEnumList(enumClass).iterator(); } //----------------------------------------------------------------------- /** *

Gets an Entry from the map of Enums.

* * @param enumClass the class of the Enum to get * @return the enum entry */ private static Entry getEntry(Class enumClass) { if (enumClass == null) { throw new IllegalArgumentException("The Enum Class must not be null"); } if (Enum.class.isAssignableFrom(enumClass) == false) { throw new IllegalArgumentException("The Class must be a subclass of Enum"); } Entry entry = (Entry) cEnumClasses.get(enumClass); if (entry == null) { try { // LANG-76 - try to force class initialization for JDK 1.5+ Class.forName(enumClass.getName(), true, enumClass.getClassLoader()); entry = (Entry) cEnumClasses.get(enumClass); } catch (Exception e) { // Ignore } } return entry; } /** *

Creates an Entry for storing the Enums.

* *

This accounts for subclassed Enums.

* * @param enumClass the class of the Enum to get * @return the enum entry */ private static Entry createEntry(Class enumClass) { Entry entry = new Entry(); Class cls = enumClass.getSuperclass(); while (cls != null && cls != Enum.class && cls != ValuedEnum.class) { Entry loopEntry = (Entry) cEnumClasses.get(cls); if (loopEntry != null) { entry.list.addAll(loopEntry.list); entry.map.putAll(loopEntry.map); break; // stop here, as this will already have had superclasses added } cls = cls.getSuperclass(); } return entry; } //----------------------------------------------------------------------- /** *

Retrieve the name of this Enum item, set in the constructor.

* * @return the String name of this Enum item */ public final String getName() { return iName; } /** *

Retrieves the Class of this Enum item, set in the constructor.

* *

This is normally the same as getClass(), but for * advanced Enums may be different. If overridden, it must return a * constant value.

* * @return the Class of the enum * @since 2.0 */ public Class getEnumClass() { return getClass(); } /** *

Tests for equality.

* *

Two Enum objects are considered equal * if they have the same class names and the same names. * Identity is tested for first, so this method usually runs fast.

* *

If the parameter is in a different class loader than this instance, * reflection is used to compare the names.

* * @param other the other object to compare for equality * @return true if the Enums are equal */ public final boolean equals(Object other) { if (other == this) { return true; } else if (other == null) { return false; } else if (other.getClass() == this.getClass()) { // Ok to do a class cast to Enum here since the test above // guarantee both // classes are in the same class loader. return iName.equals(((Enum) other).iName); } else { // This and other are in different class loaders, we must check indirectly if (other.getClass().getName().equals(this.getClass().getName()) == false) { return false; } return iName.equals( getNameInOtherClassLoader(other) ); } } /** *

Returns a suitable hashCode for the enumeration.

* * @return a hashcode based on the name */ public final int hashCode() { return iHashCode; } /** *

Tests for order.

* *

The default ordering is alphabetic by name, but this * can be overridden by subclasses.

* *

If the parameter is in a different class loader than this instance, * reflection is used to compare the names.

* * @see java.lang.Comparable#compareTo(Object) * @param other the other object to compare to * @return -ve if this is less than the other object, +ve if greater * than, 0 of equal * @throws ClassCastException if other is not an Enum * @throws NullPointerException if other is null */ public int compareTo(Object other) { if (other == this) { return 0; } if (other.getClass() != this.getClass()) { if (other.getClass().getName().equals(this.getClass().getName())) { return iName.compareTo( getNameInOtherClassLoader(other) ); } throw new ClassCastException( "Different enum class '" + ClassUtils.getShortClassName(other.getClass()) + "'"); } return iName.compareTo(((Enum) other).iName); } /** *

Use reflection to return an objects class name.

* * @param other The object to determine the class name for * @return The class name */ private String getNameInOtherClassLoader(Object other) { try { Method mth = other.getClass().getMethod("getName", null); String name = (String) mth.invoke(other, null); return name; } catch (NoSuchMethodException e) { // ignore - should never happen } catch (IllegalAccessException e) { // ignore - should never happen } catch (InvocationTargetException e) { // ignore - should never happen } throw new IllegalStateException("This should not happen"); } /** *

Human readable description of this Enum item.

* * @return String in the form type[name], for example: * Color[Red]. Note that the package name is stripped from * the type name. */ public String toString() { if (iToString == null) { String shortName = ClassUtils.getShortClassName(getEnumClass()); iToString = shortName + "[" + getName() + "]"; } return iToString; } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/enum/EnumUtils.java100644 0 0 12010 11513702445 24477 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.enum; import java.util.Iterator; import java.util.List; import java.util.Map; /** *

Utility class for accessing and manipulating {@link Enum}s.

* * @deprecated Replaced by {@link org.apache.commons.lang.enums.EnumUtils org.apache.commons.lang.enums.EnumUtils} * and will be removed in version 3.0. All classes in this package are deprecated and repackaged to * {@link org.apache.commons.lang.enums} since enum is a Java 1.5 keyword. * @see org.apache.commons.lang.enums.EnumUtils * @see Enum * @see ValuedEnum * @author Apache Software Foundation * @author Gary Gregory * @since 1.0 * @version $Id: EnumUtils.java 905636 2010-02-02 14:03:32Z niallp $ */ public class EnumUtils { /** * Public constructor. This class should not normally be instantiated. * @since 2.0 */ public EnumUtils() { super(); } /** *

Gets an Enum object by class and name.

* * @param enumClass the class of the Enum to get * @param name the name of the Enum to get, may be null * @return the enum object * @throws IllegalArgumentException if the enum class is null */ public static Enum getEnum(Class enumClass, String name) { return Enum.getEnum(enumClass, name); } /** *

Gets a ValuedEnum object by class and value.

* * @param enumClass the class of the Enum to get * @param value the value of the Enum to get * @return the enum object, or null if the enum does not exist * @throws IllegalArgumentException if the enum class is null */ public static ValuedEnum getEnum(Class enumClass, int value) { return (ValuedEnum) ValuedEnum.getEnum(enumClass, value); } /** *

Gets the Map of Enum objects by * name using the Enum class.

* *

If the requested class has no enum objects an empty * Map is returned. The Map is unmodifiable.

* * @param enumClass the class of the Enum to get * @return the enum object Map * @throws IllegalArgumentException if the enum class is null * @throws IllegalArgumentException if the enum class is not a subclass * of Enum */ public static Map getEnumMap(Class enumClass) { return Enum.getEnumMap(enumClass); } /** *

Gets the List of Enum objects using * the Enum class.

* *

The list is in the order that the objects were created * (source code order).

* *

If the requested class has no enum objects an empty * List is returned. The List is unmodifiable.

* * @param enumClass the class of the Enum to get * @return the enum object Map * @throws IllegalArgumentException if the enum class is null * @throws IllegalArgumentException if the enum class is not a subclass * of Enum */ public static List getEnumList(Class enumClass) { return Enum.getEnumList(enumClass); } /** *

Gets an Iterator over the Enum objects * in an Enum class.

* *

The iterator is in the order that the objects were created * (source code order).

* *

If the requested class has no enum objects an empty * Iterator is returned. The Iterator * is unmodifiable.

* * @param enumClass the class of the Enum to get * @return an Iterator of the Enum objects * @throws IllegalArgumentException if the enum class is null * @throws IllegalArgumentException if the enum class is not a subclass of Enum */ public static Iterator iterator(Class enumClass) { return Enum.getEnumList(enumClass).iterator(); } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/enum/package.html100644 0 0 3713 11513702445 24162 0ustar 0 0

Deprecated and replaced by {@link org.apache.commons.lang.enums} and will be removed in version 3.0.

All classes in this package are deprecated and repackaged to {@link org.apache.commons.lang.enums} since enum is a Java 1.5 keyword.

Provides an implementation of the C style enum in the Java world.

The classic example being an RGB color enumeration.

public final class ColorEnum extends Enum {
    public static final ColorEnum RED = new ColorEnum("Red");
    public static final ColorEnum GREEN = new ColorEnum("Green");
    public static final ColorEnum BLUE = new ColorEnum("Blue");

    private ColorEnum(String color) {
        super(color);
    }

    public static ColorEnum getEnum(String color) {
        return (ColorEnum) getEnum(ColorEnum.class, color);
    }

    public static Map getEnumMap() {
        return getEnumMap(ColorEnum.class);
    }

    public static List getEnumList() {
        return getEnumList(ColorEnum.class);
    }

    public static Iterator iterator() {
        return iterator(ColorEnum.class);
    }
}
@since 1.0 commons-lang-2.6-src/src/main/java/org/apache/commons/lang/enum/ValuedEnum.java100644 0 0 16076 11513702445 24637 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.enum; import java.util.Iterator; import java.util.List; import org.apache.commons.lang.ClassUtils; /** *

Abstract superclass for type-safe enums with integer values suitable * for use in switch statements.

* *

NOTE:Due to the way in which Java ClassLoaders work, comparing * Enum objects should always be done using the equals() method, * not ==. The equals() method will try == first so * in most cases the effect is the same.

* *

To use this class, it must be subclassed. For example:

* *
 * public final class JavaVersionEnum extends ValuedEnum {
 *   //standard enums for version of JVM
 *   public static final int  JAVA1_0_VALUE  = 100;
 *   public static final int  JAVA1_1_VALUE  = 110;
 *   public static final int  JAVA1_2_VALUE  = 120;
 *   public static final int  JAVA1_3_VALUE  = 130;
 *   public static final JavaVersionEnum  JAVA1_0  = new JavaVersionEnum( "Java 1.0", JAVA1_0_VALUE );
 *   public static final JavaVersionEnum  JAVA1_1  = new JavaVersionEnum( "Java 1.1", JAVA1_1_VALUE );
 *   public static final JavaVersionEnum  JAVA1_2  = new JavaVersionEnum( "Java 1.2", JAVA1_2_VALUE );
 *   public static final JavaVersionEnum  JAVA1_3  = new JavaVersionEnum( "Java 1.3", JAVA1_3_VALUE );
 *
 *   private JavaVersionEnum(String name, int value) {
 *     super( name, value );
 *   }
 * 
 *   public static JavaVersionEnum getEnum(String javaVersion) {
 *     return (JavaVersionEnum) getEnum(JavaVersionEnum.class, javaVersion);
 *   }
 * 
 *   public static JavaVersionEnum getEnum(int javaVersion) {
 *     return (JavaVersionEnum) getEnum(JavaVersionEnum.class, javaVersion);
 *   }
 * 
 *   public static Map getEnumMap() {
 *     return getEnumMap(JavaVersionEnum.class);
 *   }
 * 
 *   public static List getEnumList() {
 *     return getEnumList(JavaVersionEnum.class);
 *   }
 * 
 *   public static Iterator iterator() {
 *     return iterator(JavaVersionEnum.class);
 *   }
 * }
 * 
* *

The above class could then be used as follows:

* *
 * public void doSomething(JavaVersionEnum ver) {
 *   switch (ver.getValue()) {
 *     case JAVA1_0_VALUE:
 *       // ...
 *       break;
 *     case JAVA1_1_VALUE:
 *       // ...
 *       break;
 *     //...
 *   }
 * }
 * 
* *

As shown, each enum has a name and a value. These can be accessed using * getName and getValue.

* *

The getEnum and iterator methods are recommended. * Unfortunately, Java restrictions require these to be coded as shown in each subclass. * An alternative choice is to use the {@link EnumUtils} class.

* * @deprecated Replaced by {@link org.apache.commons.lang.enums.ValuedEnum org.apache.commons.lang.enums.ValuedEnum} * and will be removed in version 3.0. All classes in this package are deprecated and repackaged to * {@link org.apache.commons.lang.enums} since enum is a Java 1.5 keyword. * @see org.apache.commons.lang.enums.ValuedEnum * @author Apache Avalon project * @author Apache Software Foundation * @since 1.0 * @version $Id: ValuedEnum.java 905636 2010-02-02 14:03:32Z niallp $ */ public abstract class ValuedEnum extends Enum { /** * Required for serialization support. Lang version 1.0.1 serial compatibility. * * @see java.io.Serializable */ private static final long serialVersionUID = -7129650521543789085L; /** * The value contained in enum. */ private final int iValue; /** * Constructor for enum item. * * @param name the name of enum item * @param value the value of enum item */ protected ValuedEnum(String name, int value) { super(name); iValue = value; } /** *

Gets an Enum object by class and value.

* *

This method loops through the list of Enum, * thus if there are many Enums this will be * slow.

* * @param enumClass the class of the Enum to get * @param value the value of the Enum to get * @return the enum object, or null if the enum does not exist * @throws IllegalArgumentException if the enum class is null */ protected static Enum getEnum(Class enumClass, int value) { if (enumClass == null) { throw new IllegalArgumentException("The Enum Class must not be null"); } List list = Enum.getEnumList(enumClass); for (Iterator it = list.iterator(); it.hasNext();) { ValuedEnum enumeration = (ValuedEnum) it.next(); if (enumeration.getValue() == value) { return enumeration; } } return null; } /** *

Get value of enum item.

* * @return the enum item's value. */ public final int getValue() { return iValue; } /** *

Tests for order.

* *

The default ordering is numeric by value, but this * can be overridden by subclasses.

* * @see java.lang.Comparable#compareTo(Object) * @param other the other object to compare to * @return -ve if this is less than the other object, +ve if greater than, * 0 of equal * @throws ClassCastException if other is not an Enum * @throws NullPointerException if other is null */ public int compareTo(Object other) { return iValue - ((ValuedEnum) other).iValue; } /** *

Human readable description of this Enum item.

* * @return String in the form type[name=value], for example: * JavaVersion[Java 1.0=100]. Note that the package name is * stripped from the type name. */ public String toString() { if (iToString == null) { String shortName = ClassUtils.getShortClassName(getEnumClass()); iToString = shortName + "[" + getName() + "=" + getValue() + "]"; } return iToString; } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/enums/Enum.java100644 0 0 61072 11513702442 23652 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.enums; import java.io.Serializable; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.WeakHashMap; import org.apache.commons.lang.ClassUtils; import org.apache.commons.lang.StringUtils; /** *

Abstract superclass for type-safe enums.

* *

One feature of the C programming language lacking in Java is enumerations. The * C implementation based on ints was poor and open to abuse. The original Java * recommendation and most of the JDK also uses int constants. It has been recognised * however that a more robust type-safe class-based solution can be designed. This * class follows the basic Java type-safe enumeration pattern.

* *

NOTE: Due to the way in which Java ClassLoaders work, comparing * Enum objects should always be done using equals(), not ==. * The equals() method will try == first so in most cases the effect is the same.

* *

Of course, if you actually want (or don't mind) Enums in different class * loaders being non-equal, then you can use ==.

* *

Simple Enums

* *

To use this class, it must be subclassed. For example:

* *
 * public final class ColorEnum extends Enum {
 *   public static final ColorEnum RED = new ColorEnum("Red");
 *   public static final ColorEnum GREEN = new ColorEnum("Green");
 *   public static final ColorEnum BLUE = new ColorEnum("Blue");
 *
 *   private ColorEnum(String color) {
 *     super(color);
 *   }
 * 
 *   public static ColorEnum getEnum(String color) {
 *     return (ColorEnum) getEnum(ColorEnum.class, color);
 *   }
 * 
 *   public static Map getEnumMap() {
 *     return getEnumMap(ColorEnum.class);
 *   }
 * 
 *   public static List getEnumList() {
 *     return getEnumList(ColorEnum.class);
 *   }
 * 
 *   public static Iterator iterator() {
 *     return iterator(ColorEnum.class);
 *   }
 * }
 * 
* *

As shown, each enum has a name. This can be accessed using getName.

* *

The getEnum and iterator methods are recommended. * Unfortunately, Java restrictions require these to be coded as shown in each subclass. * An alternative choice is to use the {@link EnumUtils} class.

* *

Subclassed Enums

*

A hierarchy of Enum classes can be built. In this case, the superclass is * unaffected by the addition of subclasses (as per normal Java). The subclasses * may add additional Enum constants of the type of the superclass. The * query methods on the subclass will return all of the Enum constants from the * superclass and subclass.

* *
 * public final class ExtraColorEnum extends ColorEnum {
 *   // NOTE: Color enum declared above is final, change that to get this
 *   // example to compile.
 *   public static final ColorEnum YELLOW = new ExtraColorEnum("Yellow");
 *
 *   private ExtraColorEnum(String color) {
 *     super(color);
 *   }
 * 
 *   public static ColorEnum getEnum(String color) {
 *     return (ColorEnum) getEnum(ExtraColorEnum.class, color);
 *   }
 * 
 *   public static Map getEnumMap() {
 *     return getEnumMap(ExtraColorEnum.class);
 *   }
 * 
 *   public static List getEnumList() {
 *     return getEnumList(ExtraColorEnum.class);
 *   }
 * 
 *   public static Iterator iterator() {
 *     return iterator(ExtraColorEnum.class);
 *   }
 * }
 * 
* *

This example will return RED, GREEN, BLUE, YELLOW from the List and iterator * methods in that order. The RED, GREEN and BLUE instances will be the same (==) * as those from the superclass ColorEnum. Note that YELLOW is declared as a * ColorEnum and not an ExtraColorEnum.

* *

Functional Enums

* *

The enums can have functionality by defining subclasses and * overriding the getEnumClass() method:

* *
 *   public static final OperationEnum PLUS = new PlusOperation();
 *   private static final class PlusOperation extends OperationEnum {
 *     private PlusOperation() {
 *       super("Plus");
 *     }
 *     public int eval(int a, int b) {
 *       return a + b;
 *     }
 *   }
 *   public static final OperationEnum MINUS = new MinusOperation();
 *   private static final class MinusOperation extends OperationEnum {
 *     private MinusOperation() {
 *       super("Minus");
 *     }
 *     public int eval(int a, int b) {
 *       return a - b;
 *     }
 *   }
 *
 *   private OperationEnum(String color) {
 *     super(color);
 *   }
 * 
 *   public final Class getEnumClass() {     // NOTE: new method!
 *     return OperationEnum.class;
 *   }
 *
 *   public abstract double eval(double a, double b);
 * 
 *   public static OperationEnum getEnum(String name) {
 *     return (OperationEnum) getEnum(OperationEnum.class, name);
 *   }
 * 
 *   public static Map getEnumMap() {
 *     return getEnumMap(OperationEnum.class);
 *   }
 * 
 *   public static List getEnumList() {
 *     return getEnumList(OperationEnum.class);
 *   }
 * 
 *   public static Iterator iterator() {
 *     return iterator(OperationEnum.class);
 *   }
 * }
 * 
*

The code above will work on JDK 1.2. If JDK1.3 and later is used, * the subclasses may be defined as anonymous.

* *

Nested class Enums

* *

Care must be taken with class loading when defining a static nested class * for enums. The static nested class can be loaded without the surrounding outer * class being loaded. This can result in an empty list/map/iterator being returned. * One solution is to define a static block that references the outer class where * the constants are defined. For example:

* *
 * public final class Outer {
 *   public static final BWEnum BLACK = new BWEnum("Black");
 *   public static final BWEnum WHITE = new BWEnum("White");
 *
 *   // static nested enum class
 *   public static final class BWEnum extends Enum {
 * 
 *     static {
 *       // explicitly reference BWEnum class to force constants to load
 *       Object obj = Outer.BLACK;
 *     }
 * 
 *     // ... other methods omitted
 *   }
 * }
 * 
* *

Although the above solves the problem, it is not recommended. The best solution * is to define the constants in the enum class, and hold references in the outer class: * *

 * public final class Outer {
 *   public static final BWEnum BLACK = BWEnum.BLACK;
 *   public static final BWEnum WHITE = BWEnum.WHITE;
 *
 *   // static nested enum class
 *   public static final class BWEnum extends Enum {
 *     // only define constants in enum classes - private if desired
 *     private static final BWEnum BLACK = new BWEnum("Black");
 *     private static final BWEnum WHITE = new BWEnum("White");
 * 
 *     // ... other methods omitted
 *   }
 * }
 * 
* *

For more details, see the 'Nested' test cases. * *

Lang Enums and Java 5.0 Enums

* *

Enums were added to Java in Java 5.0. The main differences between Lang's * implementation and the new official JDK implementation are:

*
    *
  • The standard Enum is a not just a superclass, but is a type baked into the * language.
  • *
  • The standard Enum does not support extension, so the standard methods that * are provided in the Lang enum are not available.
  • *
  • Lang mandates a String name, whereas the standard Enum uses the class * name as its name. getName() changes to name().
  • *
* *

Generally people should use the standard Enum. Migrating from the Lang * enum to the standard Enum is not as easy as it might be due to the lack of * class inheritence in standard Enums. This means that it's not possible * to provide a 'super-enum' which could provide the same utility methods * that the Lang enum does. The following utility class is a Java 5.0 * version of our EnumUtils class and provides those utility methods.

* *
 * import java.util.*;
 * 
 * public class EnumUtils {
 * 
 *   public static Enum getEnum(Class enumClass, String token) {
 *     return Enum.valueOf(enumClass, token);
 *   }
 * 
 *   public static Map getEnumMap(Class enumClass) {
 *     HashMap map = new HashMap();
 *     Iterator itr = EnumUtils.iterator(enumClass);
 *     while(itr.hasNext()) {
 *       Enum enm = (Enum) itr.next();
 *       map.put( enm.name(), enm );
 *     }
 *     return map;
 *   }
 * 
 *   public static List getEnumList(Class enumClass) {
 *     return new ArrayList( EnumSet.allOf(enumClass) );
 *   }
 * 
 *   public static Iterator iterator(Class enumClass) {
 *     return EnumUtils.getEnumList(enumClass).iterator();
 *   }
 * }
 * 
* * @author Apache Avalon project * @author Apache Software Foundation * @author Chris Webb * @author Mike Bowler * @author Matthias Eichel * @since 2.1 (class existed in enum package from v1.0) * @version $Id: Enum.java 912394 2010-02-21 20:16:22Z niallp $ */ public abstract class Enum implements Comparable, Serializable { /** * Required for serialization support. * * @see java.io.Serializable */ private static final long serialVersionUID = -487045951170455942L; // After discussion, the default size for HashMaps is used, as the // sizing algorithm changes across the JDK versions /** * An empty Map, as JDK1.2 didn't have an empty map. */ private static final Map EMPTY_MAP = Collections.unmodifiableMap(new HashMap(0)); /** * Map, key of class name, value of Entry. */ private static Map cEnumClasses // LANG-334: To avoid exposing a mutating map, // we copy it each time we add to it. This is cheaper than // using a synchronized map since we are almost entirely reads = new WeakHashMap(); /** * The string representation of the Enum. */ private final String iName; /** * The hashcode representation of the Enum. */ private transient final int iHashCode; /** * The toString representation of the Enum. * @since 2.0 */ protected transient String iToString = null; /** *

Enable the iterator to retain the source code order.

*/ private static class Entry { /** * Map of Enum name to Enum. */ final Map map = new HashMap(); /** * Map of Enum name to Enum. */ final Map unmodifiableMap = Collections.unmodifiableMap(map); /** * List of Enums in source code order. */ final List list = new ArrayList(25); /** * Map of Enum name to Enum. */ final List unmodifiableList = Collections.unmodifiableList(list); /** *

Restrictive constructor.

*/ protected Entry() { super(); } } /** *

Constructor to add a new named item to the enumeration.

* * @param name the name of the enum object, * must not be empty or null * @throws IllegalArgumentException if the name is null * or an empty string * @throws IllegalArgumentException if the getEnumClass() method returns * a null or invalid Class */ protected Enum(String name) { super(); init(name); iName = name; iHashCode = 7 + getEnumClass().hashCode() + 3 * name.hashCode(); // cannot create toString here as subclasses may want to include other data } /** * Initializes the enumeration. * * @param name the enum name * @throws IllegalArgumentException if the name is null or empty or duplicate * @throws IllegalArgumentException if the enumClass is null or invalid */ private void init(String name) { if (StringUtils.isEmpty(name)) { throw new IllegalArgumentException("The Enum name must not be empty or null"); } Class enumClass = getEnumClass(); if (enumClass == null) { throw new IllegalArgumentException("getEnumClass() must not be null"); } Class cls = getClass(); boolean ok = false; while (cls != null && cls != Enum.class && cls != ValuedEnum.class) { if (cls == enumClass) { ok = true; break; } cls = cls.getSuperclass(); } if (ok == false) { throw new IllegalArgumentException("getEnumClass() must return a superclass of this class"); } Entry entry; synchronized( Enum.class ) { // LANG-334 // create entry entry = (Entry) cEnumClasses.get(enumClass); if (entry == null) { entry = createEntry(enumClass); Map myMap = new WeakHashMap( ); // we avoid the (Map) constructor to achieve JDK 1.2 support myMap.putAll( cEnumClasses ); myMap.put(enumClass, entry); cEnumClasses = myMap; } } if (entry.map.containsKey(name)) { throw new IllegalArgumentException("The Enum name must be unique, '" + name + "' has already been added"); } entry.map.put(name, this); entry.list.add(this); } /** *

Handle the deserialization of the class to ensure that multiple * copies are not wastefully created, or illegal enum types created.

* * @return the resolved object */ protected Object readResolve() { Entry entry = (Entry) cEnumClasses.get(getEnumClass()); if (entry == null) { return null; } return entry.map.get(getName()); } //-------------------------------------------------------------------------------- /** *

Gets an Enum object by class and name.

* * @param enumClass the class of the Enum to get, must not * be null * @param name the name of the Enum to get, * may be null * @return the enum object, or null if the enum does not exist * @throws IllegalArgumentException if the enum class * is null */ protected static Enum getEnum(Class enumClass, String name) { Entry entry = getEntry(enumClass); if (entry == null) { return null; } return (Enum) entry.map.get(name); } /** *

Gets the Map of Enum objects by * name using the Enum class.

* *

If the requested class has no enum objects an empty * Map is returned.

* * @param enumClass the class of the Enum to get, * must not be null * @return the enum object Map * @throws IllegalArgumentException if the enum class is null * @throws IllegalArgumentException if the enum class is not a subclass of Enum */ protected static Map getEnumMap(Class enumClass) { Entry entry = getEntry(enumClass); if (entry == null) { return EMPTY_MAP; } return entry.unmodifiableMap; } /** *

Gets the List of Enum objects using the * Enum class.

* *

The list is in the order that the objects were created (source code order). * If the requested class has no enum objects an empty List is * returned.

* * @param enumClass the class of the Enum to get, * must not be null * @return the enum object Map * @throws IllegalArgumentException if the enum class is null * @throws IllegalArgumentException if the enum class is not a subclass of Enum */ protected static List getEnumList(Class enumClass) { Entry entry = getEntry(enumClass); if (entry == null) { return Collections.EMPTY_LIST; } return entry.unmodifiableList; } /** *

Gets an Iterator over the Enum objects in * an Enum class.

* *

The Iterator is in the order that the objects were * created (source code order). If the requested class has no enum * objects an empty Iterator is returned.

* * @param enumClass the class of the Enum to get, * must not be null * @return an iterator of the Enum objects * @throws IllegalArgumentException if the enum class is null * @throws IllegalArgumentException if the enum class is not a subclass of Enum */ protected static Iterator iterator(Class enumClass) { return Enum.getEnumList(enumClass).iterator(); } //----------------------------------------------------------------------- /** *

Gets an Entry from the map of Enums.

* * @param enumClass the class of the Enum to get * @return the enum entry */ private static Entry getEntry(Class enumClass) { if (enumClass == null) { throw new IllegalArgumentException("The Enum Class must not be null"); } if (Enum.class.isAssignableFrom(enumClass) == false) { throw new IllegalArgumentException("The Class must be a subclass of Enum"); } Entry entry = (Entry) cEnumClasses.get(enumClass); if (entry == null) { try { // LANG-76 - try to force class initialization for JDK 1.5+ Class.forName(enumClass.getName(), true, enumClass.getClassLoader()); entry = (Entry) cEnumClasses.get(enumClass); } catch (Exception e) { // Ignore } } return entry; } /** *

Creates an Entry for storing the Enums.

* *

This accounts for subclassed Enums.

* * @param enumClass the class of the Enum to get * @return the enum entry */ private static Entry createEntry(Class enumClass) { Entry entry = new Entry(); Class cls = enumClass.getSuperclass(); while (cls != null && cls != Enum.class && cls != ValuedEnum.class) { Entry loopEntry = (Entry) cEnumClasses.get(cls); if (loopEntry != null) { entry.list.addAll(loopEntry.list); entry.map.putAll(loopEntry.map); break; // stop here, as this will already have had superclasses added } cls = cls.getSuperclass(); } return entry; } //----------------------------------------------------------------------- /** *

Retrieve the name of this Enum item, set in the constructor.

* * @return the String name of this Enum item */ public final String getName() { return iName; } /** *

Retrieves the Class of this Enum item, set in the constructor.

* *

This is normally the same as getClass(), but for * advanced Enums may be different. If overridden, it must return a * constant value.

* * @return the Class of the enum * @since 2.0 */ public Class getEnumClass() { return getClass(); } /** *

Tests for equality.

* *

Two Enum objects are considered equal * if they have the same class names and the same names. * Identity is tested for first, so this method usually runs fast.

* *

If the parameter is in a different class loader than this instance, * reflection is used to compare the names.

* * @param other the other object to compare for equality * @return true if the Enums are equal */ public final boolean equals(Object other) { if (other == this) { return true; } else if (other == null) { return false; } else if (other.getClass() == this.getClass()) { // Ok to do a class cast to Enum here since the test above // guarantee both // classes are in the same class loader. return iName.equals(((Enum) other).iName); } else { // This and other are in different class loaders, we must check indirectly if (other.getClass().getName().equals(this.getClass().getName()) == false) { return false; } return iName.equals( getNameInOtherClassLoader(other) ); } } /** *

Returns a suitable hashCode for the enumeration.

* * @return a hashcode based on the name */ public final int hashCode() { return iHashCode; } /** *

Tests for order.

* *

The default ordering is alphabetic by name, but this * can be overridden by subclasses.

* *

If the parameter is in a different class loader than this instance, * reflection is used to compare the names.

* * @see java.lang.Comparable#compareTo(Object) * @param other the other object to compare to * @return -ve if this is less than the other object, +ve if greater * than, 0 of equal * @throws ClassCastException if other is not an Enum * @throws NullPointerException if other is null */ public int compareTo(Object other) { if (other == this) { return 0; } if (other.getClass() != this.getClass()) { if (other.getClass().getName().equals(this.getClass().getName())) { return iName.compareTo( getNameInOtherClassLoader(other) ); } throw new ClassCastException( "Different enum class '" + ClassUtils.getShortClassName(other.getClass()) + "'"); } return iName.compareTo(((Enum) other).iName); } /** *

Use reflection to return an objects class name.

* * @param other The object to determine the class name for * @return The class name */ private String getNameInOtherClassLoader(Object other) { try { Method mth = other.getClass().getMethod("getName", null); String name = (String) mth.invoke(other, null); return name; } catch (NoSuchMethodException e) { // ignore - should never happen } catch (IllegalAccessException e) { // ignore - should never happen } catch (InvocationTargetException e) { // ignore - should never happen } throw new IllegalStateException("This should not happen"); } /** *

Human readable description of this Enum item.

* * @return String in the form type[name], for example: * Color[Red]. Note that the package name is stripped from * the type name. */ public String toString() { if (iToString == null) { String shortName = ClassUtils.getShortClassName(getEnumClass()); iToString = shortName + "[" + getName() + "]"; } return iToString; } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/enums/EnumUtils.java100644 0 0 11271 11513702442 24667 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.enums; import java.util.Iterator; import java.util.List; import java.util.Map; /** *

Utility class for accessing and manipulating {@link Enum}s.

* * @see Enum * @see ValuedEnum * @author Apache Software Foundation * @author Gary Gregory * @since 2.1 (class existed in enum package from v1.0) * @version $Id: EnumUtils.java 905636 2010-02-02 14:03:32Z niallp $ */ public class EnumUtils { /** * Public constructor. This class should not normally be instantiated. * @since 2.0 */ public EnumUtils() { super(); } /** *

Gets an Enum object by class and name.

* * @param enumClass the class of the Enum to get * @param name the name of the Enum to get, may be null * @return the enum object * @throws IllegalArgumentException if the enum class is null */ public static Enum getEnum(Class enumClass, String name) { return Enum.getEnum(enumClass, name); } /** *

Gets a ValuedEnum object by class and value.

* * @param enumClass the class of the Enum to get * @param value the value of the Enum to get * @return the enum object, or null if the enum does not exist * @throws IllegalArgumentException if the enum class is null */ public static ValuedEnum getEnum(Class enumClass, int value) { return (ValuedEnum) ValuedEnum.getEnum(enumClass, value); } /** *

Gets the Map of Enum objects by * name using the Enum class.

* *

If the requested class has no enum objects an empty * Map is returned. The Map is unmodifiable.

* * @param enumClass the class of the Enum to get * @return the enum object Map * @throws IllegalArgumentException if the enum class is null * @throws IllegalArgumentException if the enum class is not a subclass * of Enum */ public static Map getEnumMap(Class enumClass) { return Enum.getEnumMap(enumClass); } /** *

Gets the List of Enum objects using * the Enum class.

* *

The list is in the order that the objects were created * (source code order).

* *

If the requested class has no enum objects an empty * List is returned. The List is unmodifiable.

* * @param enumClass the class of the Enum to get * @return the enum object Map * @throws IllegalArgumentException if the enum class is null * @throws IllegalArgumentException if the enum class is not a subclass * of Enum */ public static List getEnumList(Class enumClass) { return Enum.getEnumList(enumClass); } /** *

Gets an Iterator over the Enum objects * in an Enum class.

* *

The iterator is in the order that the objects were created * (source code order).

* *

If the requested class has no enum objects an empty * Iterator is returned. The Iterator * is unmodifiable.

* * @param enumClass the class of the Enum to get * @return an Iterator of the Enum objects * @throws IllegalArgumentException if the enum class is null * @throws IllegalArgumentException if the enum class is not a subclass of Enum */ public static Iterator iterator(Class enumClass) { return Enum.getEnumList(enumClass).iterator(); } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/enums/package.html100644 0 0 3262 11513702442 24341 0ustar 0 0

Provides an implementation of the C style enum in the Java world.

The classic example being an RGB color enumeration.

public final class ColorEnum extends Enum {
    public static final ColorEnum RED = new ColorEnum("Red");
    public static final ColorEnum GREEN = new ColorEnum("Green");
    public static final ColorEnum BLUE = new ColorEnum("Blue");

    private ColorEnum(String color) {
        super(color);
    }

    public static ColorEnum getEnum(String color) {
        return (ColorEnum) getEnum(ColorEnum.class, color);
    }

    public static Map getEnumMap() {
        return getEnumMap(ColorEnum.class);
    }

    public static List getEnumList() {
        return getEnumList(ColorEnum.class);
    }

    public static Iterator iterator() {
        return iterator(ColorEnum.class);
    }
}
@since 2.1 commons-lang-2.6-src/src/main/java/org/apache/commons/lang/enums/ValuedEnum.java100644 0 0 21060 11513702442 25004 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.enums; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Iterator; import java.util.List; import org.apache.commons.lang.ClassUtils; /** *

Abstract superclass for type-safe enums with integer values suitable * for use in switch statements.

* *

NOTE:Due to the way in which Java ClassLoaders work, comparing * Enum objects should always be done using the equals() method, * not ==. The equals() method will try == first so * in most cases the effect is the same.

* *

To use this class, it must be subclassed. For example:

* *
 * public final class JavaVersionEnum extends ValuedEnum {
 *   //standard enums for version of JVM
 *   public static final int  JAVA1_0_VALUE  = 100;
 *   public static final int  JAVA1_1_VALUE  = 110;
 *   public static final int  JAVA1_2_VALUE  = 120;
 *   public static final int  JAVA1_3_VALUE  = 130;
 *   public static final JavaVersionEnum  JAVA1_0  = new JavaVersionEnum( "Java 1.0", JAVA1_0_VALUE );
 *   public static final JavaVersionEnum  JAVA1_1  = new JavaVersionEnum( "Java 1.1", JAVA1_1_VALUE );
 *   public static final JavaVersionEnum  JAVA1_2  = new JavaVersionEnum( "Java 1.2", JAVA1_2_VALUE );
 *   public static final JavaVersionEnum  JAVA1_3  = new JavaVersionEnum( "Java 1.3", JAVA1_3_VALUE );
 *
 *   private JavaVersionEnum(String name, int value) {
 *     super( name, value );
 *   }
 * 
 *   public static JavaVersionEnum getEnum(String javaVersion) {
 *     return (JavaVersionEnum) getEnum(JavaVersionEnum.class, javaVersion);
 *   }
 * 
 *   public static JavaVersionEnum getEnum(int javaVersion) {
 *     return (JavaVersionEnum) getEnum(JavaVersionEnum.class, javaVersion);
 *   }
 * 
 *   public static Map getEnumMap() {
 *     return getEnumMap(JavaVersionEnum.class);
 *   }
 * 
 *   public static List getEnumList() {
 *     return getEnumList(JavaVersionEnum.class);
 *   }
 * 
 *   public static Iterator iterator() {
 *     return iterator(JavaVersionEnum.class);
 *   }
 * }
 * 
* *

NOTE:These are declared final, so compilers may * inline the code. Ensure you recompile everything when using final.

* *

The above class could then be used as follows:

* *
 * public void doSomething(JavaVersionEnum ver) {
 *   switch (ver.getValue()) {
 *     case JAVA1_0_VALUE:
 *       // ...
 *       break;
 *     case JAVA1_1_VALUE:
 *       // ...
 *       break;
 *     //...
 *   }
 * }
 * 
* *

As shown, each enum has a name and a value. These can be accessed using * getName and getValue.

* *

NOTE: Because the switch is ultimately sitting on top of an * int, the example above is not type-safe. That is, there is nothing that * checks that JAVA1_0_VALUE is a legal constant for JavaVersionEnum.

* *

The getEnum and iterator methods are recommended. * Unfortunately, Java restrictions require these to be coded as shown in each subclass. * An alternative choice is to use the {@link EnumUtils} class.

* * @author Apache Avalon project * @author Apache Software Foundation * @since 2.1 (class existed in enum package from v1.0) * @version $Id: ValuedEnum.java 905636 2010-02-02 14:03:32Z niallp $ */ public abstract class ValuedEnum extends Enum { /** * Required for serialization support. * * @see java.io.Serializable */ private static final long serialVersionUID = -7129650521543789085L; /** * The value contained in enum. */ private final int iValue; /** * Constructor for enum item. * * @param name the name of enum item * @param value the value of enum item */ protected ValuedEnum(String name, int value) { super(name); iValue = value; } /** *

Gets an Enum object by class and value.

* *

This method loops through the list of Enum, * thus if there are many Enums this will be * slow.

* * @param enumClass the class of the Enum to get * @param value the value of the Enum to get * @return the enum object, or null if the enum does not exist * @throws IllegalArgumentException if the enum class is null */ protected static Enum getEnum(Class enumClass, int value) { if (enumClass == null) { throw new IllegalArgumentException("The Enum Class must not be null"); } List list = Enum.getEnumList(enumClass); for (Iterator it = list.iterator(); it.hasNext();) { ValuedEnum enumeration = (ValuedEnum) it.next(); if (enumeration.getValue() == value) { return enumeration; } } return null; } /** *

Get value of enum item.

* * @return the enum item's value. */ public final int getValue() { return iValue; } /** *

Tests for order.

* *

The default ordering is numeric by value, but this * can be overridden by subclasses.

* *

NOTE: From v2.2 the enums must be of the same type. * If the parameter is in a different class loader than this instance, * reflection is used to compare the values.

* * @see java.lang.Comparable#compareTo(Object) * @param other the other object to compare to * @return -ve if this is less than the other object, +ve if greater than, * 0 of equal * @throws ClassCastException if other is not an Enum * @throws NullPointerException if other is null */ public int compareTo(Object other) { if (other == this) { return 0; } if (other.getClass() != this.getClass()) { if (other.getClass().getName().equals(this.getClass().getName())) { return iValue - getValueInOtherClassLoader(other); } throw new ClassCastException( "Different enum class '" + ClassUtils.getShortClassName(other.getClass()) + "'"); } return iValue - ((ValuedEnum) other).iValue; } /** *

Use reflection to return an objects value.

* * @param other the object to determine the value for * @return the value */ private int getValueInOtherClassLoader(Object other) { try { Method mth = other.getClass().getMethod("getValue", null); Integer value = (Integer) mth.invoke(other, null); return value.intValue(); } catch (NoSuchMethodException e) { // ignore - should never happen } catch (IllegalAccessException e) { // ignore - should never happen } catch (InvocationTargetException e) { // ignore - should never happen } throw new IllegalStateException("This should not happen"); } /** *

Human readable description of this Enum item.

* * @return String in the form type[name=value], for example: * JavaVersion[Java 1.0=100]. Note that the package name is * stripped from the type name. */ public String toString() { if (iToString == null) { String shortName = ClassUtils.getShortClassName(getEnumClass()); iToString = shortName + "[" + getName() + "=" + getValue() + "]"; } return iToString; } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/exception/CloneFailedException.java100644 0 0 4157 11513702442 27622 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.exception; /** * Exception thrown when a clone cannot be created. In contrast to * {@link CloneNotSupportedException} this is a {@link RuntimeException}. * * @author Apache Software Foundation * @since 2.6 */ public class CloneFailedException extends NestableRuntimeException { // ~ Static fields/initializers --------------------------------------------- private static final long serialVersionUID = 20091223L; // ~ Constructors ----------------------------------------------------------- /** * Constructs a CloneFailedException. * * @param message description of the exception * @since upcoming */ public CloneFailedException(final String message) { super(message); } /** * Constructs a CloneFailedException. * * @param cause cause of the exception * @since upcoming */ public CloneFailedException(final Throwable cause) { super(cause); } /** * Constructs a CloneFailedException. * * @param message description of the exception * @param cause cause of the exception * @since upcoming */ public CloneFailedException(final String message, final Throwable cause) { super(message, cause); } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/exception/ExceptionUtils.java100644 0 0 117131 11513702442 26612 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.exception; import java.io.PrintStream; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.StringTokenizer; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.ClassUtils; import org.apache.commons.lang.NullArgumentException; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.SystemUtils; /** *

Provides utilities for manipulating and examining * Throwable objects.

* * @author Apache Software Foundation * @author Daniel L. Rall * @author Dmitri Plotnikov * @author Gary Gregory * @author Pete Gieser * @since 1.0 * @version $Id: ExceptionUtils.java 905837 2010-02-02 23:32:11Z niallp $ */ public class ExceptionUtils { /** *

Used when printing stack frames to denote the start of a * wrapped exception.

* *

Package private for accessibility by test suite.

*/ static final String WRAPPED_MARKER = " [wrapped] "; // Lock object for CAUSE_METHOD_NAMES private static final Object CAUSE_METHOD_NAMES_LOCK = new Object(); /** *

The names of methods commonly used to access a wrapped exception.

*/ private static String[] CAUSE_METHOD_NAMES = { "getCause", "getNextException", "getTargetException", "getException", "getSourceException", "getRootCause", "getCausedByException", "getNested", "getLinkedException", "getNestedException", "getLinkedCause", "getThrowable", }; /** *

The Method object for Java 1.4 getCause.

*/ private static final Method THROWABLE_CAUSE_METHOD; /** *

The Method object for Java 1.4 initCause.

*/ private static final Method THROWABLE_INITCAUSE_METHOD; static { Method causeMethod; try { causeMethod = Throwable.class.getMethod("getCause", null); } catch (Exception e) { causeMethod = null; } THROWABLE_CAUSE_METHOD = causeMethod; try { causeMethod = Throwable.class.getMethod("initCause", new Class[]{Throwable.class}); } catch (Exception e) { causeMethod = null; } THROWABLE_INITCAUSE_METHOD = causeMethod; } /** *

* Public constructor allows an instance of ExceptionUtils to be created, although that is not * normally necessary. *

*/ public ExceptionUtils() { super(); } //----------------------------------------------------------------------- /** *

Adds to the list of method names used in the search for Throwable * objects.

* * @param methodName the methodName to add to the list, null * and empty strings are ignored * @since 2.0 */ public static void addCauseMethodName(String methodName) { if (StringUtils.isNotEmpty(methodName) && !isCauseMethodName(methodName)) { List list = getCauseMethodNameList(); if (list.add(methodName)) { synchronized(CAUSE_METHOD_NAMES_LOCK) { CAUSE_METHOD_NAMES = toArray(list); } } } } /** *

Removes from the list of method names used in the search for Throwable * objects.

* * @param methodName the methodName to remove from the list, null * and empty strings are ignored * @since 2.1 */ public static void removeCauseMethodName(String methodName) { if (StringUtils.isNotEmpty(methodName)) { List list = getCauseMethodNameList(); if (list.remove(methodName)) { synchronized(CAUSE_METHOD_NAMES_LOCK) { CAUSE_METHOD_NAMES = toArray(list); } } } } /** *

Sets the cause of a Throwable using introspection, allowing * source code compatibility between pre-1.4 and post-1.4 Java releases.

* *

The typical use of this method is inside a constructor as in * the following example:

* *
     * import org.apache.commons.lang.exception.ExceptionUtils;
     *  
     * public class MyException extends Exception {
     *  
     *    public MyException(String msg) {
     *       super(msg);
     *    }
     *
     *    public MyException(String msg, Throwable cause) {
     *       super(msg);
     *       ExceptionUtils.setCause(this, cause);
     *    }
     * }
     * 
* * @param target the target Throwable * @param cause the Throwable to set in the target * @return a true if the target has been modified * @since 2.2 */ public static boolean setCause(Throwable target, Throwable cause) { if (target == null) { throw new NullArgumentException("target"); } Object[] causeArgs = new Object[]{cause}; boolean modifiedTarget = false; if (THROWABLE_INITCAUSE_METHOD != null) { try { THROWABLE_INITCAUSE_METHOD.invoke(target, causeArgs); modifiedTarget = true; } catch (IllegalAccessException ignored) { // Exception ignored. } catch (InvocationTargetException ignored) { // Exception ignored. } } try { Method setCauseMethod = target.getClass().getMethod("setCause", new Class[]{Throwable.class}); setCauseMethod.invoke(target, causeArgs); modifiedTarget = true; } catch (NoSuchMethodException ignored) { // Exception ignored. } catch (IllegalAccessException ignored) { // Exception ignored. } catch (InvocationTargetException ignored) { // Exception ignored. } return modifiedTarget; } /** * Returns the given list as a String[]. * @param list a list to transform. * @return the given list as a String[]. */ private static String[] toArray(List list) { return (String[]) list.toArray(new String[list.size()]); } /** * Returns {@link #CAUSE_METHOD_NAMES} as a List. * * @return {@link #CAUSE_METHOD_NAMES} as a List. */ private static ArrayList getCauseMethodNameList() { synchronized(CAUSE_METHOD_NAMES_LOCK) { return new ArrayList(Arrays.asList(CAUSE_METHOD_NAMES)); } } /** *

Tests if the list of method names used in the search for Throwable * objects include the given name.

* * @param methodName the methodName to search in the list. * @return if the list of method names used in the search for Throwable * objects include the given name. * @since 2.1 */ public static boolean isCauseMethodName(String methodName) { synchronized(CAUSE_METHOD_NAMES_LOCK) { return ArrayUtils.indexOf(CAUSE_METHOD_NAMES, methodName) >= 0; } } //----------------------------------------------------------------------- /** *

Introspects the Throwable to obtain the cause.

* *

The method searches for methods with specific names that return a * Throwable object. This will pick up most wrapping exceptions, * including those from JDK 1.4, and * {@link org.apache.commons.lang.exception.NestableException NestableException}. * The method names can be added to using {@link #addCauseMethodName(String)}.

* *

The default list searched for are:

*
    *
  • getCause()
  • *
  • getNextException()
  • *
  • getTargetException()
  • *
  • getException()
  • *
  • getSourceException()
  • *
  • getRootCause()
  • *
  • getCausedByException()
  • *
  • getNested()
  • *
* *

In the absence of any such method, the object is inspected for a * detail field assignable to a Throwable.

* *

If none of the above is found, returns null.

* * @param throwable the throwable to introspect for a cause, may be null * @return the cause of the Throwable, * null if none found or null throwable input * @since 1.0 */ public static Throwable getCause(Throwable throwable) { synchronized(CAUSE_METHOD_NAMES_LOCK) { return getCause(throwable, CAUSE_METHOD_NAMES); } } /** *

Introspects the Throwable to obtain the cause.

* *
    *
  1. Try known exception types.
  2. *
  3. Try the supplied array of method names.
  4. *
  5. Try the field 'detail'.
  6. *
* *

A null set of method names means use the default set. * A null in the set of method names will be ignored.

* * @param throwable the throwable to introspect for a cause, may be null * @param methodNames the method names, null treated as default set * @return the cause of the Throwable, * null if none found or null throwable input * @since 1.0 */ public static Throwable getCause(Throwable throwable, String[] methodNames) { if (throwable == null) { return null; } Throwable cause = getCauseUsingWellKnownTypes(throwable); if (cause == null) { if (methodNames == null) { synchronized(CAUSE_METHOD_NAMES_LOCK) { methodNames = CAUSE_METHOD_NAMES; } } for (int i = 0; i < methodNames.length; i++) { String methodName = methodNames[i]; if (methodName != null) { cause = getCauseUsingMethodName(throwable, methodName); if (cause != null) { break; } } } if (cause == null) { cause = getCauseUsingFieldName(throwable, "detail"); } } return cause; } /** *

Introspects the Throwable to obtain the root cause.

* *

This method walks through the exception chain to the last element, * "root" of the tree, using {@link #getCause(Throwable)}, and * returns that exception.

* *

From version 2.2, this method handles recursive cause structures * that might otherwise cause infinite loops. If the throwable parameter * has a cause of itself, then null will be returned. If the throwable * parameter cause chain loops, the last element in the chain before the * loop is returned.

* * @param throwable the throwable to get the root cause for, may be null * @return the root cause of the Throwable, * null if none found or null throwable input */ public static Throwable getRootCause(Throwable throwable) { List list = getThrowableList(throwable); return (list.size() < 2 ? null : (Throwable)list.get(list.size() - 1)); } /** *

Finds a Throwable for known types.

* *

Uses instanceof checks to examine the exception, * looking for well known types which could contain chained or * wrapped exceptions.

* * @param throwable the exception to examine * @return the wrapped exception, or null if not found */ private static Throwable getCauseUsingWellKnownTypes(Throwable throwable) { if (throwable instanceof Nestable) { return ((Nestable) throwable).getCause(); } else if (throwable instanceof SQLException) { return ((SQLException) throwable).getNextException(); } else if (throwable instanceof InvocationTargetException) { return ((InvocationTargetException) throwable).getTargetException(); } else { return null; } } /** *

Finds a Throwable by method name.

* * @param throwable the exception to examine * @param methodName the name of the method to find and invoke * @return the wrapped exception, or null if not found */ private static Throwable getCauseUsingMethodName(Throwable throwable, String methodName) { Method method = null; try { method = throwable.getClass().getMethod(methodName, null); } catch (NoSuchMethodException ignored) { // exception ignored } catch (SecurityException ignored) { // exception ignored } if (method != null && Throwable.class.isAssignableFrom(method.getReturnType())) { try { return (Throwable) method.invoke(throwable, ArrayUtils.EMPTY_OBJECT_ARRAY); } catch (IllegalAccessException ignored) { // exception ignored } catch (IllegalArgumentException ignored) { // exception ignored } catch (InvocationTargetException ignored) { // exception ignored } } return null; } /** *

Finds a Throwable by field name.

* * @param throwable the exception to examine * @param fieldName the name of the attribute to examine * @return the wrapped exception, or null if not found */ private static Throwable getCauseUsingFieldName(Throwable throwable, String fieldName) { Field field = null; try { field = throwable.getClass().getField(fieldName); } catch (NoSuchFieldException ignored) { // exception ignored } catch (SecurityException ignored) { // exception ignored } if (field != null && Throwable.class.isAssignableFrom(field.getType())) { try { return (Throwable) field.get(throwable); } catch (IllegalAccessException ignored) { // exception ignored } catch (IllegalArgumentException ignored) { // exception ignored } } return null; } //----------------------------------------------------------------------- /** *

Checks if the Throwable class has a getCause method.

* *

This is true for JDK 1.4 and above.

* * @return true if Throwable is nestable * @since 2.0 */ public static boolean isThrowableNested() { return THROWABLE_CAUSE_METHOD != null; } /** *

Checks whether this Throwable class can store a cause.

* *

This method does not check whether it actually does store a cause.

* * @param throwable the Throwable to examine, may be null * @return boolean true if nested otherwise false * @since 2.0 */ public static boolean isNestedThrowable(Throwable throwable) { if (throwable == null) { return false; } if (throwable instanceof Nestable) { return true; } else if (throwable instanceof SQLException) { return true; } else if (throwable instanceof InvocationTargetException) { return true; } else if (isThrowableNested()) { return true; } Class cls = throwable.getClass(); synchronized(CAUSE_METHOD_NAMES_LOCK) { for (int i = 0, isize = CAUSE_METHOD_NAMES.length; i < isize; i++) { try { Method method = cls.getMethod(CAUSE_METHOD_NAMES[i], null); if (method != null && Throwable.class.isAssignableFrom(method.getReturnType())) { return true; } } catch (NoSuchMethodException ignored) { // exception ignored } catch (SecurityException ignored) { // exception ignored } } } try { Field field = cls.getField("detail"); if (field != null) { return true; } } catch (NoSuchFieldException ignored) { // exception ignored } catch (SecurityException ignored) { // exception ignored } return false; } //----------------------------------------------------------------------- /** *

Counts the number of Throwable objects in the * exception chain.

* *

A throwable without cause will return 1. * A throwable with one cause will return 2 and so on. * A null throwable will return 0.

* *

From version 2.2, this method handles recursive cause structures * that might otherwise cause infinite loops. The cause chain is * processed until the end is reached, or until the next item in the * chain is already in the result set.

* * @param throwable the throwable to inspect, may be null * @return the count of throwables, zero if null input */ public static int getThrowableCount(Throwable throwable) { return getThrowableList(throwable).size(); } /** *

Returns the list of Throwable objects in the * exception chain.

* *

A throwable without cause will return an array containing * one element - the input throwable. * A throwable with one cause will return an array containing * two elements. - the input throwable and the cause throwable. * A null throwable will return an array of size zero.

* *

From version 2.2, this method handles recursive cause structures * that might otherwise cause infinite loops. The cause chain is * processed until the end is reached, or until the next item in the * chain is already in the result set.

* * @see #getThrowableList(Throwable) * @param throwable the throwable to inspect, may be null * @return the array of throwables, never null */ public static Throwable[] getThrowables(Throwable throwable) { List list = getThrowableList(throwable); return (Throwable[]) list.toArray(new Throwable[list.size()]); } /** *

Returns the list of Throwable objects in the * exception chain.

* *

A throwable without cause will return a list containing * one element - the input throwable. * A throwable with one cause will return a list containing * two elements. - the input throwable and the cause throwable. * A null throwable will return a list of size zero.

* *

This method handles recursive cause structures that might * otherwise cause infinite loops. The cause chain is processed until * the end is reached, or until the next item in the chain is already * in the result set.

* * @param throwable the throwable to inspect, may be null * @return the list of throwables, never null * @since Commons Lang 2.2 */ public static List getThrowableList(Throwable throwable) { List list = new ArrayList(); while (throwable != null && list.contains(throwable) == false) { list.add(throwable); throwable = ExceptionUtils.getCause(throwable); } return list; } //----------------------------------------------------------------------- /** *

Returns the (zero based) index of the first Throwable * that matches the specified class (exactly) in the exception chain. * Subclasses of the specified class do not match - see * {@link #indexOfType(Throwable, Class)} for the opposite.

* *

A null throwable returns -1. * A null type returns -1. * No match in the chain returns -1.

* * @param throwable the throwable to inspect, may be null * @param clazz the class to search for, subclasses do not match, null returns -1 * @return the index into the throwable chain, -1 if no match or null input */ public static int indexOfThrowable(Throwable throwable, Class clazz) { return indexOf(throwable, clazz, 0, false); } /** *

Returns the (zero based) index of the first Throwable * that matches the specified type in the exception chain from * a specified index. * Subclasses of the specified class do not match - see * {@link #indexOfType(Throwable, Class, int)} for the opposite.

* *

A null throwable returns -1. * A null type returns -1. * No match in the chain returns -1. * A negative start index is treated as zero. * A start index greater than the number of throwables returns -1.

* * @param throwable the throwable to inspect, may be null * @param clazz the class to search for, subclasses do not match, null returns -1 * @param fromIndex the (zero based) index of the starting position, * negative treated as zero, larger than chain size returns -1 * @return the index into the throwable chain, -1 if no match or null input */ public static int indexOfThrowable(Throwable throwable, Class clazz, int fromIndex) { return indexOf(throwable, clazz, fromIndex, false); } //----------------------------------------------------------------------- /** *

Returns the (zero based) index of the first Throwable * that matches the specified class or subclass in the exception chain. * Subclasses of the specified class do match - see * {@link #indexOfThrowable(Throwable, Class)} for the opposite.

* *

A null throwable returns -1. * A null type returns -1. * No match in the chain returns -1.

* * @param throwable the throwable to inspect, may be null * @param type the type to search for, subclasses match, null returns -1 * @return the index into the throwable chain, -1 if no match or null input * @since 2.1 */ public static int indexOfType(Throwable throwable, Class type) { return indexOf(throwable, type, 0, true); } /** *

Returns the (zero based) index of the first Throwable * that matches the specified type in the exception chain from * a specified index. * Subclasses of the specified class do match - see * {@link #indexOfThrowable(Throwable, Class)} for the opposite.

* *

A null throwable returns -1. * A null type returns -1. * No match in the chain returns -1. * A negative start index is treated as zero. * A start index greater than the number of throwables returns -1.

* * @param throwable the throwable to inspect, may be null * @param type the type to search for, subclasses match, null returns -1 * @param fromIndex the (zero based) index of the starting position, * negative treated as zero, larger than chain size returns -1 * @return the index into the throwable chain, -1 if no match or null input * @since 2.1 */ public static int indexOfType(Throwable throwable, Class type, int fromIndex) { return indexOf(throwable, type, fromIndex, true); } /** *

Worker method for the indexOfType methods.

* * @param throwable the throwable to inspect, may be null * @param type the type to search for, subclasses match, null returns -1 * @param fromIndex the (zero based) index of the starting position, * negative treated as zero, larger than chain size returns -1 * @param subclass if true, compares with {@link Class#isAssignableFrom(Class)}, otherwise compares * using references * @return index of the type within throwables nested withing the specified throwable */ private static int indexOf(Throwable throwable, Class type, int fromIndex, boolean subclass) { if (throwable == null || type == null) { return -1; } if (fromIndex < 0) { fromIndex = 0; } Throwable[] throwables = ExceptionUtils.getThrowables(throwable); if (fromIndex >= throwables.length) { return -1; } if (subclass) { for (int i = fromIndex; i < throwables.length; i++) { if (type.isAssignableFrom(throwables[i].getClass())) { return i; } } } else { for (int i = fromIndex; i < throwables.length; i++) { if (type.equals(throwables[i].getClass())) { return i; } } } return -1; } //----------------------------------------------------------------------- /** *

Prints a compact stack trace for the root cause of a throwable * to System.err.

* *

The compact stack trace starts with the root cause and prints * stack frames up to the place where it was caught and wrapped. * Then it prints the wrapped exception and continues with stack frames * until the wrapper exception is caught and wrapped again, etc.

* *

The output of this method is consistent across JDK versions. * Note that this is the opposite order to the JDK1.4 display.

* *

The method is equivalent to printStackTrace for throwables * that don't have nested causes.

* * @param throwable the throwable to output * @since 2.0 */ public static void printRootCauseStackTrace(Throwable throwable) { printRootCauseStackTrace(throwable, System.err); } /** *

Prints a compact stack trace for the root cause of a throwable.

* *

The compact stack trace starts with the root cause and prints * stack frames up to the place where it was caught and wrapped. * Then it prints the wrapped exception and continues with stack frames * until the wrapper exception is caught and wrapped again, etc.

* *

The output of this method is consistent across JDK versions. * Note that this is the opposite order to the JDK1.4 display.

* *

The method is equivalent to printStackTrace for throwables * that don't have nested causes.

* * @param throwable the throwable to output, may be null * @param stream the stream to output to, may not be null * @throws IllegalArgumentException if the stream is null * @since 2.0 */ public static void printRootCauseStackTrace(Throwable throwable, PrintStream stream) { if (throwable == null) { return; } if (stream == null) { throw new IllegalArgumentException("The PrintStream must not be null"); } String trace[] = getRootCauseStackTrace(throwable); for (int i = 0; i < trace.length; i++) { stream.println(trace[i]); } stream.flush(); } /** *

Prints a compact stack trace for the root cause of a throwable.

* *

The compact stack trace starts with the root cause and prints * stack frames up to the place where it was caught and wrapped. * Then it prints the wrapped exception and continues with stack frames * until the wrapper exception is caught and wrapped again, etc.

* *

The output of this method is consistent across JDK versions. * Note that this is the opposite order to the JDK1.4 display.

* *

The method is equivalent to printStackTrace for throwables * that don't have nested causes.

* * @param throwable the throwable to output, may be null * @param writer the writer to output to, may not be null * @throws IllegalArgumentException if the writer is null * @since 2.0 */ public static void printRootCauseStackTrace(Throwable throwable, PrintWriter writer) { if (throwable == null) { return; } if (writer == null) { throw new IllegalArgumentException("The PrintWriter must not be null"); } String trace[] = getRootCauseStackTrace(throwable); for (int i = 0; i < trace.length; i++) { writer.println(trace[i]); } writer.flush(); } //----------------------------------------------------------------------- /** *

Creates a compact stack trace for the root cause of the supplied * Throwable.

* *

The output of this method is consistent across JDK versions. * It consists of the root exception followed by each of its wrapping * exceptions separated by '[wrapped]'. Note that this is the opposite * order to the JDK1.4 display.

* * @param throwable the throwable to examine, may be null * @return an array of stack trace frames, never null * @since 2.0 */ public static String[] getRootCauseStackTrace(Throwable throwable) { if (throwable == null) { return ArrayUtils.EMPTY_STRING_ARRAY; } Throwable throwables[] = getThrowables(throwable); int count = throwables.length; ArrayList frames = new ArrayList(); List nextTrace = getStackFrameList(throwables[count - 1]); for (int i = count; --i >= 0;) { List trace = nextTrace; if (i != 0) { nextTrace = getStackFrameList(throwables[i - 1]); removeCommonFrames(trace, nextTrace); } if (i == count - 1) { frames.add(throwables[i].toString()); } else { frames.add(WRAPPED_MARKER + throwables[i].toString()); } for (int j = 0; j < trace.size(); j++) { frames.add(trace.get(j)); } } return (String[]) frames.toArray(new String[0]); } /** *

Removes common frames from the cause trace given the two stack traces.

* * @param causeFrames stack trace of a cause throwable * @param wrapperFrames stack trace of a wrapper throwable * @throws IllegalArgumentException if either argument is null * @since 2.0 */ public static void removeCommonFrames(List causeFrames, List wrapperFrames) { if (causeFrames == null || wrapperFrames == null) { throw new IllegalArgumentException("The List must not be null"); } int causeFrameIndex = causeFrames.size() - 1; int wrapperFrameIndex = wrapperFrames.size() - 1; while (causeFrameIndex >= 0 && wrapperFrameIndex >= 0) { // Remove the frame from the cause trace if it is the same // as in the wrapper trace String causeFrame = (String) causeFrames.get(causeFrameIndex); String wrapperFrame = (String) wrapperFrames.get(wrapperFrameIndex); if (causeFrame.equals(wrapperFrame)) { causeFrames.remove(causeFrameIndex); } causeFrameIndex--; wrapperFrameIndex--; } } //----------------------------------------------------------------------- /** *

A way to get the entire nested stack-trace of an throwable.

* *

The result of this method is highly dependent on the JDK version * and whether the exceptions override printStackTrace or not.

* * @param throwable the Throwable to be examined * @return the nested stack trace, with the root cause first * @since 2.0 */ public static String getFullStackTrace(Throwable throwable) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw, true); Throwable[] ts = getThrowables(throwable); for (int i = 0; i < ts.length; i++) { ts[i].printStackTrace(pw); if (isNestedThrowable(ts[i])) { break; } } return sw.getBuffer().toString(); } //----------------------------------------------------------------------- /** *

Gets the stack trace from a Throwable as a String.

* *

The result of this method vary by JDK version as this method * uses {@link Throwable#printStackTrace(java.io.PrintWriter)}. * On JDK1.3 and earlier, the cause exception will not be shown * unless the specified throwable alters printStackTrace.

* * @param throwable the Throwable to be examined * @return the stack trace as generated by the exception's * printStackTrace(PrintWriter) method */ public static String getStackTrace(Throwable throwable) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw, true); throwable.printStackTrace(pw); return sw.getBuffer().toString(); } /** *

Captures the stack trace associated with the specified * Throwable object, decomposing it into a list of * stack frames.

* *

The result of this method vary by JDK version as this method * uses {@link Throwable#printStackTrace(java.io.PrintWriter)}. * On JDK1.3 and earlier, the cause exception will not be shown * unless the specified throwable alters printStackTrace.

* * @param throwable the Throwable to examine, may be null * @return an array of strings describing each stack frame, never null */ public static String[] getStackFrames(Throwable throwable) { if (throwable == null) { return ArrayUtils.EMPTY_STRING_ARRAY; } return getStackFrames(getStackTrace(throwable)); } //----------------------------------------------------------------------- /** *

Returns an array where each element is a line from the argument.

* *

The end of line is determined by the value of {@link SystemUtils#LINE_SEPARATOR}.

* *

Functionality shared between the * getStackFrames(Throwable) methods of this and the * {@link org.apache.commons.lang.exception.NestableDelegate} classes.

* * @param stackTrace a stack trace String * @return an array where each element is a line from the argument */ static String[] getStackFrames(String stackTrace) { String linebreak = SystemUtils.LINE_SEPARATOR; StringTokenizer frames = new StringTokenizer(stackTrace, linebreak); List list = new ArrayList(); while (frames.hasMoreTokens()) { list.add(frames.nextToken()); } return toArray(list); } /** *

Produces a List of stack frames - the message * is not included. Only the trace of the specified exception is * returned, any caused by trace is stripped.

* *

This works in most cases - it will only fail if the exception * message contains a line that starts with: * "   at".

* * @param t is any throwable * @return List of stack frames */ static List getStackFrameList(Throwable t) { String stackTrace = getStackTrace(t); String linebreak = SystemUtils.LINE_SEPARATOR; StringTokenizer frames = new StringTokenizer(stackTrace, linebreak); List list = new ArrayList(); boolean traceStarted = false; while (frames.hasMoreTokens()) { String token = frames.nextToken(); // Determine if the line starts with at int at = token.indexOf("at"); if (at != -1 && token.substring(0, at).trim().length() == 0) { traceStarted = true; list.add(token); } else if (traceStarted) { break; } } return list; } //----------------------------------------------------------------------- /** * Gets a short message summarising the exception. *

* The message returned is of the form * {ClassNameWithoutPackage}: {ThrowableMessage} * * @param th the throwable to get a message for, null returns empty string * @return the message, non-null * @since Commons Lang 2.2 */ public static String getMessage(Throwable th) { if (th == null) { return ""; } String clsName = ClassUtils.getShortClassName(th, null); String msg = th.getMessage(); return clsName + ": " + StringUtils.defaultString(msg); } //----------------------------------------------------------------------- /** * Gets a short message summarising the root cause exception. *

* The message returned is of the form * {ClassNameWithoutPackage}: {ThrowableMessage} * * @param th the throwable to get a message for, null returns empty string * @return the message, non-null * @since Commons Lang 2.2 */ public static String getRootCauseMessage(Throwable th) { Throwable root = ExceptionUtils.getRootCause(th); root = (root == null ? th : root); return getMessage(root); } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/exception/Nestable.java100644 0 0 16107 11513702442 25351 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.exception; import java.io.PrintStream; import java.io.PrintWriter; /** * An interface to be implemented by {@link java.lang.Throwable} * extensions which would like to be able to nest root exceptions * inside themselves. * * @author Daniel L. Rall * @author Kasper Nielsen * @author Steven Caswell * @author Pete Gieser * @since 1.0 * @version $Id: Nestable.java 512889 2007-02-28 18:18:20Z dlr $ */ public interface Nestable { /** * Returns the reference to the exception or error that caused the * exception implementing the Nestable to be thrown. * * @return throwable that caused the original exception */ public Throwable getCause(); /** * Returns the error message of this and any nested * Throwable. * * @return the error message */ public String getMessage(); /** * Returns the error message of the Throwable in the chain * of Throwables at the specified index, numbered from 0. * * @param index the index of the Throwable in the chain of * Throwables * @return the error message, or null if the Throwable at the * specified index in the chain does not contain a message * @throws IndexOutOfBoundsException if the index argument is * negative or not less than the count of Throwables in the * chain */ public String getMessage(int index); /** * Returns the error message of this and any nested Throwables * in an array of Strings, one element for each message. Any * Throwable not containing a message is represented in the * array by a null. This has the effect of cause the length of the returned * array to be equal to the result of the {@link #getThrowableCount()} * operation. * * @return the error messages */ public String[] getMessages(); /** * Returns the Throwable in the chain of * Throwables at the specified index, numbered from 0. * * @param index the index, numbered from 0, of the Throwable in * the chain of Throwables * @return the Throwable * @throws IndexOutOfBoundsException if the index argument is * negative or not less than the count of Throwables in the * chain */ public Throwable getThrowable(int index); /** * Returns the number of nested Throwables represented by * this Nestable, including this Nestable. * * @return the throwable count */ public int getThrowableCount(); /** * Returns this Nestable and any nested Throwables * in an array of Throwables, one element for each * Throwable. * * @return the Throwables */ public Throwable[] getThrowables(); /** * Returns the index, numbered from 0, of the first occurrence of the * specified type, or a subclass, in the chain of Throwables. * The method returns -1 if the specified type is not found in the chain. *

* NOTE: From v2.1, we have clarified the Nestable interface * such that this method matches subclasses. * If you want to NOT match subclasses, please use * {@link ExceptionUtils#indexOfThrowable(Throwable, Class)} * (which is avaiable in all versions of lang). * * @param type the type to find, subclasses match, null returns -1 * @return index of the first occurrence of the type in the chain, or -1 if * the type is not found */ public int indexOfThrowable(Class type); /** * Returns the index, numbered from 0, of the first Throwable * that matches the specified type, or a subclass, in the chain of Throwables * with an index greater than or equal to the specified index. * The method returns -1 if the specified type is not found in the chain. *

* NOTE: From v2.1, we have clarified the Nestable interface * such that this method matches subclasses. * If you want to NOT match subclasses, please use * {@link ExceptionUtils#indexOfThrowable(Throwable, Class, int)} * (which is avaiable in all versions of lang). * * @param type the type to find, subclasses match, null returns -1 * @param fromIndex the index, numbered from 0, of the starting position in * the chain to be searched * @return index of the first occurrence of the type in the chain, or -1 if * the type is not found * @throws IndexOutOfBoundsException if the fromIndex argument * is negative or not less than the count of Throwables in the * chain */ public int indexOfThrowable(Class type, int fromIndex); /** * Prints the stack trace of this exception to the specified print * writer. Includes information from the exception, if any, * which caused this exception. * * @param out PrintWriter to use for output. */ public void printStackTrace(PrintWriter out); /** * Prints the stack trace of this exception to the specified print * stream. Includes information from the exception, if any, * which caused this exception. * * @param out PrintStream to use for output. */ public void printStackTrace(PrintStream out); /** * Prints the stack trace for this exception only--root cause not * included--using the provided writer. Used by * {@link org.apache.commons.lang.exception.NestableDelegate} to write * individual stack traces to a buffer. The implementation of * this method should call * super.printStackTrace(out); in most cases. * * @param out The writer to use. */ public void printPartialStackTrace(PrintWriter out); } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/exception/NestableDelegate.java100644 0 0 36442 11513702442 27010 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.exception; import java.io.PrintStream; import java.io.PrintWriter; import java.io.Serializable; import java.io.StringWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; /** *

A shared implementation of the nestable exception functionality.

*

* The code is shared between * {@link org.apache.commons.lang.exception.NestableError NestableError}, * {@link org.apache.commons.lang.exception.NestableException NestableException} and * {@link org.apache.commons.lang.exception.NestableRuntimeException NestableRuntimeException}. *

* * @author Apache Software Foundation * @author Rafal Krzewski * @author Daniel L. Rall * @author Kasper Nielsen * @author Steven Caswell * @author Sean C. Sullivan * @since 1.0 * @version $Id: NestableDelegate.java 905636 2010-02-02 14:03:32Z niallp $ */ public class NestableDelegate implements Serializable { /** * Required for serialization support. * * @see java.io.Serializable */ private static final long serialVersionUID = 1L; /** * Constructor error message. */ private transient static final String MUST_BE_THROWABLE = "The Nestable implementation passed to the NestableDelegate(Nestable) " + "constructor must extend java.lang.Throwable"; /** * Holds the reference to the exception or error that we're * wrapping (which must be a {@link * org.apache.commons.lang.exception.Nestable} implementation). */ private Throwable nestable = null; /** * Whether to print the stack trace top-down. * This public flag may be set by calling code, typically in initialisation. * This exists for backwards compatability, setting it to false will return * the library to v1.0 behaviour (but will affect all users of the library * in the classloader). * @since 2.0 */ public static boolean topDown = true; /** * Whether to trim the repeated stack trace. * This public flag may be set by calling code, typically in initialisation. * This exists for backwards compatability, setting it to false will return * the library to v1.0 behaviour (but will affect all users of the library * in the classloader). * @since 2.0 */ public static boolean trimStackFrames = true; /** * Whether to match subclasses via indexOf. * This public flag may be set by calling code, typically in initialisation. * This exists for backwards compatability, setting it to false will return * the library to v2.0 behaviour (but will affect all users of the library * in the classloader). * @since 2.1 */ public static boolean matchSubclasses = true; /** * Constructs a new NestableDelegate instance to manage the * specified Nestable. * * @param nestable the Nestable implementation (must extend * {@link java.lang.Throwable}) * @since 2.0 */ public NestableDelegate(Nestable nestable) { if (nestable instanceof Throwable) { this.nestable = (Throwable) nestable; } else { throw new IllegalArgumentException(MUST_BE_THROWABLE); } } /** * Returns the error message of the Throwable in the chain of Throwables at the * specified index, numbered from 0. * * @param index * the index of the Throwable in the chain of Throwables * @return the error message, or null if the Throwable at the specified index in the chain does not * contain a message * @throws IndexOutOfBoundsException * if the index argument is negative or not less than the count of Throwables * in the chain * @since 2.0 */ public String getMessage(int index) { Throwable t = this.getThrowable(index); if (Nestable.class.isInstance(t)) { return ((Nestable) t).getMessage(0); } return t.getMessage(); } /** * Returns the full message contained by the Nestable and any nested Throwables. * * @param baseMsg * the base message to use when creating the full message. Should be generally be called via * nestableHelper.getMessage(super.getMessage()), where super is an * instance of {@link java.lang.Throwable}. * @return The concatenated message for this and all nested Throwables * @since 2.0 */ public String getMessage(String baseMsg) { Throwable nestedCause = ExceptionUtils.getCause(this.nestable); String causeMsg = nestedCause == null ? null : nestedCause.getMessage(); if (nestedCause == null || causeMsg == null) { return baseMsg; // may be null, which is a valid result } if (baseMsg == null) { return causeMsg; } return baseMsg + ": " + causeMsg; } /** * Returns the error message of this and any nested Throwables in an array of Strings, one element * for each message. Any Throwable not containing a message is represented in the array by a null. * This has the effect of cause the length of the returned array to be equal to the result of the * {@link #getThrowableCount()} operation. * * @return the error messages * @since 2.0 */ public String[] getMessages() { Throwable[] throwables = this.getThrowables(); String[] msgs = new String[throwables.length]; for (int i = 0; i < throwables.length; i++) { msgs[i] = (Nestable.class.isInstance(throwables[i]) ? ((Nestable) throwables[i]).getMessage(0) : throwables[i].getMessage()); } return msgs; } /** * Returns the Throwable in the chain of * Throwables at the specified index, numbered from 0. * * @param index the index, numbered from 0, of the Throwable in * the chain of Throwables * @return the Throwable * @throws IndexOutOfBoundsException if the index argument is * negative or not less than the count of Throwables in the * chain * @since 2.0 */ public Throwable getThrowable(int index) { if (index == 0) { return this.nestable; } Throwable[] throwables = this.getThrowables(); return throwables[index]; } /** * Returns the number of Throwables contained in the * Nestable contained by this delegate. * * @return the throwable count * @since 2.0 */ public int getThrowableCount() { return ExceptionUtils.getThrowableCount(this.nestable); } /** * Returns this delegate's Nestable and any nested * Throwables in an array of Throwables, one * element for each Throwable. * * @return the Throwables * @since 2.0 */ public Throwable[] getThrowables() { return ExceptionUtils.getThrowables(this.nestable); } /** * Returns the index, numbered from 0, of the first Throwable * that matches the specified type, or a subclass, in the chain of Throwables * with an index greater than or equal to the specified index. * The method returns -1 if the specified type is not found in the chain. *

* NOTE: From v2.1, we have clarified the Nestable interface * such that this method matches subclasses. * If you want to NOT match subclasses, please use * {@link ExceptionUtils#indexOfThrowable(Throwable, Class, int)} * (which is avaiable in all versions of lang). * An alternative is to use the public static flag {@link #matchSubclasses} * on NestableDelegate, however this is not recommended. * * @param type the type to find, subclasses match, null returns -1 * @param fromIndex the index, numbered from 0, of the starting position in * the chain to be searched * @return index of the first occurrence of the type in the chain, or -1 if * the type is not found * @throws IndexOutOfBoundsException if the fromIndex argument * is negative or not less than the count of Throwables in the * chain * @since 2.0 */ public int indexOfThrowable(Class type, int fromIndex) { if (type == null) { return -1; } if (fromIndex < 0) { throw new IndexOutOfBoundsException("The start index was out of bounds: " + fromIndex); } Throwable[] throwables = ExceptionUtils.getThrowables(this.nestable); if (fromIndex >= throwables.length) { throw new IndexOutOfBoundsException("The start index was out of bounds: " + fromIndex + " >= " + throwables.length); } if (matchSubclasses) { for (int i = fromIndex; i < throwables.length; i++) { if (type.isAssignableFrom(throwables[i].getClass())) { return i; } } } else { for (int i = fromIndex; i < throwables.length; i++) { if (type.equals(throwables[i].getClass())) { return i; } } } return -1; } /** * Prints the stack trace of this exception the the standar error * stream. */ public void printStackTrace() { printStackTrace(System.err); } /** * Prints the stack trace of this exception to the specified * stream. * * @param out PrintStream to use for output. * @see #printStackTrace(PrintWriter) */ public void printStackTrace(PrintStream out) { synchronized (out) { PrintWriter pw = new PrintWriter(out, false); printStackTrace(pw); // Flush the PrintWriter before it's GC'ed. pw.flush(); } } /** * Prints the stack trace of this exception to the specified * writer. If the Throwable class has a getCause * method (i.e. running on jre1.4 or higher), this method just * uses Throwable's printStackTrace() method. Otherwise, generates * the stack-trace, by taking into account the 'topDown' and * 'trimStackFrames' parameters. The topDown and trimStackFrames * are set to 'true' by default (produces jre1.4-like stack trace). * * @param out PrintWriter to use for output. */ public void printStackTrace(PrintWriter out) { Throwable throwable = this.nestable; // if running on jre1.4 or higher, use default printStackTrace if (ExceptionUtils.isThrowableNested()) { if (throwable instanceof Nestable) { ((Nestable)throwable).printPartialStackTrace(out); } else { throwable.printStackTrace(out); } return; } // generating the nested stack trace List stacks = new ArrayList(); while (throwable != null) { String[] st = getStackFrames(throwable); stacks.add(st); throwable = ExceptionUtils.getCause(throwable); } // If NOT topDown, reverse the stack String separatorLine = "Caused by: "; if (!topDown) { separatorLine = "Rethrown as: "; Collections.reverse(stacks); } // Remove the repeated lines in the stack if (trimStackFrames) { trimStackFrames(stacks); } synchronized (out) { for (Iterator iter=stacks.iterator(); iter.hasNext();) { String[] st = (String[]) iter.next(); for (int i=0, len=st.length; i < len; i++) { out.println(st[i]); } if (iter.hasNext()) { out.print(separatorLine); } } } } /** * Captures the stack trace associated with the specified * Throwable object, decomposing it into a list of * stack frames. * * @param t The Throwable. * @return An array of strings describing each stack frame. * @since 2.0 */ protected String[] getStackFrames(Throwable t) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw, true); // Avoid infinite loop between decompose() and printStackTrace(). if (t instanceof Nestable) { ((Nestable) t).printPartialStackTrace(pw); } else { t.printStackTrace(pw); } return ExceptionUtils.getStackFrames(sw.getBuffer().toString()); } /** * Trims the stack frames. The first set is left untouched. The rest * of the frames are truncated from the bottom by comparing with * one just on top. * * @param stacks The list containing String[] elements * @since 2.0 */ protected void trimStackFrames(List stacks) { for (int size=stacks.size(), i=size-1; i > 0; i--) { String[] curr = (String[]) stacks.get(i); String[] next = (String[]) stacks.get(i-1); List currList = new ArrayList(Arrays.asList(curr)); List nextList = new ArrayList(Arrays.asList(next)); ExceptionUtils.removeCommonFrames(currList, nextList); int trimmed = curr.length - currList.size(); if (trimmed > 0) { currList.add("\t... "+trimmed+" more"); stacks.set( i, currList.toArray(new String[currList.size()]) ); } } } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/exception/NestableError.java100644 0 0 12000 11513702442 26347 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.exception; import java.io.PrintStream; import java.io.PrintWriter; /** * The base class of all errors which can contain other exceptions. * * @author Daniel L. Rall * @see org.apache.commons.lang.exception.NestableException * @since 1.0 * @version $Id: NestableError.java 512889 2007-02-28 18:18:20Z dlr $ */ public class NestableError extends Error implements Nestable { /** * Required for serialization support. * * @see java.io.Serializable */ private static final long serialVersionUID = 1L; /** * The helper instance which contains much of the code which we * delegate to. */ protected NestableDelegate delegate = new NestableDelegate(this); /** * Holds the reference to the exception or error that caused * this exception to be thrown. */ private Throwable cause = null; /** * Constructs a new NestableError without specified * detail message. */ public NestableError() { super(); } /** * Constructs a new NestableError with specified * detail message. * * @param msg The error message. */ public NestableError(String msg) { super(msg); } /** * Constructs a new NestableError with specified * nested Throwable. * * @param cause the exception or error that caused this exception to be * thrown */ public NestableError(Throwable cause) { super(); this.cause = cause; } /** * Constructs a new NestableError with specified * detail message and nested Throwable. * * @param msg the error message * @param cause the exception or error that caused this exception to be * thrown */ public NestableError(String msg, Throwable cause) { super(msg); this.cause = cause; } /** * {@inheritDoc} */ public Throwable getCause() { return cause; } /** * Returns the detail message string of this throwable. If it was * created with a null message, returns the following: * (cause==null ? null : cause.toString()). * * @return String message string of the throwable */ public String getMessage() { if (super.getMessage() != null) { return super.getMessage(); } else if (cause != null) { return cause.toString(); } else { return null; } } /** * {@inheritDoc} */ public String getMessage(int index) { if (index == 0) { return super.getMessage(); } return delegate.getMessage(index); } /** * {@inheritDoc} */ public String[] getMessages() { return delegate.getMessages(); } /** * {@inheritDoc} */ public Throwable getThrowable(int index) { return delegate.getThrowable(index); } /** * {@inheritDoc} */ public int getThrowableCount() { return delegate.getThrowableCount(); } /** * {@inheritDoc} */ public Throwable[] getThrowables() { return delegate.getThrowables(); } /** * {@inheritDoc} */ public int indexOfThrowable(Class type) { return delegate.indexOfThrowable(type, 0); } /** * {@inheritDoc} */ public int indexOfThrowable(Class type, int fromIndex) { return delegate.indexOfThrowable(type, fromIndex); } /** * {@inheritDoc} */ public void printStackTrace() { delegate.printStackTrace(); } /** * {@inheritDoc} */ public void printStackTrace(PrintStream out) { delegate.printStackTrace(out); } /** * {@inheritDoc} */ public void printStackTrace(PrintWriter out) { delegate.printStackTrace(out); } /** * {@inheritDoc} */ public final void printPartialStackTrace(PrintWriter out) { super.printStackTrace(out); } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/exception/NestableException.java100644 0 0 16341 11513702442 27230 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.exception; import java.io.PrintStream; import java.io.PrintWriter; /** * The base class of all exceptions which can contain other exceptions. * * It is intended to ease the debugging by carrying on the information * about the exception which was caught and provoked throwing the * current exception. Catching and rethrowing may occur multiple * times, and provided that all exceptions except the first one * are descendants of NestedException, when the * exception is finally printed out using any of the * printStackTrace() methods, the stack trace will contain * the information about all exceptions thrown and caught on * the way. *

Running the following program *

 *  1 import org.apache.commons.lang.exception.NestableException;
 *  2
 *  3 public class Test {
 *  4     public static void main( String[] args ) {
 *  5         try {
 *  6             a();
 *  7         } catch(Exception e) {
 *  8             e.printStackTrace();
 *  9         }
 * 10      }
 * 11
 * 12      public static void a() throws Exception {
 * 13          try {
 * 14              b();
 * 15          } catch(Exception e) {
 * 16              throw new NestableException("foo", e);
 * 17          }
 * 18      }
 * 19
 * 20      public static void b() throws Exception {
 * 21          try {
 * 22              c();
 * 23          } catch(Exception e) {
 * 24              throw new NestableException("bar", e);
 * 25          }
 * 26      }
 * 27
 * 28      public static void c() throws Exception {
 * 29          throw new Exception("baz");
 * 30      }
 * 31 }
 * 
*

Yields the following stack trace: *

 * org.apache.commons.lang.exception.NestableException: foo
 *         at Test.a(Test.java:16)
 *         at Test.main(Test.java:6)
 * Caused by: org.apache.commons.lang.exception.NestableException: bar
 *         at Test.b(Test.java:24)
 *         at Test.a(Test.java:14)
 *         ... 1 more
 * Caused by: java.lang.Exception: baz
 *         at Test.c(Test.java:29)
 *         at Test.b(Test.java:22)
 *         ... 2 more
 * 

* * @author Rafal Krzewski * @author Daniel L. Rall * @author Kasper Nielsen * @author Steven Caswell * @since 1.0 * @version $Id: NestableException.java 512889 2007-02-28 18:18:20Z dlr $ */ public class NestableException extends Exception implements Nestable { /** * Required for serialization support. * * @see java.io.Serializable */ private static final long serialVersionUID = 1L; /** * The helper instance which contains much of the code which we * delegate to. */ protected NestableDelegate delegate = new NestableDelegate(this); /** * Holds the reference to the exception or error that caused * this exception to be thrown. */ private Throwable cause = null; /** * Constructs a new NestableException without specified * detail message. */ public NestableException() { super(); } /** * Constructs a new NestableException with specified * detail message. * * @param msg The error message. */ public NestableException(String msg) { super(msg); } /** * Constructs a new NestableException with specified * nested Throwable. * * @param cause the exception or error that caused this exception to be * thrown */ public NestableException(Throwable cause) { super(); this.cause = cause; } /** * Constructs a new NestableException with specified * detail message and nested Throwable. * * @param msg the error message * @param cause the exception or error that caused this exception to be * thrown */ public NestableException(String msg, Throwable cause) { super(msg); this.cause = cause; } /** * {@inheritDoc} */ public Throwable getCause() { return cause; } /** * Returns the detail message string of this throwable. If it was * created with a null message, returns the following: * (cause==null ? null : cause.toString()). * * @return String message string of the throwable */ public String getMessage() { if (super.getMessage() != null) { return super.getMessage(); } else if (cause != null) { return cause.toString(); } else { return null; } } /** * {@inheritDoc} */ public String getMessage(int index) { if (index == 0) { return super.getMessage(); } return delegate.getMessage(index); } /** * {@inheritDoc} */ public String[] getMessages() { return delegate.getMessages(); } /** * {@inheritDoc} */ public Throwable getThrowable(int index) { return delegate.getThrowable(index); } /** * {@inheritDoc} */ public int getThrowableCount() { return delegate.getThrowableCount(); } /** * {@inheritDoc} */ public Throwable[] getThrowables() { return delegate.getThrowables(); } /** * {@inheritDoc} */ public int indexOfThrowable(Class type) { return delegate.indexOfThrowable(type, 0); } /** * {@inheritDoc} */ public int indexOfThrowable(Class type, int fromIndex) { return delegate.indexOfThrowable(type, fromIndex); } /** * {@inheritDoc} */ public void printStackTrace() { delegate.printStackTrace(); } /** * {@inheritDoc} */ public void printStackTrace(PrintStream out) { delegate.printStackTrace(out); } /** * {@inheritDoc} */ public void printStackTrace(PrintWriter out) { delegate.printStackTrace(out); } /** * {@inheritDoc} */ public final void printPartialStackTrace(PrintWriter out) { super.printStackTrace(out); } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/exception/NestableRuntimeException.java100644 0 0 12540 11513702442 30571 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.exception; import java.io.PrintStream; import java.io.PrintWriter; /** * The base class of all runtime exceptions which can contain other * exceptions. * * @see org.apache.commons.lang.exception.NestableException * @author Rafal Krzewski * @author Daniel L. Rall * @author Kasper Nielsen * @author Steven Caswell * @since 1.0 * @version $Id: NestableRuntimeException.java 512889 2007-02-28 18:18:20Z dlr $ */ public class NestableRuntimeException extends RuntimeException implements Nestable { /** * Required for serialization support. * * @see java.io.Serializable */ private static final long serialVersionUID = 1L; /** * The helper instance which contains much of the code which we * delegate to. */ protected NestableDelegate delegate = new NestableDelegate(this); /** * Holds the reference to the exception or error that caused * this exception to be thrown. */ private Throwable cause = null; /** * Constructs a new NestableRuntimeException without specified * detail message. */ public NestableRuntimeException() { super(); } /** * Constructs a new NestableRuntimeException with specified * detail message. * * @param msg the error message */ public NestableRuntimeException(String msg) { super(msg); } /** * Constructs a new NestableRuntimeException with specified * nested Throwable. * * @param cause the exception or error that caused this exception to be * thrown */ public NestableRuntimeException(Throwable cause) { super(); this.cause = cause; } /** * Constructs a new NestableRuntimeException with specified * detail message and nested Throwable. * * @param msg the error message * @param cause the exception or error that caused this exception to be * thrown */ public NestableRuntimeException(String msg, Throwable cause) { super(msg); this.cause = cause; } /** * {@inheritDoc} */ public Throwable getCause() { return cause; } /** * Returns the detail message string of this throwable. If it was * created with a null message, returns the following: * (cause==null ? null : cause.toString()). * * @return String message string of the throwable */ public String getMessage() { if (super.getMessage() != null) { return super.getMessage(); } else if (cause != null) { return cause.toString(); } else { return null; } } /** * {@inheritDoc} */ public String getMessage(int index) { if (index == 0) { return super.getMessage(); } return delegate.getMessage(index); } /** * {@inheritDoc} */ public String[] getMessages() { return delegate.getMessages(); } /** * {@inheritDoc} */ public Throwable getThrowable(int index) { return delegate.getThrowable(index); } /** * {@inheritDoc} */ public int getThrowableCount() { return delegate.getThrowableCount(); } /** * {@inheritDoc} */ public Throwable[] getThrowables() { return delegate.getThrowables(); } /** * {@inheritDoc} */ public int indexOfThrowable(Class type) { return delegate.indexOfThrowable(type, 0); } /** * {@inheritDoc} */ public int indexOfThrowable(Class type, int fromIndex) { return delegate.indexOfThrowable(type, fromIndex); } /** * {@inheritDoc} */ public void printStackTrace() { delegate.printStackTrace(); } /** * {@inheritDoc} */ public void printStackTrace(PrintStream out) { delegate.printStackTrace(out); } /** * {@inheritDoc} */ public void printStackTrace(PrintWriter out) { delegate.printStackTrace(out); } /** * {@inheritDoc} */ public final void printPartialStackTrace(PrintWriter out) { super.printStackTrace(out); } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/exception/package.html100644 0 0 2270 11513702442 25206 0ustar 0 0 Provides JDK 1.4 style Nested Exception functionality for those on prior Java versions.

Includes a static utility to create version independent Nested Exception which can handle JDK 1.4 Exceptions as well as others.

Lastly, {@link org.apache.commons.lang.exception.ExceptionUtils} also contains Throwable manipulation and examination routines.

@since 1.0 commons-lang-2.6-src/src/main/java/org/apache/commons/lang/IllegalClassException.java100644 0 0 7165 11513702446 26024 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang; /** *

Thrown when an object is an instance of an unexpected type (a class or interface). * This exception supplements the standard IllegalArgumentException * by providing a more semantically rich description of the problem.

* *

IllegalClassException represents the case where a method takes * in a genericly typed parameter like Object (typically because it has to due to some * other interface it implements), but this implementation only actually accepts a specific * type, for example String. This exception would be used in place of * IllegalArgumentException, yet it still extends it.

* *
 * public void foo(Object obj) {
 *   if (obj instanceof String == false) {
 *     throw new IllegalClassException(String.class, obj);
 *   }
 *   // do something with the string
 * }
 * 
* * @author Apache Software Foundation * @author Matthew Hawthorne * @author Gary Gregory * @since 2.0 * @version $Id: IllegalClassException.java 905636 2010-02-02 14:03:32Z niallp $ */ public class IllegalClassException extends IllegalArgumentException { /** * Required for serialization support. * * @see java.io.Serializable */ private static final long serialVersionUID = 8063272569377254819L; /** *

Instantiates with the expected type, and actual object.

* * @param expected the expected type * @param actual the actual object * @since 2.1 */ public IllegalClassException(Class expected, Object actual) { super( "Expected: " + safeGetClassName(expected) + ", actual: " + (actual == null ? "null" : actual.getClass().getName())); } /** *

Instantiates with the expected and actual types.

* * @param expected the expected type * @param actual the actual type */ public IllegalClassException(Class expected, Class actual) { super( "Expected: " + safeGetClassName(expected) + ", actual: " + safeGetClassName(actual)); } /** *

Instantiates with the specified message.

* * @param message the exception message */ public IllegalClassException(String message) { super(message); } /** *

Returns the class name or null if the class is * null.

* * @param cls a Class * @return the name of cls, or null if if cls is null. */ private static final String safeGetClassName(Class cls) { return cls == null ? null : cls.getName(); } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/IncompleteArgumentException.java100644 0 0 6322 11513702446 27261 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang; import java.util.Arrays; /** *

Thrown to indicate an incomplete argument to a method. * This exception supplements the standard IllegalArgumentException * by providing a more semantically rich description of the problem.

* *

IncompleteArgumentException represents the case where a method takes * in a parameter that has a number of properties, some of which have not been set. * A case might be a search requirements bean that must have three properties set * in order for the method to run, but only one is actually set. * This exception would be used in place of * IllegalArgumentException, yet it still extends it.

* *
 * public void foo(PersonSearcher search) {
 *   if (search.getSurname() == null ||
 *       search.getForename() == null ||
 *       search.getSex() == null) {
 *     throw new IncompleteArgumentException("search");
 *   }
 *   // do something with the searcher
 * }
 * 
* * @author Matthew Hawthorne * @since 2.0 * @version $Id: IncompleteArgumentException.java 437554 2006-08-28 06:21:41Z bayard $ */ public class IncompleteArgumentException extends IllegalArgumentException { /** * Required for serialization support. * * @see java.io.Serializable */ private static final long serialVersionUID = 4954193403612068178L; /** *

Instantiates with the specified description.

* * @param argName a description of the incomplete argument */ public IncompleteArgumentException(String argName) { super(argName + " is incomplete."); } /** *

Instantiates with the specified description.

* * @param argName a description of the incomplete argument * @param items an array describing the arguments missing */ public IncompleteArgumentException(String argName, String[] items) { super( argName + " is missing the following items: " + safeArrayToString(items)); } /** *

Converts an array to a string without throwing an exception.

* * @param array an array * @return the array as a string */ private static final String safeArrayToString(Object[] array) { return array == null ? null : Arrays.asList(array).toString(); } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/IntHashMap.java100644 0 0 27513 11513702446 23621 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Note: originally released under the GNU LGPL v2.1, * but rereleased by the original author under the ASF license (above). */ package org.apache.commons.lang; /** *

A hash map that uses primitive ints for the key rather than objects.

* *

Note that this class is for internal optimization purposes only, and may * not be supported in future releases of Apache Commons Lang. Utilities of * this sort may be included in future releases of Apache Commons Collections.

* * @author Apache Software Foundation * @author Justin Couch * @author Alex Chaffee (alex@apache.org) * @since 2.0 * @version $Revision: 905857 $ * @see java.util.HashMap */ class IntHashMap { /** * The hash table data. */ private transient Entry table[]; /** * The total number of entries in the hash table. */ private transient int count; /** * The table is rehashed when its size exceeds this threshold. (The * value of this field is (int)(capacity * loadFactor).) * * @serial */ private int threshold; /** * The load factor for the hashtable. * * @serial */ private final float loadFactor; /** *

Innerclass that acts as a datastructure to create a new entry in the * table.

*/ private static class Entry { final int hash; final int key; // TODO not read; seems to be always same as hash Object value; Entry next; /** *

Create a new entry with the given values.

* * @param hash The code used to hash the object with * @param key The key used to enter this in the table * @param value The value for this key * @param next A reference to the next entry in the table */ protected Entry(int hash, int key, Object value, Entry next) { this.hash = hash; this.key = key; this.value = value; this.next = next; } } /** *

Constructs a new, empty hashtable with a default capacity and load * factor, which is 20 and 0.75 respectively.

*/ public IntHashMap() { this(20, 0.75f); } /** *

Constructs a new, empty hashtable with the specified initial capacity * and default load factor, which is 0.75.

* * @param initialCapacity the initial capacity of the hashtable. * @throws IllegalArgumentException if the initial capacity is less * than zero. */ public IntHashMap(int initialCapacity) { this(initialCapacity, 0.75f); } /** *

Constructs a new, empty hashtable with the specified initial * capacity and the specified load factor.

* * @param initialCapacity the initial capacity of the hashtable. * @param loadFactor the load factor of the hashtable. * @throws IllegalArgumentException if the initial capacity is less * than zero, or if the load factor is nonpositive. */ public IntHashMap(int initialCapacity, float loadFactor) { super(); if (initialCapacity < 0) { throw new IllegalArgumentException("Illegal Capacity: " + initialCapacity); } if (loadFactor <= 0) { throw new IllegalArgumentException("Illegal Load: " + loadFactor); } if (initialCapacity == 0) { initialCapacity = 1; } this.loadFactor = loadFactor; table = new Entry[initialCapacity]; threshold = (int) (initialCapacity * loadFactor); } /** *

Returns the number of keys in this hashtable.

* * @return the number of keys in this hashtable. */ public int size() { return count; } /** *

Tests if this hashtable maps no keys to values.

* * @return true if this hashtable maps no keys to values; * false otherwise. */ public boolean isEmpty() { return count == 0; } /** *

Tests if some key maps into the specified value in this hashtable. * This operation is more expensive than the containsKey * method.

* *

Note that this method is identical in functionality to containsValue, * (which is part of the Map interface in the collections framework).

* * @param value a value to search for. * @return true if and only if some key maps to the * value argument in this hashtable as * determined by the equals method; * false otherwise. * @throws NullPointerException if the value is null. * @see #containsKey(int) * @see #containsValue(Object) * @see java.util.Map */ public boolean contains(Object value) { if (value == null) { throw new NullPointerException(); } Entry tab[] = table; for (int i = tab.length; i-- > 0;) { for (Entry e = tab[i]; e != null; e = e.next) { if (e.value.equals(value)) { return true; } } } return false; } /** *

Returns true if this HashMap maps one or more keys * to this value.

* *

Note that this method is identical in functionality to contains * (which predates the Map interface).

* * @param value value whose presence in this HashMap is to be tested. * @return boolean true if the value is contained * @see java.util.Map * @since JDK1.2 */ public boolean containsValue(Object value) { return contains(value); } /** *

Tests if the specified object is a key in this hashtable.

* * @param key possible key. * @return true if and only if the specified object is a * key in this hashtable, as determined by the equals * method; false otherwise. * @see #contains(Object) */ public boolean containsKey(int key) { Entry tab[] = table; int hash = key; int index = (hash & 0x7FFFFFFF) % tab.length; for (Entry e = tab[index]; e != null; e = e.next) { if (e.hash == hash) { return true; } } return false; } /** *

Returns the value to which the specified key is mapped in this map.

* * @param key a key in the hashtable. * @return the value to which the key is mapped in this hashtable; * null if the key is not mapped to any value in * this hashtable. * @see #put(int, Object) */ public Object get(int key) { Entry tab[] = table; int hash = key; int index = (hash & 0x7FFFFFFF) % tab.length; for (Entry e = tab[index]; e != null; e = e.next) { if (e.hash == hash) { return e.value; } } return null; } /** *

Increases the capacity of and internally reorganizes this * hashtable, in order to accommodate and access its entries more * efficiently.

* *

This method is called automatically when the number of keys * in the hashtable exceeds this hashtable's capacity and load * factor.

*/ protected void rehash() { int oldCapacity = table.length; Entry oldMap[] = table; int newCapacity = oldCapacity * 2 + 1; Entry newMap[] = new Entry[newCapacity]; threshold = (int) (newCapacity * loadFactor); table = newMap; for (int i = oldCapacity; i-- > 0;) { for (Entry old = oldMap[i]; old != null;) { Entry e = old; old = old.next; int index = (e.hash & 0x7FFFFFFF) % newCapacity; e.next = newMap[index]; newMap[index] = e; } } } /** *

Maps the specified key to the specified * value in this hashtable. The key cannot be * null.

* *

The value can be retrieved by calling the get method * with a key that is equal to the original key.

* * @param key the hashtable key. * @param value the value. * @return the previous value of the specified key in this hashtable, * or null if it did not have one. * @throws NullPointerException if the key is null. * @see #get(int) */ public Object put(int key, Object value) { // Makes sure the key is not already in the hashtable. Entry tab[] = table; int hash = key; int index = (hash & 0x7FFFFFFF) % tab.length; for (Entry e = tab[index]; e != null; e = e.next) { if (e.hash == hash) { Object old = e.value; e.value = value; return old; } } if (count >= threshold) { // Rehash the table if the threshold is exceeded rehash(); tab = table; index = (hash & 0x7FFFFFFF) % tab.length; } // Creates the new entry. Entry e = new Entry(hash, key, value, tab[index]); tab[index] = e; count++; return null; } /** *

Removes the key (and its corresponding value) from this * hashtable.

* *

This method does nothing if the key is not present in the * hashtable.

* * @param key the key that needs to be removed. * @return the value to which the key had been mapped in this hashtable, * or null if the key did not have a mapping. */ public Object remove(int key) { Entry tab[] = table; int hash = key; int index = (hash & 0x7FFFFFFF) % tab.length; for (Entry e = tab[index], prev = null; e != null; prev = e, e = e.next) { if (e.hash == hash) { if (prev != null) { prev.next = e.next; } else { tab[index] = e.next; } count--; Object oldValue = e.value; e.value = null; return oldValue; } } return null; } /** *

Clears this hashtable so that it contains no keys.

*/ public synchronized void clear() { Entry tab[] = table; for (int index = tab.length; --index >= 0;) { tab[index] = null; } count = 0; } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/LocaleUtils.java100644 0 0 31303 11513702446 24035 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; /** *

Operations to assist when working with a {@link Locale}.

* *

This class tries to handle null input gracefully. * An exception will not be thrown for a null input. * Each method documents its behaviour in more detail.

* * @author Apache Software Foundation * @since 2.2 * @version $Id: LocaleUtils.java 911968 2010-02-19 20:26:21Z niallp $ */ public class LocaleUtils { /** Unmodifiable list of available locales. */ private static List cAvailableLocaleList; // lazily created by availableLocaleList() /** Unmodifiable set of available locales. */ private static Set cAvailableLocaleSet; // lazily created by availableLocaleSet() /** Unmodifiable map of language locales by country. */ private static final Map cLanguagesByCountry = Collections.synchronizedMap(new HashMap()); /** Unmodifiable map of country locales by language. */ private static final Map cCountriesByLanguage = Collections.synchronizedMap(new HashMap()); /** *

LocaleUtils instances should NOT be constructed in standard programming. * Instead, the class should be used as LocaleUtils.toLocale("en_GB");.

* *

This constructor is public to permit tools that require a JavaBean instance * to operate.

*/ public LocaleUtils() { super(); } //----------------------------------------------------------------------- /** *

Converts a String to a Locale.

* *

This method takes the string format of a locale and creates the * locale object from it.

* *
     *   LocaleUtils.toLocale("en")         = new Locale("en", "")
     *   LocaleUtils.toLocale("en_GB")      = new Locale("en", "GB")
     *   LocaleUtils.toLocale("en_GB_xxx")  = new Locale("en", "GB", "xxx")   (#)
     * 
* *

(#) The behaviour of the JDK variant constructor changed between JDK1.3 and JDK1.4. * In JDK1.3, the constructor upper cases the variant, in JDK1.4, it doesn't. * Thus, the result from getVariant() may vary depending on your JDK.

* *

This method validates the input strictly. * The language code must be lowercase. * The country code must be uppercase. * The separator must be an underscore. * The length must be correct. *

* * @param str the locale String to convert, null returns null * @return a Locale, null if null input * @throws IllegalArgumentException if the string is an invalid format */ public static Locale toLocale(String str) { if (str == null) { return null; } int len = str.length(); if (len != 2 && len != 5 && len < 7) { throw new IllegalArgumentException("Invalid locale format: " + str); } char ch0 = str.charAt(0); char ch1 = str.charAt(1); if (ch0 < 'a' || ch0 > 'z' || ch1 < 'a' || ch1 > 'z') { throw new IllegalArgumentException("Invalid locale format: " + str); } if (len == 2) { return new Locale(str, ""); } else { if (str.charAt(2) != '_') { throw new IllegalArgumentException("Invalid locale format: " + str); } char ch3 = str.charAt(3); if (ch3 == '_') { return new Locale(str.substring(0, 2), "", str.substring(4)); } char ch4 = str.charAt(4); if (ch3 < 'A' || ch3 > 'Z' || ch4 < 'A' || ch4 > 'Z') { throw new IllegalArgumentException("Invalid locale format: " + str); } if (len == 5) { return new Locale(str.substring(0, 2), str.substring(3, 5)); } else { if (str.charAt(5) != '_') { throw new IllegalArgumentException("Invalid locale format: " + str); } return new Locale(str.substring(0, 2), str.substring(3, 5), str.substring(6)); } } } //----------------------------------------------------------------------- /** *

Obtains the list of locales to search through when performing * a locale search.

* *
     * localeLookupList(Locale("fr","CA","xxx"))
     *   = [Locale("fr","CA","xxx"), Locale("fr","CA"), Locale("fr")]
     * 
* * @param locale the locale to start from * @return the unmodifiable list of Locale objects, 0 being locale, never null */ public static List localeLookupList(Locale locale) { return localeLookupList(locale, locale); } //----------------------------------------------------------------------- /** *

Obtains the list of locales to search through when performing * a locale search.

* *
     * localeLookupList(Locale("fr", "CA", "xxx"), Locale("en"))
     *   = [Locale("fr","CA","xxx"), Locale("fr","CA"), Locale("fr"), Locale("en"]
     * 
* *

The result list begins with the most specific locale, then the * next more general and so on, finishing with the default locale. * The list will never contain the same locale twice.

* * @param locale the locale to start from, null returns empty list * @param defaultLocale the default locale to use if no other is found * @return the unmodifiable list of Locale objects, 0 being locale, never null */ public static List localeLookupList(Locale locale, Locale defaultLocale) { List list = new ArrayList(4); if (locale != null) { list.add(locale); if (locale.getVariant().length() > 0) { list.add(new Locale(locale.getLanguage(), locale.getCountry())); } if (locale.getCountry().length() > 0) { list.add(new Locale(locale.getLanguage(), "")); } if (list.contains(defaultLocale) == false) { list.add(defaultLocale); } } return Collections.unmodifiableList(list); } //----------------------------------------------------------------------- /** *

Obtains an unmodifiable list of installed locales.

* *

This method is a wrapper around {@link Locale#getAvailableLocales()}. * It is more efficient, as the JDK method must create a new array each * time it is called.

* * @return the unmodifiable list of available locales */ public static List availableLocaleList() { if(cAvailableLocaleList == null) { initAvailableLocaleList(); } return cAvailableLocaleList; } /** * Initializes the availableLocaleList. It is separate from availableLocaleList() * to avoid the synchronized block affecting normal use, yet synchronized and * lazy loading to avoid a static block affecting other methods in this class. */ private static synchronized void initAvailableLocaleList() { if(cAvailableLocaleList == null) { List list = Arrays.asList(Locale.getAvailableLocales()); cAvailableLocaleList = Collections.unmodifiableList(list); } } //----------------------------------------------------------------------- /** *

Obtains an unmodifiable set of installed locales.

* *

This method is a wrapper around {@link Locale#getAvailableLocales()}. * It is more efficient, as the JDK method must create a new array each * time it is called.

* * @return the unmodifiable set of available locales */ public static Set availableLocaleSet() { if(cAvailableLocaleSet == null) { initAvailableLocaleSet(); } return cAvailableLocaleSet; } /** * Initializes the availableLocaleSet. It is separate from availableLocaleSet() * to avoid the synchronized block affecting normal use, yet synchronized and * lazy loading to avoid a static block affecting other methods in this class. */ private static synchronized void initAvailableLocaleSet() { if(cAvailableLocaleSet == null) { cAvailableLocaleSet = Collections.unmodifiableSet( new HashSet(availableLocaleList()) ); } } //----------------------------------------------------------------------- /** *

Checks if the locale specified is in the list of available locales.

* * @param locale the Locale object to check if it is available * @return true if the locale is a known locale */ public static boolean isAvailableLocale(Locale locale) { return availableLocaleList().contains(locale); } //----------------------------------------------------------------------- /** *

Obtains the list of languages supported for a given country.

* *

This method takes a country code and searches to find the * languages available for that country. Variant locales are removed.

* * @param countryCode the 2 letter country code, null returns empty * @return an unmodifiable List of Locale objects, never null */ public static List languagesByCountry(String countryCode) { List langs = (List) cLanguagesByCountry.get(countryCode); //syncd if (langs == null) { if (countryCode != null) { langs = new ArrayList(); List locales = availableLocaleList(); for (int i = 0; i < locales.size(); i++) { Locale locale = (Locale) locales.get(i); if (countryCode.equals(locale.getCountry()) && locale.getVariant().length() == 0) { langs.add(locale); } } langs = Collections.unmodifiableList(langs); } else { langs = Collections.EMPTY_LIST; } cLanguagesByCountry.put(countryCode, langs); //syncd } return langs; } //----------------------------------------------------------------------- /** *

Obtains the list of countries supported for a given language.

* *

This method takes a language code and searches to find the * countries available for that language. Variant locales are removed.

* * @param languageCode the 2 letter language code, null returns empty * @return an unmodifiable List of Locale objects, never null */ public static List countriesByLanguage(String languageCode) { List countries = (List) cCountriesByLanguage.get(languageCode); //syncd if (countries == null) { if (languageCode != null) { countries = new ArrayList(); List locales = availableLocaleList(); for (int i = 0; i < locales.size(); i++) { Locale locale = (Locale) locales.get(i); if (languageCode.equals(locale.getLanguage()) && locale.getCountry().length() != 0 && locale.getVariant().length() == 0) { countries.add(locale); } } countries = Collections.unmodifiableList(countries); } else { countries = Collections.EMPTY_LIST; } cCountriesByLanguage.put(languageCode, countries); //syncd } return countries; } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/math/DoubleRange.java100644 0 0 33516 11513702442 24741 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.math; import java.io.Serializable; import org.apache.commons.lang.text.StrBuilder; /** *

DoubleRange represents an inclusive range of doubles.

* * @author Apache Software Foundation * @since 2.0 * @version $Id: DoubleRange.java 1057072 2011-01-10 01:55:57Z niallp $ */ public final class DoubleRange extends Range implements Serializable { /** * Required for serialization support. * * @see java.io.Serializable */ private static final long serialVersionUID = 71849363892740L; /** * The minimum number in this range (inclusive). */ private final double min; /** * The maximum number in this range (inclusive). */ private final double max; /** * Cached output minObject (class is immutable). */ private transient Double minObject = null; /** * Cached output maxObject (class is immutable). */ private transient Double maxObject = null; /** * Cached output hashCode (class is immutable). */ private transient int hashCode = 0; /** * Cached output toString (class is immutable). */ private transient String toString = null; /** *

Constructs a new DoubleRange using the specified * number as both the minimum and maximum in this range.

* * @param number the number to use for this range * @throws IllegalArgumentException if the number is NaN */ public DoubleRange(double number) { super(); if (Double.isNaN(number)) { throw new IllegalArgumentException("The number must not be NaN"); } this.min = number; this.max = number; } /** *

Constructs a new DoubleRange using the specified * number as both the minimum and maximum in this range.

* * @param number the number to use for this range, must not * be null * @throws IllegalArgumentException if the number is null * @throws IllegalArgumentException if the number is NaN */ public DoubleRange(Number number) { super(); if (number == null) { throw new IllegalArgumentException("The number must not be null"); } this.min = number.doubleValue(); this.max = number.doubleValue(); if (Double.isNaN(min) || Double.isNaN(max)) { throw new IllegalArgumentException("The number must not be NaN"); } if (number instanceof Double) { this.minObject = (Double) number; this.maxObject = (Double) number; } } /** *

Constructs a new DoubleRange with the specified * minimum and maximum numbers (both inclusive).

* *

The arguments may be passed in the order (min,max) or (max,min). The * getMinimum and getMaximum methods will return the correct values.

* * @param number1 first number that defines the edge of the range, inclusive * @param number2 second number that defines the edge of the range, inclusive * @throws IllegalArgumentException if either number is NaN */ public DoubleRange(double number1, double number2) { super(); if (Double.isNaN(number1) || Double.isNaN(number2)) { throw new IllegalArgumentException("The numbers must not be NaN"); } if (number2 < number1) { this.min = number2; this.max = number1; } else { this.min = number1; this.max = number2; } } /** *

Constructs a new DoubleRange with the specified * minimum and maximum numbers (both inclusive).

* *

The arguments may be passed in the order (min,max) or (max,min). The * getMinimum and getMaximum methods will return the correct values.

* * @param number1 first number that defines the edge of the range, inclusive * @param number2 second number that defines the edge of the range, inclusive * @throws IllegalArgumentException if either number is null * @throws IllegalArgumentException if either number is NaN */ public DoubleRange(Number number1, Number number2) { super(); if (number1 == null || number2 == null) { throw new IllegalArgumentException("The numbers must not be null"); } double number1val = number1.doubleValue(); double number2val = number2.doubleValue(); if (Double.isNaN(number1val) || Double.isNaN(number2val)) { throw new IllegalArgumentException("The numbers must not be NaN"); } if (number2val < number1val) { this.min = number2val; this.max = number1val; if (number2 instanceof Double) { this.minObject = (Double) number2; } if (number1 instanceof Double) { this.maxObject = (Double) number1; } } else { this.min = number1val; this.max = number2val; if (number1 instanceof Double) { this.minObject = (Double) number1; } if (number2 instanceof Double) { this.maxObject = (Double) number2; } } } // Accessors //-------------------------------------------------------------------- /** *

Returns the minimum number in this range.

* * @return the minimum number in this range */ public Number getMinimumNumber() { if (minObject == null) { minObject = new Double(min); } return minObject; } /** *

Gets the minimum number in this range as a long.

* *

This conversion can lose information for large values or decimals.

* * @return the minimum number in this range */ public long getMinimumLong() { return (long) min; } /** *

Gets the minimum number in this range as a int.

* *

This conversion can lose information for large values or decimals.

* * @return the minimum number in this range */ public int getMinimumInteger() { return (int) min; } /** *

Gets the minimum number in this range as a double.

* * @return the minimum number in this range */ public double getMinimumDouble() { return min; } /** *

Gets the minimum number in this range as a float.

* *

This conversion can lose information for large values.

* * @return the minimum number in this range */ public float getMinimumFloat() { return (float) min; } /** *

Returns the maximum number in this range.

* * @return the maximum number in this range */ public Number getMaximumNumber() { if (maxObject == null) { maxObject = new Double(max); } return maxObject; } /** *

Gets the maximum number in this range as a long.

* *

This conversion can lose information for large values or decimals.

* * @return the maximum number in this range */ public long getMaximumLong() { return (long) max; } /** *

Gets the maximum number in this range as a int.

* *

This conversion can lose information for large values or decimals.

* * @return the maximum number in this range */ public int getMaximumInteger() { return (int) max; } /** *

Gets the maximum number in this range as a double.

* * @return the maximum number in this range */ public double getMaximumDouble() { return max; } /** *

Gets the maximum number in this range as a float.

* *

This conversion can lose information for large values.

* * @return the maximum number in this range */ public float getMaximumFloat() { return (float) max; } // Tests //-------------------------------------------------------------------- /** *

Tests whether the specified number occurs within * this range using double comparison.

* *

null is handled and returns false.

* * @param number the number to test, may be null * @return true if the specified number occurs within this range */ public boolean containsNumber(Number number) { if (number == null) { return false; } return containsDouble(number.doubleValue()); } /** *

Tests whether the specified double occurs within * this range using double comparison.

* *

This implementation overrides the superclass for performance as it is * the most common case.

* * @param value the double to test * @return true if the specified number occurs within this * range by double comparison */ public boolean containsDouble(double value) { return value >= min && value <= max; } // Range tests //-------------------------------------------------------------------- /** *

Tests whether the specified range occurs entirely within this range * using double comparison.

* *

null is handled and returns false.

* * @param range the range to test, may be null * @return true if the specified range occurs entirely within this range * @throws IllegalArgumentException if the range is not of this type */ public boolean containsRange(Range range) { if (range == null) { return false; } return containsDouble(range.getMinimumDouble()) && containsDouble(range.getMaximumDouble()); } /** *

Tests whether the specified range overlaps with this range * using double comparison.

* *

null is handled and returns false.

* * @param range the range to test, may be null * @return true if the specified range overlaps with this range */ public boolean overlapsRange(Range range) { if (range == null) { return false; } return range.containsDouble(min) || range.containsDouble(max) || containsDouble(range.getMinimumDouble()); } // Basics //-------------------------------------------------------------------- /** *

Compares this range to another object to test if they are equal.

. * *

To be equal, the class, minimum and maximum must be equal.

* * @param obj the reference object with which to compare * @return true if this object is equal */ public boolean equals(Object obj) { if (obj == this) { return true; } if (obj instanceof DoubleRange == false) { return false; } DoubleRange range = (DoubleRange) obj; return (Double.doubleToLongBits(min) == Double.doubleToLongBits(range.min) && Double.doubleToLongBits(max) == Double.doubleToLongBits(range.max)); } /** *

Gets a hashCode for the range.

* * @return a hash code value for this object */ public int hashCode() { if (hashCode == 0) { hashCode = 17; hashCode = 37 * hashCode + getClass().hashCode(); long lng = Double.doubleToLongBits(min); hashCode = 37 * hashCode + ((int) (lng ^ (lng >> 32))); lng = Double.doubleToLongBits(max); hashCode = 37 * hashCode + ((int) (lng ^ (lng >> 32))); } return hashCode; } /** *

Gets the range as a String.

* *

The format of the String is 'Range[min,max]'.

* * @return the String representation of this range */ public String toString() { if (toString == null) { StrBuilder buf = new StrBuilder(32); buf.append("Range["); buf.append(min); buf.append(','); buf.append(max); buf.append(']'); toString = buf.toString(); } return toString; } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/math/FloatRange.java100644 0 0 32700 11513702442 24566 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.math; import java.io.Serializable; /** *

FloatRange represents an inclusive range of floats.

* * @author Apache Software Foundation * @since 2.0 * @version $Id: FloatRange.java 905636 2010-02-02 14:03:32Z niallp $ */ public final class FloatRange extends Range implements Serializable { /** * Required for serialization support. * * @see java.io.Serializable */ private static final long serialVersionUID = 71849363892750L; /** * The minimum number in this range (inclusive). */ private final float min; /** * The maximum number in this range (inclusive). */ private final float max; /** * Cached output minObject (class is immutable). */ private transient Float minObject = null; /** * Cached output maxObject (class is immutable). */ private transient Float maxObject = null; /** * Cached output hashCode (class is immutable). */ private transient int hashCode = 0; /** * Cached output toString (class is immutable). */ private transient String toString = null; /** *

Constructs a new FloatRange using the specified * number as both the minimum and maximum in this range.

* * @param number the number to use for this range * @throws IllegalArgumentException if the number is NaN */ public FloatRange(float number) { super(); if (Float.isNaN(number)) { throw new IllegalArgumentException("The number must not be NaN"); } this.min = number; this.max = number; } /** *

Constructs a new FloatRange using the specified * number as both the minimum and maximum in this range.

* * @param number the number to use for this range, must not * be null * @throws IllegalArgumentException if the number is null * @throws IllegalArgumentException if the number is NaN */ public FloatRange(Number number) { super(); if (number == null) { throw new IllegalArgumentException("The number must not be null"); } this.min = number.floatValue(); this.max = number.floatValue(); if (Float.isNaN(min) || Float.isNaN(max)) { throw new IllegalArgumentException("The number must not be NaN"); } if (number instanceof Float) { this.minObject = (Float) number; this.maxObject = (Float) number; } } /** *

Constructs a new FloatRange with the specified * minimum and maximum numbers (both inclusive).

* *

The arguments may be passed in the order (min,max) or (max,min). The * getMinimum and getMaximum methods will return the correct values.

* * @param number1 first number that defines the edge of the range, inclusive * @param number2 second number that defines the edge of the range, inclusive * @throws IllegalArgumentException if either number is NaN */ public FloatRange(float number1, float number2) { super(); if (Float.isNaN(number1) || Float.isNaN(number2)) { throw new IllegalArgumentException("The numbers must not be NaN"); } if (number2 < number1) { this.min = number2; this.max = number1; } else { this.min = number1; this.max = number2; } } /** *

Constructs a new FloatRange with the specified * minimum and maximum numbers (both inclusive).

* *

The arguments may be passed in the order (min,max) or (max,min). The * getMinimum and getMaximum methods will return the correct values.

* * @param number1 first number that defines the edge of the range, inclusive * @param number2 second number that defines the edge of the range, inclusive * @throws IllegalArgumentException if either number is null * @throws IllegalArgumentException if either number is NaN */ public FloatRange(Number number1, Number number2) { super(); if (number1 == null || number2 == null) { throw new IllegalArgumentException("The numbers must not be null"); } float number1val = number1.floatValue(); float number2val = number2.floatValue(); if (Float.isNaN(number1val) || Float.isNaN(number2val)) { throw new IllegalArgumentException("The numbers must not be NaN"); } if (number2val < number1val) { this.min = number2val; this.max = number1val; if (number2 instanceof Float) { this.minObject = (Float) number2; } if (number1 instanceof Float) { this.maxObject = (Float) number1; } } else { this.min = number1val; this.max = number2val; if (number1 instanceof Float) { this.minObject = (Float) number1; } if (number2 instanceof Float) { this.maxObject = (Float) number2; } } } // Accessors //-------------------------------------------------------------------- /** *

Returns the minimum number in this range.

* * @return the minimum number in this range */ public Number getMinimumNumber() { if (minObject == null) { minObject = new Float(min); } return minObject; } /** *

Gets the minimum number in this range as a long.

* *

This conversion can lose information for large values or decimals.

* * @return the minimum number in this range */ public long getMinimumLong() { return (long) min; } /** *

Gets the minimum number in this range as a int.

* *

This conversion can lose information for large values or decimals.

* * @return the minimum number in this range */ public int getMinimumInteger() { return (int) min; } /** *

Gets the minimum number in this range as a double.

* * @return the minimum number in this range */ public double getMinimumDouble() { return min; } /** *

Gets the minimum number in this range as a float.

* * @return the minimum number in this range */ public float getMinimumFloat() { return min; } /** *

Returns the maximum number in this range.

* * @return the maximum number in this range */ public Number getMaximumNumber() { if (maxObject == null) { maxObject = new Float(max); } return maxObject; } /** *

Gets the maximum number in this range as a long.

* *

This conversion can lose information for large values or decimals.

* * @return the maximum number in this range */ public long getMaximumLong() { return (long) max; } /** *

Gets the maximum number in this range as a int.

* *

This conversion can lose information for large values or decimals.

* * @return the maximum number in this range */ public int getMaximumInteger() { return (int) max; } /** *

Gets the maximum number in this range as a double.

* * @return the maximum number in this range */ public double getMaximumDouble() { return max; } /** *

Gets the maximum number in this range as a float.

* * @return the maximum number in this range */ public float getMaximumFloat() { return max; } // Tests //-------------------------------------------------------------------- /** *

Tests whether the specified number occurs within * this range using float comparison.

* *

null is handled and returns false.

* * @param number the number to test, may be null * @return true if the specified number occurs within this range */ public boolean containsNumber(Number number) { if (number == null) { return false; } return containsFloat(number.floatValue()); } /** *

Tests whether the specified float occurs within * this range using float comparison.

* *

This implementation overrides the superclass for performance as it is * the most common case.

* * @param value the float to test * @return true if the specified number occurs within this * range by float comparison */ public boolean containsFloat(float value) { return value >= min && value <= max; } // Range tests //-------------------------------------------------------------------- /** *

Tests whether the specified range occurs entirely within this range * using float comparison.

* *

null is handled and returns false.

* * @param range the range to test, may be null * @return true if the specified range occurs entirely within this range * @throws IllegalArgumentException if the range is not of this type */ public boolean containsRange(Range range) { if (range == null) { return false; } return containsFloat(range.getMinimumFloat()) && containsFloat(range.getMaximumFloat()); } /** *

Tests whether the specified range overlaps with this range * using float comparison.

* *

null is handled and returns false.

* * @param range the range to test, may be null * @return true if the specified range overlaps with this range */ public boolean overlapsRange(Range range) { if (range == null) { return false; } return range.containsFloat(min) || range.containsFloat(max) || containsFloat(range.getMinimumFloat()); } // Basics //-------------------------------------------------------------------- /** *

Compares this range to another object to test if they are equal.

. * *

To be equal, the class, minimum and maximum must be equal.

* * @param obj the reference object with which to compare * @return true if this object is equal */ public boolean equals(Object obj) { if (obj == this) { return true; } if (obj instanceof FloatRange == false) { return false; } FloatRange range = (FloatRange) obj; return (Float.floatToIntBits(min) == Float.floatToIntBits(range.min) && Float.floatToIntBits(max) == Float.floatToIntBits(range.max)); } /** *

Gets a hashCode for the range.

* * @return a hash code value for this object */ public int hashCode() { if (hashCode == 0) { hashCode = 17; hashCode = 37 * hashCode + getClass().hashCode(); hashCode = 37 * hashCode + Float.floatToIntBits(min); hashCode = 37 * hashCode + Float.floatToIntBits(max); } return hashCode; } /** *

Gets the range as a String.

* *

The format of the String is 'Range[min,max]'.

* * @return the String representation of this range */ public String toString() { if (toString == null) { StringBuffer buf = new StringBuffer(32); buf.append("Range["); buf.append(min); buf.append(','); buf.append(max); buf.append(']'); toString = buf.toString(); } return toString; } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/math/Fraction.java100644 0 0 105707 11513702442 24341 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.math; import java.math.BigInteger; import org.apache.commons.lang.text.StrBuilder; /** *

Fraction is a Number implementation that * stores fractions accurately.

* *

This class is immutable, and interoperable with most methods that accept * a Number.

* * @author Apache Software Foundation * @author Travis Reeder * @author Tim O'Brien * @author Pete Gieser * @author C. Scott Ananian * @since 2.0 * @version $Id: Fraction.java 1057072 2011-01-10 01:55:57Z niallp $ */ public final class Fraction extends Number implements Comparable { /** * Required for serialization support. Lang version 2.0. * * @see java.io.Serializable */ private static final long serialVersionUID = 65382027393090L; /** * Fraction representation of 0. */ public static final Fraction ZERO = new Fraction(0, 1); /** * Fraction representation of 1. */ public static final Fraction ONE = new Fraction(1, 1); /** * Fraction representation of 1/2. */ public static final Fraction ONE_HALF = new Fraction(1, 2); /** * Fraction representation of 1/3. */ public static final Fraction ONE_THIRD = new Fraction(1, 3); /** * Fraction representation of 2/3. */ public static final Fraction TWO_THIRDS = new Fraction(2, 3); /** * Fraction representation of 1/4. */ public static final Fraction ONE_QUARTER = new Fraction(1, 4); /** * Fraction representation of 2/4. */ public static final Fraction TWO_QUARTERS = new Fraction(2, 4); /** * Fraction representation of 3/4. */ public static final Fraction THREE_QUARTERS = new Fraction(3, 4); /** * Fraction representation of 1/5. */ public static final Fraction ONE_FIFTH = new Fraction(1, 5); /** * Fraction representation of 2/5. */ public static final Fraction TWO_FIFTHS = new Fraction(2, 5); /** * Fraction representation of 3/5. */ public static final Fraction THREE_FIFTHS = new Fraction(3, 5); /** * Fraction representation of 4/5. */ public static final Fraction FOUR_FIFTHS = new Fraction(4, 5); /** * The numerator number part of the fraction (the three in three sevenths). */ private final int numerator; /** * The denominator number part of the fraction (the seven in three sevenths). */ private final int denominator; /** * Cached output hashCode (class is immutable). */ private transient int hashCode = 0; /** * Cached output toString (class is immutable). */ private transient String toString = null; /** * Cached output toProperString (class is immutable). */ private transient String toProperString = null; /** *

Constructs a Fraction instance with the 2 parts * of a fraction Y/Z.

* * @param numerator the numerator, for example the three in 'three sevenths' * @param denominator the denominator, for example the seven in 'three sevenths' */ private Fraction(int numerator, int denominator) { super(); this.numerator = numerator; this.denominator = denominator; } /** *

Creates a Fraction instance with the 2 parts * of a fraction Y/Z.

* *

Any negative signs are resolved to be on the numerator.

* * @param numerator the numerator, for example the three in 'three sevenths' * @param denominator the denominator, for example the seven in 'three sevenths' * @return a new fraction instance * @throws ArithmeticException if the denomiator is zero */ public static Fraction getFraction(int numerator, int denominator) { if (denominator == 0) { throw new ArithmeticException("The denominator must not be zero"); } if (denominator < 0) { if (numerator==Integer.MIN_VALUE || denominator==Integer.MIN_VALUE) { throw new ArithmeticException("overflow: can't negate"); } numerator = -numerator; denominator = -denominator; } return new Fraction(numerator, denominator); } /** *

Creates a Fraction instance with the 3 parts * of a fraction X Y/Z.

* *

The negative sign must be passed in on the whole number part.

* * @param whole the whole number, for example the one in 'one and three sevenths' * @param numerator the numerator, for example the three in 'one and three sevenths' * @param denominator the denominator, for example the seven in 'one and three sevenths' * @return a new fraction instance * @throws ArithmeticException if the denomiator is zero * @throws ArithmeticException if the denominator is negative * @throws ArithmeticException if the numerator is negative * @throws ArithmeticException if the resulting numerator exceeds * Integer.MAX_VALUE */ public static Fraction getFraction(int whole, int numerator, int denominator) { if (denominator == 0) { throw new ArithmeticException("The denominator must not be zero"); } if (denominator < 0) { throw new ArithmeticException("The denominator must not be negative"); } if (numerator < 0) { throw new ArithmeticException("The numerator must not be negative"); } long numeratorValue; if (whole < 0) { numeratorValue = whole * (long)denominator - numerator; } else { numeratorValue = whole * (long)denominator + numerator; } if (numeratorValue < Integer.MIN_VALUE || numeratorValue > Integer.MAX_VALUE) { throw new ArithmeticException("Numerator too large to represent as an Integer."); } return new Fraction((int) numeratorValue, denominator); } /** *

Creates a reduced Fraction instance with the 2 parts * of a fraction Y/Z.

* *

For example, if the input parameters represent 2/4, then the created * fraction will be 1/2.

* *

Any negative signs are resolved to be on the numerator.

* * @param numerator the numerator, for example the three in 'three sevenths' * @param denominator the denominator, for example the seven in 'three sevenths' * @return a new fraction instance, with the numerator and denominator reduced * @throws ArithmeticException if the denominator is zero */ public static Fraction getReducedFraction(int numerator, int denominator) { if (denominator == 0) { throw new ArithmeticException("The denominator must not be zero"); } if (numerator==0) { return ZERO; // normalize zero. } // allow 2^k/-2^31 as a valid fraction (where k>0) if (denominator==Integer.MIN_VALUE && (numerator&1)==0) { numerator/=2; denominator/=2; } if (denominator < 0) { if (numerator==Integer.MIN_VALUE || denominator==Integer.MIN_VALUE) { throw new ArithmeticException("overflow: can't negate"); } numerator = -numerator; denominator = -denominator; } // simplify fraction. int gcd = greatestCommonDivisor(numerator, denominator); numerator /= gcd; denominator /= gcd; return new Fraction(numerator, denominator); } /** *

Creates a Fraction instance from a double value.

* *

This method uses the * continued fraction algorithm, computing a maximum of * 25 convergents and bounding the denominator by 10,000.

* * @param value the double value to convert * @return a new fraction instance that is close to the value * @throws ArithmeticException if |value| > Integer.MAX_VALUE * or value = NaN * @throws ArithmeticException if the calculated denominator is zero * @throws ArithmeticException if the the algorithm does not converge */ public static Fraction getFraction(double value) { int sign = (value < 0 ? -1 : 1); value = Math.abs(value); if (value > Integer.MAX_VALUE || Double.isNaN(value)) { throw new ArithmeticException ("The value must not be greater than Integer.MAX_VALUE or NaN"); } int wholeNumber = (int) value; value -= wholeNumber; int numer0 = 0; // the pre-previous int denom0 = 1; // the pre-previous int numer1 = 1; // the previous int denom1 = 0; // the previous int numer2 = 0; // the current, setup in calculation int denom2 = 0; // the current, setup in calculation int a1 = (int) value; int a2 = 0; double x1 = 1; double x2 = 0; double y1 = value - a1; double y2 = 0; double delta1, delta2 = Double.MAX_VALUE; double fraction; int i = 1; // System.out.println("---"); do { delta1 = delta2; a2 = (int) (x1 / y1); x2 = y1; y2 = x1 - a2 * y1; numer2 = a1 * numer1 + numer0; denom2 = a1 * denom1 + denom0; fraction = (double) numer2 / (double) denom2; delta2 = Math.abs(value - fraction); // System.out.println(numer2 + " " + denom2 + " " + fraction + " " + delta2 + " " + y1); a1 = a2; x1 = x2; y1 = y2; numer0 = numer1; denom0 = denom1; numer1 = numer2; denom1 = denom2; i++; // System.out.println(">>" + delta1 +" "+ delta2+" "+(delta1 > delta2)+" "+i+" "+denom2); } while ((delta1 > delta2) && (denom2 <= 10000) && (denom2 > 0) && (i < 25)); if (i == 25) { throw new ArithmeticException("Unable to convert double to fraction"); } return getReducedFraction((numer0 + wholeNumber * denom0) * sign, denom0); } /** *

Creates a Fraction from a String.

* *

The formats accepted are:

* *
    *
  1. double String containing a dot
  2. *
  3. 'X Y/Z'
  4. *
  5. 'Y/Z'
  6. *
  7. 'X' (a simple whole number)
  8. *
* and a .

* * @param str the string to parse, must not be null * @return the new Fraction instance * @throws IllegalArgumentException if the string is null * @throws NumberFormatException if the number format is invalid */ public static Fraction getFraction(String str) { if (str == null) { throw new IllegalArgumentException("The string must not be null"); } // parse double format int pos = str.indexOf('.'); if (pos >= 0) { return getFraction(Double.parseDouble(str)); } // parse X Y/Z format pos = str.indexOf(' '); if (pos > 0) { int whole = Integer.parseInt(str.substring(0, pos)); str = str.substring(pos + 1); pos = str.indexOf('/'); if (pos < 0) { throw new NumberFormatException("The fraction could not be parsed as the format X Y/Z"); } else { int numer = Integer.parseInt(str.substring(0, pos)); int denom = Integer.parseInt(str.substring(pos + 1)); return getFraction(whole, numer, denom); } } // parse Y/Z format pos = str.indexOf('/'); if (pos < 0) { // simple whole number return getFraction(Integer.parseInt(str), 1); } else { int numer = Integer.parseInt(str.substring(0, pos)); int denom = Integer.parseInt(str.substring(pos + 1)); return getFraction(numer, denom); } } // Accessors //------------------------------------------------------------------- /** *

Gets the numerator part of the fraction.

* *

This method may return a value greater than the denominator, an * improper fraction, such as the seven in 7/4.

* * @return the numerator fraction part */ public int getNumerator() { return numerator; } /** *

Gets the denominator part of the fraction.

* * @return the denominator fraction part */ public int getDenominator() { return denominator; } /** *

Gets the proper numerator, always positive.

* *

An improper fraction 7/4 can be resolved into a proper one, 1 3/4. * This method returns the 3 from the proper fraction.

* *

If the fraction is negative such as -7/4, it can be resolved into * -1 3/4, so this method returns the positive proper numerator, 3.

* * @return the numerator fraction part of a proper fraction, always positive */ public int getProperNumerator() { return Math.abs(numerator % denominator); } /** *

Gets the proper whole part of the fraction.

* *

An improper fraction 7/4 can be resolved into a proper one, 1 3/4. * This method returns the 1 from the proper fraction.

* *

If the fraction is negative such as -7/4, it can be resolved into * -1 3/4, so this method returns the positive whole part -1.

* * @return the whole fraction part of a proper fraction, that includes the sign */ public int getProperWhole() { return numerator / denominator; } // Number methods //------------------------------------------------------------------- /** *

Gets the fraction as an int. This returns the whole number * part of the fraction.

* * @return the whole number fraction part */ public int intValue() { return numerator / denominator; } /** *

Gets the fraction as a long. This returns the whole number * part of the fraction.

* * @return the whole number fraction part */ public long longValue() { return (long) numerator / denominator; } /** *

Gets the fraction as a float. This calculates the fraction * as the numerator divided by denominator.

* * @return the fraction as a float */ public float floatValue() { return ((float) numerator) / ((float) denominator); } /** *

Gets the fraction as a double. This calculates the fraction * as the numerator divided by denominator.

* * @return the fraction as a double */ public double doubleValue() { return ((double) numerator) / ((double) denominator); } // Calculations //------------------------------------------------------------------- /** *

Reduce the fraction to the smallest values for the numerator and * denominator, returning the result.

* *

For example, if this fraction represents 2/4, then the result * will be 1/2.

* * @return a new reduced fraction instance, or this if no simplification possible */ public Fraction reduce() { if (numerator == 0) { return equals(ZERO) ? this : ZERO; } int gcd = greatestCommonDivisor(Math.abs(numerator), denominator); if (gcd == 1) { return this; } return Fraction.getFraction(numerator / gcd, denominator / gcd); } /** *

Gets a fraction that is the inverse (1/fraction) of this one.

* *

The returned fraction is not reduced.

* * @return a new fraction instance with the numerator and denominator * inverted. * @throws ArithmeticException if the fraction represents zero. */ public Fraction invert() { if (numerator == 0) { throw new ArithmeticException("Unable to invert zero."); } if (numerator==Integer.MIN_VALUE) { throw new ArithmeticException("overflow: can't negate numerator"); } if (numerator<0) { return new Fraction(-denominator, -numerator); } else { return new Fraction(denominator, numerator); } } /** *

Gets a fraction that is the negative (-fraction) of this one.

* *

The returned fraction is not reduced.

* * @return a new fraction instance with the opposite signed numerator */ public Fraction negate() { // the positive range is one smaller than the negative range of an int. if (numerator==Integer.MIN_VALUE) { throw new ArithmeticException("overflow: too large to negate"); } return new Fraction(-numerator, denominator); } /** *

Gets a fraction that is the positive equivalent of this one.

*

More precisely: (fraction >= 0 ? this : -fraction)

* *

The returned fraction is not reduced.

* * @return this if it is positive, or a new positive fraction * instance with the opposite signed numerator */ public Fraction abs() { if (numerator >= 0) { return this; } return negate(); } /** *

Gets a fraction that is raised to the passed in power.

* *

The returned fraction is in reduced form.

* * @param power the power to raise the fraction to * @return this if the power is one, ONE if the power * is zero (even if the fraction equals ZERO) or a new fraction instance * raised to the appropriate power * @throws ArithmeticException if the resulting numerator or denominator exceeds * Integer.MAX_VALUE */ public Fraction pow(int power) { if (power == 1) { return this; } else if (power == 0) { return ONE; } else if (power < 0) { if (power==Integer.MIN_VALUE) { // MIN_VALUE can't be negated. return this.invert().pow(2).pow(-(power/2)); } return this.invert().pow(-power); } else { Fraction f = this.multiplyBy(this); if ((power % 2) == 0) { // if even... return f.pow(power/2); } else { // if odd... return f.pow(power/2).multiplyBy(this); } } } /** *

Gets the greatest common divisor of the absolute value of * two numbers, using the "binary gcd" method which avoids * division and modulo operations. See Knuth 4.5.2 algorithm B. * This algorithm is due to Josef Stein (1961).

* * @param u a non-zero number * @param v a non-zero number * @return the greatest common divisor, never zero */ private static int greatestCommonDivisor(int u, int v) { //if either op. is abs 0 or 1, return 1: if (Math.abs(u) <= 1 || Math.abs(v) <= 1) { return 1; } // keep u and v negative, as negative integers range down to // -2^31, while positive numbers can only be as large as 2^31-1 // (i.e. we can't necessarily negate a negative number without // overflow) if (u>0) { u=-u; } // make u negative if (v>0) { v=-v; } // make v negative // B1. [Find power of 2] int k=0; while ((u&1)==0 && (v&1)==0 && k<31) { // while u and v are both even... u/=2; v/=2; k++; // cast out twos. } if (k==31) { throw new ArithmeticException("overflow: gcd is 2^31"); } // B2. Initialize: u and v have been divided by 2^k and at least // one is odd. int t = ((u&1)==1) ? v : -(u/2)/*B3*/; // t negative: u was odd, v may be even (t replaces v) // t positive: u was even, v is odd (t replaces u) do { /* assert u<0 && v<0; */ // B4/B3: cast out twos from t. while ((t&1)==0) { // while t is even.. t/=2; // cast out twos } // B5 [reset max(u,v)] if (t>0) { u = -t; } else { v = t; } // B6/B3. at this point both u and v should be odd. t = (v - u)/2; // |u| larger: t positive (replace u) // |v| larger: t negative (replace v) } while (t!=0); return -u*(1<x*y
* @throws ArithmeticException if the result can not be represented as * an int */ private static int mulAndCheck(int x, int y) { long m = ((long)x)*((long)y); if (m < Integer.MIN_VALUE || m > Integer.MAX_VALUE) { throw new ArithmeticException("overflow: mul"); } return (int)m; } /** * Multiply two non-negative integers, checking for overflow. * * @param x a non-negative factor * @param y a non-negative factor * @return the product x*y * @throws ArithmeticException if the result can not be represented as * an int */ private static int mulPosAndCheck(int x, int y) { /* assert x>=0 && y>=0; */ long m = ((long)x)*((long)y); if (m > Integer.MAX_VALUE) { throw new ArithmeticException("overflow: mulPos"); } return (int)m; } /** * Add two integers, checking for overflow. * * @param x an addend * @param y an addend * @return the sum x+y * @throws ArithmeticException if the result can not be represented as * an int */ private static int addAndCheck(int x, int y) { long s = (long)x+(long)y; if (s < Integer.MIN_VALUE || s > Integer.MAX_VALUE) { throw new ArithmeticException("overflow: add"); } return (int)s; } /** * Subtract two integers, checking for overflow. * * @param x the minuend * @param y the subtrahend * @return the difference x-y * @throws ArithmeticException if the result can not be represented as * an int */ private static int subAndCheck(int x, int y) { long s = (long)x-(long)y; if (s < Integer.MIN_VALUE || s > Integer.MAX_VALUE) { throw new ArithmeticException("overflow: add"); } return (int)s; } /** *

Adds the value of this fraction to another, returning the result in reduced form. * The algorithm follows Knuth, 4.5.1.

* * @param fraction the fraction to add, must not be null * @return a Fraction instance with the resulting values * @throws IllegalArgumentException if the fraction is null * @throws ArithmeticException if the resulting numerator or denominator exceeds * Integer.MAX_VALUE */ public Fraction add(Fraction fraction) { return addSub(fraction, true /* add */); } /** *

Subtracts the value of another fraction from the value of this one, * returning the result in reduced form.

* * @param fraction the fraction to subtract, must not be null * @return a Fraction instance with the resulting values * @throws IllegalArgumentException if the fraction is null * @throws ArithmeticException if the resulting numerator or denominator * cannot be represented in an int. */ public Fraction subtract(Fraction fraction) { return addSub(fraction, false /* subtract */); } /** * Implement add and subtract using algorithm described in Knuth 4.5.1. * * @param fraction the fraction to subtract, must not be null * @param isAdd true to add, false to subtract * @return a Fraction instance with the resulting values * @throws IllegalArgumentException if the fraction is null * @throws ArithmeticException if the resulting numerator or denominator * cannot be represented in an int. */ private Fraction addSub(Fraction fraction, boolean isAdd) { if (fraction == null) { throw new IllegalArgumentException("The fraction must not be null"); } // zero is identity for addition. if (numerator == 0) { return isAdd ? fraction : fraction.negate(); } if (fraction.numerator == 0) { return this; } // if denominators are randomly distributed, d1 will be 1 about 61% // of the time. int d1 = greatestCommonDivisor(denominator, fraction.denominator); if (d1==1) { // result is ( (u*v' +/- u'v) / u'v') int uvp = mulAndCheck(numerator, fraction.denominator); int upv = mulAndCheck(fraction.numerator, denominator); return new Fraction (isAdd ? addAndCheck(uvp, upv) : subAndCheck(uvp, upv), mulPosAndCheck(denominator, fraction.denominator)); } // the quantity 't' requires 65 bits of precision; see knuth 4.5.1 // exercise 7. we're going to use a BigInteger. // t = u(v'/d1) +/- v(u'/d1) BigInteger uvp = BigInteger.valueOf(numerator) .multiply(BigInteger.valueOf(fraction.denominator/d1)); BigInteger upv = BigInteger.valueOf(fraction.numerator) .multiply(BigInteger.valueOf(denominator/d1)); BigInteger t = isAdd ? uvp.add(upv) : uvp.subtract(upv); // but d2 doesn't need extra precision because // d2 = gcd(t,d1) = gcd(t mod d1, d1) int tmodd1 = t.mod(BigInteger.valueOf(d1)).intValue(); int d2 = (tmodd1==0)?d1:greatestCommonDivisor(tmodd1, d1); // result is (t/d2) / (u'/d1)(v'/d2) BigInteger w = t.divide(BigInteger.valueOf(d2)); if (w.bitLength() > 31) { throw new ArithmeticException ("overflow: numerator too large after multiply"); } return new Fraction (w.intValue(), mulPosAndCheck(denominator/d1, fraction.denominator/d2)); } /** *

Multiplies the value of this fraction by another, returning the * result in reduced form.

* * @param fraction the fraction to multiply by, must not be null * @return a Fraction instance with the resulting values * @throws IllegalArgumentException if the fraction is null * @throws ArithmeticException if the resulting numerator or denominator exceeds * Integer.MAX_VALUE */ public Fraction multiplyBy(Fraction fraction) { if (fraction == null) { throw new IllegalArgumentException("The fraction must not be null"); } if (numerator == 0 || fraction.numerator == 0) { return ZERO; } // knuth 4.5.1 // make sure we don't overflow unless the result *must* overflow. int d1 = greatestCommonDivisor(numerator, fraction.denominator); int d2 = greatestCommonDivisor(fraction.numerator, denominator); return getReducedFraction (mulAndCheck(numerator/d1, fraction.numerator/d2), mulPosAndCheck(denominator/d2, fraction.denominator/d1)); } /** *

Divide the value of this fraction by another.

* * @param fraction the fraction to divide by, must not be null * @return a Fraction instance with the resulting values * @throws IllegalArgumentException if the fraction is null * @throws ArithmeticException if the fraction to divide by is zero * @throws ArithmeticException if the resulting numerator or denominator exceeds * Integer.MAX_VALUE */ public Fraction divideBy(Fraction fraction) { if (fraction == null) { throw new IllegalArgumentException("The fraction must not be null"); } if (fraction.numerator == 0) { throw new ArithmeticException("The fraction to divide by must not be zero"); } return multiplyBy(fraction.invert()); } // Basics //------------------------------------------------------------------- /** *

Compares this fraction to another object to test if they are equal.

. * *

To be equal, both values must be equal. Thus 2/4 is not equal to 1/2.

* * @param obj the reference object with which to compare * @return true if this object is equal */ public boolean equals(Object obj) { if (obj == this) { return true; } if (obj instanceof Fraction == false) { return false; } Fraction other = (Fraction) obj; return (getNumerator() == other.getNumerator() && getDenominator() == other.getDenominator()); } /** *

Gets a hashCode for the fraction.

* * @return a hash code value for this object */ public int hashCode() { if (hashCode == 0) { // hashcode update should be atomic. hashCode = 37 * (37 * 17 + getNumerator()) + getDenominator(); } return hashCode; } /** *

Compares this object to another based on size.

* *

Note: this class has a natural ordering that is inconsistent * with equals, because, for example, equals treats 1/2 and 2/4 as * different, whereas compareTo treats them as equal. * * @param object the object to compare to * @return -1 if this is less, 0 if equal, +1 if greater * @throws ClassCastException if the object is not a Fraction * @throws NullPointerException if the object is null */ public int compareTo(Object object) { Fraction other = (Fraction) object; if (this==other) { return 0; } if (numerator == other.numerator && denominator == other.denominator) { return 0; } // otherwise see which is less long first = (long) numerator * (long) other.denominator; long second = (long) other.numerator * (long) denominator; if (first == second) { return 0; } else if (first < second) { return -1; } else { return 1; } } /** *

Gets the fraction as a String.

* *

The format used is 'numerator/denominator' always. * * @return a String form of the fraction */ public String toString() { if (toString == null) { toString = new StrBuilder(32) .append(getNumerator()) .append('/') .append(getDenominator()).toString(); } return toString; } /** *

Gets the fraction as a proper String in the format X Y/Z.

* *

The format used in 'wholeNumber numerator/denominator'. * If the whole number is zero it will be ommitted. If the numerator is zero, * only the whole number is returned.

* * @return a String form of the fraction */ public String toProperString() { if (toProperString == null) { if (numerator == 0) { toProperString = "0"; } else if (numerator == denominator) { toProperString = "1"; } else if (numerator == -1 * denominator) { toProperString = "-1"; } else if ((numerator>0?-numerator:numerator) < -denominator) { // note that we do the magnitude comparison test above with // NEGATIVE (not positive) numbers, since negative numbers // have a larger range. otherwise numerator==Integer.MIN_VALUE // is handled incorrectly. int properNumerator = getProperNumerator(); if (properNumerator == 0) { toProperString = Integer.toString(getProperWhole()); } else { toProperString = new StrBuilder(32) .append(getProperWhole()).append(' ') .append(properNumerator).append('/') .append(getDenominator()).toString(); } } else { toProperString = new StrBuilder(32) .append(getNumerator()).append('/') .append(getDenominator()).toString(); } } return toProperString; } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/math/IEEE754rUtils.java100644 0 0 20272 11513702442 24717 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.math; /** *

Provides IEEE-754r variants of NumberUtils methods.

* *

See: http://en.wikipedia.org/wiki/IEEE_754r

* * @since 2.4 * @author Apache Software Foundation * @version $Id: IEEE754rUtils.java 905636 2010-02-02 14:03:32Z niallp $ */ public class IEEE754rUtils { /** *

Returns the minimum value in an array.

* * @param array an array, must not be null or empty * @return the minimum value in the array * @throws IllegalArgumentException if array is null * @throws IllegalArgumentException if array is empty */ public static double min(double[] array) { // Validates input if (array == null) { throw new IllegalArgumentException("The Array must not be null"); } else if (array.length == 0) { throw new IllegalArgumentException("Array cannot be empty."); } // Finds and returns min double min = array[0]; for (int i = 1; i < array.length; i++) { min = min(array[i], min); } return min; } /** *

Returns the minimum value in an array.

* * @param array an array, must not be null or empty * @return the minimum value in the array * @throws IllegalArgumentException if array is null * @throws IllegalArgumentException if array is empty */ public static float min(float[] array) { // Validates input if (array == null) { throw new IllegalArgumentException("The Array must not be null"); } else if (array.length == 0) { throw new IllegalArgumentException("Array cannot be empty."); } // Finds and returns min float min = array[0]; for (int i = 1; i < array.length; i++) { min = min(array[i], min); } return min; } /** *

Gets the minimum of three double values.

* *

NaN is only returned if all numbers are NaN as per IEEE-754r.

* * @param a value 1 * @param b value 2 * @param c value 3 * @return the smallest of the values */ public static double min(double a, double b, double c) { return min(min(a, b), c); } /** *

Gets the minimum of two double values.

* *

NaN is only returned if all numbers are NaN as per IEEE-754r.

* * @param a value 1 * @param b value 2 * @return the smallest of the values */ public static double min(double a, double b) { if(Double.isNaN(a)) { return b; } else if(Double.isNaN(b)) { return a; } else { return Math.min(a, b); } } /** *

Gets the minimum of three float values.

* *

NaN is only returned if all numbers are NaN as per IEEE-754r.

* * @param a value 1 * @param b value 2 * @param c value 3 * @return the smallest of the values */ public static float min(float a, float b, float c) { return min(min(a, b), c); } /** *

Gets the minimum of two float values.

* *

NaN is only returned if all numbers are NaN as per IEEE-754r.

* * @param a value 1 * @param b value 2 * @return the smallest of the values */ public static float min(float a, float b) { if(Float.isNaN(a)) { return b; } else if(Float.isNaN(b)) { return a; } else { return Math.min(a, b); } } /** *

Returns the maximum value in an array.

* * @param array an array, must not be null or empty * @return the minimum value in the array * @throws IllegalArgumentException if array is null * @throws IllegalArgumentException if array is empty */ public static double max(double[] array) { // Validates input if (array== null) { throw new IllegalArgumentException("The Array must not be null"); } else if (array.length == 0) { throw new IllegalArgumentException("Array cannot be empty."); } // Finds and returns max double max = array[0]; for (int j = 1; j < array.length; j++) { max = max(array[j], max); } return max; } /** *

Returns the maximum value in an array.

* * @param array an array, must not be null or empty * @return the minimum value in the array * @throws IllegalArgumentException if array is null * @throws IllegalArgumentException if array is empty */ public static float max(float[] array) { // Validates input if (array == null) { throw new IllegalArgumentException("The Array must not be null"); } else if (array.length == 0) { throw new IllegalArgumentException("Array cannot be empty."); } // Finds and returns max float max = array[0]; for (int j = 1; j < array.length; j++) { max = max(array[j], max); } return max; } /** *

Gets the maximum of three double values.

* *

NaN is only returned if all numbers are NaN as per IEEE-754r.

* * @param a value 1 * @param b value 2 * @param c value 3 * @return the largest of the values */ public static double max(double a, double b, double c) { return max(max(a, b), c); } /** *

Gets the maximum of two double values.

* *

NaN is only returned if all numbers are NaN as per IEEE-754r.

* * @param a value 1 * @param b value 2 * @return the largest of the values */ public static double max(double a, double b) { if(Double.isNaN(a)) { return b; } else if(Double.isNaN(b)) { return a; } else { return Math.max(a, b); } } /** *

Gets the maximum of three float values.

* *

NaN is only returned if all numbers are NaN as per IEEE-754r.

* * @param a value 1 * @param b value 2 * @param c value 3 * @return the largest of the values */ public static float max(float a, float b, float c) { return max(max(a, b), c); } /** *

Gets the maximum of two float values.

* *

NaN is only returned if all numbers are NaN as per IEEE-754r.

* * @param a value 1 * @param b value 2 * @return the largest of the values */ public static float max(float a, float b) { if(Float.isNaN(a)) { return b; } else if(Float.isNaN(b)) { return a; } else { return Math.max(a, b); } } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/math/IntRange.java100644 0 0 30715 11513702442 24257 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.math; import java.io.Serializable; import org.apache.commons.lang.text.StrBuilder; /** *

IntRange represents an inclusive range of ints.

* * @author Apache Software Foundation * @since 2.0 * @version $Id: IntRange.java 1057072 2011-01-10 01:55:57Z niallp $ */ public final class IntRange extends Range implements Serializable { /** * Required for serialization support. * * @see java.io.Serializable */ private static final long serialVersionUID = 71849363892730L; /** * The minimum number in this range (inclusive). */ private final int min; /** * The maximum number in this range (inclusive). */ private final int max; /** * Cached output minObject (class is immutable). */ private transient Integer minObject = null; /** * Cached output maxObject (class is immutable). */ private transient Integer maxObject = null; /** * Cached output hashCode (class is immutable). */ private transient int hashCode = 0; /** * Cached output toString (class is immutable). */ private transient String toString = null; /** *

Constructs a new IntRange using the specified * number as both the minimum and maximum in this range.

* * @param number the number to use for this range */ public IntRange(int number) { super(); this.min = number; this.max = number; } /** *

Constructs a new IntRange using the specified * number as both the minimum and maximum in this range.

* * @param number the number to use for this range, must not be null * @throws IllegalArgumentException if the number is null */ public IntRange(Number number) { super(); if (number == null) { throw new IllegalArgumentException("The number must not be null"); } this.min = number.intValue(); this.max = number.intValue(); if (number instanceof Integer) { this.minObject = (Integer) number; this.maxObject = (Integer) number; } } /** *

Constructs a new IntRange with the specified * minimum and maximum numbers (both inclusive).

* *

The arguments may be passed in the order (min,max) or (max,min). The * getMinimum and getMaximum methods will return the correct values.

* * @param number1 first number that defines the edge of the range, inclusive * @param number2 second number that defines the edge of the range, inclusive */ public IntRange(int number1, int number2) { super(); if (number2 < number1) { this.min = number2; this.max = number1; } else { this.min = number1; this.max = number2; } } /** *

Constructs a new IntRange with the specified * minimum and maximum numbers (both inclusive).

* *

The arguments may be passed in the order (min,max) or (max,min). The * getMinimum and getMaximum methods will return the correct values.

* * @param number1 first number that defines the edge of the range, inclusive * @param number2 second number that defines the edge of the range, inclusive * @throws IllegalArgumentException if either number is null */ public IntRange(Number number1, Number number2) { super(); if (number1 == null || number2 == null) { throw new IllegalArgumentException("The numbers must not be null"); } int number1val = number1.intValue(); int number2val = number2.intValue(); if (number2val < number1val) { this.min = number2val; this.max = number1val; if (number2 instanceof Integer) { this.minObject = (Integer) number2; } if (number1 instanceof Integer) { this.maxObject = (Integer) number1; } } else { this.min = number1val; this.max = number2val; if (number1 instanceof Integer) { this.minObject = (Integer) number1; } if (number2 instanceof Integer) { this.maxObject = (Integer) number2; } } } // Accessors //-------------------------------------------------------------------- /** *

Returns the minimum number in this range.

* * @return the minimum number in this range */ public Number getMinimumNumber() { if (minObject == null) { minObject = new Integer(min); } return minObject; } /** *

Gets the minimum number in this range as a long.

* * @return the minimum number in this range */ public long getMinimumLong() { return min; } /** *

Gets the minimum number in this range as a int.

* * @return the minimum number in this range */ public int getMinimumInteger() { return min; } /** *

Gets the minimum number in this range as a double.

* * @return the minimum number in this range */ public double getMinimumDouble() { return min; } /** *

Gets the minimum number in this range as a float.

* * @return the minimum number in this range */ public float getMinimumFloat() { return min; } /** *

Returns the maximum number in this range.

* * @return the maximum number in this range */ public Number getMaximumNumber() { if (maxObject == null) { maxObject = new Integer(max); } return maxObject; } /** *

Gets the maximum number in this range as a long.

* * @return the maximum number in this range */ public long getMaximumLong() { return max; } /** *

Gets the maximum number in this range as a int.

* * @return the maximum number in this range */ public int getMaximumInteger() { return max; } /** *

Gets the maximum number in this range as a double.

* * @return the maximum number in this range */ public double getMaximumDouble() { return max; } /** *

Gets the maximum number in this range as a float.

* * @return the maximum number in this range */ public float getMaximumFloat() { return max; } // Tests //-------------------------------------------------------------------- /** *

Tests whether the specified number occurs within * this range using int comparison.

* *

null is handled and returns false.

* * @param number the number to test, may be null * @return true if the specified number occurs within this range */ public boolean containsNumber(Number number) { if (number == null) { return false; } return containsInteger(number.intValue()); } /** *

Tests whether the specified int occurs within * this range using int comparison.

* *

This implementation overrides the superclass for performance as it is * the most common case.

* * @param value the int to test * @return true if the specified number occurs within this * range by int comparison */ public boolean containsInteger(int value) { return value >= min && value <= max; } // Range tests //-------------------------------------------------------------------- /** *

Tests whether the specified range occurs entirely within this range * using int comparison.

* *

null is handled and returns false.

* * @param range the range to test, may be null * @return true if the specified range occurs entirely within this range * @throws IllegalArgumentException if the range is not of this type */ public boolean containsRange(Range range) { if (range == null) { return false; } return containsInteger(range.getMinimumInteger()) && containsInteger(range.getMaximumInteger()); } /** *

Tests whether the specified range overlaps with this range * using int comparison.

* *

null is handled and returns false.

* * @param range the range to test, may be null * @return true if the specified range overlaps with this range */ public boolean overlapsRange(Range range) { if (range == null) { return false; } return range.containsInteger(min) || range.containsInteger(max) || containsInteger(range.getMinimumInteger()); } // Basics //-------------------------------------------------------------------- /** *

Compares this range to another object to test if they are equal.

. * *

To be equal, the class, minimum and maximum must be equal.

* * @param obj the reference object with which to compare * @return true if this object is equal */ public boolean equals(Object obj) { if (obj == this) { return true; } if (obj instanceof IntRange == false) { return false; } IntRange range = (IntRange) obj; return min == range.min && max == range.max; } /** *

Gets a hashCode for the range.

* * @return a hash code value for this object */ public int hashCode() { if (hashCode == 0) { hashCode = 17; hashCode = 37 * hashCode + getClass().hashCode(); hashCode = 37 * hashCode + min; hashCode = 37 * hashCode + max; } return hashCode; } /** *

Gets the range as a String.

* *

The format of the String is 'Range[min,max]'.

* * @return the String representation of this range */ public String toString() { if (toString == null) { StrBuilder buf = new StrBuilder(32); buf.append("Range["); buf.append(min); buf.append(','); buf.append(max); buf.append(']'); toString = buf.toString(); } return toString; } /** *

Returns an array containing all the integer values in the range.

* * @return the int[] representation of this range * @since 2.4 */ public int[] toArray() { int[] array = new int[max - min + 1]; for (int i = 0; i < array.length; i++) { array[i] = min + i; } return array; } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/math/JVMRandom.java100644 0 0 15733 11513702442 24350 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "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 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.commons.lang.math; import java.util.Random; /** *

JVMRandom is a wrapper that supports all possible * Random methods via the {@link java.lang.Math#random()} method * and its system-wide {@link Random} object.

*

* It does this to allow for a Random class in which the seed is * shared between all members of the class - a better name would * have been SharedSeedRandom. *

* N.B. the current implementation overrides the methods * {@link Random#nextInt(int)} and {@link Random#nextLong()} * to produce positive numbers ranging from 0 (inclusive) * to MAX_VALUE (exclusive). * * @since 2.0 * @version $Id: JVMRandom.java 911986 2010-02-19 21:19:05Z niallp $ */ public final class JVMRandom extends Random { /** * Required for serialization support. * * @see java.io.Serializable */ private static final long serialVersionUID = 1L; private static final Random SHARED_RANDOM = new Random(); /** * Ensures that only the parent constructor can call reseed. */ private boolean constructed = false; /** * Constructs a new instance. */ public JVMRandom() { this.constructed = true; } /** * Unsupported in 2.0. * * @param seed ignored * @throws UnsupportedOperationException */ public synchronized void setSeed(long seed) { if (this.constructed) { throw new UnsupportedOperationException(); } } /** * Unsupported in 2.0. * * @return Nothing, this method always throws an UnsupportedOperationException. * @throws UnsupportedOperationException */ public synchronized double nextGaussian() { throw new UnsupportedOperationException(); } /** * Unsupported in 2.0. * * @param byteArray ignored * @throws UnsupportedOperationException */ public void nextBytes(byte[] byteArray) { throw new UnsupportedOperationException(); } /** *

Returns the next pseudorandom, uniformly distributed int value * from the Math.random() sequence.

* Identical to nextInt(Integer.MAX_VALUE) *

* N.B. All values are >= 0. *

* @return the random int */ public int nextInt() { return nextInt(Integer.MAX_VALUE); } /** *

Returns a pseudorandom, uniformly distributed int value between * 0 (inclusive) and the specified value (exclusive), from * the Math.random() sequence.

* * @param n the specified exclusive max-value * @return the random int * @throws IllegalArgumentException when n <= 0 */ public int nextInt(int n) { return SHARED_RANDOM.nextInt(n); } /** *

Returns the next pseudorandom, uniformly distributed long value * from the Math.random() sequence.

* Identical to nextLong(Long.MAX_VALUE) *

* N.B. All values are >= 0. *

* @return the random long */ public long nextLong() { return nextLong(Long.MAX_VALUE); } /** *

Returns a pseudorandom, uniformly distributed long value between * 0 (inclusive) and the specified value (exclusive), from * the Math.random() sequence.

* * @param n the specified exclusive max-value * @return the random long * @throws IllegalArgumentException when n <= 0 */ public static long nextLong(long n) { if (n <= 0) { throw new IllegalArgumentException( "Upper bound for nextInt must be positive" ); } // Code adapted from Harmony Random#nextInt(int) if ((n & -n) == n) { // n is power of 2 // dropping lower order bits improves behaviour for low values of n return next63bits() >> 63 // drop all the bits - bitsRequired(n-1); // except the ones we need } // Not a power of two long val; long bits; do { // reject some values to improve distribution bits = next63bits(); val = bits % n; } while (bits - val + (n - 1) < 0); return val; } /** *

Returns the next pseudorandom, uniformly distributed boolean value * from the Math.random() sequence.

* * @return the random boolean */ public boolean nextBoolean() { return SHARED_RANDOM.nextBoolean(); } /** *

Returns the next pseudorandom, uniformly distributed float value * between 0.0 and 1.0 from the Math.random() * sequence.

* * @return the random float */ public float nextFloat() { return SHARED_RANDOM.nextFloat(); } /** *

Synonymous to the Math.random() call.

* * @return the random double */ public double nextDouble() { return SHARED_RANDOM.nextDouble(); } /** * Get the next unsigned random long * @return unsigned random long */ private static long next63bits(){ // drop the sign bit to leave 63 random bits return SHARED_RANDOM.nextLong() & 0x7fffffffffffffffL; } /** * Count the number of bits required to represent a long number. * * @param num long number * @return number of bits required */ private static int bitsRequired(long num){ // Derived from Hacker's Delight, Figure 5-9 long y=num; // for checking right bits int n=0; // number of leading zeros found while(true){ // 64 = number of bits in a long if (num < 0) { return 64-n; // no leading zeroes left } if (y == 0) { return n; // no bits left to check } n++; num=num << 1; // check leading bits y=y >> 1; // check trailing bits } } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/math/LongRange.java100644 0 0 32045 11513702442 24422 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.math; import java.io.Serializable; import org.apache.commons.lang.text.StrBuilder; /** *

LongRange represents an inclusive range of longs.

* * @author Apache Software Foundation * @since 2.0 * @version $Id: LongRange.java 1057072 2011-01-10 01:55:57Z niallp $ */ public final class LongRange extends Range implements Serializable { /** * Required for serialization support. * * @see java.io.Serializable */ private static final long serialVersionUID = 71849363892720L; /** * The minimum number in this range (inclusive). */ private final long min; /** * The maximum number in this range (inclusive). */ private final long max; /** * Cached output minObject (class is immutable). */ private transient Long minObject = null; /** * Cached output maxObject (class is immutable). */ private transient Long maxObject = null; /** * Cached output hashCode (class is immutable). */ private transient int hashCode = 0; /** * Cached output toString (class is immutable). */ private transient String toString = null; /** *

Constructs a new LongRange using the specified * number as both the minimum and maximum in this range.

* * @param number the number to use for this range */ public LongRange(long number) { super(); this.min = number; this.max = number; } /** *

Constructs a new LongRange using the specified * number as both the minimum and maximum in this range.

* * @param number the number to use for this range, must not * be null * @throws IllegalArgumentException if the number is null */ public LongRange(Number number) { super(); if (number == null) { throw new IllegalArgumentException("The number must not be null"); } this.min = number.longValue(); this.max = number.longValue(); if (number instanceof Long) { this.minObject = (Long) number; this.maxObject = (Long) number; } } /** *

Constructs a new LongRange with the specified * minimum and maximum numbers (both inclusive).

* *

The arguments may be passed in the order (min,max) or (max,min). The * getMinimum and getMaximum methods will return the correct values.

* * @param number1 first number that defines the edge of the range, inclusive * @param number2 second number that defines the edge of the range, inclusive */ public LongRange(long number1, long number2) { super(); if (number2 < number1) { this.min = number2; this.max = number1; } else { this.min = number1; this.max = number2; } } /** *

Constructs a new LongRange with the specified * minimum and maximum numbers (both inclusive).

* *

The arguments may be passed in the order (min,max) or (max,min). The * getMinimum and getMaximum methods will return the correct values.

* * @param number1 first number that defines the edge of the range, inclusive * @param number2 second number that defines the edge of the range, inclusive * @throws IllegalArgumentException if either number is null */ public LongRange(Number number1, Number number2) { super(); if (number1 == null || number2 == null) { throw new IllegalArgumentException("The numbers must not be null"); } long number1val = number1.longValue(); long number2val = number2.longValue(); if (number2val < number1val) { this.min = number2val; this.max = number1val; if (number2 instanceof Long) { this.minObject = (Long) number2; } if (number1 instanceof Long) { this.maxObject = (Long) number1; } } else { this.min = number1val; this.max = number2val; if (number1 instanceof Long) { this.minObject = (Long) number1; } if (number2 instanceof Long) { this.maxObject = (Long) number2; } } } // Accessors //-------------------------------------------------------------------- /** *

Returns the minimum number in this range.

* * @return the minimum number in this range */ public Number getMinimumNumber() { if (minObject == null) { minObject = new Long(min); } return minObject; } /** *

Gets the minimum number in this range as a long.

* * @return the minimum number in this range */ public long getMinimumLong() { return min; } /** *

Gets the minimum number in this range as a int.

* *

This conversion can lose information for large values.

* * @return the minimum number in this range */ public int getMinimumInteger() { return (int) min; } /** *

Gets the minimum number in this range as a double.

* *

This conversion can lose information for large values.

* * @return the minimum number in this range */ public double getMinimumDouble() { return min; } /** *

Gets the minimum number in this range as a float.

* *

This conversion can lose information for large values.

* * @return the minimum number in this range */ public float getMinimumFloat() { return min; } /** *

Returns the maximum number in this range.

* * @return the maximum number in this range */ public Number getMaximumNumber() { if (maxObject == null) { maxObject = new Long(max); } return maxObject; } /** *

Gets the maximum number in this range as a long.

* * @return the maximum number in this range */ public long getMaximumLong() { return max; } /** *

Gets the maximum number in this range cast to an int.

* *

This conversion can lose information for large values.

* * @return the maximum number in this range cast to an int. */ public int getMaximumInteger() { return (int) max; } /** *

Gets the maximum number in this range as a double.

* *

This conversion can lose information for large values.

* * @return The maximum number in this range as a double. */ public double getMaximumDouble() { return max; } /** *

Gets the maximum number in this range as a float.

* *

This conversion can lose information for large values.

* * @return The maximum number in this range as a float. */ public float getMaximumFloat() { return max; } // Tests //-------------------------------------------------------------------- /** *

Tests whether the specified number occurs within * this range using long comparison.

* *

null is handled and returns false.

* * @param number the number to test, may be null * @return true if the specified number occurs within this range */ public boolean containsNumber(Number number) { if (number == null) { return false; } return containsLong(number.longValue()); } /** *

Tests whether the specified long occurs within * this range using long comparison.

* *

This implementation overrides the superclass for performance as it is * the most common case.

* * @param value the long to test * @return true if the specified number occurs within this * range by long comparison */ public boolean containsLong(long value) { return value >= min && value <= max; } // Range tests //-------------------------------------------------------------------- /** *

Tests whether the specified range occurs entirely within this range * using long comparison.

* *

null is handled and returns false.

* * @param range the range to test, may be null * @return true if the specified range occurs entirely within this range * @throws IllegalArgumentException if the range is not of this type */ public boolean containsRange(Range range) { if (range == null) { return false; } return containsLong(range.getMinimumLong()) && containsLong(range.getMaximumLong()); } /** *

Tests whether the specified range overlaps with this range * using long comparison.

* *

null is handled and returns false.

* * @param range the range to test, may be null * @return true if the specified range overlaps with this range */ public boolean overlapsRange(Range range) { if (range == null) { return false; } return range.containsLong(min) || range.containsLong(max) || containsLong(range.getMinimumLong()); } // Basics //-------------------------------------------------------------------- /** *

Compares this range to another object to test if they are equal.

. * *

To be equal, the class, minimum and maximum must be equal.

* * @param obj the reference object with which to compare * @return true if this object is equal */ public boolean equals(Object obj) { if (obj == this) { return true; } if (obj instanceof LongRange == false) { return false; } LongRange range = (LongRange) obj; return min == range.min && max == range.max; } /** *

Gets a hashCode for the range.

* * @return a hash code value for this object */ public int hashCode() { if (hashCode == 0) { hashCode = 17; hashCode = 37 * hashCode + getClass().hashCode(); hashCode = 37 * hashCode + ((int) (min ^ (min >> 32))); hashCode = 37 * hashCode + ((int) (max ^ (max >> 32))); } return hashCode; } /** *

Gets the range as a String.

* *

The format of the String is 'Range[min,max]'.

* * @return the String representation of this range */ public String toString() { if (toString == null) { StrBuilder buf = new StrBuilder(32); buf.append("Range["); buf.append(min); buf.append(','); buf.append(max); buf.append(']'); toString = buf.toString(); } return toString; } /** *

Returns an array containing all the long values in the range.

* * @return the long[] representation of this range * @since 2.4 */ public long[] toArray() { long[] array = new long[(int)(max - min + 1L)]; for(int i = 0; i < array.length; i++) { array[i] = min + i; } return array; } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/math/NumberRange.java100644 0 0 21202 11513702442 24744 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.math; import java.io.Serializable; import org.apache.commons.lang.text.StrBuilder; /** *

NumberRange represents an inclusive range of * {@link java.lang.Number} objects of the same type.

* * @author Apache Software Foundation * @author Christopher Elkins * @since 2.0 (previously in org.apache.commons.lang) * @version $Id: NumberRange.java 1057072 2011-01-10 01:55:57Z niallp $ */ public final class NumberRange extends Range implements Serializable { /** * Required for serialization support. * * @see java.io.Serializable */ private static final long serialVersionUID = 71849363892710L; /** * The minimum number in this range. */ private final Number min; /** * The maximum number in this range. */ private final Number max; /** * Cached output hashCode (class is immutable). */ private transient int hashCode = 0; /** * Cached output toString (class is immutable). */ private transient String toString = null; /** *

Constructs a new NumberRange using the specified * number as both the minimum and maximum in this range.

* * @param num the number to use for this range * @throws IllegalArgumentException if the number is null * @throws IllegalArgumentException if the number doesn't implement Comparable * @throws IllegalArgumentException if the number is Double.NaN or Float.NaN */ public NumberRange(Number num) { if (num == null) { throw new IllegalArgumentException("The number must not be null"); } if (num instanceof Comparable == false) { throw new IllegalArgumentException("The number must implement Comparable"); } if (num instanceof Double && ((Double) num).isNaN()) { throw new IllegalArgumentException("The number must not be NaN"); } if (num instanceof Float && ((Float) num).isNaN()) { throw new IllegalArgumentException("The number must not be NaN"); } this.min = num; this.max = num; } /** *

Constructs a new NumberRange with the specified * minimum and maximum numbers (both inclusive).

* *

The arguments may be passed in the order (min,max) or (max,min). The * {@link #getMinimumNumber()} and {@link #getMaximumNumber()} methods will return the * correct value.

* *

This constructor is designed to be used with two Number * objects of the same type. If two objects of different types are passed in, * an exception is thrown.

* * @param num1 first number that defines the edge of the range, inclusive * @param num2 second number that defines the edge of the range, inclusive * @throws IllegalArgumentException if either number is null * @throws IllegalArgumentException if the numbers are of different types * @throws IllegalArgumentException if the numbers don't implement Comparable */ public NumberRange(Number num1, Number num2) { if (num1 == null || num2 == null) { throw new IllegalArgumentException("The numbers must not be null"); } if (num1.getClass() != num2.getClass()) { throw new IllegalArgumentException("The numbers must be of the same type"); } if (num1 instanceof Comparable == false) { throw new IllegalArgumentException("The numbers must implement Comparable"); } if (num1 instanceof Double) { if (((Double) num1).isNaN() || ((Double) num2).isNaN()) { throw new IllegalArgumentException("The number must not be NaN"); } } else if (num1 instanceof Float) { if (((Float) num1).isNaN() || ((Float) num2).isNaN()) { throw new IllegalArgumentException("The number must not be NaN"); } } int compare = ((Comparable) num1).compareTo(num2); if (compare == 0) { this.min = num1; this.max = num1; } else if (compare > 0) { this.min = num2; this.max = num1; } else { this.min = num1; this.max = num2; } } // Accessors //-------------------------------------------------------------------- /** *

Returns the minimum number in this range.

* * @return the minimum number in this range */ public Number getMinimumNumber() { return min; } /** *

Returns the maximum number in this range.

* * @return the maximum number in this range */ public Number getMaximumNumber() { return max; } // Tests //-------------------------------------------------------------------- /** *

Tests whether the specified number occurs within * this range.

* *

null is handled and returns false.

* * @param number the number to test, may be null * @return true if the specified number occurs within this range * @throws IllegalArgumentException if the number is of a different type to the range */ public boolean containsNumber(Number number) { if (number == null) { return false; } if (number.getClass() != min.getClass()) { throw new IllegalArgumentException("The number must be of the same type as the range numbers"); } int compareMin = ((Comparable) min).compareTo(number); int compareMax = ((Comparable) max).compareTo(number); return compareMin <= 0 && compareMax >= 0; } // Range tests //-------------------------------------------------------------------- // use Range implementations // Basics //-------------------------------------------------------------------- /** *

Compares this range to another object to test if they are equal.

. * *

To be equal, the class, minimum and maximum must be equal.

* * @param obj the reference object with which to compare * @return true if this object is equal */ public boolean equals(Object obj) { if (obj == this) { return true; } if (obj instanceof NumberRange == false) { return false; } NumberRange range = (NumberRange) obj; return min.equals(range.min) && max.equals(range.max); } /** *

Gets a hashCode for the range.

* * @return a hash code value for this object */ public int hashCode() { if (hashCode == 0) { hashCode = 17; hashCode = 37 * hashCode + getClass().hashCode(); hashCode = 37 * hashCode + min.hashCode(); hashCode = 37 * hashCode + max.hashCode(); } return hashCode; } /** *

Gets the range as a String.

* *

The format of the String is 'Range[min,max]'.

* * @return the String representation of this range */ public String toString() { if (toString == null) { StrBuilder buf = new StrBuilder(32); buf.append("Range["); buf.append(min); buf.append(','); buf.append(max); buf.append(']'); toString = buf.toString(); } return toString; } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/math/NumberUtils.java100644 0 0 154046 11513702442 25045 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.math; import java.math.BigDecimal; import java.math.BigInteger; import org.apache.commons.lang.StringUtils; /** *

Provides extra functionality for Java Number classes.

* * @author Apache Software Foundation * @author Rand McNeely * @author Steve Downey * @author Eric Pugh * @author Phil Steitz * @author Matthew Hawthorne * @author Gary Gregory * @author Fredrik Westermarck * @since 2.0 * @version $Id: NumberUtils.java 1056853 2011-01-09 01:07:04Z niallp $ */ public class NumberUtils { /** Reusable Long constant for zero. */ public static final Long LONG_ZERO = new Long(0L); /** Reusable Long constant for one. */ public static final Long LONG_ONE = new Long(1L); /** Reusable Long constant for minus one. */ public static final Long LONG_MINUS_ONE = new Long(-1L); /** Reusable Integer constant for zero. */ public static final Integer INTEGER_ZERO = new Integer(0); /** Reusable Integer constant for one. */ public static final Integer INTEGER_ONE = new Integer(1); /** Reusable Integer constant for minus one. */ public static final Integer INTEGER_MINUS_ONE = new Integer(-1); /** Reusable Short constant for zero. */ public static final Short SHORT_ZERO = new Short((short) 0); /** Reusable Short constant for one. */ public static final Short SHORT_ONE = new Short((short) 1); /** Reusable Short constant for minus one. */ public static final Short SHORT_MINUS_ONE = new Short((short) -1); /** Reusable Byte constant for zero. */ public static final Byte BYTE_ZERO = new Byte((byte) 0); /** Reusable Byte constant for one. */ public static final Byte BYTE_ONE = new Byte((byte) 1); /** Reusable Byte constant for minus one. */ public static final Byte BYTE_MINUS_ONE = new Byte((byte) -1); /** Reusable Double constant for zero. */ public static final Double DOUBLE_ZERO = new Double(0.0d); /** Reusable Double constant for one. */ public static final Double DOUBLE_ONE = new Double(1.0d); /** Reusable Double constant for minus one. */ public static final Double DOUBLE_MINUS_ONE = new Double(-1.0d); /** Reusable Float constant for zero. */ public static final Float FLOAT_ZERO = new Float(0.0f); /** Reusable Float constant for one. */ public static final Float FLOAT_ONE = new Float(1.0f); /** Reusable Float constant for minus one. */ public static final Float FLOAT_MINUS_ONE = new Float(-1.0f); /** *

NumberUtils instances should NOT be constructed in standard programming. * Instead, the class should be used as NumberUtils.toInt("6");.

* *

This constructor is public to permit tools that require a JavaBean instance * to operate.

*/ public NumberUtils() { super(); } //----------------------------------------------------------------------- /** *

Convert a String to an int, returning * zero if the conversion fails.

* *

If the string is null, zero is returned.

* *
     *   NumberUtils.stringToInt(null) = 0
     *   NumberUtils.stringToInt("")   = 0
     *   NumberUtils.stringToInt("1")  = 1
     * 
* * @param str the string to convert, may be null * @return the int represented by the string, or zero if * conversion fails * @deprecated Use {@link #toInt(String)} * This method will be removed in Commons Lang 3.0 */ public static int stringToInt(String str) { return toInt(str); } /** *

Convert a String to an int, returning * zero if the conversion fails.

* *

If the string is null, zero is returned.

* *
     *   NumberUtils.toInt(null) = 0
     *   NumberUtils.toInt("")   = 0
     *   NumberUtils.toInt("1")  = 1
     * 
* * @param str the string to convert, may be null * @return the int represented by the string, or zero if * conversion fails * @since 2.1 */ public static int toInt(String str) { return toInt(str, 0); } /** *

Convert a String to an int, returning a * default value if the conversion fails.

* *

If the string is null, the default value is returned.

* *
     *   NumberUtils.stringToInt(null, 1) = 1
     *   NumberUtils.stringToInt("", 1)   = 1
     *   NumberUtils.stringToInt("1", 0)  = 1
     * 
* * @param str the string to convert, may be null * @param defaultValue the default value * @return the int represented by the string, or the default if conversion fails * @deprecated Use {@link #toInt(String, int)} * This method will be removed in Commons Lang 3.0 */ public static int stringToInt(String str, int defaultValue) { return toInt(str, defaultValue); } /** *

Convert a String to an int, returning a * default value if the conversion fails.

* *

If the string is null, the default value is returned.

* *
     *   NumberUtils.toInt(null, 1) = 1
     *   NumberUtils.toInt("", 1)   = 1
     *   NumberUtils.toInt("1", 0)  = 1
     * 
* * @param str the string to convert, may be null * @param defaultValue the default value * @return the int represented by the string, or the default if conversion fails * @since 2.1 */ public static int toInt(String str, int defaultValue) { if(str == null) { return defaultValue; } try { return Integer.parseInt(str); } catch (NumberFormatException nfe) { return defaultValue; } } /** *

Convert a String to a long, returning * zero if the conversion fails.

* *

If the string is null, zero is returned.

* *
     *   NumberUtils.toLong(null) = 0L
     *   NumberUtils.toLong("")   = 0L
     *   NumberUtils.toLong("1")  = 1L
     * 
* * @param str the string to convert, may be null * @return the long represented by the string, or 0 if * conversion fails * @since 2.1 */ public static long toLong(String str) { return toLong(str, 0L); } /** *

Convert a String to a long, returning a * default value if the conversion fails.

* *

If the string is null, the default value is returned.

* *
     *   NumberUtils.toLong(null, 1L) = 1L
     *   NumberUtils.toLong("", 1L)   = 1L
     *   NumberUtils.toLong("1", 0L)  = 1L
     * 
* * @param str the string to convert, may be null * @param defaultValue the default value * @return the long represented by the string, or the default if conversion fails * @since 2.1 */ public static long toLong(String str, long defaultValue) { if (str == null) { return defaultValue; } try { return Long.parseLong(str); } catch (NumberFormatException nfe) { return defaultValue; } } /** *

Convert a String to a float, returning * 0.0f if the conversion fails.

* *

If the string str is null, * 0.0f is returned.

* *
     *   NumberUtils.toFloat(null)   = 0.0f
     *   NumberUtils.toFloat("")     = 0.0f
     *   NumberUtils.toFloat("1.5")  = 1.5f
     * 
* * @param str the string to convert, may be null * @return the float represented by the string, or 0.0f * if conversion fails * @since 2.1 */ public static float toFloat(String str) { return toFloat(str, 0.0f); } /** *

Convert a String to a float, returning a * default value if the conversion fails.

* *

If the string str is null, the default * value is returned.

* *
     *   NumberUtils.toFloat(null, 1.1f)   = 1.0f
     *   NumberUtils.toFloat("", 1.1f)     = 1.1f
     *   NumberUtils.toFloat("1.5", 0.0f)  = 1.5f
     * 
* * @param str the string to convert, may be null * @param defaultValue the default value * @return the float represented by the string, or defaultValue * if conversion fails * @since 2.1 */ public static float toFloat(String str, float defaultValue) { if (str == null) { return defaultValue; } try { return Float.parseFloat(str); } catch (NumberFormatException nfe) { return defaultValue; } } /** *

Convert a String to a double, returning * 0.0d if the conversion fails.

* *

If the string str is null, * 0.0d is returned.

* *
     *   NumberUtils.toDouble(null)   = 0.0d
     *   NumberUtils.toDouble("")     = 0.0d
     *   NumberUtils.toDouble("1.5")  = 1.5d
     * 
* * @param str the string to convert, may be null * @return the double represented by the string, or 0.0d * if conversion fails * @since 2.1 */ public static double toDouble(String str) { return toDouble(str, 0.0d); } /** *

Convert a String to a double, returning a * default value if the conversion fails.

* *

If the string str is null, the default * value is returned.

* *
     *   NumberUtils.toDouble(null, 1.1d)   = 1.1d
     *   NumberUtils.toDouble("", 1.1d)     = 1.1d
     *   NumberUtils.toDouble("1.5", 0.0d)  = 1.5d
     * 
* * @param str the string to convert, may be null * @param defaultValue the default value * @return the double represented by the string, or defaultValue * if conversion fails * @since 2.1 */ public static double toDouble(String str, double defaultValue) { if (str == null) { return defaultValue; } try { return Double.parseDouble(str); } catch (NumberFormatException nfe) { return defaultValue; } } //----------------------------------------------------------------------- /** *

Convert a String to a byte, returning * zero if the conversion fails.

* *

If the string is null, zero is returned.

* *
     *   NumberUtils.toByte(null) = 0
     *   NumberUtils.toByte("")   = 0
     *   NumberUtils.toByte("1")  = 1
     * 
* * @param str the string to convert, may be null * @return the byte represented by the string, or zero if * conversion fails * @since 2.5 */ public static byte toByte(String str) { return toByte(str, (byte) 0); } /** *

Convert a String to a byte, returning a * default value if the conversion fails.

* *

If the string is null, the default value is returned.

* *
     *   NumberUtils.toByte(null, 1) = 1
     *   NumberUtils.toByte("", 1)   = 1
     *   NumberUtils.toByte("1", 0)  = 1
     * 
* * @param str the string to convert, may be null * @param defaultValue the default value * @return the byte represented by the string, or the default if conversion fails * @since 2.5 */ public static byte toByte(String str, byte defaultValue) { if(str == null) { return defaultValue; } try { return Byte.parseByte(str); } catch (NumberFormatException nfe) { return defaultValue; } } /** *

Convert a String to a short, returning * zero if the conversion fails.

* *

If the string is null, zero is returned.

* *
     *   NumberUtils.toShort(null) = 0
     *   NumberUtils.toShort("")   = 0
     *   NumberUtils.toShort("1")  = 1
     * 
* * @param str the string to convert, may be null * @return the short represented by the string, or zero if * conversion fails * @since 2.5 */ public static short toShort(String str) { return toShort(str, (short) 0); } /** *

Convert a String to an short, returning a * default value if the conversion fails.

* *

If the string is null, the default value is returned.

* *
     *   NumberUtils.toShort(null, 1) = 1
     *   NumberUtils.toShort("", 1)   = 1
     *   NumberUtils.toShort("1", 0)  = 1
     * 
* * @param str the string to convert, may be null * @param defaultValue the default value * @return the short represented by the string, or the default if conversion fails * @since 2.5 */ public static short toShort(String str, short defaultValue) { if(str == null) { return defaultValue; } try { return Short.parseShort(str); } catch (NumberFormatException nfe) { return defaultValue; } } //----------------------------------------------------------------------- // must handle Long, Float, Integer, Float, Short, // BigDecimal, BigInteger and Byte // useful methods: // Byte.decode(String) // Byte.valueOf(String,int radix) // Byte.valueOf(String) // Double.valueOf(String) // Float.valueOf(String) // new Float(String) // Integer.valueOf(String,int radix) // Integer.valueOf(String) // Integer.decode(String) // Integer.getInteger(String) // Integer.getInteger(String,int val) // Integer.getInteger(String,Integer val) // new Integer(String) // new Double(String) // new Byte(String) // new Long(String) // Long.getLong(String) // Long.getLong(String,int) // Long.getLong(String,Integer) // Long.valueOf(String,int) // Long.valueOf(String) // new Short(String) // Short.decode(String) // Short.valueOf(String,int) // Short.valueOf(String) // new BigDecimal(String) // new BigInteger(String) // new BigInteger(String,int radix) // Possible inputs: // 45 45.5 45E7 4.5E7 Hex Oct Binary xxxF xxxD xxxf xxxd // plus minus everything. Prolly more. A lot are not separable. /** *

Turns a string value into a java.lang.Number.

* *

First, the value is examined for a type qualifier on the end * ('f','F','d','D','l','L'). If it is found, it starts * trying to create successively larger types from the type specified * until one is found that can represent the value.

* *

If a type specifier is not found, it will check for a decimal point * and then try successively larger types from Integer to * BigInteger and from Float to * BigDecimal.

* *

If the string starts with 0x or -0x, it * will be interpreted as a hexadecimal integer. Values with leading * 0's will not be interpreted as octal.

* *

Returns null if the string is null.

* *

This method does not trim the input string, i.e., strings with leading * or trailing spaces will generate NumberFormatExceptions.

* * @param str String containing a number, may be null * @return Number created from the string * @throws NumberFormatException if the value cannot be converted */ public static Number createNumber(String str) throws NumberFormatException { if (str == null) { return null; } if (StringUtils.isBlank(str)) { throw new NumberFormatException("A blank string is not a valid number"); } if (str.startsWith("--")) { // this is protection for poorness in java.lang.BigDecimal. // it accepts this as a legal value, but it does not appear // to be in specification of class. OS X Java parses it to // a wrong value. return null; } if (str.startsWith("0x") || str.startsWith("-0x")) { return createInteger(str); } char lastChar = str.charAt(str.length() - 1); String mant; String dec; String exp; int decPos = str.indexOf('.'); int expPos = str.indexOf('e') + str.indexOf('E') + 1; if (decPos > -1) { if (expPos > -1) { if (expPos < decPos || expPos > str.length()) { throw new NumberFormatException(str + " is not a valid number."); } dec = str.substring(decPos + 1, expPos); } else { dec = str.substring(decPos + 1); } mant = str.substring(0, decPos); } else { if (expPos > -1) { if (expPos > str.length()) { throw new NumberFormatException(str + " is not a valid number."); } mant = str.substring(0, expPos); } else { mant = str; } dec = null; } if (!Character.isDigit(lastChar) && lastChar != '.') { if (expPos > -1 && expPos < str.length() - 1) { exp = str.substring(expPos + 1, str.length() - 1); } else { exp = null; } //Requesting a specific type.. String numeric = str.substring(0, str.length() - 1); boolean allZeros = isAllZeros(mant) && isAllZeros(exp); switch (lastChar) { case 'l' : case 'L' : if (dec == null && exp == null && (numeric.charAt(0) == '-' && isDigits(numeric.substring(1)) || isDigits(numeric))) { try { return createLong(numeric); } catch (NumberFormatException nfe) { //Too big for a long } return createBigInteger(numeric); } throw new NumberFormatException(str + " is not a valid number."); case 'f' : case 'F' : try { Float f = NumberUtils.createFloat(numeric); if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) { //If it's too big for a float or the float value = 0 and the string //has non-zeros in it, then float does not have the precision we want return f; } } catch (NumberFormatException nfe) { // ignore the bad number } //$FALL-THROUGH$ case 'd' : case 'D' : try { Double d = NumberUtils.createDouble(numeric); if (!(d.isInfinite() || (d.floatValue() == 0.0D && !allZeros))) { return d; } } catch (NumberFormatException nfe) { // ignore the bad number } try { return createBigDecimal(numeric); } catch (NumberFormatException e) { // ignore the bad number } //$FALL-THROUGH$ default : throw new NumberFormatException(str + " is not a valid number."); } } else { //User doesn't have a preference on the return type, so let's start //small and go from there... if (expPos > -1 && expPos < str.length() - 1) { exp = str.substring(expPos + 1, str.length()); } else { exp = null; } if (dec == null && exp == null) { //Must be an int,long,bigint try { return createInteger(str); } catch (NumberFormatException nfe) { // ignore the bad number } try { return createLong(str); } catch (NumberFormatException nfe) { // ignore the bad number } return createBigInteger(str); } else { //Must be a float,double,BigDec boolean allZeros = isAllZeros(mant) && isAllZeros(exp); try { Float f = createFloat(str); if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) { return f; } } catch (NumberFormatException nfe) { // ignore the bad number } try { Double d = createDouble(str); if (!(d.isInfinite() || (d.doubleValue() == 0.0D && !allZeros))) { return d; } } catch (NumberFormatException nfe) { // ignore the bad number } return createBigDecimal(str); } } } /** *

Utility method for {@link #createNumber(java.lang.String)}.

* *

Returns true if s is null.

* * @param str the String to check * @return if it is all zeros or null */ private static boolean isAllZeros(String str) { if (str == null) { return true; } for (int i = str.length() - 1; i >= 0; i--) { if (str.charAt(i) != '0') { return false; } } return str.length() > 0; } //----------------------------------------------------------------------- /** *

Convert a String to a Float.

* *

Returns null if the string is null.

* * @param str a String to convert, may be null * @return converted Float * @throws NumberFormatException if the value cannot be converted */ public static Float createFloat(String str) { if (str == null) { return null; } return Float.valueOf(str); } /** *

Convert a String to a Double.

* *

Returns null if the string is null.

* * @param str a String to convert, may be null * @return converted Double * @throws NumberFormatException if the value cannot be converted */ public static Double createDouble(String str) { if (str == null) { return null; } return Double.valueOf(str); } /** *

Convert a String to a Integer, handling * hex and octal notations.

* *

Returns null if the string is null.

* * @param str a String to convert, may be null * @return converted Integer * @throws NumberFormatException if the value cannot be converted */ public static Integer createInteger(String str) { if (str == null) { return null; } // decode() handles 0xAABD and 0777 (hex and octal) as well. return Integer.decode(str); } /** *

Convert a String to a Long.

* *

Returns null if the string is null.

* * @param str a String to convert, may be null * @return converted Long * @throws NumberFormatException if the value cannot be converted */ public static Long createLong(String str) { if (str == null) { return null; } return Long.valueOf(str); } /** *

Convert a String to a BigInteger.

* *

Returns null if the string is null.

* * @param str a String to convert, may be null * @return converted BigInteger * @throws NumberFormatException if the value cannot be converted */ public static BigInteger createBigInteger(String str) { if (str == null) { return null; } return new BigInteger(str); } /** *

Convert a String to a BigDecimal.

* *

Returns null if the string is null.

* * @param str a String to convert, may be null * @return converted BigDecimal * @throws NumberFormatException if the value cannot be converted */ public static BigDecimal createBigDecimal(String str) { if (str == null) { return null; } // handle JDK1.3.1 bug where "" throws IndexOutOfBoundsException if (StringUtils.isBlank(str)) { throw new NumberFormatException("A blank string is not a valid number"); } return new BigDecimal(str); } // Min in array //-------------------------------------------------------------------- /** *

Returns the minimum value in an array.

* * @param array an array, must not be null or empty * @return the minimum value in the array * @throws IllegalArgumentException if array is null * @throws IllegalArgumentException if array is empty */ public static long min(long[] array) { // Validates input if (array == null) { throw new IllegalArgumentException("The Array must not be null"); } else if (array.length == 0) { throw new IllegalArgumentException("Array cannot be empty."); } // Finds and returns min long min = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] < min) { min = array[i]; } } return min; } /** *

Returns the minimum value in an array.

* * @param array an array, must not be null or empty * @return the minimum value in the array * @throws IllegalArgumentException if array is null * @throws IllegalArgumentException if array is empty */ public static int min(int[] array) { // Validates input if (array == null) { throw new IllegalArgumentException("The Array must not be null"); } else if (array.length == 0) { throw new IllegalArgumentException("Array cannot be empty."); } // Finds and returns min int min = array[0]; for (int j = 1; j < array.length; j++) { if (array[j] < min) { min = array[j]; } } return min; } /** *

Returns the minimum value in an array.

* * @param array an array, must not be null or empty * @return the minimum value in the array * @throws IllegalArgumentException if array is null * @throws IllegalArgumentException if array is empty */ public static short min(short[] array) { // Validates input if (array == null) { throw new IllegalArgumentException("The Array must not be null"); } else if (array.length == 0) { throw new IllegalArgumentException("Array cannot be empty."); } // Finds and returns min short min = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] < min) { min = array[i]; } } return min; } /** *

Returns the minimum value in an array.

* * @param array an array, must not be null or empty * @return the minimum value in the array * @throws IllegalArgumentException if array is null * @throws IllegalArgumentException if array is empty */ public static byte min(byte[] array) { // Validates input if (array == null) { throw new IllegalArgumentException("The Array must not be null"); } else if (array.length == 0) { throw new IllegalArgumentException("Array cannot be empty."); } // Finds and returns min byte min = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] < min) { min = array[i]; } } return min; } /** *

Returns the minimum value in an array.

* * @param array an array, must not be null or empty * @return the minimum value in the array * @throws IllegalArgumentException if array is null * @throws IllegalArgumentException if array is empty * @see IEEE754rUtils#min(double[]) IEEE754rUtils for a version of this method that handles NaN differently */ public static double min(double[] array) { // Validates input if (array == null) { throw new IllegalArgumentException("The Array must not be null"); } else if (array.length == 0) { throw new IllegalArgumentException("Array cannot be empty."); } // Finds and returns min double min = array[0]; for (int i = 1; i < array.length; i++) { if (Double.isNaN(array[i])) { return Double.NaN; } if (array[i] < min) { min = array[i]; } } return min; } /** *

Returns the minimum value in an array.

* * @param array an array, must not be null or empty * @return the minimum value in the array * @throws IllegalArgumentException if array is null * @throws IllegalArgumentException if array is empty * @see IEEE754rUtils#min(float[]) IEEE754rUtils for a version of this method that handles NaN differently */ public static float min(float[] array) { // Validates input if (array == null) { throw new IllegalArgumentException("The Array must not be null"); } else if (array.length == 0) { throw new IllegalArgumentException("Array cannot be empty."); } // Finds and returns min float min = array[0]; for (int i = 1; i < array.length; i++) { if (Float.isNaN(array[i])) { return Float.NaN; } if (array[i] < min) { min = array[i]; } } return min; } // Max in array //-------------------------------------------------------------------- /** *

Returns the maximum value in an array.

* * @param array an array, must not be null or empty * @return the minimum value in the array * @throws IllegalArgumentException if array is null * @throws IllegalArgumentException if array is empty */ public static long max(long[] array) { // Validates input if (array == null) { throw new IllegalArgumentException("The Array must not be null"); } else if (array.length == 0) { throw new IllegalArgumentException("Array cannot be empty."); } // Finds and returns max long max = array[0]; for (int j = 1; j < array.length; j++) { if (array[j] > max) { max = array[j]; } } return max; } /** *

Returns the maximum value in an array.

* * @param array an array, must not be null or empty * @return the minimum value in the array * @throws IllegalArgumentException if array is null * @throws IllegalArgumentException if array is empty */ public static int max(int[] array) { // Validates input if (array == null) { throw new IllegalArgumentException("The Array must not be null"); } else if (array.length == 0) { throw new IllegalArgumentException("Array cannot be empty."); } // Finds and returns max int max = array[0]; for (int j = 1; j < array.length; j++) { if (array[j] > max) { max = array[j]; } } return max; } /** *

Returns the maximum value in an array.

* * @param array an array, must not be null or empty * @return the minimum value in the array * @throws IllegalArgumentException if array is null * @throws IllegalArgumentException if array is empty */ public static short max(short[] array) { // Validates input if (array == null) { throw new IllegalArgumentException("The Array must not be null"); } else if (array.length == 0) { throw new IllegalArgumentException("Array cannot be empty."); } // Finds and returns max short max = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] > max) { max = array[i]; } } return max; } /** *

Returns the maximum value in an array.

* * @param array an array, must not be null or empty * @return the minimum value in the array * @throws IllegalArgumentException if array is null * @throws IllegalArgumentException if array is empty */ public static byte max(byte[] array) { // Validates input if (array == null) { throw new IllegalArgumentException("The Array must not be null"); } else if (array.length == 0) { throw new IllegalArgumentException("Array cannot be empty."); } // Finds and returns max byte max = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] > max) { max = array[i]; } } return max; } /** *

Returns the maximum value in an array.

* * @param array an array, must not be null or empty * @return the minimum value in the array * @throws IllegalArgumentException if array is null * @throws IllegalArgumentException if array is empty * @see IEEE754rUtils#max(double[]) IEEE754rUtils for a version of this method that handles NaN differently */ public static double max(double[] array) { // Validates input if (array== null) { throw new IllegalArgumentException("The Array must not be null"); } else if (array.length == 0) { throw new IllegalArgumentException("Array cannot be empty."); } // Finds and returns max double max = array[0]; for (int j = 1; j < array.length; j++) { if (Double.isNaN(array[j])) { return Double.NaN; } if (array[j] > max) { max = array[j]; } } return max; } /** *

Returns the maximum value in an array.

* * @param array an array, must not be null or empty * @return the minimum value in the array * @throws IllegalArgumentException if array is null * @throws IllegalArgumentException if array is empty * @see IEEE754rUtils#max(float[]) IEEE754rUtils for a version of this method that handles NaN differently */ public static float max(float[] array) { // Validates input if (array == null) { throw new IllegalArgumentException("The Array must not be null"); } else if (array.length == 0) { throw new IllegalArgumentException("Array cannot be empty."); } // Finds and returns max float max = array[0]; for (int j = 1; j < array.length; j++) { if (Float.isNaN(array[j])) { return Float.NaN; } if (array[j] > max) { max = array[j]; } } return max; } // 3 param min //----------------------------------------------------------------------- /** *

Gets the minimum of three long values.

* * @param a value 1 * @param b value 2 * @param c value 3 * @return the smallest of the values */ public static long min(long a, long b, long c) { if (b < a) { a = b; } if (c < a) { a = c; } return a; } /** *

Gets the minimum of three int values.

* * @param a value 1 * @param b value 2 * @param c value 3 * @return the smallest of the values */ public static int min(int a, int b, int c) { if (b < a) { a = b; } if (c < a) { a = c; } return a; } /** *

Gets the minimum of three short values.

* * @param a value 1 * @param b value 2 * @param c value 3 * @return the smallest of the values */ public static short min(short a, short b, short c) { if (b < a) { a = b; } if (c < a) { a = c; } return a; } /** *

Gets the minimum of three byte values.

* * @param a value 1 * @param b value 2 * @param c value 3 * @return the smallest of the values */ public static byte min(byte a, byte b, byte c) { if (b < a) { a = b; } if (c < a) { a = c; } return a; } /** *

Gets the minimum of three double values.

* *

If any value is NaN, NaN is * returned. Infinity is handled.

* * @param a value 1 * @param b value 2 * @param c value 3 * @return the smallest of the values * @see IEEE754rUtils#min(double, double, double) for a version of this method that handles NaN differently */ public static double min(double a, double b, double c) { return Math.min(Math.min(a, b), c); } /** *

Gets the minimum of three float values.

* *

If any value is NaN, NaN is * returned. Infinity is handled.

* * @param a value 1 * @param b value 2 * @param c value 3 * @return the smallest of the values * @see IEEE754rUtils#min(float, float, float) for a version of this method that handles NaN differently */ public static float min(float a, float b, float c) { return Math.min(Math.min(a, b), c); } // 3 param max //----------------------------------------------------------------------- /** *

Gets the maximum of three long values.

* * @param a value 1 * @param b value 2 * @param c value 3 * @return the largest of the values */ public static long max(long a, long b, long c) { if (b > a) { a = b; } if (c > a) { a = c; } return a; } /** *

Gets the maximum of three int values.

* * @param a value 1 * @param b value 2 * @param c value 3 * @return the largest of the values */ public static int max(int a, int b, int c) { if (b > a) { a = b; } if (c > a) { a = c; } return a; } /** *

Gets the maximum of three short values.

* * @param a value 1 * @param b value 2 * @param c value 3 * @return the largest of the values */ public static short max(short a, short b, short c) { if (b > a) { a = b; } if (c > a) { a = c; } return a; } /** *

Gets the maximum of three byte values.

* * @param a value 1 * @param b value 2 * @param c value 3 * @return the largest of the values */ public static byte max(byte a, byte b, byte c) { if (b > a) { a = b; } if (c > a) { a = c; } return a; } /** *

Gets the maximum of three double values.

* *

If any value is NaN, NaN is * returned. Infinity is handled.

* * @param a value 1 * @param b value 2 * @param c value 3 * @return the largest of the values * @see IEEE754rUtils#max(double, double, double) for a version of this method that handles NaN differently */ public static double max(double a, double b, double c) { return Math.max(Math.max(a, b), c); } /** *

Gets the maximum of three float values.

* *

If any value is NaN, NaN is * returned. Infinity is handled.

* * @param a value 1 * @param b value 2 * @param c value 3 * @return the largest of the values * @see IEEE754rUtils#max(float, float, float) for a version of this method that handles NaN differently */ public static float max(float a, float b, float c) { return Math.max(Math.max(a, b), c); } //----------------------------------------------------------------------- /** *

Compares two doubles for order.

* *

This method is more comprehensive than the standard Java greater * than, less than and equals operators.

*
    *
  • It returns -1 if the first value is less than the second.
  • *
  • It returns +1 if the first value is greater than the second.
  • *
  • It returns 0 if the values are equal.
  • *
* *

* The ordering is as follows, largest to smallest: *

    *
  • NaN *
  • Positive infinity *
  • Maximum double *
  • Normal positive numbers *
  • +0.0 *
  • -0.0 *
  • Normal negative numbers *
  • Minimum double (-Double.MAX_VALUE) *
  • Negative infinity *
*

* *

Comparing NaN with NaN will * return 0.

* * @param lhs the first double * @param rhs the second double * @return -1 if lhs is less, +1 if greater, * 0 if equal to rhs */ public static int compare(double lhs, double rhs) { if (lhs < rhs) { return -1; } if (lhs > rhs) { return +1; } // Need to compare bits to handle 0.0 == -0.0 being true // compare should put -0.0 < +0.0 // Two NaNs are also == for compare purposes // where NaN == NaN is false long lhsBits = Double.doubleToLongBits(lhs); long rhsBits = Double.doubleToLongBits(rhs); if (lhsBits == rhsBits) { return 0; } // Something exotic! A comparison to NaN or 0.0 vs -0.0 // Fortunately NaN's long is > than everything else // Also negzeros bits < poszero // NAN: 9221120237041090560 // MAX: 9218868437227405311 // NEGZERO: -9223372036854775808 if (lhsBits < rhsBits) { return -1; } else { return +1; } } /** *

Compares two floats for order.

* *

This method is more comprehensive than the standard Java greater than, * less than and equals operators.

*
    *
  • It returns -1 if the first value is less than the second. *
  • It returns +1 if the first value is greater than the second. *
  • It returns 0 if the values are equal. *
* *

The ordering is as follows, largest to smallest: *

    *
  • NaN *
  • Positive infinity *
  • Maximum float *
  • Normal positive numbers *
  • +0.0 *
  • -0.0 *
  • Normal negative numbers *
  • Minimum float (-Float.MAX_VALUE) *
  • Negative infinity *
* *

Comparing NaN with NaN will return * 0.

* * @param lhs the first float * @param rhs the second float * @return -1 if lhs is less, +1 if greater, * 0 if equal to rhs */ public static int compare(float lhs, float rhs) { if (lhs < rhs) { return -1; } if (lhs > rhs) { return +1; } //Need to compare bits to handle 0.0 == -0.0 being true // compare should put -0.0 < +0.0 // Two NaNs are also == for compare purposes // where NaN == NaN is false int lhsBits = Float.floatToIntBits(lhs); int rhsBits = Float.floatToIntBits(rhs); if (lhsBits == rhsBits) { return 0; } //Something exotic! A comparison to NaN or 0.0 vs -0.0 //Fortunately NaN's int is > than everything else //Also negzeros bits < poszero //NAN: 2143289344 //MAX: 2139095039 //NEGZERO: -2147483648 if (lhsBits < rhsBits) { return -1; } else { return +1; } } //----------------------------------------------------------------------- /** *

Checks whether the String contains only * digit characters.

* *

Null and empty String will return * false.

* * @param str the String to check * @return true if str contains only unicode numeric */ public static boolean isDigits(String str) { if (StringUtils.isEmpty(str)) { return false; } for (int i = 0; i < str.length(); i++) { if (!Character.isDigit(str.charAt(i))) { return false; } } return true; } /** *

Checks whether the String a valid Java number.

* *

Valid numbers include hexadecimal marked with the 0x * qualifier, scientific notation and numbers marked with a type * qualifier (e.g. 123L).

* *

Null and empty String will return * false.

* * @param str the String to check * @return true if the string is a correctly formatted number */ public static boolean isNumber(String str) { if (StringUtils.isEmpty(str)) { return false; } char[] chars = str.toCharArray(); int sz = chars.length; boolean hasExp = false; boolean hasDecPoint = false; boolean allowSigns = false; boolean foundDigit = false; // deal with any possible sign up front int start = (chars[0] == '-') ? 1 : 0; if (sz > start + 1) { if (chars[start] == '0' && chars[start + 1] == 'x') { int i = start + 2; if (i == sz) { return false; // str == "0x" } // checking hex (it can't be anything else) for (; i < chars.length; i++) { if ((chars[i] < '0' || chars[i] > '9') && (chars[i] < 'a' || chars[i] > 'f') && (chars[i] < 'A' || chars[i] > 'F')) { return false; } } return true; } } sz--; // don't want to loop to the last char, check it afterwords // for type qualifiers int i = start; // loop to the next to last char or to the last char if we need another digit to // make a valid number (e.g. chars[0..5] = "1234E") while (i < sz || (i < sz + 1 && allowSigns && !foundDigit)) { if (chars[i] >= '0' && chars[i] <= '9') { foundDigit = true; allowSigns = false; } else if (chars[i] == '.') { if (hasDecPoint || hasExp) { // two decimal points or dec in exponent return false; } hasDecPoint = true; } else if (chars[i] == 'e' || chars[i] == 'E') { // we've already taken care of hex. if (hasExp) { // two E's return false; } if (!foundDigit) { return false; } hasExp = true; allowSigns = true; } else if (chars[i] == '+' || chars[i] == '-') { if (!allowSigns) { return false; } allowSigns = false; foundDigit = false; // we need a digit after the E } else { return false; } i++; } if (i < chars.length) { if (chars[i] >= '0' && chars[i] <= '9') { // no type qualifier, OK return true; } if (chars[i] == 'e' || chars[i] == 'E') { // can't have an E at the last byte return false; } if (chars[i] == '.') { if (hasDecPoint || hasExp) { // two decimal points or dec in exponent return false; } // single trailing decimal point after non-exponent is ok return foundDigit; } if (!allowSigns && (chars[i] == 'd' || chars[i] == 'D' || chars[i] == 'f' || chars[i] == 'F')) { return foundDigit; } if (chars[i] == 'l' || chars[i] == 'L') { // not allowing L with an exponent return foundDigit && !hasExp; } // last character is illegal return false; } // allowSigns is true iff the val ends in 'E' // found digit it to make sure weird stuff like '.' and '1E-' doesn't pass return !allowSigns && foundDigit; } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/math/package.html100644 0 0 2170 11513702442 24140 0ustar 0 0 Extends {@link java.math} for business mathematical classes. This package is intended for business mathematical use, not scientific use. See Commons Math for a more complete set of mathematical classes. @since 2.0

These classes are immutable, and therefore thread-safe.

commons-lang-2.6-src/src/main/java/org/apache/commons/lang/math/RandomUtils.java100644 0 0 13127 11513702442 25007 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "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 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.commons.lang.math; import java.util.Random; /** *

RandomUtils is a wrapper that supports all possible * {@link java.util.Random} methods via the {@link java.lang.Math#random()} * method and its system-wide Random object. * * @author Gary D. Gregory * @since 2.0 * @version $Id: RandomUtils.java 906320 2010-02-04 01:41:10Z sebb $ */ public class RandomUtils { /** * An instance of {@link JVMRandom}. */ public static final Random JVM_RANDOM = new JVMRandom(); // should be possible for JVM_RANDOM? // public static void nextBytes(byte[]) { // public synchronized double nextGaussian(); // } /** *

Returns the next pseudorandom, uniformly distributed int value * from the Math.random() sequence.

* N.B. All values are >= 0. * @return the random int */ public static int nextInt() { return nextInt(JVM_RANDOM); } /** *

Returns the next pseudorandom, uniformly distributed int value * from the given random sequence.

* * @param random the Random sequence generator. * @return the random int */ public static int nextInt(Random random) { return random.nextInt(); } /** *

Returns a pseudorandom, uniformly distributed int value * between 0 (inclusive) and the specified value * (exclusive), from the Math.random() sequence.

* * @param n the specified exclusive max-value * @return the random int */ public static int nextInt(int n) { return nextInt(JVM_RANDOM, n); } /** *

Returns a pseudorandom, uniformly distributed int value * between 0 (inclusive) and the specified value * (exclusive), from the given Random sequence.

* * @param random the Random sequence generator. * @param n the specified exclusive max-value * @return the random int */ public static int nextInt(Random random, int n) { // check this cannot return 'n' return random.nextInt(n); } /** *

Returns the next pseudorandom, uniformly distributed long value * from the Math.random() sequence.

* N.B. All values are >= 0. * @return the random long */ public static long nextLong() { return nextLong(JVM_RANDOM); } /** *

Returns the next pseudorandom, uniformly distributed long value * from the given Random sequence.

* * @param random the Random sequence generator. * @return the random long */ public static long nextLong(Random random) { return random.nextLong(); } /** *

Returns the next pseudorandom, uniformly distributed boolean value * from the Math.random() sequence.

* * @return the random boolean */ public static boolean nextBoolean() { return nextBoolean(JVM_RANDOM); } /** *

Returns the next pseudorandom, uniformly distributed boolean value * from the given random sequence.

* * @param random the Random sequence generator. * @return the random boolean */ public static boolean nextBoolean(Random random) { return random.nextBoolean(); } /** *

Returns the next pseudorandom, uniformly distributed float value * between 0.0 and 1.0 from the Math.random() * sequence.

* * @return the random float */ public static float nextFloat() { return nextFloat(JVM_RANDOM); } /** *

Returns the next pseudorandom, uniformly distributed float value * between 0.0 and 1.0 from the given Random * sequence.

* * @param random the Random sequence generator. * @return the random float */ public static float nextFloat(Random random) { return random.nextFloat(); } /** *

Returns the next pseudorandom, uniformly distributed float value * between 0.0 and 1.0 from the Math.random() * sequence.

* * @return the random double */ public static double nextDouble() { return nextDouble(JVM_RANDOM); } /** *

Returns the next pseudorandom, uniformly distributed float value * between 0.0 and 1.0 from the given Random * sequence.

* * @param random the Random sequence generator. * @return the random double */ public static double nextDouble(Random random) { return random.nextDouble(); } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/math/Range.java100644 0 0 37123 11513702442 23604 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.math; import org.apache.commons.lang.text.StrBuilder; /** *

Range represents a range of numbers of the same type.

* *

Specific subclasses hold the range values as different types. Each * subclass should be immutable and {@link java.io.Serializable Serializable} * if possible.

* * @author Apache Software Foundation * @since 2.0 * @version $Id: Range.java 1057072 2011-01-10 01:55:57Z niallp $ */ public abstract class Range { /** *

Constructs a new range.

*/ public Range() { super(); } // Accessors //-------------------------------------------------------------------- /** *

Gets the minimum number in this range.

* * @return the minimum number in this range */ public abstract Number getMinimumNumber(); /** *

Gets the minimum number in this range as a long.

* *

This implementation uses the {@link #getMinimumNumber()} method. * Subclasses may be able to optimise this.

* * @return the minimum number in this range */ public long getMinimumLong() { return getMinimumNumber().longValue(); } /** *

Gets the minimum number in this range as a int.

* *

This implementation uses the {@link #getMinimumNumber()} method. * Subclasses may be able to optimise this.

* * @return the minimum number in this range */ public int getMinimumInteger() { return getMinimumNumber().intValue(); } /** *

Gets the minimum number in this range as a double.

* *

This implementation uses the {@link #getMinimumNumber()} method. * Subclasses may be able to optimise this.

* * @return the minimum number in this range */ public double getMinimumDouble() { return getMinimumNumber().doubleValue(); } /** *

Gets the minimum number in this range as a float.

* *

This implementation uses the {@link #getMinimumNumber()} method. * Subclasses may be able to optimise this.

* * @return the minimum number in this range */ public float getMinimumFloat() { return getMinimumNumber().floatValue(); } /** *

Gets the maximum number in this range.

* * @return the maximum number in this range */ public abstract Number getMaximumNumber(); /** *

Gets the maximum number in this range as a long.

* *

This implementation uses the {@link #getMaximumNumber()} method. * Subclasses may be able to optimise this.

* * @return the maximum number in this range */ public long getMaximumLong() { return getMaximumNumber().longValue(); } /** *

Gets the maximum number in this range as a int.

* *

This implementation uses the {@link #getMaximumNumber()} method. * Subclasses may be able to optimise this.

* * @return the maximum number in this range */ public int getMaximumInteger() { return getMaximumNumber().intValue(); } /** *

Gets the maximum number in this range as a double.

* *

This implementation uses the {@link #getMaximumNumber()} method. * Subclasses may be able to optimise this.

* * @return the maximum number in this range */ public double getMaximumDouble() { return getMaximumNumber().doubleValue(); } /** *

Gets the maximum number in this range as a float.

* *

This implementation uses the {@link #getMaximumNumber()} method. * Subclasses may be able to optimise this.

* * @return the maximum number in this range */ public float getMaximumFloat() { return getMaximumNumber().floatValue(); } // Include tests //-------------------------------------------------------------------- /** *

Tests whether the specified Number occurs within * this range.

* *

The exact comparison implementation varies by subclass. It is * intended that an int specific subclass will compare using * int comparison.

* *

null is handled and returns false.

* * @param number the number to test, may be null * @return true if the specified number occurs within this range * @throws IllegalArgumentException if the Number cannot be compared */ public abstract boolean containsNumber(Number number); /** *

Tests whether the specified Number occurs within * this range using long comparison..

* *

null is handled and returns false.

* *

This implementation forwards to the {@link #containsLong(long)} method.

* * @param value the long to test, may be null * @return true if the specified number occurs within this * range by long comparison */ public boolean containsLong(Number value) { if (value == null) { return false; } return containsLong(value.longValue()); } /** *

Tests whether the specified long occurs within * this range using long comparison.

* *

This implementation uses the {@link #getMinimumLong()} and * {@link #getMaximumLong()} methods and should be good for most uses.

* * @param value the long to test * @return true if the specified number occurs within this * range by long comparison */ public boolean containsLong(long value) { return value >= getMinimumLong() && value <= getMaximumLong(); } /** *

Tests whether the specified Number occurs within * this range using int comparison..

* *

null is handled and returns false.

* *

This implementation forwards to the {@link #containsInteger(int)} method.

* * @param value the integer to test, may be null * @return true if the specified number occurs within this * range by int comparison */ public boolean containsInteger(Number value) { if (value == null) { return false; } return containsInteger(value.intValue()); } /** *

Tests whether the specified int occurs within * this range using int comparison.

* *

This implementation uses the {@link #getMinimumInteger()} and * {@link #getMaximumInteger()} methods and should be good for most uses.

* * @param value the int to test * @return true if the specified number occurs within this * range by int comparison */ public boolean containsInteger(int value) { return value >= getMinimumInteger() && value <= getMaximumInteger(); } /** *

Tests whether the specified Number occurs within * this range using double comparison..

* *

null is handled and returns false.

* *

This implementation forwards to the {@link #containsDouble(double)} method.

* * @param value the double to test, may be null * @return true if the specified number occurs within this * range by double comparison */ public boolean containsDouble(Number value) { if (value == null) { return false; } return containsDouble(value.doubleValue()); } /** *

Tests whether the specified double occurs within * this range using double comparison.

* *

This implementation uses the {@link #getMinimumDouble()} and * {@link #getMaximumDouble()} methods and should be good for most uses.

* * @param value the double to test * @return true if the specified number occurs within this * range by double comparison */ public boolean containsDouble(double value) { int compareMin = NumberUtils.compare(getMinimumDouble(), value); int compareMax = NumberUtils.compare(getMaximumDouble(), value); return compareMin <= 0 && compareMax >= 0; } /** *

Tests whether the specified Number occurs within * this range using float comparison.

* *

null is handled and returns false.

* *

This implementation forwards to the {@link #containsFloat(float)} method.

* * @param value the float to test, may be null * @return true if the specified number occurs within this * range by float comparison */ public boolean containsFloat(Number value) { if (value == null) { return false; } return containsFloat(value.floatValue()); } /** *

Tests whether the specified float occurs within * this range using float comparison.

* *

This implementation uses the {@link #getMinimumFloat()} and * {@link #getMaximumFloat()} methods and should be good for most uses.

* * @param value the float to test * @return true if the specified number occurs within this * range by float comparison */ public boolean containsFloat(float value) { int compareMin = NumberUtils.compare(getMinimumFloat(), value); int compareMax = NumberUtils.compare(getMaximumFloat(), value); return compareMin <= 0 && compareMax >= 0; } // Range tests //-------------------------------------------------------------------- /** *

Tests whether the specified range occurs entirely within this range.

* *

The exact comparison implementation varies by subclass. It is * intended that an int specific subclass will compare using * int comparison.

* *

null is handled and returns false.

* *

This implementation uses the {@link #containsNumber(Number)} method. * Subclasses may be able to optimise this.

* * @param range the range to test, may be null * @return true if the specified range occurs entirely within * this range; otherwise, false * @throws IllegalArgumentException if the Range cannot be compared */ public boolean containsRange(Range range) { if (range == null) { return false; } return containsNumber(range.getMinimumNumber()) && containsNumber(range.getMaximumNumber()); } /** *

Tests whether the specified range overlaps with this range.

* *

The exact comparison implementation varies by subclass. It is * intended that an int specific subclass will compare using * int comparison.

* *

null is handled and returns false.

* *

This implementation uses the {@link #containsNumber(Number)} and * {@link #containsRange(Range)} methods. * Subclasses may be able to optimise this.

* * @param range the range to test, may be null * @return true if the specified range overlaps with this * range; otherwise, false * @throws IllegalArgumentException if the Range cannot be compared */ public boolean overlapsRange(Range range) { if (range == null) { return false; } return range.containsNumber(getMinimumNumber()) || range.containsNumber(getMaximumNumber()) || containsNumber(range.getMinimumNumber()); } // Basics //-------------------------------------------------------------------- /** *

Compares this range to another object to test if they are equal.

. * *

To be equal, the class, minimum and maximum must be equal.

* *

This implementation uses the {@link #getMinimumNumber()} and * {@link #getMaximumNumber()} methods. * Subclasses may be able to optimise this.

* * @param obj the reference object with which to compare * @return true if this object is equal */ public boolean equals(Object obj) { if (obj == this) { return true; } else if (obj == null || obj.getClass() != getClass()) { return false; } else { Range range = (Range) obj; return getMinimumNumber().equals(range.getMinimumNumber()) && getMaximumNumber().equals(range.getMaximumNumber()); } } /** *

Gets a hashCode for the range.

* *

This implementation uses the {@link #getMinimumNumber()} and * {@link #getMaximumNumber()} methods. * Subclasses may be able to optimise this.

* * @return a hash code value for this object */ public int hashCode() { int result = 17; result = 37 * result + getClass().hashCode(); result = 37 * result + getMinimumNumber().hashCode(); result = 37 * result + getMaximumNumber().hashCode(); return result; } /** *

Gets the range as a String.

* *

The format of the String is 'Range[min,max]'.

* *

This implementation uses the {@link #getMinimumNumber()} and * {@link #getMaximumNumber()} methods. * Subclasses may be able to optimise this.

* * @return the String representation of this range */ public String toString() { StrBuilder buf = new StrBuilder(32); buf.append("Range["); buf.append(getMinimumNumber()); buf.append(','); buf.append(getMaximumNumber()); buf.append(']'); return buf.toString(); } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/mutable/Mutable.java100644 0 0 3754 11513702444 24626 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.mutable; /** * Provides mutable access to a value. *

* Mutable is used as a generic interface to the implementations in this package. *

* A typical use case would be to enable a primitive or string to be passed to a method and allow that method to * effectively change the value of the primitive/string. Another use case is to store a frequently changing primitive in * a collection (for example a total in a map) without needing to create new Integer/Long wrapper objects. * * @author Apache Software Foundation * @author Matthew Hawthorne * @since 2.1 * @version $Id: Mutable.java 905636 2010-02-02 14:03:32Z niallp $ */ public interface Mutable { /** * Gets the value of this mutable. * * @return the stored value */ Object getValue(); /** * Sets the value of this mutable. * * @param value * the value to store * @throws NullPointerException * if the object is null and null is invalid * @throws ClassCastException * if the type is invalid */ void setValue(Object value); } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/mutable/MutableBoolean.java100644 0 0 13653 11513702444 26145 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.mutable; import java.io.Serializable; import org.apache.commons.lang.BooleanUtils; /** * A mutable boolean wrapper. * * @see Boolean * @since 2.2 * @author Apache Software Foundation * @version $Id: MutableBoolean.java 905707 2010-02-02 16:59:59Z niallp $ */ public class MutableBoolean implements Mutable, Serializable, Comparable { /** * Required for serialization support. * * @see java.io.Serializable */ private static final long serialVersionUID = -4830728138360036487L; /** The mutable value. */ private boolean value; /** * Constructs a new MutableBoolean with the default value of false. */ public MutableBoolean() { super(); } /** * Constructs a new MutableBoolean with the specified value. * * @param value the initial value to store */ public MutableBoolean(boolean value) { super(); this.value = value; } /** * Constructs a new MutableBoolean with the specified value. * * @param value the initial value to store, not null * @throws NullPointerException if the object is null */ public MutableBoolean(Boolean value) { super(); this.value = value.booleanValue(); } //----------------------------------------------------------------------- /** * Gets the value as a Boolean instance. * * @return the value as a Boolean, never null */ public Object getValue() { return BooleanUtils.toBooleanObject(this.value); } /** * Sets the value. * * @param value the value to set */ public void setValue(boolean value) { this.value = value; } /** * Sets the value from any Boolean instance. * * @param value the value to set, not null * @throws NullPointerException if the object is null */ public void setValue(Object value) { setValue(((Boolean) value).booleanValue()); } //----------------------------------------------------------------------- /** * Checks if the current value is true. * * @return true if the current value is true * @since 2.5 */ public boolean isTrue() { return value == true; } /** * Checks if the current value is false. * * @return true if the current value is false * @since 2.5 */ public boolean isFalse() { return value == false; } //----------------------------------------------------------------------- /** * Returns the value of this MutableBoolean as a boolean. * * @return the boolean value represented by this object. */ public boolean booleanValue() { return value; } //----------------------------------------------------------------------- /** * Gets this mutable as an instance of Boolean. * * @return a Boolean instance containing the value from this mutable, never null * @since 2.5 */ public Boolean toBoolean() { return BooleanUtils.toBooleanObject(this.value); } //----------------------------------------------------------------------- /** * Compares this object to the specified object. The result is true if and only if the argument is * not null and is an MutableBoolean object that contains the same * boolean value as this object. * * @param obj the object to compare with, null returns false * @return true if the objects are the same; false otherwise. */ public boolean equals(Object obj) { if (obj instanceof MutableBoolean) { return value == ((MutableBoolean) obj).booleanValue(); } return false; } /** * Returns a suitable hash code for this mutable. * * @return the hash code returned by Boolean.TRUE or Boolean.FALSE */ public int hashCode() { return value ? Boolean.TRUE.hashCode() : Boolean.FALSE.hashCode(); } //----------------------------------------------------------------------- /** * Compares this mutable to another in ascending order. * * @param obj the other mutable to compare to, not null * @return negative if this is less, zero if equal, positive if greater * where false is less than true */ public int compareTo(Object obj) { MutableBoolean other = (MutableBoolean) obj; boolean anotherVal = other.value; return value == anotherVal ? 0 : (value ? 1 : -1); } //----------------------------------------------------------------------- /** * Returns the String value of this mutable. * * @return the mutable value as a string */ public String toString() { return String.valueOf(value); } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/mutable/MutableByte.java100644 0 0 20042 11513702444 25457 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.mutable; /** * A mutable byte wrapper. * * @see Byte * @since 2.1 * @author Apache Software Foundation * @version $Id: MutableByte.java 905707 2010-02-02 16:59:59Z niallp $ */ public class MutableByte extends Number implements Comparable, Mutable { /** * Required for serialization support. * * @see java.io.Serializable */ private static final long serialVersionUID = -1585823265L; /** The mutable value. */ private byte value; /** * Constructs a new MutableByte with the default value of zero. */ public MutableByte() { super(); } /** * Constructs a new MutableByte with the specified value. * * @param value the initial value to store */ public MutableByte(byte value) { super(); this.value = value; } /** * Constructs a new MutableByte with the specified value. * * @param value the initial value to store, not null * @throws NullPointerException if the object is null */ public MutableByte(Number value) { super(); this.value = value.byteValue(); } /** * Constructs a new MutableByte parsing the given string. * * @param value the string to parse, not null * @throws NumberFormatException if the string cannot be parsed into a byte * @since 2.5 */ public MutableByte(String value) throws NumberFormatException { super(); this.value = Byte.parseByte(value); } //----------------------------------------------------------------------- /** * Gets the value as a Byte instance. * * @return the value as a Byte, never null */ public Object getValue() { return new Byte(this.value); } /** * Sets the value. * * @param value the value to set */ public void setValue(byte value) { this.value = value; } /** * Sets the value from any Number instance. * * @param value the value to set, not null * @throws NullPointerException if the object is null * @throws ClassCastException if the type is not a {@link Number} */ public void setValue(Object value) { setValue(((Number) value).byteValue()); } //----------------------------------------------------------------------- /** * Increments the value. * * @since Commons Lang 2.2 */ public void increment() { value++; } /** * Decrements the value. * * @since Commons Lang 2.2 */ public void decrement() { value--; } //----------------------------------------------------------------------- /** * Adds a value to the value of this instance. * * @param operand the value to add, not null * @since Commons Lang 2.2 */ public void add(byte operand) { this.value += operand; } /** * Adds a value to the value of this instance. * * @param operand the value to add, not null * @throws NullPointerException if the object is null * @since Commons Lang 2.2 */ public void add(Number operand) { this.value += operand.byteValue(); } /** * Subtracts a value from the value of this instance. * * @param operand the value to subtract, not null * @since Commons Lang 2.2 */ public void subtract(byte operand) { this.value -= operand; } /** * Subtracts a value from the value of this instance. * * @param operand the value to subtract, not null * @throws NullPointerException if the object is null * @since Commons Lang 2.2 */ public void subtract(Number operand) { this.value -= operand.byteValue(); } //----------------------------------------------------------------------- // shortValue relies on Number implementation /** * Returns the value of this MutableByte as a byte. * * @return the numeric value represented by this object after conversion to type byte. */ public byte byteValue() { return value; } /** * Returns the value of this MutableByte as an int. * * @return the numeric value represented by this object after conversion to type int. */ public int intValue() { return value; } /** * Returns the value of this MutableByte as a long. * * @return the numeric value represented by this object after conversion to type long. */ public long longValue() { return value; } /** * Returns the value of this MutableByte as a float. * * @return the numeric value represented by this object after conversion to type float. */ public float floatValue() { return value; } /** * Returns the value of this MutableByte as a double. * * @return the numeric value represented by this object after conversion to type double. */ public double doubleValue() { return value; } //----------------------------------------------------------------------- /** * Gets this mutable as an instance of Byte. * * @return a Byte instance containing the value from this mutable */ public Byte toByte() { return new Byte(byteValue()); } //----------------------------------------------------------------------- /** * Compares this object to the specified object. The result is true if and only if the argument is * not null and is a MutableByte object that contains the same byte value * as this object. * * @param obj the object to compare with, null returns false * @return true if the objects are the same; false otherwise. */ public boolean equals(Object obj) { if (obj instanceof MutableByte) { return value == ((MutableByte) obj).byteValue(); } return false; } /** * Returns a suitable hash code for this mutable. * * @return a suitable hash code */ public int hashCode() { return value; } //----------------------------------------------------------------------- /** * Compares this mutable to another in ascending order. * * @param obj the other mutable to compare to, not null * @return negative if this is less, zero if equal, positive if greater * @throws ClassCastException if the argument is not a MutableByte */ public int compareTo(Object obj) { MutableByte other = (MutableByte) obj; byte anotherVal = other.value; return value < anotherVal ? -1 : (value == anotherVal ? 0 : 1); } //----------------------------------------------------------------------- /** * Returns the String value of this mutable. * * @return the mutable value as a string */ public String toString() { return String.valueOf(value); } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/mutable/MutableDouble.java100644 0 0 23430 11513702444 25772 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.mutable; import org.apache.commons.lang.math.NumberUtils; /** * A mutable double wrapper. * * @see Double * @since 2.1 * @author Apache Software Foundation * @version $Id: MutableDouble.java 905707 2010-02-02 16:59:59Z niallp $ */ public class MutableDouble extends Number implements Comparable, Mutable { /** * Required for serialization support. * * @see java.io.Serializable */ private static final long serialVersionUID = 1587163916L; /** The mutable value. */ private double value; /** * Constructs a new MutableDouble with the default value of zero. */ public MutableDouble() { super(); } /** * Constructs a new MutableDouble with the specified value. * * @param value the initial value to store */ public MutableDouble(double value) { super(); this.value = value; } /** * Constructs a new MutableDouble with the specified value. * * @param value the initial value to store, not null * @throws NullPointerException if the object is null */ public MutableDouble(Number value) { super(); this.value = value.doubleValue(); } /** * Constructs a new MutableDouble parsing the given string. * * @param value the string to parse, not null * @throws NumberFormatException if the string cannot be parsed into a double * @since 2.5 */ public MutableDouble(String value) throws NumberFormatException { super(); this.value = Double.parseDouble(value); } //----------------------------------------------------------------------- /** * Gets the value as a Double instance. * * @return the value as a Double, never null */ public Object getValue() { return new Double(this.value); } /** * Sets the value. * * @param value the value to set */ public void setValue(double value) { this.value = value; } /** * Sets the value from any Number instance. * * @param value the value to set, not null * @throws NullPointerException if the object is null * @throws ClassCastException if the type is not a {@link Number} */ public void setValue(Object value) { setValue(((Number) value).doubleValue()); } //----------------------------------------------------------------------- /** * Checks whether the double value is the special NaN value. * * @return true if NaN */ public boolean isNaN() { return Double.isNaN(value); } /** * Checks whether the double value is infinite. * * @return true if infinite */ public boolean isInfinite() { return Double.isInfinite(value); } //----------------------------------------------------------------------- /** * Increments the value. * * @since Commons Lang 2.2 */ public void increment() { value++; } /** * Decrements the value. * * @since Commons Lang 2.2 */ public void decrement() { value--; } //----------------------------------------------------------------------- /** * Adds a value to the value of this instance. * * @param operand the value to add * @since Commons Lang 2.2 */ public void add(double operand) { this.value += operand; } /** * Adds a value to the value of this instance. * * @param operand the value to add, not null * @throws NullPointerException if the object is null * @since Commons Lang 2.2 */ public void add(Number operand) { this.value += operand.doubleValue(); } /** * Subtracts a value from the value of this instance. * * @param operand the value to subtract, not null * @since Commons Lang 2.2 */ public void subtract(double operand) { this.value -= operand; } /** * Subtracts a value from the value of this instance. * * @param operand the value to subtract, not null * @throws NullPointerException if the object is null * @since Commons Lang 2.2 */ public void subtract(Number operand) { this.value -= operand.doubleValue(); } //----------------------------------------------------------------------- // shortValue and bytValue rely on Number implementation /** * Returns the value of this MutableDouble as an int. * * @return the numeric value represented by this object after conversion to type int. */ public int intValue() { return (int) value; } /** * Returns the value of this MutableDouble as a long. * * @return the numeric value represented by this object after conversion to type long. */ public long longValue() { return (long) value; } /** * Returns the value of this MutableDouble as a float. * * @return the numeric value represented by this object after conversion to type float. */ public float floatValue() { return (float) value; } /** * Returns the value of this MutableDouble as a double. * * @return the numeric value represented by this object after conversion to type double. */ public double doubleValue() { return value; } //----------------------------------------------------------------------- /** * Gets this mutable as an instance of Double. * * @return a Double instance containing the value from this mutable, never null */ public Double toDouble() { return new Double(doubleValue()); } //----------------------------------------------------------------------- /** * Compares this object against the specified object. The result is true if and only if the argument * is not null and is a Double object that represents a double that has the identical * bit pattern to the bit pattern of the double represented by this object. For this purpose, two * double values are considered to be the same if and only if the method * {@link Double#doubleToLongBits(double)}returns the same long value when applied to each. *

* Note that in most cases, for two instances of class Double,d1 and d2, * the value of d1.equals(d2) is true if and only if

* *
     *   d1.doubleValue() == d2.doubleValue()
     * 
* *
*

* also has the value true. However, there are two exceptions: *

    *
  • If d1 and d2 both represent Double.NaN, then the * equals method returns true, even though Double.NaN==Double.NaN has * the value false. *
  • If d1 represents +0.0 while d2 represents -0.0, * or vice versa, the equal test has the value false, even though * +0.0==-0.0 has the value true. This allows hashtables to operate properly. *
* * @param obj the object to compare with, null returns false * @return true if the objects are the same; false otherwise. */ public boolean equals(Object obj) { return (obj instanceof MutableDouble) && (Double.doubleToLongBits(((MutableDouble) obj).value) == Double.doubleToLongBits(value)); } /** * Returns a suitable hash code for this mutable. * * @return a suitable hash code */ public int hashCode() { long bits = Double.doubleToLongBits(value); return (int) (bits ^ (bits >>> 32)); } //----------------------------------------------------------------------- /** * Compares this mutable to another in ascending order. * * @param obj the other mutable to compare to, not null * @return negative if this is less, zero if equal, positive if greater * @throws ClassCastException if the argument is not a MutableDouble */ public int compareTo(Object obj) { MutableDouble other = (MutableDouble) obj; double anotherVal = other.value; return NumberUtils.compare(value, anotherVal); } //----------------------------------------------------------------------- /** * Returns the String value of this mutable. * * @return the mutable value as a string */ public String toString() { return String.valueOf(value); } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/mutable/MutableFloat.java100644 0 0 23233 11513702444 25626 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.mutable; import org.apache.commons.lang.math.NumberUtils; /** * A mutable float wrapper. * * @see Float * @since 2.1 * @author Apache Software Foundation * @version $Id: MutableFloat.java 905707 2010-02-02 16:59:59Z niallp $ */ public class MutableFloat extends Number implements Comparable, Mutable { /** * Required for serialization support. * * @see java.io.Serializable */ private static final long serialVersionUID = 5787169186L; /** The mutable value. */ private float value; /** * Constructs a new MutableFloat with the default value of zero. */ public MutableFloat() { super(); } /** * Constructs a new MutableFloat with the specified value. * * @param value the initial value to store */ public MutableFloat(float value) { super(); this.value = value; } /** * Constructs a new MutableFloat with the specified value. * * @param value the initial value to store, not null * @throws NullPointerException if the object is null */ public MutableFloat(Number value) { super(); this.value = value.floatValue(); } /** * Constructs a new MutableFloat parsing the given string. * * @param value the string to parse, not null * @throws NumberFormatException if the string cannot be parsed into a float * @since 2.5 */ public MutableFloat(String value) throws NumberFormatException { super(); this.value = Float.parseFloat(value); } //----------------------------------------------------------------------- /** * Gets the value as a Float instance. * * @return the value as a Float, never null */ public Object getValue() { return new Float(this.value); } /** * Sets the value. * * @param value the value to set */ public void setValue(float value) { this.value = value; } /** * Sets the value from any Number instance. * * @param value the value to set, not null * @throws NullPointerException if the object is null * @throws ClassCastException if the type is not a {@link Number} */ public void setValue(Object value) { setValue(((Number) value).floatValue()); } //----------------------------------------------------------------------- /** * Checks whether the float value is the special NaN value. * * @return true if NaN */ public boolean isNaN() { return Float.isNaN(value); } /** * Checks whether the float value is infinite. * * @return true if infinite */ public boolean isInfinite() { return Float.isInfinite(value); } //----------------------------------------------------------------------- /** * Increments the value. * * @since Commons Lang 2.2 */ public void increment() { value++; } /** * Decrements the value. * * @since Commons Lang 2.2 */ public void decrement() { value--; } //----------------------------------------------------------------------- /** * Adds a value to the value of this instance. * * @param operand the value to add, not null * @since Commons Lang 2.2 */ public void add(float operand) { this.value += operand; } /** * Adds a value to the value of this instance. * * @param operand the value to add, not null * @throws NullPointerException if the object is null * @since Commons Lang 2.2 */ public void add(Number operand) { this.value += operand.floatValue(); } /** * Subtracts a value from the value of this instance. * * @param operand the value to subtract * @since Commons Lang 2.2 */ public void subtract(float operand) { this.value -= operand; } /** * Subtracts a value from the value of this instance. * * @param operand the value to subtract, not null * @throws NullPointerException if the object is null * @since Commons Lang 2.2 */ public void subtract(Number operand) { this.value -= operand.floatValue(); } //----------------------------------------------------------------------- // shortValue and bytValue rely on Number implementation /** * Returns the value of this MutableFloat as an int. * * @return the numeric value represented by this object after conversion to type int. */ public int intValue() { return (int) value; } /** * Returns the value of this MutableFloat as a long. * * @return the numeric value represented by this object after conversion to type long. */ public long longValue() { return (long) value; } /** * Returns the value of this MutableFloat as a float. * * @return the numeric value represented by this object after conversion to type float. */ public float floatValue() { return value; } /** * Returns the value of this MutableFloat as a double. * * @return the numeric value represented by this object after conversion to type double. */ public double doubleValue() { return value; } //----------------------------------------------------------------------- /** * Gets this mutable as an instance of Float. * * @return a Float instance containing the value from this mutable, never null */ public Float toFloat() { return new Float(floatValue()); } //----------------------------------------------------------------------- /** * Compares this object against some other object. The result is true if and only if the argument is * not null and is a Float object that represents a float that has the * identical bit pattern to the bit pattern of the float represented by this object. For this * purpose, two float values are considered to be the same if and only if the method * {@link Float#floatToIntBits(float)}returns the same int value when applied to each. *

* Note that in most cases, for two instances of class Float,f1 and f2, * the value of f1.equals(f2) is true if and only if

* *
     *   f1.floatValue() == f2.floatValue()
     * 
* *
*

* also has the value true. However, there are two exceptions: *

    *
  • If f1 and f2 both represent Float.NaN, then the * equals method returns true, even though Float.NaN==Float.NaN has * the value false. *
  • If f1 represents +0.0f while f2 represents -0.0f, * or vice versa, the equal test has the value false, even though * 0.0f==-0.0f has the value true. *
* This definition allows hashtables to operate properly. * * @param obj the object to compare with, null returns false * @return true if the objects are the same; false otherwise. * @see java.lang.Float#floatToIntBits(float) */ public boolean equals(Object obj) { return (obj instanceof MutableFloat) && (Float.floatToIntBits(((MutableFloat) obj).value) == Float.floatToIntBits(value)); } /** * Returns a suitable hash code for this mutable. * * @return a suitable hash code */ public int hashCode() { return Float.floatToIntBits(value); } //----------------------------------------------------------------------- /** * Compares this mutable to another in ascending order. * * @param obj the other mutable to compare to, not null * @return negative if this is less, zero if equal, positive if greater */ public int compareTo(Object obj) { MutableFloat other = (MutableFloat) obj; float anotherVal = other.value; return NumberUtils.compare(value, anotherVal); } //----------------------------------------------------------------------- /** * Returns the String value of this mutable. * * @return the mutable value as a string */ public String toString() { return String.valueOf(value); } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/mutable/MutableInt.java100644 0 0 17507 11513702444 25322 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.mutable; /** * A mutable int wrapper. * * @see Integer * @since 2.1 * @author Apache Software Foundation * @version $Id: MutableInt.java 905707 2010-02-02 16:59:59Z niallp $ */ public class MutableInt extends Number implements Comparable, Mutable { /** * Required for serialization support. * * @see java.io.Serializable */ private static final long serialVersionUID = 512176391864L; /** The mutable value. */ private int value; /** * Constructs a new MutableInt with the default value of zero. */ public MutableInt() { super(); } /** * Constructs a new MutableInt with the specified value. * * @param value the initial value to store */ public MutableInt(int value) { super(); this.value = value; } /** * Constructs a new MutableInt with the specified value. * * @param value the initial value to store, not null * @throws NullPointerException if the object is null */ public MutableInt(Number value) { super(); this.value = value.intValue(); } /** * Constructs a new MutableInt parsing the given string. * * @param value the string to parse, not null * @throws NumberFormatException if the string cannot be parsed into an int * @since 2.5 */ public MutableInt(String value) throws NumberFormatException { super(); this.value = Integer.parseInt(value); } //----------------------------------------------------------------------- /** * Gets the value as a Integer instance. * * @return the value as a Integer, never null */ public Object getValue() { return new Integer(this.value); } /** * Sets the value. * * @param value the value to set */ public void setValue(int value) { this.value = value; } /** * Sets the value from any Number instance. * * @param value the value to set, not null * @throws NullPointerException if the object is null * @throws ClassCastException if the type is not a {@link Number} */ public void setValue(Object value) { setValue(((Number) value).intValue()); } //----------------------------------------------------------------------- /** * Increments the value. * * @since Commons Lang 2.2 */ public void increment() { value++; } /** * Decrements the value. * * @since Commons Lang 2.2 */ public void decrement() { value--; } //----------------------------------------------------------------------- /** * Adds a value to the value of this instance. * * @param operand the value to add, not null * @since Commons Lang 2.2 */ public void add(int operand) { this.value += operand; } /** * Adds a value to the value of this instance. * * @param operand the value to add, not null * @throws NullPointerException if the object is null * @since Commons Lang 2.2 */ public void add(Number operand) { this.value += operand.intValue(); } /** * Subtracts a value from the value of this instance. * * @param operand the value to subtract, not null * @since Commons Lang 2.2 */ public void subtract(int operand) { this.value -= operand; } /** * Subtracts a value from the value of this instance. * * @param operand the value to subtract, not null * @throws NullPointerException if the object is null * @since Commons Lang 2.2 */ public void subtract(Number operand) { this.value -= operand.intValue(); } //----------------------------------------------------------------------- // shortValue and bytValue rely on Number implementation /** * Returns the value of this MutableInt as an int. * * @return the numeric value represented by this object after conversion to type int. */ public int intValue() { return value; } /** * Returns the value of this MutableInt as a long. * * @return the numeric value represented by this object after conversion to type long. */ public long longValue() { return value; } /** * Returns the value of this MutableInt as a float. * * @return the numeric value represented by this object after conversion to type float. */ public float floatValue() { return value; } /** * Returns the value of this MutableInt as a double. * * @return the numeric value represented by this object after conversion to type double. */ public double doubleValue() { return value; } //----------------------------------------------------------------------- /** * Gets this mutable as an instance of Integer. * * @return a Integer instance containing the value from this mutable, never null */ public Integer toInteger() { return new Integer(intValue()); } //----------------------------------------------------------------------- /** * Compares this object to the specified object. The result is true if and only if the argument is * not null and is a MutableInt object that contains the same int value * as this object. * * @param obj the object to compare with, null returns false * @return true if the objects are the same; false otherwise. */ public boolean equals(Object obj) { if (obj instanceof MutableInt) { return value == ((MutableInt) obj).intValue(); } return false; } /** * Returns a suitable hash code for this mutable. * * @return a suitable hash code */ public int hashCode() { return value; } //----------------------------------------------------------------------- /** * Compares this mutable to another in ascending order. * * @param obj the other mutable to compare to, not null * @return negative if this is less, zero if equal, positive if greater * @throws ClassCastException if the argument is not a MutableInt */ public int compareTo(Object obj) { MutableInt other = (MutableInt) obj; int anotherVal = other.value; return value < anotherVal ? -1 : (value == anotherVal ? 0 : 1); } //----------------------------------------------------------------------- /** * Returns the String value of this mutable. * * @return the mutable value as a string */ public String toString() { return String.valueOf(value); } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/mutable/MutableLong.java100644 0 0 17552 11513702444 25467 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.mutable; /** * A mutable long wrapper. * * @see Long * @since 2.1 * @author Apache Software Foundation * @version $Id: MutableLong.java 905707 2010-02-02 16:59:59Z niallp $ */ public class MutableLong extends Number implements Comparable, Mutable { /** * Required for serialization support. * * @see java.io.Serializable */ private static final long serialVersionUID = 62986528375L; /** The mutable value. */ private long value; /** * Constructs a new MutableLong with the default value of zero. */ public MutableLong() { super(); } /** * Constructs a new MutableLong with the specified value. * * @param value the initial value to store */ public MutableLong(long value) { super(); this.value = value; } /** * Constructs a new MutableLong with the specified value. * * @param value the initial value to store, not null * @throws NullPointerException if the object is null */ public MutableLong(Number value) { super(); this.value = value.longValue(); } /** * Constructs a new MutableLong parsing the given string. * * @param value the string to parse, not null * @throws NumberFormatException if the string cannot be parsed into a long * @since 2.5 */ public MutableLong(String value) throws NumberFormatException { super(); this.value = Long.parseLong(value); } //----------------------------------------------------------------------- /** * Gets the value as a Long instance. * * @return the value as a Long, never null */ public Object getValue() { return new Long(this.value); } /** * Sets the value. * * @param value the value to set */ public void setValue(long value) { this.value = value; } /** * Sets the value from any Number instance. * * @param value the value to set, not null * @throws NullPointerException if the object is null * @throws ClassCastException if the type is not a {@link Number} */ public void setValue(Object value) { setValue(((Number) value).longValue()); } //----------------------------------------------------------------------- /** * Increments the value. * * @since Commons Lang 2.2 */ public void increment() { value++; } /** * Decrements the value. * * @since Commons Lang 2.2 */ public void decrement() { value--; } //----------------------------------------------------------------------- /** * Adds a value to the value of this instance. * * @param operand the value to add, not null * @since Commons Lang 2.2 */ public void add(long operand) { this.value += operand; } /** * Adds a value to the value of this instance. * * @param operand the value to add, not null * @throws NullPointerException if the object is null * @since Commons Lang 2.2 */ public void add(Number operand) { this.value += operand.longValue(); } /** * Subtracts a value from the value of this instance. * * @param operand the value to subtract, not null * @since Commons Lang 2.2 */ public void subtract(long operand) { this.value -= operand; } /** * Subtracts a value from the value of this instance. * * @param operand the value to subtract, not null * @throws NullPointerException if the object is null * @since Commons Lang 2.2 */ public void subtract(Number operand) { this.value -= operand.longValue(); } //----------------------------------------------------------------------- // shortValue and bytValue rely on Number implementation /** * Returns the value of this MutableLong as an int. * * @return the numeric value represented by this object after conversion to type int. */ public int intValue() { return (int) value; } /** * Returns the value of this MutableLong as a long. * * @return the numeric value represented by this object after conversion to type long. */ public long longValue() { return value; } /** * Returns the value of this MutableLong as a float. * * @return the numeric value represented by this object after conversion to type float. */ public float floatValue() { return value; } /** * Returns the value of this MutableLong as a double. * * @return the numeric value represented by this object after conversion to type double. */ public double doubleValue() { return value; } //----------------------------------------------------------------------- /** * Gets this mutable as an instance of Long. * * @return a Long instance containing the value from this mutable, never null */ public Long toLong() { return new Long(longValue()); } //----------------------------------------------------------------------- /** * Compares this object to the specified object. The result is true if and only if the argument * is not null and is a MutableLong object that contains the same long * value as this object. * * @param obj the object to compare with, null returns false * @return true if the objects are the same; false otherwise. */ public boolean equals(Object obj) { if (obj instanceof MutableLong) { return value == ((MutableLong) obj).longValue(); } return false; } /** * Returns a suitable hash code for this mutable. * * @return a suitable hash code */ public int hashCode() { return (int) (value ^ (value >>> 32)); } //----------------------------------------------------------------------- /** * Compares this mutable to another in ascending order. * * @param obj the other mutable to compare to, not null * @return negative if this is less, zero if equal, positive if greater * @throws ClassCastException if the argument is not a MutableLong */ public int compareTo(Object obj) { MutableLong other = (MutableLong) obj; long anotherVal = other.value; return value < anotherVal ? -1 : (value == anotherVal ? 0 : 1); } //----------------------------------------------------------------------- /** * Returns the String value of this mutable. * * @return the mutable value as a string */ public String toString() { return String.valueOf(value); } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/mutable/MutableObject.java100644 0 0 7007 11513702444 25750 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.mutable; import java.io.Serializable; /** * A mutable Object wrapper. * * @since 2.1 * @author Apache Software Foundation * @version $Id: MutableObject.java 905636 2010-02-02 14:03:32Z niallp $ */ public class MutableObject implements Mutable, Serializable { /** * Required for serialization support. * * @see java.io.Serializable */ private static final long serialVersionUID = 86241875189L; /** The mutable value. */ private Object value; /** * Constructs a new MutableObject with the default value of null. */ public MutableObject() { super(); } /** * Constructs a new MutableObject with the specified value. * * @param value the initial value to store */ public MutableObject(Object value) { super(); this.value = value; } //----------------------------------------------------------------------- /** * Gets the value. * * @return the value, may be null */ public Object getValue() { return this.value; } /** * Sets the value. * * @param value the value to set */ public void setValue(Object value) { this.value = value; } //----------------------------------------------------------------------- /** * Compares this object against the specified object. The result is true if and only if the argument * is not null and is a MutableObject object that contains the same Object * value as this object. * * @param obj the object to compare with, null returns false * @return true if the objects are the same; false otherwise. */ public boolean equals(Object obj) { if (obj instanceof MutableObject) { Object other = ((MutableObject) obj).value; return value == other || (value != null && value.equals(other)); } return false; } /** * Returns the value's hash code or 0 if the value is null. * * @return the value's hash code or 0 if the value is null. */ public int hashCode() { return value == null ? 0 : value.hashCode(); } //----------------------------------------------------------------------- /** * Returns the String value of this mutable. * * @return the mutable value as a string */ public String toString() { return value == null ? "null" : value.toString(); } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/mutable/MutableShort.java100644 0 0 20137 11513702444 25660 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.mutable; /** * A mutable short wrapper. * * @see Short * @since 2.1 * @author Apache Software Foundation * @version $Id: MutableShort.java 905707 2010-02-02 16:59:59Z niallp $ */ public class MutableShort extends Number implements Comparable, Mutable { /** * Required for serialization support. * * @see java.io.Serializable */ private static final long serialVersionUID = -2135791679L; /** The mutable value. */ private short value; /** * Constructs a new MutableShort with the default value of zero. */ public MutableShort() { super(); } /** * Constructs a new MutableShort with the specified value. * * @param value the initial value to store */ public MutableShort(short value) { super(); this.value = value; } /** * Constructs a new MutableShort with the specified value. * * @param value the initial value to store, not null * @throws NullPointerException if the object is null */ public MutableShort(Number value) { super(); this.value = value.shortValue(); } /** * Constructs a new MutableShort parsing the given string. * * @param value the string to parse, not null * @throws NumberFormatException if the string cannot be parsed into a short * @since 2.5 */ public MutableShort(String value) throws NumberFormatException { super(); this.value = Short.parseShort(value); } //----------------------------------------------------------------------- /** * Gets the value as a Short instance. * * @return the value as a Short, never null */ public Object getValue() { return new Short(this.value); } /** * Sets the value. * * @param value the value to set */ public void setValue(short value) { this.value = value; } /** * Sets the value from any Number instance. * * @param value the value to set, not null * @throws NullPointerException if the object is null * @throws ClassCastException if the type is not a {@link Number} */ public void setValue(Object value) { setValue(((Number) value).shortValue()); } //----------------------------------------------------------------------- /** * Increments the value. * * @since Commons Lang 2.2 */ public void increment() { value++; } /** * Decrements the value. * * @since Commons Lang 2.2 */ public void decrement() { value--; } //----------------------------------------------------------------------- /** * Adds a value to the value of this instance. * * @param operand the value to add, not null * @since Commons Lang 2.2 */ public void add(short operand) { this.value += operand; } /** * Adds a value to the value of this instance. * * @param operand the value to add, not null * @throws NullPointerException if the object is null * @since Commons Lang 2.2 */ public void add(Number operand) { this.value += operand.shortValue(); } /** * Subtracts a value from the value of this instance. * * @param operand the value to subtract, not null * @since Commons Lang 2.2 */ public void subtract(short operand) { this.value -= operand; } /** * Subtracts a value from the value of this instance. * * @param operand the value to subtract, not null * @throws NullPointerException if the object is null * @since Commons Lang 2.2 */ public void subtract(Number operand) { this.value -= operand.shortValue(); } //----------------------------------------------------------------------- // bytValue relies on Number implementation /** * Returns the value of this MutableShort as a short. * * @return the numeric value represented by this object after conversion to type short. */ public short shortValue() { return value; } /** * Returns the value of this MutableShort as an int. * * @return the numeric value represented by this object after conversion to type int. */ public int intValue() { return value; } /** * Returns the value of this MutableShort as a long. * * @return the numeric value represented by this object after conversion to type long. */ public long longValue() { return value; } /** * Returns the value of this MutableShort as a float. * * @return the numeric value represented by this object after conversion to type float. */ public float floatValue() { return value; } /** * Returns the value of this MutableShort as a double. * * @return the numeric value represented by this object after conversion to type double. */ public double doubleValue() { return value; } //----------------------------------------------------------------------- /** * Gets this mutable as an instance of Short. * * @return a Short instance containing the value from this mutable, never null */ public Short toShort() { return new Short(shortValue()); } //----------------------------------------------------------------------- /** * Compares this object to the specified object. The result is true if and only if the argument * is not null and is a MutableShort object that contains the same short * value as this object. * * @param obj the object to compare with, null returns false * @return true if the objects are the same; false otherwise. */ public boolean equals(Object obj) { if (obj instanceof MutableShort) { return value == ((MutableShort) obj).shortValue(); } return false; } /** * Returns a suitable hash code for this mutable. * * @return a suitable hash code */ public int hashCode() { return value; } //----------------------------------------------------------------------- /** * Compares this mutable to another in ascending order. * * @param obj the other mutable to compare to, not null * @return negative if this is less, zero if equal, positive if greater * @throws ClassCastException if the argument is not a MutableShort */ public int compareTo(Object obj) { MutableShort other = (MutableShort) obj; short anotherVal = other.value; return value < anotherVal ? -1 : (value == anotherVal ? 0 : 1); } //----------------------------------------------------------------------- /** * Returns the String value of this mutable. * * @return the mutable value as a string */ public String toString() { return String.valueOf(value); } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/mutable/package.html100644 0 0 2031 11513702444 24636 0ustar 0 0 Provides typed mutable wrappers to primitive values and Object. @since 2.1

These classes are not thread-safe.

commons-lang-2.6-src/src/main/java/org/apache/commons/lang/NotImplementedException.java100644 0 0 23330 11513702446 26421 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang; import java.io.PrintStream; import java.io.PrintWriter; import org.apache.commons.lang.exception.Nestable; import org.apache.commons.lang.exception.NestableDelegate; /** *

Thrown to indicate that a block of code has not been implemented. * This exception supplements UnsupportedOperationException * by providing a more semantically rich description of the problem.

* *

NotImplementedException represents the case where the * author has yet to implement the logic at this point in the program. * This can act as an exception based TODO tag. * Because this logic might be within a catch block, this exception * suports exception chaining.

* *
 * public void foo() {
 *   try {
 *     // do something that throws an Exception
 *   } catch (Exception ex) {
 *     // don't know what to do here yet
 *     throw new NotImplementedException("TODO", ex);
 *   }
 * }
 * 
* * @author Apache Software Foundation * @author Matthew Hawthorne * @since 2.0 * @version $Id: NotImplementedException.java 905636 2010-02-02 14:03:32Z niallp $ */ public class NotImplementedException extends UnsupportedOperationException implements Nestable { private static final String DEFAULT_MESSAGE = "Code is not implemented"; /** * Required for serialization support. * * @see java.io.Serializable */ private static final long serialVersionUID = -6894122266938754088L; /** * The exception helper to delegate nested exception handling to. */ private NestableDelegate delegate = new NestableDelegate(this); /** * Holds the reference to the exception or error that caused * this exception to be thrown. */ private Throwable cause; //----------------------------------------------------------------------- /** * Constructs a new NotImplementedException with default message. * * @since 2.1 */ public NotImplementedException() { super(DEFAULT_MESSAGE); } /** * Constructs a new NotImplementedException with specified * detail message. * * @param msg the error message. */ public NotImplementedException(String msg) { super(msg == null ? DEFAULT_MESSAGE : msg); } /** * Constructs a new NotImplementedException with specified * nested Throwable and default message. * * @param cause the exception that caused this exception to be thrown * @since 2.1 */ public NotImplementedException(Throwable cause) { super(DEFAULT_MESSAGE); this.cause = cause; } /** * Constructs a new NotImplementedException with specified * detail message and nested Throwable. * * @param msg the error message * @param cause the exception that caused this exception to be thrown * @since 2.1 */ public NotImplementedException(String msg, Throwable cause) { super(msg == null ? DEFAULT_MESSAGE : msg); this.cause = cause; } /** * Constructs a new NotImplementedException referencing the specified class. * * @param clazz * the Class that has not implemented the method */ public NotImplementedException(Class clazz) { super(clazz == null ? DEFAULT_MESSAGE : DEFAULT_MESSAGE + " in " + clazz); } // ----------------------------------------------------------------------- /** * Gets the root cause of this exception. * @return the root cause of this exception. * * @since 2.1 */ public Throwable getCause() { return cause; } /** * Gets the combined the error message of this and any nested errors. * * @return the error message * @since 2.1 */ public String getMessage() { if (super.getMessage() != null) { return super.getMessage(); } else if (cause != null) { return cause.toString(); } else { return null; } } /** * Returns the error message of the Throwable in the chain * of Throwables at the specified index, numbered from 0. * * @param index the index of the Throwable in the chain * @return the error message, or null if the Throwable at the * specified index in the chain does not contain a message * @throws IndexOutOfBoundsException if the index argument is * negative or not less than the count of Throwables in the chain * @since 2.1 */ public String getMessage(int index) { if (index == 0) { return super.getMessage(); } return delegate.getMessage(index); } /** * Returns the error message of this and any nested Throwable objects. * Each throwable returns a message, a null string is included in the array if * there is no message for a particular Throwable. * * @return the error messages * @since 2.1 */ public String[] getMessages() { return delegate.getMessages(); } /** * Returns the Throwable in the chain by index. * * @param index the index to retrieve * @return the Throwable * @throws IndexOutOfBoundsException if the index argument is * negative or not less than the count of Throwables in the chain * @since 2.1 */ public Throwable getThrowable(int index) { return delegate.getThrowable(index); } /** * Returns the number of nested Throwables represented by * this Nestable, including this Nestable. * * @return the throwable count * @since 2.1 */ public int getThrowableCount() { return delegate.getThrowableCount(); } /** * Returns this Nestable and any nested Throwables * in an array of Throwables, one element for each * Throwable. * * @return the Throwables * @since 2.1 */ public Throwable[] getThrowables() { return delegate.getThrowables(); } /** * Returns the index of the first occurrence of the specified type. * If there is no match, -1 is returned. * * @param type the type to search for * @return index of the first occurrence of the type in the chain, or -1 if * the type is not found * @since 2.1 */ public int indexOfThrowable(Class type) { return delegate.indexOfThrowable(type, 0); } /** * Returns the index of the first occurrence of the specified type starting * from the specified index. If there is no match, -1 is returned. * * @param type the type to search for * @param fromIndex the index of the starting position in the chain to be searched * @return index of the first occurrence of the type in the chain, or -1 if * the type is not found * @throws IndexOutOfBoundsException if the fromIndex argument * is negative or not less than the count of Throwables in the chain * @since 2.1 */ public int indexOfThrowable(Class type, int fromIndex) { return delegate.indexOfThrowable(type, fromIndex); } /** * Prints the stack trace of this exception. * Includes information from the exception, if any, which caused this exception. * * @since 2.1 */ public void printStackTrace() { delegate.printStackTrace(); } /** * Prints the stack trace of this exception to the specified stream. * Includes information from the exception, if any, which caused this exception. * * @param out the stream to write to * @since 2.1 */ public void printStackTrace(PrintStream out) { delegate.printStackTrace(out); } /** * Prints the stack trace of this exception to the specified writer. * Includes information from the exception, if any, which caused this exception. * * @param out the writer to write to * @since 2.1 */ public void printStackTrace(PrintWriter out) { delegate.printStackTrace(out); } /** * Prints the stack trace for this exception only (root cause not included) * using the specified writer. * * @param out the writer to write to * @since 2.1 */ public final void printPartialStackTrace(PrintWriter out) { super.printStackTrace(out); } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/NullArgumentException.java100644 0 0 4611 11513702445 26072 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang; /** *

Thrown to indicate that an argument was null and should * not have been. * This exception supplements the standard IllegalArgumentException * by providing a more semantically rich description of the problem.

* *

NullArgumentException represents the case where a method takes * in a parameter that must not be null. * Some coding standards would use NullPointerException for this case, * others will use IllegalArgumentException. * Thus this exception would be used in place of * IllegalArgumentException, yet it still extends it.

* *
 * public void foo(String str) {
 *   if (str == null) {
 *     throw new NullArgumentException("str");
 *   }
 *   // do something with the string
 * }
 * 
* * @author Apache Software Foundation * @author Matthew Hawthorne * @since 2.0 * @version $Id: NullArgumentException.java 905636 2010-02-02 14:03:32Z niallp $ */ public class NullArgumentException extends IllegalArgumentException { /** * Required for serialization support. * * @see java.io.Serializable */ private static final long serialVersionUID = 1174360235354917591L; /** *

Instantiates with the given argument name.

* * @param argName the name of the argument that was null. */ public NullArgumentException(String argName) { super((argName == null ? "Argument" : argName) + " must not be null."); } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/NumberRange.java100644 0 0 16067 11513702445 24033 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang; import org.apache.commons.lang.text.StrBuilder; /** *

Represents a range of {@link Number} objects.

* *

This class uses double comparisons. This means that it * is unsuitable for dealing with large Long, BigDecimal * or BigInteger numbers.

* * @author Apache Software Foundation * @author Christopher Elkins * @since 1.0 * @version $Revision: 1057072 $ $Date: 2011-01-10 01:55:57 +0000 (Mon, 10 Jan 2011) $ * * @deprecated Use one of the Range classes in org.apache.commons.lang.math. * Class will be removed in Commons Lang 3.0. * */ public final class NumberRange { /* The minimum number in this range. */ private final Number min; /* The maximum number in this range. */ private final Number max; /** *

Constructs a new NumberRange using * number as both the minimum and maximum in * this range.

* * @param num the number to use for this range * @throws NullPointerException if the number is null */ public NumberRange(Number num) { if (num == null) { throw new NullPointerException("The number must not be null"); } this.min = num; this.max = num; } /** *

Constructs a new NumberRange with the specified * minimum and maximum numbers.

* *

If the maximum is less than the minimum, the range will be constructed * from the minimum value to the minimum value, not what you would expect!.

* * @param min the minimum number in this range * @param max the maximum number in this range * @throws NullPointerException if either the minimum or maximum number is * null */ public NumberRange(Number min, Number max) { if (min == null) { throw new NullPointerException("The minimum value must not be null"); } else if (max == null) { throw new NullPointerException("The maximum value must not be null"); } if (max.doubleValue() < min.doubleValue()) { this.min = this.max = min; } else { this.min = min; this.max = max; } } /** *

Returns the minimum number in this range.

* * @return the minimum number in this range */ public Number getMinimum() { return min; } /** *

Returns the maximum number in this range.

* * @return the maximum number in this range */ public Number getMaximum() { return max; } /** *

Tests whether the specified number occurs within * this range using double comparison.

* * @param number the number to test * @return true if the specified number occurs within this * range; otherwise, false */ public boolean includesNumber(Number number) { if (number == null) { return false; } else { return !(min.doubleValue() > number.doubleValue()) && !(max.doubleValue() < number.doubleValue()); } } /** *

Tests whether the specified range occurs entirely within this * range using double comparison.

* * @param range the range to test * @return true if the specified range occurs entirely within * this range; otherwise, false */ public boolean includesRange(NumberRange range) { if (range == null) { return false; } else { return includesNumber(range.min) && includesNumber(range.max); } } /** *

Tests whether the specified range overlaps with this range * using double comparison.

* * @param range the range to test * @return true if the specified range overlaps with this * range; otherwise, false */ public boolean overlaps(NumberRange range) { if (range == null) { return false; } else { return range.includesNumber(min) || range.includesNumber(max) || includesRange(range); } } /** *

Indicates whether some other Object is * "equal" to this one.

* * @param obj the reference object with which to compare * @return true if this object is the same as the obj * argument; false otherwise */ public boolean equals(Object obj) { if (obj == this) { return true; } else if (!(obj instanceof NumberRange)) { return false; } else { NumberRange range = (NumberRange)obj; return min.equals(range.min) && max.equals(range.max); } } /** *

Returns a hash code value for this object.

* * @return a hash code value for this object */ public int hashCode() { int result = 17; result = 37 * result + min.hashCode(); result = 37 * result + max.hashCode(); return result; } /** *

Returns the string representation of this range.

* *

This string is the string representation of the minimum and * maximum numbers in the range, separated by a hyphen. If a number * is negative, then it is enclosed in parentheses.

* * @return the string representation of this range */ public String toString() { StrBuilder sb = new StrBuilder(); if (min.doubleValue() < 0) { sb.append('(') .append(min) .append(')'); } else { sb.append(min); } sb.append('-'); if (max.doubleValue() < 0) { sb.append('(') .append(max) .append(')'); } else { sb.append(max); } return sb.toString(); } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/NumberUtils.java100644 0 0 61075 11513702446 24077 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang; import java.math.BigDecimal; import java.math.BigInteger; /** *

Provides extra functionality for Java Number classes.

* * @author Apache Software Foundation * @author Rand McNeely * @author Steve Downey * @author Eric Pugh * @author Phil Steitz * @since 1.0 * @version $Id: NumberUtils.java 905636 2010-02-02 14:03:32Z niallp $ * * @deprecated Moved to org.apache.commons.lang.math. * Class will be removed in Commons Lang 3.0. */ public final class NumberUtils { // DEPRECATED CLASS !!! /** *

NumberUtils instances should NOT be constructed in standard programming. * Instead, the class should be used as NumberUtils.stringToInt("6");.

* *

This constructor is public to permit tools that require a JavaBean instance * to operate.

*/ public NumberUtils() { super(); } //-------------------------------------------------------------------- /** *

Convert a String to an int, returning * zero if the conversion fails.

* * @param str the string to convert * @return the int represented by the string, or zero if * conversion fails */ public static int stringToInt(String str) { return stringToInt(str, 0); } /** *

Convert a String to an int, returning a * default value if the conversion fails.

* * @param str the string to convert * @param defaultValue the default value * @return the int represented by the string, or the default if conversion fails */ public static int stringToInt(String str, int defaultValue) { try { return Integer.parseInt(str); } catch (NumberFormatException nfe) { return defaultValue; } } //-------------------------------------------------------------------- // must handle Long, Float, Integer, Float, Short, // BigDecimal, BigInteger and Byte // useful methods: // Byte.decode(String) // Byte.valueOf(String,int radix) // Byte.valueOf(String) // Double.valueOf(String) // Float.valueOf(String) // new Float(String) // Integer.valueOf(String,int radix) // Integer.valueOf(String) // Integer.decode(String) // Integer.getInteger(String) // Integer.getInteger(String,int val) // Integer.getInteger(String,Integer val) // new Integer(String) // new Double(String) // new Byte(String) // new Long(String) // Long.getLong(String) // Long.getLong(String,int) // Long.getLong(String,Integer) // Long.valueOf(String,int) // Long.valueOf(String) // new Short(String) // Short.decode(String) // Short.valueOf(String,int) // Short.valueOf(String) // new BigDecimal(String) // new BigInteger(String) // new BigInteger(String,int radix) // Possible inputs: // 45 45.5 45E7 4.5E7 Hex Oct Binary xxxF xxxD xxxf xxxd // plus minus everything. Prolly more. A lot are not separable. /** *

Turns a string value into a java.lang.Number.

* *

First, the value is examined for a type qualifier on the end * ('f','F','d','D','l','L'). If it is found, it starts * trying to create successively larger types from the type specified * until one is found that can hold the value.

* *

If a type specifier is not found, it will check for a decimal point * and then try successively larger types from Integer to * BigInteger and from Float to * BigDecimal.

* *

If the string starts with 0x or -0x, it * will be interpreted as a hexadecimal integer. Values with leading * 0's will not be interpreted as octal.

* * @param val String containing a number * @return Number created from the string * @throws NumberFormatException if the value cannot be converted */ public static Number createNumber(String val) throws NumberFormatException { if (val == null) { return null; } if (val.length() == 0) { throw new NumberFormatException("\"\" is not a valid number."); } if (val.length() == 1 && !Character.isDigit(val.charAt(0))) { throw new NumberFormatException(val + " is not a valid number."); } if (val.startsWith("--")) { // this is protection for poorness in java.lang.BigDecimal. // it accepts this as a legal value, but it does not appear // to be in specification of class. OS X Java parses it to // a wrong value. return null; } if (val.startsWith("0x") || val.startsWith("-0x")) { return createInteger(val); } char lastChar = val.charAt(val.length() - 1); String mant; String dec; String exp; int decPos = val.indexOf('.'); int expPos = val.indexOf('e') + val.indexOf('E') + 1; if (decPos > -1) { if (expPos > -1) { if (expPos < decPos) { throw new NumberFormatException(val + " is not a valid number."); } dec = val.substring(decPos + 1, expPos); } else { dec = val.substring(decPos + 1); } mant = val.substring(0, decPos); } else { if (expPos > -1) { mant = val.substring(0, expPos); } else { mant = val; } dec = null; } if (!Character.isDigit(lastChar)) { if (expPos > -1 && expPos < val.length() - 1) { exp = val.substring(expPos + 1, val.length() - 1); } else { exp = null; } //Requesting a specific type.. String numeric = val.substring(0, val.length() - 1); boolean allZeros = isAllZeros(mant) && isAllZeros(exp); switch (lastChar) { case 'l' : case 'L' : if (dec == null && exp == null && (numeric.charAt(0) == '-' && isDigits(numeric.substring(1)) || isDigits(numeric))) { try { return createLong(numeric); } catch (NumberFormatException nfe) { //Too big for a long } return createBigInteger(numeric); } throw new NumberFormatException(val + " is not a valid number."); case 'f' : case 'F' : try { Float f = NumberUtils.createFloat(numeric); if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) { //If it's too big for a float or the float value = 0 and the string //has non-zeros in it, then float does not have the precision we want return f; } } catch (NumberFormatException e) { // ignore the bad number } //$FALL-THROUGH$ case 'd' : case 'D' : try { Double d = NumberUtils.createDouble(numeric); if (!(d.isInfinite() || (d.floatValue() == 0.0D && !allZeros))) { return d; } } catch (NumberFormatException nfe) { // empty catch } try { return createBigDecimal(numeric); } catch (NumberFormatException e) { // empty catch } //$FALL-THROUGH$ default : throw new NumberFormatException(val + " is not a valid number."); } } else { //User doesn't have a preference on the return type, so let's start //small and go from there... if (expPos > -1 && expPos < val.length() - 1) { exp = val.substring(expPos + 1, val.length()); } else { exp = null; } if (dec == null && exp == null) { //Must be an int,long,bigint try { return createInteger(val); } catch (NumberFormatException nfe) { // empty catch } try { return createLong(val); } catch (NumberFormatException nfe) { // empty catch } return createBigInteger(val); } else { //Must be a float,double,BigDec boolean allZeros = isAllZeros(mant) && isAllZeros(exp); try { Float f = createFloat(val); if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) { return f; } } catch (NumberFormatException nfe) { // empty catch } try { Double d = createDouble(val); if (!(d.isInfinite() || (d.doubleValue() == 0.0D && !allZeros))) { return d; } } catch (NumberFormatException nfe) { // empty catch } return createBigDecimal(val); } } } /** *

Utility method for {@link #createNumber(java.lang.String)}.

* *

Returns true if s is null.

* * @param s the String to check * @return if it is all zeros or null */ private static boolean isAllZeros(String s) { if (s == null) { return true; } for (int i = s.length() - 1; i >= 0; i--) { if (s.charAt(i) != '0') { return false; } } return s.length() > 0; } //-------------------------------------------------------------------- /** *

Convert a String to a Float.

* * @param val a String to convert * @return converted Float * @throws NumberFormatException if the value cannot be converted */ public static Float createFloat(String val) { return Float.valueOf(val); } /** *

Convert a String to a Double.

* * @param val a String to convert * @return converted Double * @throws NumberFormatException if the value cannot be converted */ public static Double createDouble(String val) { return Double.valueOf(val); } /** *

Convert a String to a Integer, handling * hex and octal notations.

* * @param val a String to convert * @return converted Integer * @throws NumberFormatException if the value cannot be converted */ public static Integer createInteger(String val) { // decode() handles 0xAABD and 0777 (hex and octal) as well. return Integer.decode(val); } /** *

Convert a String to a Long.

* * @param val a String to convert * @return converted Long * @throws NumberFormatException if the value cannot be converted */ public static Long createLong(String val) { return Long.valueOf(val); } /** *

Convert a String to a BigInteger.

* * @param val a String to convert * @return converted BigInteger * @throws NumberFormatException if the value cannot be converted */ public static BigInteger createBigInteger(String val) { BigInteger bi = new BigInteger(val); return bi; } /** *

Convert a String to a BigDecimal.

* * @param val a String to convert * @return converted BigDecimal * @throws NumberFormatException if the value cannot be converted */ public static BigDecimal createBigDecimal(String val) { BigDecimal bd = new BigDecimal(val); return bd; } //-------------------------------------------------------------------- /** *

Gets the minimum of three long values.

* * @param a value 1 * @param b value 2 * @param c value 3 * @return the smallest of the values */ public static long minimum(long a, long b, long c) { if (b < a) { a = b; } if (c < a) { a = c; } return a; } /** *

Gets the minimum of three int values.

* * @param a value 1 * @param b value 2 * @param c value 3 * @return the smallest of the values */ public static int minimum(int a, int b, int c) { if (b < a) { a = b; } if (c < a) { a = c; } return a; } /** *

Gets the maximum of three long values.

* * @param a value 1 * @param b value 2 * @param c value 3 * @return the largest of the values */ public static long maximum(long a, long b, long c) { if (b > a) { a = b; } if (c > a) { a = c; } return a; } /** *

Gets the maximum of three int values.

* * @param a value 1 * @param b value 2 * @param c value 3 * @return the largest of the values */ public static int maximum(int a, int b, int c) { if (b > a) { a = b; } if (c > a) { a = c; } return a; } //-------------------------------------------------------------------- /** *

Compares two doubles for order.

* *

This method is more comprehensive than the standard Java greater * than, less than and equals operators.

*
    *
  • It returns -1 if the first value is less than the second. *
  • It returns +1 if the first value is greater than the second. *
  • It returns 0 if the values are equal. *
* *

* The ordering is as follows, largest to smallest: *

    *
  • NaN *
  • Positive infinity *
  • Maximum double *
  • Normal positive numbers *
  • +0.0 *
  • -0.0 *
  • Normal negative numbers *
  • Minimum double (-Double.MAX_VALUE) *
  • Negative infinity *
*

* *

Comparing NaN with NaN will * return 0.

* * @param lhs the first double * @param rhs the second double * @return -1 if lhs is less, +1 if greater, * 0 if equal to rhs */ public static int compare(double lhs, double rhs) { if (lhs < rhs) { return -1; } if (lhs > rhs) { return +1; } // Need to compare bits to handle 0.0 == -0.0 being true // compare should put -0.0 < +0.0 // Two NaNs are also == for compare purposes // where NaN == NaN is false long lhsBits = Double.doubleToLongBits(lhs); long rhsBits = Double.doubleToLongBits(rhs); if (lhsBits == rhsBits) { return 0; } // Something exotic! A comparison to NaN or 0.0 vs -0.0 // Fortunately NaN's long is > than everything else // Also negzeros bits < poszero // NAN: 9221120237041090560 // MAX: 9218868437227405311 // NEGZERO: -9223372036854775808 if (lhsBits < rhsBits) { return -1; } else { return +1; } } /** *

Compares two floats for order.

* *

This method is more comprehensive than the standard Java greater than, * less than and equals operators.

*
    *
  • It returns -1 if the first value is less than the second. *
  • It returns +1 if the first value is greater than the second. *
  • It returns 0 if the values are equal. *
* *

The ordering is as follows, largest to smallest: *

    *
  • NaN *
  • Positive infinity *
  • Maximum float *
  • Normal positive numbers *
  • +0.0 *
  • -0.0 *
  • Normal negative numbers *
  • Minimum float (-Float.MAX_VALUE) *
  • Negative infinity *
* *

Comparing NaN with NaN will return * 0.

* * @param lhs the first float * @param rhs the second float * @return -1 if lhs is less, +1 if greater, * 0 if equal to rhs */ public static int compare(float lhs, float rhs) { if (lhs < rhs) { return -1; } if (lhs > rhs) { return +1; } //Need to compare bits to handle 0.0 == -0.0 being true // compare should put -0.0 < +0.0 // Two NaNs are also == for compare purposes // where NaN == NaN is false int lhsBits = Float.floatToIntBits(lhs); int rhsBits = Float.floatToIntBits(rhs); if (lhsBits == rhsBits) { return 0; } //Something exotic! A comparison to NaN or 0.0 vs -0.0 //Fortunately NaN's int is > than everything else //Also negzeros bits < poszero //NAN: 2143289344 //MAX: 2139095039 //NEGZERO: -2147483648 if (lhsBits < rhsBits) { return -1; } else { return +1; } } //-------------------------------------------------------------------- /** *

Checks whether the String contains only * digit characters.

* *

Null and empty String will return * false.

* * @param str the String to check * @return true if str contains only unicode numeric */ public static boolean isDigits(String str) { if ((str == null) || (str.length() == 0)) { return false; } for (int i = 0; i < str.length(); i++) { if (!Character.isDigit(str.charAt(i))) { return false; } } return true; } /** *

Checks whether the String a valid Java number.

* *

Valid numbers include hexadecimal marked with the 0x * qualifier, scientific notation and numbers marked with a type * qualifier (e.g. 123L).

* *

Null and empty String will return * false.

* * @param str the String to check * @return true if the string is a correctly formatted number */ public static boolean isNumber(String str) { if (StringUtils.isEmpty(str)) { return false; } char[] chars = str.toCharArray(); int sz = chars.length; boolean hasExp = false; boolean hasDecPoint = false; boolean allowSigns = false; boolean foundDigit = false; // deal with any possible sign up front int start = (chars[0] == '-') ? 1 : 0; if (sz > start + 1) { if (chars[start] == '0' && chars[start + 1] == 'x') { int i = start + 2; if (i == sz) { return false; // str == "0x" } // checking hex (it can't be anything else) for (; i < chars.length; i++) { if ((chars[i] < '0' || chars[i] > '9') && (chars[i] < 'a' || chars[i] > 'f') && (chars[i] < 'A' || chars[i] > 'F')) { return false; } } return true; } } sz--; // don't want to loop to the last char, check it afterwords // for type qualifiers int i = start; // loop to the next to last char or to the last char if we need another digit to // make a valid number (e.g. chars[0..5] = "1234E") while (i < sz || (i < sz + 1 && allowSigns && !foundDigit)) { if (chars[i] >= '0' && chars[i] <= '9') { foundDigit = true; allowSigns = false; } else if (chars[i] == '.') { if (hasDecPoint || hasExp) { // two decimal points or dec in exponent return false; } hasDecPoint = true; } else if (chars[i] == 'e' || chars[i] == 'E') { // we've already taken care of hex. if (hasExp) { // two E's return false; } if (!foundDigit) { return false; } hasExp = true; allowSigns = true; } else if (chars[i] == '+' || chars[i] == '-') { if (!allowSigns) { return false; } allowSigns = false; foundDigit = false; // we need a digit after the E } else { return false; } i++; } if (i < chars.length) { if (chars[i] >= '0' && chars[i] <= '9') { // no type qualifier, OK return true; } if (chars[i] == 'e' || chars[i] == 'E') { // can't have an E at the last byte return false; } if (!allowSigns && (chars[i] == 'd' || chars[i] == 'D' || chars[i] == 'f' || chars[i] == 'F')) { return foundDigit; } if (chars[i] == 'l' || chars[i] == 'L') { // not allowing L with an exponent return foundDigit && !hasExp; } // last character is illegal return false; } // allowSigns is true iff the val ends in 'E' // found digit it to make sure weird stuff like '.' and '1E-' doesn't pass return !allowSigns && foundDigit; } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/ObjectUtils.java100644 0 0 45112 11513702445 24046 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang; import java.io.Serializable; import java.lang.reflect.Array; import java.lang.reflect.InvocationTargetException; import org.apache.commons.lang.exception.CloneFailedException; import org.apache.commons.lang.reflect.MethodUtils; /** *

Operations on Object.

* *

This class tries to handle null input gracefully. * An exception will generally not be thrown for a null input. * Each method documents its behaviour in more detail.

* *

#ThreadSafe#

* @author Apache Software Foundation * @author Nissim Karpenstein * @author Janek Bogucki * @author Daniel L. Rall * @author Gary Gregory * @author Mario Winterer * @author David J. M. Karlsen * @since 1.0 * @version $Id: ObjectUtils.java 1057434 2011-01-11 01:27:37Z niallp $ */ //@Immutable public class ObjectUtils { /** *

Singleton used as a null placeholder where * null has another meaning.

* *

For example, in a HashMap the * {@link java.util.HashMap#get(java.lang.Object)} method returns * null if the Map contains * null or if there is no matching key. The * Null placeholder can be used to distinguish between * these two cases.

* *

Another example is Hashtable, where null * cannot be stored.

* *

This instance is Serializable.

*/ public static final Null NULL = new Null(); /** *

ObjectUtils instances should NOT be constructed in * standard programming. Instead, the class should be used as * ObjectUtils.defaultIfNull("a","b");.

* *

This constructor is public to permit tools that require a JavaBean instance * to operate.

*/ public ObjectUtils() { super(); } // Defaulting //----------------------------------------------------------------------- /** *

Returns a default value if the object passed is * null.

* *
     * ObjectUtils.defaultIfNull(null, null)      = null
     * ObjectUtils.defaultIfNull(null, "")        = ""
     * ObjectUtils.defaultIfNull(null, "zz")      = "zz"
     * ObjectUtils.defaultIfNull("abc", *)        = "abc"
     * ObjectUtils.defaultIfNull(Boolean.TRUE, *) = Boolean.TRUE
     * 
* * @param object the Object to test, may be null * @param defaultValue the default value to return, may be null * @return object if it is not null, defaultValue otherwise */ public static Object defaultIfNull(Object object, Object defaultValue) { return object != null ? object : defaultValue; } /** *

Compares two objects for equality, where either one or both * objects may be null.

* *
     * ObjectUtils.equals(null, null)                  = true
     * ObjectUtils.equals(null, "")                    = false
     * ObjectUtils.equals("", null)                    = false
     * ObjectUtils.equals("", "")                      = true
     * ObjectUtils.equals(Boolean.TRUE, null)          = false
     * ObjectUtils.equals(Boolean.TRUE, "true")        = false
     * ObjectUtils.equals(Boolean.TRUE, Boolean.TRUE)  = true
     * ObjectUtils.equals(Boolean.TRUE, Boolean.FALSE) = false
     * 
* * @param object1 the first object, may be null * @param object2 the second object, may be null * @return true if the values of both objects are the same */ public static boolean equals(Object object1, Object object2) { if (object1 == object2) { return true; } if ((object1 == null) || (object2 == null)) { return false; } return object1.equals(object2); } /** *

Compares two objects for inequality, where either one or both * objects may be null.

* *
     * ObjectUtils.notEqual(null, null)                  = false
     * ObjectUtils.notEqual(null, "")                    = true
     * ObjectUtils.notEqual("", null)                    = true
     * ObjectUtils.notEqual("", "")                      = false
     * ObjectUtils.notEqual(Boolean.TRUE, null)          = true
     * ObjectUtils.notEqual(Boolean.TRUE, "true")        = true
     * ObjectUtils.notEqual(Boolean.TRUE, Boolean.TRUE)  = false
     * ObjectUtils.notEqual(Boolean.TRUE, Boolean.FALSE) = true
     * 
* * @param object1 the first object, may be null * @param object2 the second object, may be null * @return false if the values of both objects are the same * @since 2.6 */ public static boolean notEqual(Object object1, Object object2) { return ObjectUtils.equals(object1, object2) == false; } /** *

Gets the hash code of an object returning zero when the * object is null.

* *
     * ObjectUtils.hashCode(null)   = 0
     * ObjectUtils.hashCode(obj)    = obj.hashCode()
     * 
* * @param obj the object to obtain the hash code of, may be null * @return the hash code of the object, or zero if null * @since 2.1 */ public static int hashCode(Object obj) { return (obj == null) ? 0 : obj.hashCode(); } // Identity ToString //----------------------------------------------------------------------- /** *

Gets the toString that would be produced by Object * if a class did not override toString itself. null * will return null.

* *
     * ObjectUtils.identityToString(null)         = null
     * ObjectUtils.identityToString("")           = "java.lang.String@1e23"
     * ObjectUtils.identityToString(Boolean.TRUE) = "java.lang.Boolean@7fa"
     * 
* * @param object the object to create a toString for, may be * null * @return the default toString text, or null if * null passed in */ public static String identityToString(Object object) { if (object == null) { return null; } StringBuffer buffer = new StringBuffer(); identityToString(buffer, object); return buffer.toString(); } /** *

Appends the toString that would be produced by Object * if a class did not override toString itself. null * will throw a NullPointerException for either of the two parameters.

* *
     * ObjectUtils.identityToString(buf, "")            = buf.append("java.lang.String@1e23"
     * ObjectUtils.identityToString(buf, Boolean.TRUE)  = buf.append("java.lang.Boolean@7fa"
     * ObjectUtils.identityToString(buf, Boolean.TRUE)  = buf.append("java.lang.Boolean@7fa")
     * 
* * @param buffer the buffer to append to * @param object the object to create a toString for * @since 2.4 */ public static void identityToString(StringBuffer buffer, Object object) { if (object == null) { throw new NullPointerException("Cannot get the toString of a null identity"); } buffer.append(object.getClass().getName()) .append('@') .append(Integer.toHexString(System.identityHashCode(object))); } /** *

Appends the toString that would be produced by Object * if a class did not override toString itself. null * will return null.

* *
     * ObjectUtils.appendIdentityToString(*, null)            = null
     * ObjectUtils.appendIdentityToString(null, "")           = "java.lang.String@1e23"
     * ObjectUtils.appendIdentityToString(null, Boolean.TRUE) = "java.lang.Boolean@7fa"
     * ObjectUtils.appendIdentityToString(buf, Boolean.TRUE)  = buf.append("java.lang.Boolean@7fa")
     * 
* * @param buffer the buffer to append to, may be null * @param object the object to create a toString for, may be null * @return the default toString text, or null if * null passed in * @since 2.0 * @deprecated The design of this method is bad - see LANG-360. Instead, use identityToString(StringBuffer, Object). */ public static StringBuffer appendIdentityToString(StringBuffer buffer, Object object) { if (object == null) { return null; } if (buffer == null) { buffer = new StringBuffer(); } return buffer .append(object.getClass().getName()) .append('@') .append(Integer.toHexString(System.identityHashCode(object))); } // ToString //----------------------------------------------------------------------- /** *

Gets the toString of an Object returning * an empty string ("") if null input.

* *
     * ObjectUtils.toString(null)         = ""
     * ObjectUtils.toString("")           = ""
     * ObjectUtils.toString("bat")        = "bat"
     * ObjectUtils.toString(Boolean.TRUE) = "true"
     * 
* * @see StringUtils#defaultString(String) * @see String#valueOf(Object) * @param obj the Object to toString, may be null * @return the passed in Object's toString, or nullStr if null input * @since 2.0 */ public static String toString(Object obj) { return obj == null ? "" : obj.toString(); } /** *

Gets the toString of an Object returning * a specified text if null input.

* *
     * ObjectUtils.toString(null, null)           = null
     * ObjectUtils.toString(null, "null")         = "null"
     * ObjectUtils.toString("", "null")           = ""
     * ObjectUtils.toString("bat", "null")        = "bat"
     * ObjectUtils.toString(Boolean.TRUE, "null") = "true"
     * 
* * @see StringUtils#defaultString(String,String) * @see String#valueOf(Object) * @param obj the Object to toString, may be null * @param nullStr the String to return if null input, may be null * @return the passed in Object's toString, or nullStr if null input * @since 2.0 */ public static String toString(Object obj, String nullStr) { return obj == null ? nullStr : obj.toString(); } // Min/Max //----------------------------------------------------------------------- /** * Null safe comparison of Comparables. * * @param c1 the first comparable, may be null * @param c2 the second comparable, may be null * @return *
    *
  • If both objects are non-null and unequal, the lesser object. *
  • If both objects are non-null and equal, c1. *
  • If one of the comparables is null, the non-null object. *
  • If both the comparables are null, null is returned. *
*/ public static Object min(Comparable c1, Comparable c2) { return (compare(c1, c2, true) <= 0 ? c1 : c2); } /** * Null safe comparison of Comparables. * * @param c1 the first comparable, may be null * @param c2 the second comparable, may be null * @return *
    *
  • If both objects are non-null and unequal, the greater object. *
  • If both objects are non-null and equal, c1. *
  • If one of the comparables is null, the non-null object. *
  • If both the comparables are null, null is returned. *
*/ public static Object max(Comparable c1, Comparable c2) { return (compare(c1, c2, false) >= 0 ? c1 : c2); } /** * Null safe comparison of Comparables. * {@code null} is assumed to be less than a non-{@code null} value. * * @param c1 the first comparable, may be null * @param c2 the second comparable, may be null * @return a negative value if c1 < c2, zero if c1 = c2 * and a positive value if c1 > c2 * @since 2.6 */ public static int compare(Comparable c1, Comparable c2) { return compare(c1, c2, false); } /** * Null safe comparison of Comparables. * * @param c1 the first comparable, may be null * @param c2 the second comparable, may be null * @param nullGreater if true null is considered greater * than a Non-null value or if false null is * considered less than a Non-null value * @return a negative value if c1 < c2, zero if c1 = c2 * and a positive value if c1 > c2 * @see java.util.Comparator#compare(Object, Object) * @since 2.6 */ public static int compare(Comparable c1, Comparable c2, boolean nullGreater) { if (c1 == c2) { return 0; } else if (c1 == null) { return (nullGreater ? 1 : -1); } else if (c2 == null) { return (nullGreater ? -1 : 1); } return c1.compareTo(c2); } /** * Clone an object. * * @param o the object to clone * @return the clone if the object implements {@link Cloneable} otherwise null * @throws CloneFailedException if the object is cloneable and the clone operation fails * @since 2.6 */ public static Object clone(final Object o) { if (o instanceof Cloneable) { final Object result; if (o.getClass().isArray()) { final Class componentType = o.getClass().getComponentType(); if (!componentType.isPrimitive()) { result = ((Object[])o).clone(); } else { int length = Array.getLength(o); result = Array.newInstance(componentType, length); while (length-- > 0) { Array.set(result, length, Array.get(o, length)); } } } else { try { result = MethodUtils.invokeMethod(o, "clone", null); } catch (final NoSuchMethodException e) { throw new CloneFailedException("Cloneable type " + o.getClass().getName() + " has no clone method", e); } catch (final IllegalAccessException e) { throw new CloneFailedException("Cannot clone Cloneable type " + o.getClass().getName(), e); } catch (final InvocationTargetException e) { throw new CloneFailedException("Exception cloning Cloneable type " + o.getClass().getName(), e.getTargetException()); } } return result; } return null; } /** * Clone an object if possible. This method is similar to {@link #clone(Object)}, but will * return the provided instance as the return value instead of null if the instance * is not cloneable. This is more convenient if the caller uses different * implementations (e.g. of a service) and some of the implementations do not allow concurrent * processing or have state. In such cases the implementation can simply provide a proper * clone implementation and the caller's code does not have to change. * * @param o the object to clone * @return the clone if the object implements {@link Cloneable} otherwise the object itself * @throws CloneFailedException if the object is cloneable and the clone operation fails * @since 2.6 */ public static Object cloneIfPossible(final Object o) { final Object clone = clone(o); return clone == null ? o : clone; } // Null //----------------------------------------------------------------------- /** *

Class used as a null placeholder where null * has another meaning.

* *

For example, in a HashMap the * {@link java.util.HashMap#get(java.lang.Object)} method returns * null if the Map contains * null or if there is no matching key. The * Null placeholder can be used to distinguish between * these two cases.

* *

Another example is Hashtable, where null * cannot be stored.

*/ public static class Null implements Serializable { /** * Required for serialization support. Declare serialization compatibility with Commons Lang 1.0 * * @see java.io.Serializable */ private static final long serialVersionUID = 7092611880189329093L; /** * Restricted constructor - singleton. */ Null() { super(); } /** *

Ensure singleton.

* * @return the singleton value */ private Object readResolve() { return ObjectUtils.NULL; } } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/overview.html100644 0 0 1607 11513702446 23472 0ustar 0 0

This document is the API specification for the Apache Commons Lang library.

commons-lang-2.6-src/src/main/java/org/apache/commons/lang/package.html100644 0 0 2112 11513702446 23207 0ustar 0 0 Provides highly reusable static utility methods, chiefly concerned with adding value to the {@link java.lang} classes. @since 1.0

Most of these classes are immutable and thus thread-safe. However Charset is not currently guaranteed thread-safe under all circumstances.

commons-lang-2.6-src/src/main/java/org/apache/commons/lang/RandomStringUtils.java100644 0 0 31072 11513702445 25247 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang; import java.util.Random; /** *

Operations for random Strings.

*

Currently private high surrogate characters are ignored. * These are unicode characters that fall between the values 56192 (db80) * and 56319 (dbff) as we don't know how to handle them. * High and low surrogates are correctly dealt with - that is if a * high surrogate is randomly chosen, 55296 (d800) to 56191 (db7f) * then it is followed by a low surrogate. If a low surrogate is chosen, * 56320 (dc00) to 57343 (dfff) then it is placed after a randomly * chosen high surrogate.

* *

#ThreadSafe#

* @author Apache Software Foundation * @author Steven Caswell * @author Gary Gregory * @author Phil Steitz * @since 1.0 * @version $Id: RandomStringUtils.java 1056988 2011-01-09 17:58:53Z niallp $ */ public class RandomStringUtils { /** *

Random object used by random method. This has to be not local * to the random method so as to not return the same value in the * same millisecond.

*/ private static final Random RANDOM = new Random(); /** *

RandomStringUtils instances should NOT be constructed in * standard programming. Instead, the class should be used as * RandomStringUtils.random(5);.

* *

This constructor is public to permit tools that require a JavaBean instance * to operate.

*/ public RandomStringUtils() { super(); } // Random //----------------------------------------------------------------------- /** *

Creates a random string whose length is the number of characters * specified.

* *

Characters will be chosen from the set of all characters.

* * @param count the length of random string to create * @return the random string */ public static String random(int count) { return random(count, false, false); } /** *

Creates a random string whose length is the number of characters * specified.

* *

Characters will be chosen from the set of characters whose * ASCII value is between 32 and 126 (inclusive).

* * @param count the length of random string to create * @return the random string */ public static String randomAscii(int count) { return random(count, 32, 127, false, false); } /** *

Creates a random string whose length is the number of characters * specified.

* *

Characters will be chosen from the set of alphabetic * characters.

* * @param count the length of random string to create * @return the random string */ public static String randomAlphabetic(int count) { return random(count, true, false); } /** *

Creates a random string whose length is the number of characters * specified.

* *

Characters will be chosen from the set of alpha-numeric * characters.

* * @param count the length of random string to create * @return the random string */ public static String randomAlphanumeric(int count) { return random(count, true, true); } /** *

Creates a random string whose length is the number of characters * specified.

* *

Characters will be chosen from the set of numeric * characters.

* * @param count the length of random string to create * @return the random string */ public static String randomNumeric(int count) { return random(count, false, true); } /** *

Creates a random string whose length is the number of characters * specified.

* *

Characters will be chosen from the set of alpha-numeric * characters as indicated by the arguments.

* * @param count the length of random string to create * @param letters if true, generated string will include * alphabetic characters * @param numbers if true, generated string will include * numeric characters * @return the random string */ public static String random(int count, boolean letters, boolean numbers) { return random(count, 0, 0, letters, numbers); } /** *

Creates a random string whose length is the number of characters * specified.

* *

Characters will be chosen from the set of alpha-numeric * characters as indicated by the arguments.

* * @param count the length of random string to create * @param start the position in set of chars to start at * @param end the position in set of chars to end before * @param letters if true, generated string will include * alphabetic characters * @param numbers if true, generated string will include * numeric characters * @return the random string */ public static String random(int count, int start, int end, boolean letters, boolean numbers) { return random(count, start, end, letters, numbers, null, RANDOM); } /** *

Creates a random string based on a variety of options, using * default source of randomness.

* *

This method has exactly the same semantics as * {@link #random(int,int,int,boolean,boolean,char[],Random)}, but * instead of using an externally supplied source of randomness, it uses * the internal static {@link Random} instance.

* * @param count the length of random string to create * @param start the position in set of chars to start at * @param end the position in set of chars to end before * @param letters only allow letters? * @param numbers only allow numbers? * @param chars the set of chars to choose randoms from. * If null, then it will use the set of all chars. * @return the random string * @throws ArrayIndexOutOfBoundsException if there are not * (end - start) + 1 characters in the set array. */ public static String random(int count, int start, int end, boolean letters, boolean numbers, char[] chars) { return random(count, start, end, letters, numbers, chars, RANDOM); } /** *

Creates a random string based on a variety of options, using * supplied source of randomness.

* *

If start and end are both 0, start and end are set * to ' ' and 'z', the ASCII printable * characters, will be used, unless letters and numbers are both * false, in which case, start and end are set to * 0 and Integer.MAX_VALUE. * *

If set is not null, characters between start and * end are chosen.

* *

This method accepts a user-supplied {@link Random} * instance to use as a source of randomness. By seeding a single * {@link Random} instance with a fixed seed and using it for each call, * the same random sequence of strings can be generated repeatedly * and predictably.

* * @param count the length of random string to create * @param start the position in set of chars to start at * @param end the position in set of chars to end before * @param letters only allow letters? * @param numbers only allow numbers? * @param chars the set of chars to choose randoms from. * If null, then it will use the set of all chars. * @param random a source of randomness. * @return the random string * @throws ArrayIndexOutOfBoundsException if there are not * (end - start) + 1 characters in the set array. * @throws IllegalArgumentException if count < 0. * @since 2.0 */ public static String random(int count, int start, int end, boolean letters, boolean numbers, char[] chars, Random random) { if (count == 0) { return ""; } else if (count < 0) { throw new IllegalArgumentException("Requested random string length " + count + " is less than 0."); } if ((start == 0) && (end == 0)) { end = 'z' + 1; start = ' '; if (!letters && !numbers) { start = 0; end = Integer.MAX_VALUE; } } char[] buffer = new char[count]; int gap = end - start; while (count-- != 0) { char ch; if (chars == null) { ch = (char) (random.nextInt(gap) + start); } else { ch = chars[random.nextInt(gap) + start]; } if ((letters && Character.isLetter(ch)) || (numbers && Character.isDigit(ch)) || (!letters && !numbers)) { if(ch >= 56320 && ch <= 57343) { if(count == 0) { count++; } else { // low surrogate, insert high surrogate after putting it in buffer[count] = ch; count--; buffer[count] = (char) (55296 + random.nextInt(128)); } } else if(ch >= 55296 && ch <= 56191) { if(count == 0) { count++; } else { // high surrogate, insert low surrogate before putting it in buffer[count] = (char) (56320 + random.nextInt(128)); count--; buffer[count] = ch; } } else if(ch >= 56192 && ch <= 56319) { // private high surrogate, no effing clue, so skip it count++; } else { buffer[count] = ch; } } else { count++; } } return new String(buffer); } /** *

Creates a random string whose length is the number of characters * specified.

* *

Characters will be chosen from the set of characters * specified.

* * @param count the length of random string to create * @param chars the String containing the set of characters to use, * may be null * @return the random string * @throws IllegalArgumentException if count < 0. */ public static String random(int count, String chars) { if (chars == null) { return random(count, 0, 0, false, false, null, RANDOM); } return random(count, chars.toCharArray()); } /** *

Creates a random string whose length is the number of characters * specified.

* *

Characters will be chosen from the set of characters specified.

* * @param count the length of random string to create * @param chars the character array containing the set of characters to use, * may be null * @return the random string * @throws IllegalArgumentException if count < 0. */ public static String random(int count, char[] chars) { if (chars == null) { return random(count, 0, 0, false, false, null, RANDOM); } return random(count, 0, chars.length, false, false, chars, RANDOM); } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/reflect/ConstructorUtils.java100644 0 0 36050 11513702443 26610 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.reflect; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Modifier; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.ClassUtils; /** *

Utility reflection methods focussed on constructors, modelled after * {@link MethodUtils}.

* *

Known Limitations

Accessing Public Constructors In A Default * Access Superclass

There is an issue when invoking public constructors * contained in a default access superclass. Reflection locates these * constructors fine and correctly assigns them as public. However, an * IllegalAccessException is thrown if the constructors is * invoked.

* *

ConstructorUtils contains a workaround for this situation. It * will attempt to call setAccessible on this constructor. If this * call succeeds, then the method can be invoked as normal. This call will only * succeed when the application has sufficient security privilages. If this call * fails then a warning will be logged and the method may fail.

* * @author Apache Software Foundation * @author Craig R. McClanahan * @author Ralph Schaer * @author Chris Audley * @author Rey Francois * @author Gregor Rayman * @author Jan Sorensen * @author Robert Burrell Donkin * @author Rodney Waldhoff * @since 2.5 * @version $Id: ConstructorUtils.java 1056863 2011-01-09 02:00:25Z niallp $ */ public class ConstructorUtils { /** *

ConstructorUtils instances should NOT be constructed in standard * programming. Instead, the class should be used as * ConstructorUtils.invokeConstructor(cls, args).

* *

This constructor is public to permit tools that require a JavaBean * instance to operate.

*/ public ConstructorUtils() { super(); } /** *

Returns new instance of klazz created using the actual * arguments args. The formal parameter types are inferred from * the actual values of args. See * {@link #invokeExactConstructor(Class, Object[], Class[])} for more * details.

* *

The signatures should be assignment compatible.

* * @param cls the class to be constructed. * @param arg the actual argument * @return new instance of klazz * * @throws NoSuchMethodException If the constructor cannot be found * @throws IllegalAccessException If an error occurs accessing the constructor * @throws InvocationTargetException If an error occurs invoking the constructor * @throws InstantiationException If an error occurs instantiating the class * * @see #invokeConstructor(java.lang.Class, java.lang.Object[], java.lang.Class[]) */ public static Object invokeConstructor(Class cls, Object arg) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { return invokeConstructor(cls, new Object[] { arg }); } /** *

Returns new instance of klazz created using the actual * arguments args. The formal parameter types are inferred from * the actual values of args. See * {@link #invokeExactConstructor(Class, Object[], Class[])} for more * details.

*

The signatures should be assignment compatible.

* * @param cls the class to be constructed. * @param args actual argument array * @return new instance of klazz * * @throws NoSuchMethodException If the constructor cannot be found * @throws IllegalAccessException If an error occurs accessing the * constructor * @throws InvocationTargetException If an error occurs invoking the * constructor * @throws InstantiationException If an error occurs instantiating the class * * @see #invokeConstructor(java.lang.Class, java.lang.Object[], * java.lang.Class[]) */ public static Object invokeConstructor(Class cls, Object[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { if (null == args) { args = ArrayUtils.EMPTY_OBJECT_ARRAY; } Class parameterTypes[] = new Class[args.length]; for (int i = 0; i < args.length; i++) { parameterTypes[i] = args[i].getClass(); } return invokeConstructor(cls, args, parameterTypes); } /** *

Returns new instance of klazz created using constructor * with signature parameterTypes and actual arguments * args.

* *

The signatures should be assignment compatible.

* * @param cls the class to be constructed. * @param args actual argument array * @param parameterTypes parameter types array * @return new instance of klazz * * @throws NoSuchMethodException if matching constructor cannot be found * @throws IllegalAccessException thrown on the constructor's invocation * @throws InvocationTargetException thrown on the constructor's invocation * @throws InstantiationException thrown on the constructor's invocation * @see Constructor#newInstance */ public static Object invokeConstructor(Class cls, Object[] args, Class[] parameterTypes) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { if (parameterTypes == null) { parameterTypes = ArrayUtils.EMPTY_CLASS_ARRAY; } if (args == null) { args = ArrayUtils.EMPTY_OBJECT_ARRAY; } Constructor ctor = getMatchingAccessibleConstructor(cls, parameterTypes); if (null == ctor) { throw new NoSuchMethodException("No such accessible constructor on object: " + cls.getName()); } return ctor.newInstance(args); } /** *

Returns new instance of klazz created using the actual * arguments args. The formal parameter types are inferred from * the actual values of args. See * {@link #invokeExactConstructor(Class, Object[], Class[])} for more * details.

* *

The signatures should match exactly.

* * @param cls the class to be constructed. * @param arg the actual argument * @return new instance of klazz * * @throws NoSuchMethodException If the constructor cannot be found * @throws IllegalAccessException If an error occurs accessing the constructor * @throws InvocationTargetException If an error occurs invoking the constructor * @throws InstantiationException If an error occurs instantiating the class * * @see #invokeExactConstructor(java.lang.Class, java.lang.Object[], java.lang.Class[]) */ public static Object invokeExactConstructor(Class cls, Object arg) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { return invokeExactConstructor(cls, new Object[] { arg }); } /** *

Returns new instance of klazz created using the actual * arguments args. The formal parameter types are inferred from * the actual values of args. See * {@link #invokeExactConstructor(Class, Object[], Class[])} for more * details.

* *

The signatures should match exactly.

* * @param cls the class to be constructed. * @param args actual argument array * @return new instance of klazz * * @throws NoSuchMethodException If the constructor cannot be found * @throws IllegalAccessException If an error occurs accessing the * constructor * @throws InvocationTargetException If an error occurs invoking the * constructor * @throws InstantiationException If an error occurs instantiating the class * * @see #invokeExactConstructor(java.lang.Class, java.lang.Object[], * java.lang.Class[]) */ public static Object invokeExactConstructor(Class cls, Object[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { if (null == args) { args = ArrayUtils.EMPTY_OBJECT_ARRAY; } int arguments = args.length; Class parameterTypes[] = new Class[arguments]; for (int i = 0; i < arguments; i++) { parameterTypes[i] = args[i].getClass(); } return invokeExactConstructor(cls, args, parameterTypes); } /** *

Returns new instance of klazz created using constructor * with signature parameterTypes and actual arguments * args.

* *

The signatures should match exactly.

* * @param cls the class to be constructed. * @param args actual argument array * @param parameterTypes parameter types array * @return new instance of klazz * * @throws NoSuchMethodException if matching constructor cannot be found * @throws IllegalAccessException thrown on the constructor's invocation * @throws InvocationTargetException thrown on the constructor's invocation * @throws InstantiationException thrown on the constructor's invocation * @see Constructor#newInstance */ public static Object invokeExactConstructor(Class cls, Object[] args, Class[] parameterTypes) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { if (args == null) { args = ArrayUtils.EMPTY_OBJECT_ARRAY; } if (parameterTypes == null) { parameterTypes = ArrayUtils.EMPTY_CLASS_ARRAY; } Constructor ctor = getAccessibleConstructor(cls, parameterTypes); if (null == ctor) { throw new NoSuchMethodException("No such accessible constructor on object: " + cls.getName()); } return ctor.newInstance(args); } /** * Returns a constructor with single argument. * @param cls the class to be constructed * @param parameterType The constructor parameter type * @return null if matching accessible constructor can not be found. * @see Class#getConstructor * @see #getAccessibleConstructor(java.lang.reflect.Constructor) */ public static Constructor getAccessibleConstructor(Class cls, Class parameterType) { return getAccessibleConstructor(cls, new Class[] { parameterType }); } /** * Returns a constructor given a class and signature. * @param cls the class to be constructed * @param parameterTypes the parameter array * @return null if matching accessible constructor can not be found * @see Class#getConstructor * @see #getAccessibleConstructor(java.lang.reflect.Constructor) */ public static Constructor getAccessibleConstructor(Class cls, Class[] parameterTypes) { try { return getAccessibleConstructor(cls.getConstructor(parameterTypes)); } catch (NoSuchMethodException e) { return (null); } } /** * Returns accessible version of the given constructor. * @param ctor prototype constructor object. * @return null if accessible constructor can not be found. * @see java.lang.SecurityManager */ public static Constructor getAccessibleConstructor(Constructor ctor) { return MemberUtils.isAccessible(ctor) && Modifier.isPublic(ctor.getDeclaringClass().getModifiers()) ? ctor : null; } /** *

Find an accessible constructor with compatible parameters. Compatible * parameters mean that every method parameter is assignable from the given * parameters. In other words, it finds constructor that will take the * parameters given.

* *

First it checks if there is constructor matching the exact signature. * If no such, all the constructors of the class are tested if their * signatures are assignment compatible with the parameter types. The first * matching constructor is returned.

* * @param cls find constructor for this class * @param parameterTypes find method with compatible parameters * @return a valid Constructor object. If there's no matching constructor, * returns null. */ public static Constructor getMatchingAccessibleConstructor(Class cls, Class[] parameterTypes) { // see if we can find the constructor directly // most of the time this works and it's much faster try { Constructor ctor = cls.getConstructor(parameterTypes); MemberUtils.setAccessibleWorkaround(ctor); return ctor; } catch (NoSuchMethodException e) { /* SWALLOW */ } Constructor result = null; // search through all constructors Constructor[] ctors = cls.getConstructors(); // return best match: for (int i = 0; i < ctors.length; i++) { // compare parameters if (ClassUtils.isAssignable(parameterTypes, ctors[i].getParameterTypes(), true)) { // get accessible version of constructor Constructor ctor = getAccessibleConstructor(ctors[i]); if (ctor != null) { MemberUtils.setAccessibleWorkaround(ctor); if (result == null || MemberUtils.compareParameterTypes(ctor.getParameterTypes(), result .getParameterTypes(), parameterTypes) < 0) { result = ctor; } } } } return result; } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/reflect/FieldUtils.java100644 0 0 64204 11513702443 25310 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.reflect; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.Iterator; import org.apache.commons.lang.ClassUtils; /** * Utilities for working with fields by reflection. Adapted and refactored * from the dormant [reflect] Commons sandbox component. *

* The ability is provided to break the scoping restrictions coded by the * programmer. This can allow fields to be changed that shouldn't be. This * facility should be used with care. * * @author Apache Software Foundation * @author Matt Benson * @since 2.5 * @version $Id: FieldUtils.java 1057009 2011-01-09 19:48:06Z niallp $ */ public class FieldUtils { /** * FieldUtils instances should NOT be constructed in standard programming. *

* This constructor is public to permit tools that require a JavaBean instance * to operate. */ public FieldUtils() { super(); } /** * Gets an accessible Field by name respecting scope. * Superclasses/interfaces will be considered. * * @param cls the class to reflect, must not be null * @param fieldName the field name to obtain * @return the Field object * @throws IllegalArgumentException if the class or field name is null */ public static Field getField(Class cls, String fieldName) { Field field = getField(cls, fieldName, false); MemberUtils.setAccessibleWorkaround(field); return field; } /** * Gets an accessible Field by name breaking scope * if requested. Superclasses/interfaces will be considered. * * @param cls the class to reflect, must not be null * @param fieldName the field name to obtain * @param forceAccess whether to break scope restrictions using the * setAccessible method. False will only * match public fields. * @return the Field object * @throws IllegalArgumentException if the class or field name is null */ public static Field getField(final Class cls, String fieldName, boolean forceAccess) { if (cls == null) { throw new IllegalArgumentException("The class must not be null"); } if (fieldName == null) { throw new IllegalArgumentException("The field name must not be null"); } // Sun Java 1.3 has a bugged implementation of getField hence we write the // code ourselves // getField() will return the Field object with the declaring class // set correctly to the class that declares the field. Thus requesting the // field on a subclass will return the field from the superclass. // // priority order for lookup: // searchclass private/protected/package/public // superclass protected/package/public // private/different package blocks access to further superclasses // implementedinterface public // check up the superclass hierarchy for (Class acls = cls; acls != null; acls = acls.getSuperclass()) { try { Field field = acls.getDeclaredField(fieldName); // getDeclaredField checks for non-public scopes as well // and it returns accurate results if (!Modifier.isPublic(field.getModifiers())) { if (forceAccess) { field.setAccessible(true); } else { continue; } } return field; } catch (NoSuchFieldException ex) { // ignore } } // check the public interface case. This must be manually searched for // incase there is a public supersuperclass field hidden by a private/package // superclass field. Field match = null; for (Iterator intf = ClassUtils.getAllInterfaces(cls).iterator(); intf .hasNext();) { try { Field test = ((Class) intf.next()).getField(fieldName); if (match != null) { throw new IllegalArgumentException( "Reference to field " + fieldName + " is ambiguous relative to " + cls + "; a matching field exists on two or more implemented interfaces."); } match = test; } catch (NoSuchFieldException ex) { // ignore } } return match; } /** * Gets an accessible Field by name respecting scope. * Only the specified class will be considered. * * @param cls the class to reflect, must not be null * @param fieldName the field name to obtain * @return the Field object * @throws IllegalArgumentException if the class or field name is null */ public static Field getDeclaredField(Class cls, String fieldName) { return getDeclaredField(cls, fieldName, false); } /** * Gets an accessible Field by name breaking scope * if requested. Only the specified class will be considered. * * @param cls the class to reflect, must not be null * @param fieldName the field name to obtain * @param forceAccess whether to break scope restrictions using the * setAccessible method. False will only match public fields. * @return the Field object * @throws IllegalArgumentException if the class or field name is null */ public static Field getDeclaredField(Class cls, String fieldName, boolean forceAccess) { if (cls == null) { throw new IllegalArgumentException("The class must not be null"); } if (fieldName == null) { throw new IllegalArgumentException("The field name must not be null"); } try { // only consider the specified class by using getDeclaredField() Field field = cls.getDeclaredField(fieldName); if (!MemberUtils.isAccessible(field)) { if (forceAccess) { field.setAccessible(true); } else { return null; } } return field; } catch (NoSuchFieldException e) { } return null; } /** * Read an accessible static Field. * @param field to read * @return the field value * @throws IllegalArgumentException if the field is null or not static * @throws IllegalAccessException if the field is not accessible */ public static Object readStaticField(Field field) throws IllegalAccessException { return readStaticField(field, false); } /** * Read a static Field. * @param field to read * @param forceAccess whether to break scope restrictions using the * setAccessible method. * @return the field value * @throws IllegalArgumentException if the field is null or not static * @throws IllegalAccessException if the field is not made accessible */ public static Object readStaticField(Field field, boolean forceAccess) throws IllegalAccessException { if (field == null) { throw new IllegalArgumentException("The field must not be null"); } if (!Modifier.isStatic(field.getModifiers())) { throw new IllegalArgumentException("The field '" + field.getName() + "' is not static"); } return readField(field, (Object) null, forceAccess); } /** * Read the named public static field. Superclasses will be considered. * @param cls the class to reflect, must not be null * @param fieldName the field name to obtain * @return the value of the field * @throws IllegalArgumentException if the class or field name is null * @throws IllegalAccessException if the field is not accessible */ public static Object readStaticField(Class cls, String fieldName) throws IllegalAccessException { return readStaticField(cls, fieldName, false); } /** * Read the named static field. Superclasses will be considered. * @param cls the class to reflect, must not be null * @param fieldName the field name to obtain * @param forceAccess whether to break scope restrictions using the * setAccessible method. False will only * match public fields. * @return the Field object * @throws IllegalArgumentException if the class or field name is null * @throws IllegalAccessException if the field is not made accessible */ public static Object readStaticField(Class cls, String fieldName, boolean forceAccess) throws IllegalAccessException { Field field = getField(cls, fieldName, forceAccess); if (field == null) { throw new IllegalArgumentException("Cannot locate field " + fieldName + " on " + cls); } //already forced access above, don't repeat it here: return readStaticField(field, false); } /** * Gets a static Field value by name. The field must be public. * Only the specified class will be considered. * * @param cls the class to reflect, must not be null * @param fieldName the field name to obtain * @return the value of the field * @throws IllegalArgumentException if the class or field name is null * @throws IllegalAccessException if the field is not accessible */ public static Object readDeclaredStaticField(Class cls, String fieldName) throws IllegalAccessException { return readDeclaredStaticField(cls, fieldName, false); } /** * Gets a static Field value by name. Only the specified class will * be considered. * * @param cls the class to reflect, must not be null * @param fieldName the field name to obtain * @param forceAccess whether to break scope restrictions using the * setAccessible method. False will only * match public fields. * @return the Field object * @throws IllegalArgumentException if the class or field name is null * @throws IllegalAccessException if the field is not made accessible */ public static Object readDeclaredStaticField(Class cls, String fieldName, boolean forceAccess) throws IllegalAccessException { Field field = getDeclaredField(cls, fieldName, forceAccess); if (field == null) { throw new IllegalArgumentException("Cannot locate declared field " + cls.getName() + "." + fieldName); } //already forced access above, don't repeat it here: return readStaticField(field, false); } /** * Read an accessible Field. * @param field the field to use * @param target the object to call on, may be null for static fields * @return the field value * @throws IllegalArgumentException if the field is null * @throws IllegalAccessException if the field is not accessible */ public static Object readField(Field field, Object target) throws IllegalAccessException { return readField(field, target, false); } /** * Read a Field. * @param field the field to use * @param target the object to call on, may be null for static fields * @param forceAccess whether to break scope restrictions using the * setAccessible method. * @return the field value * @throws IllegalArgumentException if the field is null * @throws IllegalAccessException if the field is not made accessible */ public static Object readField(Field field, Object target, boolean forceAccess) throws IllegalAccessException { if (field == null) { throw new IllegalArgumentException("The field must not be null"); } if (forceAccess && !field.isAccessible()) { field.setAccessible(true); } else { MemberUtils.setAccessibleWorkaround(field); } return field.get(target); } /** * Read the named public field. Superclasses will be considered. * @param target the object to reflect, must not be null * @param fieldName the field name to obtain * @return the value of the field * @throws IllegalArgumentException if the class or field name is null * @throws IllegalAccessException if the named field is not public */ public static Object readField(Object target, String fieldName) throws IllegalAccessException { return readField(target, fieldName, false); } /** * Read the named field. Superclasses will be considered. * @param target the object to reflect, must not be null * @param fieldName the field name to obtain * @param forceAccess whether to break scope restrictions using the * setAccessible method. False will only * match public fields. * @return the field value * @throws IllegalArgumentException if the class or field name is null * @throws IllegalAccessException if the named field is not made accessible */ public static Object readField(Object target, String fieldName, boolean forceAccess) throws IllegalAccessException { if (target == null) { throw new IllegalArgumentException("target object must not be null"); } Class cls = target.getClass(); Field field = getField(cls, fieldName, forceAccess); if (field == null) { throw new IllegalArgumentException("Cannot locate field " + fieldName + " on " + cls); } //already forced access above, don't repeat it here: return readField(field, target); } /** * Read the named public field. Only the class of the specified object will be considered. * @param target the object to reflect, must not be null * @param fieldName the field name to obtain * @return the value of the field * @throws IllegalArgumentException if the class or field name is null * @throws IllegalAccessException if the named field is not public */ public static Object readDeclaredField(Object target, String fieldName) throws IllegalAccessException { return readDeclaredField(target, fieldName, false); } /** * Gets a Field value by name. Only the class of the specified * object will be considered. * * @param target the object to reflect, must not be null * @param fieldName the field name to obtain * @param forceAccess whether to break scope restrictions using the * setAccessible method. False will only * match public fields. * @return the Field object * @throws IllegalArgumentException if target or fieldName is null * @throws IllegalAccessException if the field is not made accessible */ public static Object readDeclaredField(Object target, String fieldName, boolean forceAccess) throws IllegalAccessException { if (target == null) { throw new IllegalArgumentException("target object must not be null"); } Class cls = target.getClass(); Field field = getDeclaredField(cls, fieldName, forceAccess); if (field == null) { throw new IllegalArgumentException("Cannot locate declared field " + cls.getName() + "." + fieldName); } //already forced access above, don't repeat it here: return readField(field, target); } /** * Write a public static Field. * @param field to write * @param value to set * @throws IllegalArgumentException if the field is null or not static * @throws IllegalAccessException if the field is not public or is final */ public static void writeStaticField(Field field, Object value) throws IllegalAccessException { writeStaticField(field, value, false); } /** * Write a static Field. * @param field to write * @param value to set * @param forceAccess whether to break scope restrictions using the * setAccessible method. False will only * match public fields. * @throws IllegalArgumentException if the field is null or not static * @throws IllegalAccessException if the field is not made accessible or is final */ public static void writeStaticField(Field field, Object value, boolean forceAccess) throws IllegalAccessException { if (field == null) { throw new IllegalArgumentException("The field must not be null"); } if (!Modifier.isStatic(field.getModifiers())) { throw new IllegalArgumentException("The field '" + field.getName() + "' is not static"); } writeField(field, (Object) null, value, forceAccess); } /** * Write a named public static Field. Superclasses will be considered. * @param cls Class on which the Field is to be found * @param fieldName to write * @param value to set * @throws IllegalArgumentException if the field cannot be located or is not static * @throws IllegalAccessException if the field is not public or is final */ public static void writeStaticField(Class cls, String fieldName, Object value) throws IllegalAccessException { writeStaticField(cls, fieldName, value, false); } /** * Write a named static Field. Superclasses will be considered. * @param cls Class on which the Field is to be found * @param fieldName to write * @param value to set * @param forceAccess whether to break scope restrictions using the * setAccessible method. False will only * match public fields. * @throws IllegalArgumentException if the field cannot be located or is not static * @throws IllegalAccessException if the field is not made accessible or is final */ public static void writeStaticField(Class cls, String fieldName, Object value, boolean forceAccess) throws IllegalAccessException { Field field = getField(cls, fieldName, forceAccess); if (field == null) { throw new IllegalArgumentException("Cannot locate field " + fieldName + " on " + cls); } //already forced access above, don't repeat it here: writeStaticField(field, value); } /** * Write a named public static Field. Only the specified class will be considered. * @param cls Class on which the Field is to be found * @param fieldName to write * @param value to set * @throws IllegalArgumentException if the field cannot be located or is not static * @throws IllegalAccessException if the field is not public or is final */ public static void writeDeclaredStaticField(Class cls, String fieldName, Object value) throws IllegalAccessException { writeDeclaredStaticField(cls, fieldName, value, false); } /** * Write a named static Field. Only the specified class will be considered. * @param cls Class on which the Field is to be found * @param fieldName to write * @param value to set * @param forceAccess whether to break scope restrictions using the * setAccessible method. False will only * match public fields. * @throws IllegalArgumentException if the field cannot be located or is not static * @throws IllegalAccessException if the field is not made accessible or is final */ public static void writeDeclaredStaticField(Class cls, String fieldName, Object value, boolean forceAccess) throws IllegalAccessException { Field field = getDeclaredField(cls, fieldName, forceAccess); if (field == null) { throw new IllegalArgumentException("Cannot locate declared field " + cls.getName() + "." + fieldName); } //already forced access above, don't repeat it here: writeField(field, (Object) null, value); } /** * Write an accessible field. * @param field to write * @param target the object to call on, may be null for static fields * @param value to set * @throws IllegalArgumentException if the field is null * @throws IllegalAccessException if the field is not accessible or is final */ public static void writeField(Field field, Object target, Object value) throws IllegalAccessException { writeField(field, target, value, false); } /** * Write a field. * @param field to write * @param target the object to call on, may be null for static fields * @param value to set * @param forceAccess whether to break scope restrictions using the * setAccessible method. False will only * match public fields. * @throws IllegalArgumentException if the field is null * @throws IllegalAccessException if the field is not made accessible or is final */ public static void writeField(Field field, Object target, Object value, boolean forceAccess) throws IllegalAccessException { if (field == null) { throw new IllegalArgumentException("The field must not be null"); } if (forceAccess && !field.isAccessible()) { field.setAccessible(true); } else { MemberUtils.setAccessibleWorkaround(field); } field.set(target, value); } /** * Write a public field. Superclasses will be considered. * @param target the object to reflect, must not be null * @param fieldName the field name to obtain * @param value to set * @throws IllegalArgumentException if target or fieldName is null * @throws IllegalAccessException if the field is not accessible */ public static void writeField(Object target, String fieldName, Object value) throws IllegalAccessException { writeField(target, fieldName, value, false); } /** * Write a field. Superclasses will be considered. * @param target the object to reflect, must not be null * @param fieldName the field name to obtain * @param value to set * @param forceAccess whether to break scope restrictions using the * setAccessible method. False will only * match public fields. * @throws IllegalArgumentException if target or fieldName is null * @throws IllegalAccessException if the field is not made accessible */ public static void writeField(Object target, String fieldName, Object value, boolean forceAccess) throws IllegalAccessException { if (target == null) { throw new IllegalArgumentException("target object must not be null"); } Class cls = target.getClass(); Field field = getField(cls, fieldName, forceAccess); if (field == null) { throw new IllegalArgumentException("Cannot locate declared field " + cls.getName() + "." + fieldName); } //already forced access above, don't repeat it here: writeField(field, target, value); } /** * Write a public field. Only the specified class will be considered. * @param target the object to reflect, must not be null * @param fieldName the field name to obtain * @param value to set * @throws IllegalArgumentException if target or fieldName is null * @throws IllegalAccessException if the field is not made accessible */ public static void writeDeclaredField(Object target, String fieldName, Object value) throws IllegalAccessException { writeDeclaredField(target, fieldName, value, false); } /** * Write a public field. Only the specified class will be considered. * @param target the object to reflect, must not be null * @param fieldName the field name to obtain * @param value to set * @param forceAccess whether to break scope restrictions using the * setAccessible method. False will only * match public fields. * @throws IllegalArgumentException if target or fieldName is null * @throws IllegalAccessException if the field is not made accessible */ public static void writeDeclaredField(Object target, String fieldName, Object value, boolean forceAccess) throws IllegalAccessException { if (target == null) { throw new IllegalArgumentException("target object must not be null"); } Class cls = target.getClass(); Field field = getDeclaredField(cls, fieldName, forceAccess); if (field == null) { throw new IllegalArgumentException("Cannot locate declared field " + cls.getName() + "." + fieldName); } //already forced access above, don't repeat it here: writeField(field, target, value); } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/reflect/MemberUtils.java100644 0 0 20610 11513702443 25465 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.reflect; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.ClassUtils; import org.apache.commons.lang.SystemUtils; /** * Contains common code for working with Methods/Constructors, extracted and * refactored from MethodUtils when it was imported from Commons * BeanUtils. * * @author Apache Software Foundation * @author Steve Cohen * @author Matt Benson * @since 2.5 * @version $Id: MemberUtils.java 1057013 2011-01-09 20:04:16Z niallp $ */ abstract class MemberUtils { // TODO extract an interface to implement compareParameterSets(...)? private static final int ACCESS_TEST = Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE; private static final Method IS_SYNTHETIC; static { Method isSynthetic = null; if (SystemUtils.isJavaVersionAtLeast(1.5f)) { // cannot call synthetic methods: try { isSynthetic = Member.class.getMethod("isSynthetic", ArrayUtils.EMPTY_CLASS_ARRAY); } catch (Exception e) { } } IS_SYNTHETIC = isSynthetic; } /** Array of primitive number types ordered by "promotability" */ private static final Class[] ORDERED_PRIMITIVE_TYPES = { Byte.TYPE, Short.TYPE, Character.TYPE, Integer.TYPE, Long.TYPE, Float.TYPE, Double.TYPE }; /** * XXX Default access superclass workaround * * When a public class has a default access superclass with public members, * these members are accessible. Calling them from compiled code works fine. * Unfortunately, on some JVMs, using reflection to invoke these members * seems to (wrongly) to prevent access even when the modifer is public. * Calling setAccessible(true) solves the problem but will only work from * sufficiently privileged code. Better workarounds would be gratefully * accepted. * @param o the AccessibleObject to set as accessible */ static void setAccessibleWorkaround(AccessibleObject o) { if (o == null || o.isAccessible()) { return; } Member m = (Member) o; if (Modifier.isPublic(m.getModifiers()) && isPackageAccess(m.getDeclaringClass().getModifiers())) { try { o.setAccessible(true); } catch (SecurityException e) { // ignore in favor of subsequent IllegalAccessException } } } /** * Learn whether a given set of modifiers implies package access. * @param modifiers to test * @return true unless package/protected/private modifier detected */ static boolean isPackageAccess(int modifiers) { return (modifiers & ACCESS_TEST) == 0; } /** * Check a Member for basic accessibility. * @param m Member to check * @return true if m is accessible */ static boolean isAccessible(Member m) { return m != null && Modifier.isPublic(m.getModifiers()) && !isSynthetic(m); } /** * Try to learn whether a given member, on JDK >= 1.5, is synthetic. * @param m Member to check * @return true if m was introduced by the compiler. */ static boolean isSynthetic(Member m) { if (IS_SYNTHETIC != null) { try { return ((Boolean) IS_SYNTHETIC.invoke(m, null)).booleanValue(); } catch (Exception e) { } } return false; } /** * Compare the relative fitness of two sets of parameter types in terms of * matching a third set of runtime parameter types, such that a list ordered * by the results of the comparison would return the best match first * (least). * * @param left the "left" parameter set * @param right the "right" parameter set * @param actual the runtime parameter types to match against * left/right * @return int consistent with compare semantics */ static int compareParameterTypes(Class[] left, Class[] right, Class[] actual) { float leftCost = getTotalTransformationCost(actual, left); float rightCost = getTotalTransformationCost(actual, right); return leftCost < rightCost ? -1 : rightCost < leftCost ? 1 : 0; } /** * Returns the sum of the object transformation cost for each class in the * source argument list. * @param srcArgs The source arguments * @param destArgs The destination arguments * @return The total transformation cost */ private static float getTotalTransformationCost(Class[] srcArgs, Class[] destArgs) { float totalCost = 0.0f; for (int i = 0; i < srcArgs.length; i++) { Class srcClass, destClass; srcClass = srcArgs[i]; destClass = destArgs[i]; totalCost += getObjectTransformationCost(srcClass, destClass); } return totalCost; } /** * Gets the number of steps required needed to turn the source class into * the destination class. This represents the number of steps in the object * hierarchy graph. * @param srcClass The source class * @param destClass The destination class * @return The cost of transforming an object */ private static float getObjectTransformationCost(Class srcClass, Class destClass) { if (destClass.isPrimitive()) { return getPrimitivePromotionCost(srcClass, destClass); } float cost = 0.0f; while (srcClass != null && !destClass.equals(srcClass)) { if (destClass.isInterface() && ClassUtils.isAssignable(srcClass, destClass)) { // slight penalty for interface match. // we still want an exact match to override an interface match, // but // an interface match should override anything where we have to // get a superclass. cost += 0.25f; break; } cost++; srcClass = srcClass.getSuperclass(); } /* * If the destination class is null, we've travelled all the way up to * an Object match. We'll penalize this by adding 1.5 to the cost. */ if (srcClass == null) { cost += 1.5f; } return cost; } /** * Get the number of steps required to promote a primitive number to another * type. * @param srcClass the (primitive) source class * @param destClass the (primitive) destination class * @return The cost of promoting the primitive */ private static float getPrimitivePromotionCost(final Class srcClass, final Class destClass) { float cost = 0.0f; Class cls = srcClass; if (!cls.isPrimitive()) { // slight unwrapping penalty cost += 0.1f; cls = ClassUtils.wrapperToPrimitive(cls); } for (int i = 0; cls != destClass && i < ORDERED_PRIMITIVE_TYPES.length; i++) { if (cls == ORDERED_PRIMITIVE_TYPES[i]) { cost += 0.1f; if (i < ORDERED_PRIMITIVE_TYPES.length - 1) { cls = ORDERED_PRIMITIVE_TYPES[i + 1]; } } } return cost; } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/reflect/MethodUtils.java100644 0 0 71653 11513702443 25513 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.reflect; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.ClassUtils; /** *

Utility reflection methods focused on methods, originally from Commons BeanUtils. * Differences from the BeanUtils version may be noted, especially where similar functionality * already existed within Lang. *

* *

Known Limitations

*

Accessing Public Methods In A Default Access Superclass

*

There is an issue when invoking public methods contained in a default access superclass on JREs prior to 1.4. * Reflection locates these methods fine and correctly assigns them as public. * However, an IllegalAccessException is thrown if the method is invoked.

* *

MethodUtils contains a workaround for this situation. * It will attempt to call setAccessible on this method. * If this call succeeds, then the method can be invoked as normal. * This call will only succeed when the application has sufficient security privileges. * If this call fails then the method may fail.

* * @author Apache Software Foundation * @author Craig R. McClanahan * @author Ralph Schaer * @author Chris Audley * @author Rey François * @author Gregor Raýman * @author Jan Sorensen * @author Robert Burrell Donkin * @author Matt Benson * @since 2.5 * @version $Id: MethodUtils.java 911986 2010-02-19 21:19:05Z niallp $ */ public class MethodUtils { /** *

MethodUtils instances should NOT be constructed in standard programming. * Instead, the class should be used as * MethodUtils.getAccessibleMethod(method).

* *

This constructor is public to permit tools that require a JavaBean * instance to operate.

*/ public MethodUtils() { super(); } /** *

Invoke a named method whose parameter type matches the object type.

* *

This method delegates the method search to {@link #getMatchingAccessibleMethod(Class, String, Class[])}.

* *

This method supports calls to methods taking primitive parameters * via passing in wrapping classes. So, for example, a Boolean object * would match a boolean primitive.

* *

This is a convenient wrapper for * {@link #invokeMethod(Object object, String methodName, Object[] args)}. *

* * @param object invoke method on this object * @param methodName get method with this name * @param arg use this argument * @return The value returned by the invoked method * * @throws NoSuchMethodException if there is no such accessible method * @throws InvocationTargetException wraps an exception thrown by the method invoked * @throws IllegalAccessException if the requested method is not accessible via reflection */ public static Object invokeMethod(Object object, String methodName, Object arg) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { return invokeMethod(object, methodName, new Object[] { arg }); } /** *

Invoke a named method whose parameter type matches the object type.

* *

This method delegates the method search to {@link #getMatchingAccessibleMethod(Class, String, Class[])}.

* *

This method supports calls to methods taking primitive parameters * via passing in wrapping classes. So, for example, a Boolean object * would match a boolean primitive.

* *

This is a convenient wrapper for * {@link #invokeMethod(Object object,String methodName, Object[] args, Class[] parameterTypes)}. *

* * @param object invoke method on this object * @param methodName get method with this name * @param args use these arguments - treat null as empty array * @return The value returned by the invoked method * * @throws NoSuchMethodException if there is no such accessible method * @throws InvocationTargetException wraps an exception thrown by the method invoked * @throws IllegalAccessException if the requested method is not accessible via reflection */ public static Object invokeMethod(Object object, String methodName, Object[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { if (args == null) { args = ArrayUtils.EMPTY_OBJECT_ARRAY; } int arguments = args.length; Class[] parameterTypes = new Class[arguments]; for (int i = 0; i < arguments; i++) { parameterTypes[i] = args[i].getClass(); } return invokeMethod(object, methodName, args, parameterTypes); } /** *

Invoke a named method whose parameter type matches the object type.

* *

This method delegates the method search to {@link #getMatchingAccessibleMethod(Class, String, Class[])}.

* *

This method supports calls to methods taking primitive parameters * via passing in wrapping classes. So, for example, a Boolean object * would match a boolean primitive.

* * @param object invoke method on this object * @param methodName get method with this name * @param args use these arguments - treat null as empty array * @param parameterTypes match these parameters - treat null as empty array * @return The value returned by the invoked method * * @throws NoSuchMethodException if there is no such accessible method * @throws InvocationTargetException wraps an exception thrown by the method invoked * @throws IllegalAccessException if the requested method is not accessible via reflection */ public static Object invokeMethod(Object object, String methodName, Object[] args, Class[] parameterTypes) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { if (parameterTypes == null) { parameterTypes = ArrayUtils.EMPTY_CLASS_ARRAY; } if (args == null) { args = ArrayUtils.EMPTY_OBJECT_ARRAY; } Method method = getMatchingAccessibleMethod(object.getClass(), methodName, parameterTypes); if (method == null) { throw new NoSuchMethodException("No such accessible method: " + methodName + "() on object: " + object.getClass().getName()); } return method.invoke(object, args); } /** *

Invoke a method whose parameter type matches exactly the object * type.

* *

This is a convenient wrapper for * {@link #invokeExactMethod(Object object,String methodName,Object [] args)}. *

* * @param object invoke method on this object * @param methodName get method with this name * @param arg use this argument * @return The value returned by the invoked method * * @throws NoSuchMethodException if there is no such accessible method * @throws InvocationTargetException wraps an exception thrown by the * method invoked * @throws IllegalAccessException if the requested method is not accessible * via reflection */ public static Object invokeExactMethod(Object object, String methodName, Object arg) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { return invokeExactMethod(object, methodName, new Object[] { arg }); } /** *

Invoke a method whose parameter types match exactly the object * types.

* *

This uses reflection to invoke the method obtained from a call to * getAccessibleMethod().

* * @param object invoke method on this object * @param methodName get method with this name * @param args use these arguments - treat null as empty array * @return The value returned by the invoked method * * @throws NoSuchMethodException if there is no such accessible method * @throws InvocationTargetException wraps an exception thrown by the * method invoked * @throws IllegalAccessException if the requested method is not accessible * via reflection */ public static Object invokeExactMethod(Object object, String methodName, Object[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { if (args == null) { args = ArrayUtils.EMPTY_OBJECT_ARRAY; } int arguments = args.length; Class[] parameterTypes = new Class[arguments]; for (int i = 0; i < arguments; i++) { parameterTypes[i] = args[i].getClass(); } return invokeExactMethod(object, methodName, args, parameterTypes); } /** *

Invoke a method whose parameter types match exactly the parameter * types given.

* *

This uses reflection to invoke the method obtained from a call to * getAccessibleMethod().

* * @param object invoke method on this object * @param methodName get method with this name * @param args use these arguments - treat null as empty array * @param parameterTypes match these parameters - treat null as empty array * @return The value returned by the invoked method * * @throws NoSuchMethodException if there is no such accessible method * @throws InvocationTargetException wraps an exception thrown by the * method invoked * @throws IllegalAccessException if the requested method is not accessible * via reflection */ public static Object invokeExactMethod(Object object, String methodName, Object[] args, Class[] parameterTypes) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { if (args == null) { args = ArrayUtils.EMPTY_OBJECT_ARRAY; } if (parameterTypes == null) { parameterTypes = ArrayUtils.EMPTY_CLASS_ARRAY; } Method method = getAccessibleMethod(object.getClass(), methodName, parameterTypes); if (method == null) { throw new NoSuchMethodException("No such accessible method: " + methodName + "() on object: " + object.getClass().getName()); } return method.invoke(object, args); } /** *

Invoke a static method whose parameter types match exactly the parameter * types given.

* *

This uses reflection to invoke the method obtained from a call to * {@link #getAccessibleMethod(Class, String, Class[])}.

* * @param cls invoke static method on this class * @param methodName get method with this name * @param args use these arguments - treat null as empty array * @param parameterTypes match these parameters - treat null as empty array * @return The value returned by the invoked method * * @throws NoSuchMethodException if there is no such accessible method * @throws InvocationTargetException wraps an exception thrown by the * method invoked * @throws IllegalAccessException if the requested method is not accessible * via reflection */ public static Object invokeExactStaticMethod(Class cls, String methodName, Object[] args, Class[] parameterTypes) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { if (args == null) { args = ArrayUtils.EMPTY_OBJECT_ARRAY; } if (parameterTypes == null) { parameterTypes = ArrayUtils.EMPTY_CLASS_ARRAY; } Method method = getAccessibleMethod(cls, methodName, parameterTypes); if (method == null) { throw new NoSuchMethodException("No such accessible method: " + methodName + "() on class: " + cls.getName()); } return method.invoke(null, args); } /** *

Invoke a named static method whose parameter type matches the object type.

* *

This method delegates the method search to {@link #getMatchingAccessibleMethod(Class, String, Class[])}.

* *

This method supports calls to methods taking primitive parameters * via passing in wrapping classes. So, for example, a Boolean class * would match a boolean primitive.

* *

This is a convenient wrapper for * {@link #invokeStaticMethod(Class objectClass,String methodName,Object [] args)}. *

* * @param cls invoke static method on this class * @param methodName get method with this name * @param arg use this argument * @return The value returned by the invoked method * * @throws NoSuchMethodException if there is no such accessible method * @throws InvocationTargetException wraps an exception thrown by the * method invoked * @throws IllegalAccessException if the requested method is not accessible * via reflection */ public static Object invokeStaticMethod(Class cls, String methodName, Object arg) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { return invokeStaticMethod(cls, methodName, new Object[] { arg }); } /** *

Invoke a named static method whose parameter type matches the object type.

* *

This method delegates the method search to {@link #getMatchingAccessibleMethod(Class, String, Class[])}.

* *

This method supports calls to methods taking primitive parameters * via passing in wrapping classes. So, for example, a Boolean class * would match a boolean primitive.

* *

This is a convenient wrapper for * {@link #invokeStaticMethod(Class objectClass,String methodName,Object [] args,Class[] parameterTypes)}. *

* * @param cls invoke static method on this class * @param methodName get method with this name * @param args use these arguments - treat null as empty array * @return The value returned by the invoked method * * @throws NoSuchMethodException if there is no such accessible method * @throws InvocationTargetException wraps an exception thrown by the * method invoked * @throws IllegalAccessException if the requested method is not accessible * via reflection */ public static Object invokeStaticMethod(Class cls, String methodName, Object[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { if (args == null) { args = ArrayUtils.EMPTY_OBJECT_ARRAY; } int arguments = args.length; Class[] parameterTypes = new Class[arguments]; for (int i = 0; i < arguments; i++) { parameterTypes[i] = args[i].getClass(); } return invokeStaticMethod(cls, methodName, args, parameterTypes); } /** *

Invoke a named static method whose parameter type matches the object type.

* *

This method delegates the method search to {@link #getMatchingAccessibleMethod(Class, String, Class[])}.

* *

This method supports calls to methods taking primitive parameters * via passing in wrapping classes. So, for example, a Boolean class * would match a boolean primitive.

* * * @param cls invoke static method on this class * @param methodName get method with this name * @param args use these arguments - treat null as empty array * @param parameterTypes match these parameters - treat null as empty array * @return The value returned by the invoked method * * @throws NoSuchMethodException if there is no such accessible method * @throws InvocationTargetException wraps an exception thrown by the * method invoked * @throws IllegalAccessException if the requested method is not accessible * via reflection */ public static Object invokeStaticMethod(Class cls, String methodName, Object[] args, Class[] parameterTypes) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { if (parameterTypes == null) { parameterTypes = ArrayUtils.EMPTY_CLASS_ARRAY; } if (args == null) { args = ArrayUtils.EMPTY_OBJECT_ARRAY; } Method method = getMatchingAccessibleMethod(cls, methodName, parameterTypes); if (method == null) { throw new NoSuchMethodException("No such accessible method: " + methodName + "() on class: " + cls.getName()); } return method.invoke(null, args); } /** *

Invoke a static method whose parameter type matches exactly the object * type.

* *

This is a convenient wrapper for * {@link #invokeExactStaticMethod(Class objectClass,String methodName,Object [] args)}. *

* * @param cls invoke static method on this class * @param methodName get method with this name * @param arg use this argument * @return The value returned by the invoked method * * @throws NoSuchMethodException if there is no such accessible method * @throws InvocationTargetException wraps an exception thrown by the * method invoked * @throws IllegalAccessException if the requested method is not accessible * via reflection */ public static Object invokeExactStaticMethod(Class cls, String methodName, Object arg) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { return invokeExactStaticMethod(cls, methodName, new Object[] { arg }); } /** *

Invoke a static method whose parameter types match exactly the object * types.

* *

This uses reflection to invoke the method obtained from a call to * {@link #getAccessibleMethod(Class, String, Class[])}.

* * @param cls invoke static method on this class * @param methodName get method with this name * @param args use these arguments - treat null as empty array * @return The value returned by the invoked method * * @throws NoSuchMethodException if there is no such accessible method * @throws InvocationTargetException wraps an exception thrown by the * method invoked * @throws IllegalAccessException if the requested method is not accessible * via reflection */ public static Object invokeExactStaticMethod(Class cls, String methodName, Object[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { if (args == null) { args = ArrayUtils.EMPTY_OBJECT_ARRAY; } int arguments = args.length; Class[] parameterTypes = new Class[arguments]; for (int i = 0; i < arguments; i++) { parameterTypes[i] = args[i].getClass(); } return invokeExactStaticMethod(cls, methodName, args, parameterTypes); } /** *

Return an accessible method (that is, one that can be invoked via * reflection) with given name and a single parameter. If no such method * can be found, return null. * Basically, a convenience wrapper that constructs a Class * array for you.

* * @param cls get method from this class * @param methodName get method with this name * @param parameterType taking this type of parameter * @return The accessible method */ public static Method getAccessibleMethod(Class cls, String methodName, Class parameterType) { return getAccessibleMethod(cls, methodName, new Class[] { parameterType }); } /** *

Return an accessible method (that is, one that can be invoked via * reflection) with given name and parameters. If no such method * can be found, return null. * This is just a convenient wrapper for * {@link #getAccessibleMethod(Method method)}.

* * @param cls get method from this class * @param methodName get method with this name * @param parameterTypes with these parameters types * @return The accessible method */ public static Method getAccessibleMethod(Class cls, String methodName, Class[] parameterTypes) { try { return getAccessibleMethod(cls.getMethod(methodName, parameterTypes)); } catch (NoSuchMethodException e) { return (null); } } /** *

Return an accessible method (that is, one that can be invoked via * reflection) that implements the specified Method. If no such method * can be found, return null.

* * @param method The method that we wish to call * @return The accessible method */ public static Method getAccessibleMethod(Method method) { if (!MemberUtils.isAccessible(method)) { return null; } // If the declaring class is public, we are done Class cls = method.getDeclaringClass(); if (Modifier.isPublic(cls.getModifiers())) { return method; } String methodName = method.getName(); Class[] parameterTypes = method.getParameterTypes(); // Check the implemented interfaces and subinterfaces method = getAccessibleMethodFromInterfaceNest(cls, methodName, parameterTypes); // Check the superclass chain if (method == null) { method = getAccessibleMethodFromSuperclass(cls, methodName, parameterTypes); } return method; } /** *

Return an accessible method (that is, one that can be invoked via * reflection) by scanning through the superclasses. If no such method * can be found, return null.

* * @param cls Class to be checked * @param methodName Method name of the method we wish to call * @param parameterTypes The parameter type signatures * @return the accessible method or null if not found */ private static Method getAccessibleMethodFromSuperclass(Class cls, String methodName, Class[] parameterTypes) { Class parentClass = cls.getSuperclass(); while (parentClass != null) { if (Modifier.isPublic(parentClass.getModifiers())) { try { return parentClass.getMethod(methodName, parameterTypes); } catch (NoSuchMethodException e) { return null; } } parentClass = parentClass.getSuperclass(); } return null; } /** *

Return an accessible method (that is, one that can be invoked via * reflection) that implements the specified method, by scanning through * all implemented interfaces and subinterfaces. If no such method * can be found, return null.

* *

There isn't any good reason why this method must be private. * It is because there doesn't seem any reason why other classes should * call this rather than the higher level methods.

* * @param cls Parent class for the interfaces to be checked * @param methodName Method name of the method we wish to call * @param parameterTypes The parameter type signatures * @return the accessible method or null if not found */ private static Method getAccessibleMethodFromInterfaceNest(Class cls, String methodName, Class[] parameterTypes) { Method method = null; // Search up the superclass chain for (; cls != null; cls = cls.getSuperclass()) { // Check the implemented interfaces of the parent class Class[] interfaces = cls.getInterfaces(); for (int i = 0; i < interfaces.length; i++) { // Is this interface public? if (!Modifier.isPublic(interfaces[i].getModifiers())) { continue; } // Does the method exist on this interface? try { method = interfaces[i].getDeclaredMethod(methodName, parameterTypes); } catch (NoSuchMethodException e) { /* * Swallow, if no method is found after the loop then this * method returns null. */ } if (method != null) { break; } // Recursively check our parent interfaces method = getAccessibleMethodFromInterfaceNest(interfaces[i], methodName, parameterTypes); if (method != null) { break; } } } return method; } /** *

Find an accessible method that matches the given name and has compatible parameters. * Compatible parameters mean that every method parameter is assignable from * the given parameters. * In other words, it finds a method with the given name * that will take the parameters given.

* *

This method is used by * {@link * #invokeMethod(Object object, String methodName, Object[] args, Class[] parameterTypes)}. * *

This method can match primitive parameter by passing in wrapper classes. * For example, a Boolean will match a primitive boolean * parameter. * * @param cls find method in this class * @param methodName find method with this name * @param parameterTypes find method with most compatible parameters * @return The accessible method */ public static Method getMatchingAccessibleMethod(Class cls, String methodName, Class[] parameterTypes) { try { Method method = cls.getMethod(methodName, parameterTypes); MemberUtils.setAccessibleWorkaround(method); return method; } catch (NoSuchMethodException e) { /* SWALLOW */ } // search through all methods Method bestMatch = null; Method[] methods = cls.getMethods(); for (int i = 0, size = methods.length; i < size; i++) { if (methods[i].getName().equals(methodName)) { // compare parameters if (ClassUtils.isAssignable(parameterTypes, methods[i] .getParameterTypes(), true)) { // get accessible version of method Method accessibleMethod = getAccessibleMethod(methods[i]); if (accessibleMethod != null) { if (bestMatch == null || MemberUtils.compareParameterTypes( accessibleMethod.getParameterTypes(), bestMatch.getParameterTypes(), parameterTypes) < 0) { bestMatch = accessibleMethod; } } } } } if (bestMatch != null) { MemberUtils.setAccessibleWorkaround(bestMatch); } return bestMatch; } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/reflect/package.html100644 0 0 2075 11513702443 24640 0ustar 0 0 Accumulates common high-level uses of the java.lang.reflect APIs. @since 2.5

These classes are immutable, and therefore thread-safe.

commons-lang-2.6-src/src/main/java/org/apache/commons/lang/SerializationException.java100644 0 0 5206 11513702446 26274 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang; import org.apache.commons.lang.exception.NestableRuntimeException; /** *

Exception thrown when the Serialization process fails.

* *

The original error is wrapped within this one.

* * @author Apache Software Foundation * @since 1.0 * @version $Id: SerializationException.java 905636 2010-02-02 14:03:32Z niallp $ */ public class SerializationException extends NestableRuntimeException { /** * Required for serialization support. * * @see java.io.Serializable */ private static final long serialVersionUID = 4029025366392702726L; /** *

Constructs a new SerializationException without specified * detail message.

*/ public SerializationException() { super(); } /** *

Constructs a new SerializationException with specified * detail message.

* * @param msg The error message. */ public SerializationException(String msg) { super(msg); } /** *

Constructs a new SerializationException with specified * nested Throwable.

* * @param cause The Exception or Error * that caused this exception to be thrown. */ public SerializationException(Throwable cause) { super(cause); } /** *

Constructs a new SerializationException with specified * detail message and nested Throwable.

* * @param msg The error message. * @param cause The Exception or Error * that caused this exception to be thrown. */ public SerializationException(String msg, Throwable cause) { super(msg, cause); } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/SerializationUtils.java100644 0 0 17030 11513702446 25454 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.io.Serializable; /** *

Assists with the serialization process and performs additional functionality based * on serialization.

*

*

    *
  • Deep clone using serialization *
  • Serialize managing finally and IOException *
  • Deserialize managing finally and IOException *
* *

This class throws exceptions for invalid null inputs. * Each method documents its behaviour in more detail.

* *

#ThreadSafe#

* @author Apache Software Foundation * @author Nissim Karpenstein * @author Janek Bogucki * @author Daniel L. Rall * @author Jeff Varszegi * @author Gary Gregory * @since 1.0 * @version $Id: SerializationUtils.java 1056988 2011-01-09 17:58:53Z niallp $ */ public class SerializationUtils { /** *

SerializationUtils instances should NOT be constructed in standard programming. * Instead, the class should be used as SerializationUtils.clone(object).

* *

This constructor is public to permit tools that require a JavaBean instance * to operate.

* @since 2.0 */ public SerializationUtils() { super(); } // Clone //----------------------------------------------------------------------- /** *

Deep clone an Object using serialization.

* *

This is many times slower than writing clone methods by hand * on all objects in your object graph. However, for complex object * graphs, or for those that don't support deep cloning this can * be a simple alternative implementation. Of course all the objects * must be Serializable.

* * @param object the Serializable object to clone * @return the cloned object * @throws SerializationException (runtime) if the serialization fails */ public static Object clone(Serializable object) { return deserialize(serialize(object)); } // Serialize //----------------------------------------------------------------------- /** *

Serializes an Object to the specified stream.

* *

The stream will be closed once the object is written. * This avoids the need for a finally clause, and maybe also exception * handling, in the application code.

* *

The stream passed in is not buffered internally within this method. * This is the responsibility of your application if desired.

* * @param obj the object to serialize to bytes, may be null * @param outputStream the stream to write to, must not be null * @throws IllegalArgumentException if outputStream is null * @throws SerializationException (runtime) if the serialization fails */ public static void serialize(Serializable obj, OutputStream outputStream) { if (outputStream == null) { throw new IllegalArgumentException("The OutputStream must not be null"); } ObjectOutputStream out = null; try { // stream closed in the finally out = new ObjectOutputStream(outputStream); out.writeObject(obj); } catch (IOException ex) { throw new SerializationException(ex); } finally { try { if (out != null) { out.close(); } } catch (IOException ex) { // ignore close exception } } } /** *

Serializes an Object to a byte array for * storage/serialization.

* * @param obj the object to serialize to bytes * @return a byte[] with the converted Serializable * @throws SerializationException (runtime) if the serialization fails */ public static byte[] serialize(Serializable obj) { ByteArrayOutputStream baos = new ByteArrayOutputStream(512); serialize(obj, baos); return baos.toByteArray(); } // Deserialize //----------------------------------------------------------------------- /** *

Deserializes an Object from the specified stream.

* *

The stream will be closed once the object is written. This * avoids the need for a finally clause, and maybe also exception * handling, in the application code.

* *

The stream passed in is not buffered internally within this method. * This is the responsibility of your application if desired.

* * @param inputStream the serialized object input stream, must not be null * @return the deserialized object * @throws IllegalArgumentException if inputStream is null * @throws SerializationException (runtime) if the serialization fails */ public static Object deserialize(InputStream inputStream) { if (inputStream == null) { throw new IllegalArgumentException("The InputStream must not be null"); } ObjectInputStream in = null; try { // stream closed in the finally in = new ObjectInputStream(inputStream); return in.readObject(); } catch (ClassNotFoundException ex) { throw new SerializationException(ex); } catch (IOException ex) { throw new SerializationException(ex); } finally { try { if (in != null) { in.close(); } } catch (IOException ex) { // ignore close exception } } } /** *

Deserializes a single Object from an array of bytes.

* * @param objectData the serialized object, must not be null * @return the deserialized object * @throws IllegalArgumentException if objectData is null * @throws SerializationException (runtime) if the serialization fails */ public static Object deserialize(byte[] objectData) { if (objectData == null) { throw new IllegalArgumentException("The byte[] must not be null"); } ByteArrayInputStream bais = new ByteArrayInputStream(objectData); return deserialize(bais); } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/StringEscapeUtils.java100644 0 0 103214 11513702446 25246 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang; import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import java.util.Locale; import org.apache.commons.lang.exception.NestableRuntimeException; import org.apache.commons.lang.text.StrBuilder; /** *

Escapes and unescapes Strings for * Java, Java Script, HTML, XML, and SQL.

* *

#ThreadSafe#

* @author Apache Software Foundation * @author Apache Jakarta Turbine * @author Purple Technology * @author Alexander Day Chaffee * @author Antony Riley * @author Helge Tesgaard * @author Sean Brown * @author Gary Gregory * @author Phil Steitz * @author Pete Gieser * @since 2.0 * @version $Id: StringEscapeUtils.java 1057072 2011-01-10 01:55:57Z niallp $ */ public class StringEscapeUtils { private static final char CSV_DELIMITER = ','; private static final char CSV_QUOTE = '"'; private static final String CSV_QUOTE_STR = String.valueOf(CSV_QUOTE); private static final char[] CSV_SEARCH_CHARS = new char[] {CSV_DELIMITER, CSV_QUOTE, CharUtils.CR, CharUtils.LF}; /** *

StringEscapeUtils instances should NOT be constructed in * standard programming.

* *

Instead, the class should be used as: *

StringEscapeUtils.escapeJava("foo");

* *

This constructor is public to permit tools that require a JavaBean * instance to operate.

*/ public StringEscapeUtils() { super(); } // Java and JavaScript //-------------------------------------------------------------------------- /** *

Escapes the characters in a String using Java String rules.

* *

Deals correctly with quotes and control-chars (tab, backslash, cr, ff, etc.)

* *

So a tab becomes the characters '\\' and * 't'.

* *

The only difference between Java strings and JavaScript strings * is that in JavaScript, a single quote must be escaped.

* *

Example: *

     * input string: He didn't say, "Stop!"
     * output string: He didn't say, \"Stop!\"
     * 
*

* * @param str String to escape values in, may be null * @return String with escaped values, null if null string input */ public static String escapeJava(String str) { return escapeJavaStyleString(str, false, false); } /** *

Escapes the characters in a String using Java String rules to * a Writer.

* *

A null string input has no effect.

* * @see #escapeJava(java.lang.String) * @param out Writer to write escaped string into * @param str String to escape values in, may be null * @throws IllegalArgumentException if the Writer is null * @throws IOException if error occurs on underlying Writer */ public static void escapeJava(Writer out, String str) throws IOException { escapeJavaStyleString(out, str, false, false); } /** *

Escapes the characters in a String using JavaScript String rules.

*

Escapes any values it finds into their JavaScript String form. * Deals correctly with quotes and control-chars (tab, backslash, cr, ff, etc.)

* *

So a tab becomes the characters '\\' and * 't'.

* *

The only difference between Java strings and JavaScript strings * is that in JavaScript, a single quote must be escaped.

* *

Example: *

     * input string: He didn't say, "Stop!"
     * output string: He didn\'t say, \"Stop!\"
     * 
*

* * @param str String to escape values in, may be null * @return String with escaped values, null if null string input */ public static String escapeJavaScript(String str) { return escapeJavaStyleString(str, true, true); } /** *

Escapes the characters in a String using JavaScript String rules * to a Writer.

* *

A null string input has no effect.

* * @see #escapeJavaScript(java.lang.String) * @param out Writer to write escaped string into * @param str String to escape values in, may be null * @throws IllegalArgumentException if the Writer is null * @throws IOException if error occurs on underlying Writer **/ public static void escapeJavaScript(Writer out, String str) throws IOException { escapeJavaStyleString(out, str, true, true); } /** *

Worker method for the {@link #escapeJavaScript(String)} method.

* * @param str String to escape values in, may be null * @param escapeSingleQuotes escapes single quotes if true * @param escapeForwardSlash TODO * @return the escaped string */ private static String escapeJavaStyleString(String str, boolean escapeSingleQuotes, boolean escapeForwardSlash) { if (str == null) { return null; } try { StringWriter writer = new StringWriter(str.length() * 2); escapeJavaStyleString(writer, str, escapeSingleQuotes, escapeForwardSlash); return writer.toString(); } catch (IOException ioe) { // this should never ever happen while writing to a StringWriter throw new UnhandledException(ioe); } } /** *

Worker method for the {@link #escapeJavaScript(String)} method.

* * @param out write to receieve the escaped string * @param str String to escape values in, may be null * @param escapeSingleQuote escapes single quotes if true * @param escapeForwardSlash TODO * @throws IOException if an IOException occurs */ private static void escapeJavaStyleString(Writer out, String str, boolean escapeSingleQuote, boolean escapeForwardSlash) throws IOException { if (out == null) { throw new IllegalArgumentException("The Writer must not be null"); } if (str == null) { return; } int sz; sz = str.length(); for (int i = 0; i < sz; i++) { char ch = str.charAt(i); // handle unicode if (ch > 0xfff) { out.write("\\u" + hex(ch)); } else if (ch > 0xff) { out.write("\\u0" + hex(ch)); } else if (ch > 0x7f) { out.write("\\u00" + hex(ch)); } else if (ch < 32) { switch (ch) { case '\b' : out.write('\\'); out.write('b'); break; case '\n' : out.write('\\'); out.write('n'); break; case '\t' : out.write('\\'); out.write('t'); break; case '\f' : out.write('\\'); out.write('f'); break; case '\r' : out.write('\\'); out.write('r'); break; default : if (ch > 0xf) { out.write("\\u00" + hex(ch)); } else { out.write("\\u000" + hex(ch)); } break; } } else { switch (ch) { case '\'' : if (escapeSingleQuote) { out.write('\\'); } out.write('\''); break; case '"' : out.write('\\'); out.write('"'); break; case '\\' : out.write('\\'); out.write('\\'); break; case '/' : if (escapeForwardSlash) { out.write('\\'); } out.write('/'); break; default : out.write(ch); break; } } } } /** *

Returns an upper case hexadecimal String for the given * character.

* * @param ch The character to convert. * @return An upper case hexadecimal String */ private static String hex(char ch) { return Integer.toHexString(ch).toUpperCase(Locale.ENGLISH); } /** *

Unescapes any Java literals found in the String. * For example, it will turn a sequence of '\' and * 'n' into a newline character, unless the '\' * is preceded by another '\'.

* * @param str the String to unescape, may be null * @return a new unescaped String, null if null string input */ public static String unescapeJava(String str) { if (str == null) { return null; } try { StringWriter writer = new StringWriter(str.length()); unescapeJava(writer, str); return writer.toString(); } catch (IOException ioe) { // this should never ever happen while writing to a StringWriter throw new UnhandledException(ioe); } } /** *

Unescapes any Java literals found in the String to a * Writer.

* *

For example, it will turn a sequence of '\' and * 'n' into a newline character, unless the '\' * is preceded by another '\'.

* *

A null string input has no effect.

* * @param out the Writer used to output unescaped characters * @param str the String to unescape, may be null * @throws IllegalArgumentException if the Writer is null * @throws IOException if error occurs on underlying Writer */ public static void unescapeJava(Writer out, String str) throws IOException { if (out == null) { throw new IllegalArgumentException("The Writer must not be null"); } if (str == null) { return; } int sz = str.length(); StrBuilder unicode = new StrBuilder(4); boolean hadSlash = false; boolean inUnicode = false; for (int i = 0; i < sz; i++) { char ch = str.charAt(i); if (inUnicode) { // if in unicode, then we're reading unicode // values in somehow unicode.append(ch); if (unicode.length() == 4) { // unicode now contains the four hex digits // which represents our unicode character try { int value = Integer.parseInt(unicode.toString(), 16); out.write((char) value); unicode.setLength(0); inUnicode = false; hadSlash = false; } catch (NumberFormatException nfe) { throw new NestableRuntimeException("Unable to parse unicode value: " + unicode, nfe); } } continue; } if (hadSlash) { // handle an escaped value hadSlash = false; switch (ch) { case '\\': out.write('\\'); break; case '\'': out.write('\''); break; case '\"': out.write('"'); break; case 'r': out.write('\r'); break; case 'f': out.write('\f'); break; case 't': out.write('\t'); break; case 'n': out.write('\n'); break; case 'b': out.write('\b'); break; case 'u': { // uh-oh, we're in unicode country.... inUnicode = true; break; } default : out.write(ch); break; } continue; } else if (ch == '\\') { hadSlash = true; continue; } out.write(ch); } if (hadSlash) { // then we're in the weird case of a \ at the end of the // string, let's output it anyway. out.write('\\'); } } /** *

Unescapes any JavaScript literals found in the String.

* *

For example, it will turn a sequence of '\' and 'n' * into a newline character, unless the '\' is preceded by another * '\'.

* * @see #unescapeJava(String) * @param str the String to unescape, may be null * @return A new unescaped String, null if null string input */ public static String unescapeJavaScript(String str) { return unescapeJava(str); } /** *

Unescapes any JavaScript literals found in the String to a * Writer.

* *

For example, it will turn a sequence of '\' and 'n' * into a newline character, unless the '\' is preceded by another * '\'.

* *

A null string input has no effect.

* * @see #unescapeJava(Writer,String) * @param out the Writer used to output unescaped characters * @param str the String to unescape, may be null * @throws IllegalArgumentException if the Writer is null * @throws IOException if error occurs on underlying Writer */ public static void unescapeJavaScript(Writer out, String str) throws IOException { unescapeJava(out, str); } // HTML and XML //-------------------------------------------------------------------------- /** *

Escapes the characters in a String using HTML entities.

* *

* For example: *

*

"bread" & "butter"

* becomes: *

* &quot;bread&quot; &amp; &quot;butter&quot;. *

* *

Supports all known HTML 4.0 entities, including funky accents. * Note that the commonly used apostrophe escape character (&apos;) * is not a legal entity and so is not supported).

* * @param str the String to escape, may be null * @return a new escaped String, null if null string input * * @see #unescapeHtml(String) * @see ISO Entities * @see HTML 3.2 Character Entities for ISO Latin-1 * @see HTML 4.0 Character entity references * @see HTML 4.01 Character References * @see HTML 4.01 Code positions */ public static String escapeHtml(String str) { if (str == null) { return null; } try { StringWriter writer = new StringWriter ((int)(str.length() * 1.5)); escapeHtml(writer, str); return writer.toString(); } catch (IOException ioe) { //should be impossible throw new UnhandledException(ioe); } } /** *

Escapes the characters in a String using HTML entities and writes * them to a Writer.

* *

* For example: *

* "bread" & "butter" *

becomes:

* &quot;bread&quot; &amp; &quot;butter&quot;. * *

Supports all known HTML 4.0 entities, including funky accents. * Note that the commonly used apostrophe escape character (&apos;) * is not a legal entity and so is not supported).

* * @param writer the writer receiving the escaped string, not null * @param string the String to escape, may be null * @throws IllegalArgumentException if the writer is null * @throws IOException when Writer passed throws the exception from * calls to the {@link Writer#write(int)} methods. * * @see #escapeHtml(String) * @see #unescapeHtml(String) * @see ISO Entities * @see HTML 3.2 Character Entities for ISO Latin-1 * @see HTML 4.0 Character entity references * @see HTML 4.01 Character References * @see HTML 4.01 Code positions */ public static void escapeHtml(Writer writer, String string) throws IOException { if (writer == null ) { throw new IllegalArgumentException ("The Writer must not be null."); } if (string == null) { return; } Entities.HTML40.escape(writer, string); } //----------------------------------------------------------------------- /** *

Unescapes a string containing entity escapes to a string * containing the actual Unicode characters corresponding to the * escapes. Supports HTML 4.0 entities.

* *

For example, the string "&lt;Fran&ccedil;ais&gt;" * will become "<Français>"

* *

If an entity is unrecognized, it is left alone, and inserted * verbatim into the result string. e.g. "&gt;&zzzz;x" will * become ">&zzzz;x".

* * @param str the String to unescape, may be null * @return a new unescaped String, null if null string input * @see #escapeHtml(Writer, String) */ public static String unescapeHtml(String str) { if (str == null) { return null; } try { StringWriter writer = new StringWriter ((int)(str.length() * 1.5)); unescapeHtml(writer, str); return writer.toString(); } catch (IOException ioe) { //should be impossible throw new UnhandledException(ioe); } } /** *

Unescapes a string containing entity escapes to a string * containing the actual Unicode characters corresponding to the * escapes. Supports HTML 4.0 entities.

* *

For example, the string "&lt;Fran&ccedil;ais&gt;" * will become "<Français>"

* *

If an entity is unrecognized, it is left alone, and inserted * verbatim into the result string. e.g. "&gt;&zzzz;x" will * become ">&zzzz;x".

* * @param writer the writer receiving the unescaped string, not null * @param string the String to unescape, may be null * @throws IllegalArgumentException if the writer is null * @throws IOException if an IOException occurs * @see #escapeHtml(String) */ public static void unescapeHtml(Writer writer, String string) throws IOException { if (writer == null ) { throw new IllegalArgumentException ("The Writer must not be null."); } if (string == null) { return; } Entities.HTML40.unescape(writer, string); } //----------------------------------------------------------------------- /** *

Escapes the characters in a String using XML entities.

* *

For example: "bread" & "butter" => * &quot;bread&quot; &amp; &quot;butter&quot;. *

* *

Supports only the five basic XML entities (gt, lt, quot, amp, apos). * Does not support DTDs or external entities.

* *

Note that unicode characters greater than 0x7f are currently escaped to * their numerical \\u equivalent. This may change in future releases.

* * @param writer the writer receiving the unescaped string, not null * @param str the String to escape, may be null * @throws IllegalArgumentException if the writer is null * @throws IOException if there is a problem writing * @see #unescapeXml(java.lang.String) */ public static void escapeXml(Writer writer, String str) throws IOException { if (writer == null ) { throw new IllegalArgumentException ("The Writer must not be null."); } if (str == null) { return; } Entities.XML.escape(writer, str); } /** *

Escapes the characters in a String using XML entities.

* *

For example: "bread" & "butter" => * &quot;bread&quot; &amp; &quot;butter&quot;. *

* *

Supports only the five basic XML entities (gt, lt, quot, amp, apos). * Does not support DTDs or external entities.

* *

Note that unicode characters greater than 0x7f are currently escaped to * their numerical \\u equivalent. This may change in future releases.

* * @param str the String to escape, may be null * @return a new escaped String, null if null string input * @see #unescapeXml(java.lang.String) */ public static String escapeXml(String str) { if (str == null) { return null; } return Entities.XML.escape(str); } //----------------------------------------------------------------------- /** *

Unescapes a string containing XML entity escapes to a string * containing the actual Unicode characters corresponding to the * escapes.

* *

Supports only the five basic XML entities (gt, lt, quot, amp, apos). * Does not support DTDs or external entities.

* *

Note that numerical \\u unicode codes are unescaped to their respective * unicode characters. This may change in future releases.

* * @param writer the writer receiving the unescaped string, not null * @param str the String to unescape, may be null * @throws IllegalArgumentException if the writer is null * @throws IOException if there is a problem writing * @see #escapeXml(String) */ public static void unescapeXml(Writer writer, String str) throws IOException { if (writer == null ) { throw new IllegalArgumentException ("The Writer must not be null."); } if (str == null) { return; } Entities.XML.unescape(writer, str); } /** *

Unescapes a string containing XML entity escapes to a string * containing the actual Unicode characters corresponding to the * escapes.

* *

Supports only the five basic XML entities (gt, lt, quot, amp, apos). * Does not support DTDs or external entities.

* *

Note that numerical \\u unicode codes are unescaped to their respective * unicode characters. This may change in future releases.

* * @param str the String to unescape, may be null * @return a new unescaped String, null if null string input * @see #escapeXml(String) */ public static String unescapeXml(String str) { if (str == null) { return null; } return Entities.XML.unescape(str); } //----------------------------------------------------------------------- /** *

Escapes the characters in a String to be suitable to pass to * an SQL query.

* *

For example, *

statement.executeQuery("SELECT * FROM MOVIES WHERE TITLE='" + 
     *   StringEscapeUtils.escapeSql("McHale's Navy") + 
     *   "'");
*

* *

At present, this method only turns single-quotes into doubled single-quotes * ("McHale's Navy" => "McHale''s Navy"). It does not * handle the cases of percent (%) or underscore (_) for use in LIKE clauses.

* * see http://www.jguru.com/faq/view.jsp?EID=8881 * @param str the string to escape, may be null * @return a new String, escaped for SQL, null if null string input */ public static String escapeSql(String str) { if (str == null) { return null; } return StringUtils.replace(str, "'", "''"); } //----------------------------------------------------------------------- /** *

Returns a String value for a CSV column enclosed in double quotes, * if required.

* *

If the value contains a comma, newline or double quote, then the * String value is returned enclosed in double quotes.

*

* *

Any double quote characters in the value are escaped with another double quote.

* *

If the value does not contain a comma, newline or double quote, then the * String value is returned unchanged.

*

* * see Wikipedia and * RFC 4180. * * @param str the input CSV column String, may be null * @return the input String, enclosed in double quotes if the value contains a comma, * newline or double quote, null if null string input * @since 2.4 */ public static String escapeCsv(String str) { if (StringUtils.containsNone(str, CSV_SEARCH_CHARS)) { return str; } try { StringWriter writer = new StringWriter(); escapeCsv(writer, str); return writer.toString(); } catch (IOException ioe) { // this should never ever happen while writing to a StringWriter throw new UnhandledException(ioe); } } /** *

Writes a String value for a CSV column enclosed in double quotes, * if required.

* *

If the value contains a comma, newline or double quote, then the * String value is written enclosed in double quotes.

*

* *

Any double quote characters in the value are escaped with another double quote.

* *

If the value does not contain a comma, newline or double quote, then the * String value is written unchanged (null values are ignored).

*

* * see Wikipedia and * RFC 4180. * * @param str the input CSV column String, may be null * @param out Writer to write input string to, enclosed in double quotes if it contains * a comma, newline or double quote * @throws IOException if error occurs on underlying Writer * @since 2.4 */ public static void escapeCsv(Writer out, String str) throws IOException { if (StringUtils.containsNone(str, CSV_SEARCH_CHARS)) { if (str != null) { out.write(str); } return; } out.write(CSV_QUOTE); for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); if (c == CSV_QUOTE) { out.write(CSV_QUOTE); // escape double quote } out.write(c); } out.write(CSV_QUOTE); } /** *

Returns a String value for an unescaped CSV column.

* *

If the value is enclosed in double quotes, and contains a comma, newline * or double quote, then quotes are removed. *

* *

Any double quote escaped characters (a pair of double quotes) are unescaped * to just one double quote.

* *

If the value is not enclosed in double quotes, or is and does not contain a * comma, newline or double quote, then the String value is returned unchanged.

*

* * see Wikipedia and * RFC 4180. * * @param str the input CSV column String, may be null * @return the input String, with enclosing double quotes removed and embedded double * quotes unescaped, null if null string input * @since 2.4 */ public static String unescapeCsv(String str) { if (str == null) { return null; } try { StringWriter writer = new StringWriter(); unescapeCsv(writer, str); return writer.toString(); } catch (IOException ioe) { // this should never ever happen while writing to a StringWriter throw new UnhandledException(ioe); } } /** *

Returns a String value for an unescaped CSV column.

* *

If the value is enclosed in double quotes, and contains a comma, newline * or double quote, then quotes are removed. *

* *

Any double quote escaped characters (a pair of double quotes) are unescaped * to just one double quote.

* *

If the value is not enclosed in double quotes, or is and does not contain a * comma, newline or double quote, then the String value is returned unchanged.

*

* * see Wikipedia and * RFC 4180. * * @param str the input CSV column String, may be null * @param out Writer to write the input String to, with enclosing double quotes * removed and embedded double quotes unescaped, null if null string input * @throws IOException if error occurs on underlying Writer * @since 2.4 */ public static void unescapeCsv(Writer out, String str) throws IOException { if (str == null) { return; } if (str.length() < 2) { out.write(str); return; } if ( str.charAt(0) != CSV_QUOTE || str.charAt(str.length() - 1) != CSV_QUOTE ) { out.write(str); return; } // strip quotes String quoteless = str.substring(1, str.length() - 1); if ( StringUtils.containsAny(quoteless, CSV_SEARCH_CHARS) ) { // deal with escaped quotes; ie) "" str = StringUtils.replace(quoteless, CSV_QUOTE_STR + CSV_QUOTE_STR, CSV_QUOTE_STR); } out.write(str); } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/StringUtils.java100644 0 0 1014637 11513702445 24157 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Locale; import org.apache.commons.lang.text.StrBuilder; /** *

Operations on {@link java.lang.String} that are * null safe.

* *
    *
  • IsEmpty/IsBlank * - checks if a String contains text
  • *
  • Trim/Strip * - removes leading and trailing whitespace
  • *
  • Equals * - compares two strings null-safe
  • *
  • startsWith * - check if a String starts with a prefix null-safe
  • *
  • endsWith * - check if a String ends with a suffix null-safe
  • *
  • IndexOf/LastIndexOf/Contains * - null-safe index-of checks *
  • IndexOfAny/LastIndexOfAny/IndexOfAnyBut/LastIndexOfAnyBut * - index-of any of a set of Strings
  • *
  • ContainsOnly/ContainsNone/ContainsAny * - does String contains only/none/any of these characters
  • *
  • Substring/Left/Right/Mid * - null-safe substring extractions
  • *
  • SubstringBefore/SubstringAfter/SubstringBetween * - substring extraction relative to other strings
  • *
  • Split/Join * - splits a String into an array of substrings and vice versa
  • *
  • Remove/Delete * - removes part of a String
  • *
  • Replace/Overlay * - Searches a String and replaces one String with another
  • *
  • Chomp/Chop * - removes the last part of a String
  • *
  • LeftPad/RightPad/Center/Repeat * - pads a String
  • *
  • UpperCase/LowerCase/SwapCase/Capitalize/Uncapitalize * - changes the case of a String
  • *
  • CountMatches * - counts the number of occurrences of one String in another
  • *
  • IsAlpha/IsNumeric/IsWhitespace/IsAsciiPrintable * - checks the characters in a String
  • *
  • DefaultString * - protects against a null input String
  • *
  • Reverse/ReverseDelimited * - reverses a String
  • *
  • Abbreviate * - abbreviates a string using ellipsis
  • *
  • Difference * - compares Strings and reports on their differences
  • *
  • LevensteinDistance * - the number of changes needed to change one String into another
  • *
* *

The StringUtils class defines certain words related to * String handling.

* *
    *
  • null - null
  • *
  • empty - a zero-length string ("")
  • *
  • space - the space character (' ', char 32)
  • *
  • whitespace - the characters defined by {@link Character#isWhitespace(char)}
  • *
  • trim - the characters <= 32 as in {@link String#trim()}
  • *
* *

StringUtils handles null input Strings quietly. * That is to say that a null input will return null. * Where a boolean or int is being returned * details vary by method.

* *

A side effect of the null handling is that a * NullPointerException should be considered a bug in * StringUtils (except for deprecated methods).

* *

Methods in this class give sample code to explain their operation. * The symbol * is used to indicate any input including null.

* *

#ThreadSafe#

* @see java.lang.String * @author Apache Software Foundation * @author Apache Jakarta Turbine * @author Jon S. Stevens * @author Daniel L. Rall * @author Greg Coladonato * @author Ed Korthof * @author Rand McNeely * @author Fredrik Westermarck * @author Holger Krauth * @author Alexander Day Chaffee * @author Henning P. Schmiedehausen * @author Arun Mammen Thomas * @author Gary Gregory * @author Phil Steitz * @author Al Chou * @author Michael Davey * @author Reuben Sivan * @author Chris Hyzer * @author Scott Johnson * @since 1.0 * @version $Id: StringUtils.java 1058365 2011-01-13 00:04:49Z niallp $ */ //@Immutable public class StringUtils { // Performance testing notes (JDK 1.4, Jul03, scolebourne) // Whitespace: // Character.isWhitespace() is faster than WHITESPACE.indexOf() // where WHITESPACE is a string of all whitespace characters // // Character access: // String.charAt(n) versus toCharArray(), then array[n] // String.charAt(n) is about 15% worse for a 10K string // They are about equal for a length 50 string // String.charAt(n) is about 4 times better for a length 3 string // String.charAt(n) is best bet overall // // Append: // String.concat about twice as fast as StringBuffer.append // (not sure who tested this) /** * The empty String "". * @since 2.0 */ public static final String EMPTY = ""; /** * Represents a failed index search. * @since 2.1 */ public static final int INDEX_NOT_FOUND = -1; /** *

The maximum size to which the padding constant(s) can expand.

*/ private static final int PAD_LIMIT = 8192; /** *

StringUtils instances should NOT be constructed in * standard programming. Instead, the class should be used as * StringUtils.trim(" foo ");.

* *

This constructor is public to permit tools that require a JavaBean * instance to operate.

*/ public StringUtils() { super(); } // Empty checks //----------------------------------------------------------------------- /** *

Checks if a String is empty ("") or null.

* *
     * StringUtils.isEmpty(null)      = true
     * StringUtils.isEmpty("")        = true
     * StringUtils.isEmpty(" ")       = false
     * StringUtils.isEmpty("bob")     = false
     * StringUtils.isEmpty("  bob  ") = false
     * 
* *

NOTE: This method changed in Lang version 2.0. * It no longer trims the String. * That functionality is available in isBlank().

* * @param str the String to check, may be null * @return true if the String is empty or null */ public static boolean isEmpty(String str) { return str == null || str.length() == 0; } /** *

Checks if a String is not empty ("") and not null.

* *
     * StringUtils.isNotEmpty(null)      = false
     * StringUtils.isNotEmpty("")        = false
     * StringUtils.isNotEmpty(" ")       = true
     * StringUtils.isNotEmpty("bob")     = true
     * StringUtils.isNotEmpty("  bob  ") = true
     * 
* * @param str the String to check, may be null * @return true if the String is not empty and not null */ public static boolean isNotEmpty(String str) { return !StringUtils.isEmpty(str); } /** *

Checks if a String is whitespace, empty ("") or null.

* *
     * StringUtils.isBlank(null)      = true
     * StringUtils.isBlank("")        = true
     * StringUtils.isBlank(" ")       = true
     * StringUtils.isBlank("bob")     = false
     * StringUtils.isBlank("  bob  ") = false
     * 
* * @param str the String to check, may be null * @return true if the String is null, empty or whitespace * @since 2.0 */ public static boolean isBlank(String str) { int strLen; if (str == null || (strLen = str.length()) == 0) { return true; } for (int i = 0; i < strLen; i++) { if ((Character.isWhitespace(str.charAt(i)) == false)) { return false; } } return true; } /** *

Checks if a String is not empty (""), not null and not whitespace only.

* *
     * StringUtils.isNotBlank(null)      = false
     * StringUtils.isNotBlank("")        = false
     * StringUtils.isNotBlank(" ")       = false
     * StringUtils.isNotBlank("bob")     = true
     * StringUtils.isNotBlank("  bob  ") = true
     * 
* * @param str the String to check, may be null * @return true if the String is * not empty and not null and not whitespace * @since 2.0 */ public static boolean isNotBlank(String str) { return !StringUtils.isBlank(str); } // Trim //----------------------------------------------------------------------- /** *

Removes control characters (char <= 32) from both * ends of this String, handling null by returning * an empty String ("").

* *
     * StringUtils.clean(null)          = ""
     * StringUtils.clean("")            = ""
     * StringUtils.clean("abc")         = "abc"
     * StringUtils.clean("    abc    ") = "abc"
     * StringUtils.clean("     ")       = ""
     * 
* * @see java.lang.String#trim() * @param str the String to clean, may be null * @return the trimmed text, never null * @deprecated Use the clearer named {@link #trimToEmpty(String)}. * Method will be removed in Commons Lang 3.0. */ public static String clean(String str) { return str == null ? EMPTY : str.trim(); } /** *

Removes control characters (char <= 32) from both * ends of this String, handling null by returning * null.

* *

The String is trimmed using {@link String#trim()}. * Trim removes start and end characters <= 32. * To strip whitespace use {@link #strip(String)}.

* *

To trim your choice of characters, use the * {@link #strip(String, String)} methods.

* *
     * StringUtils.trim(null)          = null
     * StringUtils.trim("")            = ""
     * StringUtils.trim("     ")       = ""
     * StringUtils.trim("abc")         = "abc"
     * StringUtils.trim("    abc    ") = "abc"
     * 
* * @param str the String to be trimmed, may be null * @return the trimmed string, null if null String input */ public static String trim(String str) { return str == null ? null : str.trim(); } /** *

Removes control characters (char <= 32) from both * ends of this String returning null if the String is * empty ("") after the trim or if it is null. * *

The String is trimmed using {@link String#trim()}. * Trim removes start and end characters <= 32. * To strip whitespace use {@link #stripToNull(String)}.

* *
     * StringUtils.trimToNull(null)          = null
     * StringUtils.trimToNull("")            = null
     * StringUtils.trimToNull("     ")       = null
     * StringUtils.trimToNull("abc")         = "abc"
     * StringUtils.trimToNull("    abc    ") = "abc"
     * 
* * @param str the String to be trimmed, may be null * @return the trimmed String, * null if only chars <= 32, empty or null String input * @since 2.0 */ public static String trimToNull(String str) { String ts = trim(str); return isEmpty(ts) ? null : ts; } /** *

Removes control characters (char <= 32) from both * ends of this String returning an empty String ("") if the String * is empty ("") after the trim or if it is null. * *

The String is trimmed using {@link String#trim()}. * Trim removes start and end characters <= 32. * To strip whitespace use {@link #stripToEmpty(String)}.

* *
     * StringUtils.trimToEmpty(null)          = ""
     * StringUtils.trimToEmpty("")            = ""
     * StringUtils.trimToEmpty("     ")       = ""
     * StringUtils.trimToEmpty("abc")         = "abc"
     * StringUtils.trimToEmpty("    abc    ") = "abc"
     * 
* * @param str the String to be trimmed, may be null * @return the trimmed String, or an empty String if null input * @since 2.0 */ public static String trimToEmpty(String str) { return str == null ? EMPTY : str.trim(); } // Stripping //----------------------------------------------------------------------- /** *

Strips whitespace from the start and end of a String.

* *

This is similar to {@link #trim(String)} but removes whitespace. * Whitespace is defined by {@link Character#isWhitespace(char)}.

* *

A null input String returns null.

* *
     * StringUtils.strip(null)     = null
     * StringUtils.strip("")       = ""
     * StringUtils.strip("   ")    = ""
     * StringUtils.strip("abc")    = "abc"
     * StringUtils.strip("  abc")  = "abc"
     * StringUtils.strip("abc  ")  = "abc"
     * StringUtils.strip(" abc ")  = "abc"
     * StringUtils.strip(" ab c ") = "ab c"
     * 
* * @param str the String to remove whitespace from, may be null * @return the stripped String, null if null String input */ public static String strip(String str) { return strip(str, null); } /** *

Strips whitespace from the start and end of a String returning * null if the String is empty ("") after the strip.

* *

This is similar to {@link #trimToNull(String)} but removes whitespace. * Whitespace is defined by {@link Character#isWhitespace(char)}.

* *
     * StringUtils.stripToNull(null)     = null
     * StringUtils.stripToNull("")       = null
     * StringUtils.stripToNull("   ")    = null
     * StringUtils.stripToNull("abc")    = "abc"
     * StringUtils.stripToNull("  abc")  = "abc"
     * StringUtils.stripToNull("abc  ")  = "abc"
     * StringUtils.stripToNull(" abc ")  = "abc"
     * StringUtils.stripToNull(" ab c ") = "ab c"
     * 
* * @param str the String to be stripped, may be null * @return the stripped String, * null if whitespace, empty or null String input * @since 2.0 */ public static String stripToNull(String str) { if (str == null) { return null; } str = strip(str, null); return str.length() == 0 ? null : str; } /** *

Strips whitespace from the start and end of a String returning * an empty String if null input.

* *

This is similar to {@link #trimToEmpty(String)} but removes whitespace. * Whitespace is defined by {@link Character#isWhitespace(char)}.

* *
     * StringUtils.stripToEmpty(null)     = ""
     * StringUtils.stripToEmpty("")       = ""
     * StringUtils.stripToEmpty("   ")    = ""
     * StringUtils.stripToEmpty("abc")    = "abc"
     * StringUtils.stripToEmpty("  abc")  = "abc"
     * StringUtils.stripToEmpty("abc  ")  = "abc"
     * StringUtils.stripToEmpty(" abc ")  = "abc"
     * StringUtils.stripToEmpty(" ab c ") = "ab c"
     * 
* * @param str the String to be stripped, may be null * @return the trimmed String, or an empty String if null input * @since 2.0 */ public static String stripToEmpty(String str) { return str == null ? EMPTY : strip(str, null); } /** *

Strips any of a set of characters from the start and end of a String. * This is similar to {@link String#trim()} but allows the characters * to be stripped to be controlled.

* *

A null input String returns null. * An empty string ("") input returns the empty string.

* *

If the stripChars String is null, whitespace is * stripped as defined by {@link Character#isWhitespace(char)}. * Alternatively use {@link #strip(String)}.

* *
     * StringUtils.strip(null, *)          = null
     * StringUtils.strip("", *)            = ""
     * StringUtils.strip("abc", null)      = "abc"
     * StringUtils.strip("  abc", null)    = "abc"
     * StringUtils.strip("abc  ", null)    = "abc"
     * StringUtils.strip(" abc ", null)    = "abc"
     * StringUtils.strip("  abcyx", "xyz") = "  abc"
     * 
* * @param str the String to remove characters from, may be null * @param stripChars the characters to remove, null treated as whitespace * @return the stripped String, null if null String input */ public static String strip(String str, String stripChars) { if (isEmpty(str)) { return str; } str = stripStart(str, stripChars); return stripEnd(str, stripChars); } /** *

Strips any of a set of characters from the start of a String.

* *

A null input String returns null. * An empty string ("") input returns the empty string.

* *

If the stripChars String is null, whitespace is * stripped as defined by {@link Character#isWhitespace(char)}.

* *
     * StringUtils.stripStart(null, *)          = null
     * StringUtils.stripStart("", *)            = ""
     * StringUtils.stripStart("abc", "")        = "abc"
     * StringUtils.stripStart("abc", null)      = "abc"
     * StringUtils.stripStart("  abc", null)    = "abc"
     * StringUtils.stripStart("abc  ", null)    = "abc  "
     * StringUtils.stripStart(" abc ", null)    = "abc "
     * StringUtils.stripStart("yxabc  ", "xyz") = "abc  "
     * 
* * @param str the String to remove characters from, may be null * @param stripChars the characters to remove, null treated as whitespace * @return the stripped String, null if null String input */ public static String stripStart(String str, String stripChars) { int strLen; if (str == null || (strLen = str.length()) == 0) { return str; } int start = 0; if (stripChars == null) { while ((start != strLen) && Character.isWhitespace(str.charAt(start))) { start++; } } else if (stripChars.length() == 0) { return str; } else { while ((start != strLen) && (stripChars.indexOf(str.charAt(start)) != INDEX_NOT_FOUND)) { start++; } } return str.substring(start); } /** *

Strips any of a set of characters from the end of a String.

* *

A null input String returns null. * An empty string ("") input returns the empty string.

* *

If the stripChars String is null, whitespace is * stripped as defined by {@link Character#isWhitespace(char)}.

* *
     * StringUtils.stripEnd(null, *)          = null
     * StringUtils.stripEnd("", *)            = ""
     * StringUtils.stripEnd("abc", "")        = "abc"
     * StringUtils.stripEnd("abc", null)      = "abc"
     * StringUtils.stripEnd("  abc", null)    = "  abc"
     * StringUtils.stripEnd("abc  ", null)    = "abc"
     * StringUtils.stripEnd(" abc ", null)    = " abc"
     * StringUtils.stripEnd("  abcyx", "xyz") = "  abc"
     * StringUtils.stripEnd("120.00", ".0")   = "12"
     * 
* * @param str the String to remove characters from, may be null * @param stripChars the set of characters to remove, null treated as whitespace * @return the stripped String, null if null String input */ public static String stripEnd(String str, String stripChars) { int end; if (str == null || (end = str.length()) == 0) { return str; } if (stripChars == null) { while ((end != 0) && Character.isWhitespace(str.charAt(end - 1))) { end--; } } else if (stripChars.length() == 0) { return str; } else { while ((end != 0) && (stripChars.indexOf(str.charAt(end - 1)) != INDEX_NOT_FOUND)) { end--; } } return str.substring(0, end); } // StripAll //----------------------------------------------------------------------- /** *

Strips whitespace from the start and end of every String in an array. * Whitespace is defined by {@link Character#isWhitespace(char)}.

* *

A new array is returned each time, except for length zero. * A null array will return null. * An empty array will return itself. * A null array entry will be ignored.

* *
     * StringUtils.stripAll(null)             = null
     * StringUtils.stripAll([])               = []
     * StringUtils.stripAll(["abc", "  abc"]) = ["abc", "abc"]
     * StringUtils.stripAll(["abc  ", null])  = ["abc", null]
     * 
* * @param strs the array to remove whitespace from, may be null * @return the stripped Strings, null if null array input */ public static String[] stripAll(String[] strs) { return stripAll(strs, null); } /** *

Strips any of a set of characters from the start and end of every * String in an array.

* Whitespace is defined by {@link Character#isWhitespace(char)}.

* *

A new array is returned each time, except for length zero. * A null array will return null. * An empty array will return itself. * A null array entry will be ignored. * A null stripChars will strip whitespace as defined by * {@link Character#isWhitespace(char)}.

* *
     * StringUtils.stripAll(null, *)                = null
     * StringUtils.stripAll([], *)                  = []
     * StringUtils.stripAll(["abc", "  abc"], null) = ["abc", "abc"]
     * StringUtils.stripAll(["abc  ", null], null)  = ["abc", null]
     * StringUtils.stripAll(["abc  ", null], "yz")  = ["abc  ", null]
     * StringUtils.stripAll(["yabcz", null], "yz")  = ["abc", null]
     * 
* * @param strs the array to remove characters from, may be null * @param stripChars the characters to remove, null treated as whitespace * @return the stripped Strings, null if null array input */ public static String[] stripAll(String[] strs, String stripChars) { int strsLen; if (strs == null || (strsLen = strs.length) == 0) { return strs; } String[] newArr = new String[strsLen]; for (int i = 0; i < strsLen; i++) { newArr[i] = strip(strs[i], stripChars); } return newArr; } // Equals //----------------------------------------------------------------------- /** *

Compares two Strings, returning true if they are equal.

* *

nulls are handled without exceptions. Two null * references are considered to be equal. The comparison is case sensitive.

* *
     * StringUtils.equals(null, null)   = true
     * StringUtils.equals(null, "abc")  = false
     * StringUtils.equals("abc", null)  = false
     * StringUtils.equals("abc", "abc") = true
     * StringUtils.equals("abc", "ABC") = false
     * 
* * @see java.lang.String#equals(Object) * @param str1 the first String, may be null * @param str2 the second String, may be null * @return true if the Strings are equal, case sensitive, or * both null */ public static boolean equals(String str1, String str2) { return str1 == null ? str2 == null : str1.equals(str2); } /** *

Compares two Strings, returning true if they are equal ignoring * the case.

* *

nulls are handled without exceptions. Two null * references are considered equal. Comparison is case insensitive.

* *
     * StringUtils.equalsIgnoreCase(null, null)   = true
     * StringUtils.equalsIgnoreCase(null, "abc")  = false
     * StringUtils.equalsIgnoreCase("abc", null)  = false
     * StringUtils.equalsIgnoreCase("abc", "abc") = true
     * StringUtils.equalsIgnoreCase("abc", "ABC") = true
     * 
* * @see java.lang.String#equalsIgnoreCase(String) * @param str1 the first String, may be null * @param str2 the second String, may be null * @return true if the Strings are equal, case insensitive, or * both null */ public static boolean equalsIgnoreCase(String str1, String str2) { return str1 == null ? str2 == null : str1.equalsIgnoreCase(str2); } // IndexOf //----------------------------------------------------------------------- /** *

Finds the first index within a String, handling null. * This method uses {@link String#indexOf(int)}.

* *

A null or empty ("") String will return INDEX_NOT_FOUND (-1).

* *
     * StringUtils.indexOf(null, *)         = -1
     * StringUtils.indexOf("", *)           = -1
     * StringUtils.indexOf("aabaabaa", 'a') = 0
     * StringUtils.indexOf("aabaabaa", 'b') = 2
     * 
* * @param str the String to check, may be null * @param searchChar the character to find * @return the first index of the search character, * -1 if no match or null string input * @since 2.0 */ public static int indexOf(String str, char searchChar) { if (isEmpty(str)) { return INDEX_NOT_FOUND; } return str.indexOf(searchChar); } /** *

Finds the first index within a String from a start position, * handling null. * This method uses {@link String#indexOf(int, int)}.

* *

A null or empty ("") String will return (INDEX_NOT_FOUND) -1. * A negative start position is treated as zero. * A start position greater than the string length returns -1.

* *
     * StringUtils.indexOf(null, *, *)          = -1
     * StringUtils.indexOf("", *, *)            = -1
     * StringUtils.indexOf("aabaabaa", 'b', 0)  = 2
     * StringUtils.indexOf("aabaabaa", 'b', 3)  = 5
     * StringUtils.indexOf("aabaabaa", 'b', 9)  = -1
     * StringUtils.indexOf("aabaabaa", 'b', -1) = 2
     * 
* * @param str the String to check, may be null * @param searchChar the character to find * @param startPos the start position, negative treated as zero * @return the first index of the search character, * -1 if no match or null string input * @since 2.0 */ public static int indexOf(String str, char searchChar, int startPos) { if (isEmpty(str)) { return INDEX_NOT_FOUND; } return str.indexOf(searchChar, startPos); } /** *

Finds the first index within a String, handling null. * This method uses {@link String#indexOf(String)}.

* *

A null String will return -1.

* *
     * StringUtils.indexOf(null, *)          = -1
     * StringUtils.indexOf(*, null)          = -1
     * StringUtils.indexOf("", "")           = 0
     * StringUtils.indexOf("", *)            = -1 (except when * = "")
     * StringUtils.indexOf("aabaabaa", "a")  = 0
     * StringUtils.indexOf("aabaabaa", "b")  = 2
     * StringUtils.indexOf("aabaabaa", "ab") = 1
     * StringUtils.indexOf("aabaabaa", "")   = 0
     * 
* * @param str the String to check, may be null * @param searchStr the String to find, may be null * @return the first index of the search String, * -1 if no match or null string input * @since 2.0 */ public static int indexOf(String str, String searchStr) { if (str == null || searchStr == null) { return INDEX_NOT_FOUND; } return str.indexOf(searchStr); } /** *

Finds the n-th index within a String, handling null. * This method uses {@link String#indexOf(String)}.

* *

A null String will return -1.

* *
     * StringUtils.ordinalIndexOf(null, *, *)          = -1
     * StringUtils.ordinalIndexOf(*, null, *)          = -1
     * StringUtils.ordinalIndexOf("", "", *)           = 0
     * StringUtils.ordinalIndexOf("aabaabaa", "a", 1)  = 0
     * StringUtils.ordinalIndexOf("aabaabaa", "a", 2)  = 1
     * StringUtils.ordinalIndexOf("aabaabaa", "b", 1)  = 2
     * StringUtils.ordinalIndexOf("aabaabaa", "b", 2)  = 5
     * StringUtils.ordinalIndexOf("aabaabaa", "ab", 1) = 1
     * StringUtils.ordinalIndexOf("aabaabaa", "ab", 2) = 4
     * StringUtils.ordinalIndexOf("aabaabaa", "", 1)   = 0
     * StringUtils.ordinalIndexOf("aabaabaa", "", 2)   = 0
     * 
* *

Note that 'head(String str, int n)' may be implemented as:

* *
     *   str.substring(0, lastOrdinalIndexOf(str, "\n", n))
     * 
* * @param str the String to check, may be null * @param searchStr the String to find, may be null * @param ordinal the n-th searchStr to find * @return the n-th index of the search String, * -1 (INDEX_NOT_FOUND) if no match or null string input * @since 2.1 */ public static int ordinalIndexOf(String str, String searchStr, int ordinal) { return ordinalIndexOf(str, searchStr, ordinal, false); } /** *

Finds the n-th index within a String, handling null. * This method uses {@link String#indexOf(String)}.

* *

A null String will return -1.

* * @param str the String to check, may be null * @param searchStr the String to find, may be null * @param ordinal the n-th searchStr to find * @param lastIndex true if lastOrdinalIndexOf() otherwise false if ordinalIndexOf() * @return the n-th index of the search String, * -1 (INDEX_NOT_FOUND) if no match or null string input */ // Shared code between ordinalIndexOf(String,String,int) and lastOrdinalIndexOf(String,String,int) private static int ordinalIndexOf(String str, String searchStr, int ordinal, boolean lastIndex) { if (str == null || searchStr == null || ordinal <= 0) { return INDEX_NOT_FOUND; } if (searchStr.length() == 0) { return lastIndex ? str.length() : 0; } int found = 0; int index = lastIndex ? str.length() : INDEX_NOT_FOUND; do { if(lastIndex) { index = str.lastIndexOf(searchStr, index - 1); } else { index = str.indexOf(searchStr, index + 1); } if (index < 0) { return index; } found++; } while (found < ordinal); return index; } /** *

Finds the first index within a String, handling null. * This method uses {@link String#indexOf(String, int)}.

* *

A null String will return -1. * A negative start position is treated as zero. * An empty ("") search String always matches. * A start position greater than the string length only matches * an empty search String.

* *
     * StringUtils.indexOf(null, *, *)          = -1
     * StringUtils.indexOf(*, null, *)          = -1
     * StringUtils.indexOf("", "", 0)           = 0
     * StringUtils.indexOf("", *, 0)            = -1 (except when * = "")
     * StringUtils.indexOf("aabaabaa", "a", 0)  = 0
     * StringUtils.indexOf("aabaabaa", "b", 0)  = 2
     * StringUtils.indexOf("aabaabaa", "ab", 0) = 1
     * StringUtils.indexOf("aabaabaa", "b", 3)  = 5
     * StringUtils.indexOf("aabaabaa", "b", 9)  = -1
     * StringUtils.indexOf("aabaabaa", "b", -1) = 2
     * StringUtils.indexOf("aabaabaa", "", 2)   = 2
     * StringUtils.indexOf("abc", "", 9)        = 3
     * 
* * @param str the String to check, may be null * @param searchStr the String to find, may be null * @param startPos the start position, negative treated as zero * @return the first index of the search String, * -1 if no match or null string input * @since 2.0 */ public static int indexOf(String str, String searchStr, int startPos) { if (str == null || searchStr == null) { return INDEX_NOT_FOUND; } // JDK1.2/JDK1.3 have a bug, when startPos > str.length for "", hence if (searchStr.length() == 0 && startPos >= str.length()) { return str.length(); } return str.indexOf(searchStr, startPos); } /** *

Case in-sensitive find of the first index within a String.

* *

A null String will return -1. * A negative start position is treated as zero. * An empty ("") search String always matches. * A start position greater than the string length only matches * an empty search String.

* *
     * StringUtils.indexOfIgnoreCase(null, *)          = -1
     * StringUtils.indexOfIgnoreCase(*, null)          = -1
     * StringUtils.indexOfIgnoreCase("", "")           = 0
     * StringUtils.indexOfIgnoreCase("aabaabaa", "a")  = 0
     * StringUtils.indexOfIgnoreCase("aabaabaa", "b")  = 2
     * StringUtils.indexOfIgnoreCase("aabaabaa", "ab") = 1
     * 
* * @param str the String to check, may be null * @param searchStr the String to find, may be null * @return the first index of the search String, * -1 if no match or null string input * @since 2.5 */ public static int indexOfIgnoreCase(String str, String searchStr) { return indexOfIgnoreCase(str, searchStr, 0); } /** *

Case in-sensitive find of the first index within a String * from the specified position.

* *

A null String will return -1. * A negative start position is treated as zero. * An empty ("") search String always matches. * A start position greater than the string length only matches * an empty search String.

* *
     * StringUtils.indexOfIgnoreCase(null, *, *)          = -1
     * StringUtils.indexOfIgnoreCase(*, null, *)          = -1
     * StringUtils.indexOfIgnoreCase("", "", 0)           = 0
     * StringUtils.indexOfIgnoreCase("aabaabaa", "A", 0)  = 0
     * StringUtils.indexOfIgnoreCase("aabaabaa", "B", 0)  = 2
     * StringUtils.indexOfIgnoreCase("aabaabaa", "AB", 0) = 1
     * StringUtils.indexOfIgnoreCase("aabaabaa", "B", 3)  = 5
     * StringUtils.indexOfIgnoreCase("aabaabaa", "B", 9)  = -1
     * StringUtils.indexOfIgnoreCase("aabaabaa", "B", -1) = 2
     * StringUtils.indexOfIgnoreCase("aabaabaa", "", 2)   = 2
     * StringUtils.indexOfIgnoreCase("abc", "", 9)        = 3
     * 
* * @param str the String to check, may be null * @param searchStr the String to find, may be null * @param startPos the start position, negative treated as zero * @return the first index of the search String, * -1 if no match or null string input * @since 2.5 */ public static int indexOfIgnoreCase(String str, String searchStr, int startPos) { if (str == null || searchStr == null) { return INDEX_NOT_FOUND; } if (startPos < 0) { startPos = 0; } int endLimit = (str.length() - searchStr.length()) + 1; if (startPos > endLimit) { return INDEX_NOT_FOUND; } if (searchStr.length() == 0) { return startPos; } for (int i = startPos; i < endLimit; i++) { if (str.regionMatches(true, i, searchStr, 0, searchStr.length())) { return i; } } return INDEX_NOT_FOUND; } // LastIndexOf //----------------------------------------------------------------------- /** *

Finds the last index within a String, handling null. * This method uses {@link String#lastIndexOf(int)}.

* *

A null or empty ("") String will return -1.

* *
     * StringUtils.lastIndexOf(null, *)         = -1
     * StringUtils.lastIndexOf("", *)           = -1
     * StringUtils.lastIndexOf("aabaabaa", 'a') = 7
     * StringUtils.lastIndexOf("aabaabaa", 'b') = 5
     * 
* * @param str the String to check, may be null * @param searchChar the character to find * @return the last index of the search character, * -1 if no match or null string input * @since 2.0 */ public static int lastIndexOf(String str, char searchChar) { if (isEmpty(str)) { return INDEX_NOT_FOUND; } return str.lastIndexOf(searchChar); } /** *

Finds the last index within a String from a start position, * handling null. * This method uses {@link String#lastIndexOf(int, int)}.

* *

A null or empty ("") String will return -1. * A negative start position returns -1. * A start position greater than the string length searches the whole string.

* *
     * StringUtils.lastIndexOf(null, *, *)          = -1
     * StringUtils.lastIndexOf("", *,  *)           = -1
     * StringUtils.lastIndexOf("aabaabaa", 'b', 8)  = 5
     * StringUtils.lastIndexOf("aabaabaa", 'b', 4)  = 2
     * StringUtils.lastIndexOf("aabaabaa", 'b', 0)  = -1
     * StringUtils.lastIndexOf("aabaabaa", 'b', 9)  = 5
     * StringUtils.lastIndexOf("aabaabaa", 'b', -1) = -1
     * StringUtils.lastIndexOf("aabaabaa", 'a', 0)  = 0
     * 
* * @param str the String to check, may be null * @param searchChar the character to find * @param startPos the start position * @return the last index of the search character, * -1 if no match or null string input * @since 2.0 */ public static int lastIndexOf(String str, char searchChar, int startPos) { if (isEmpty(str)) { return INDEX_NOT_FOUND; } return str.lastIndexOf(searchChar, startPos); } /** *

Finds the last index within a String, handling null. * This method uses {@link String#lastIndexOf(String)}.

* *

A null String will return -1.

* *
     * StringUtils.lastIndexOf(null, *)          = -1
     * StringUtils.lastIndexOf(*, null)          = -1
     * StringUtils.lastIndexOf("", "")           = 0
     * StringUtils.lastIndexOf("aabaabaa", "a")  = 7
     * StringUtils.lastIndexOf("aabaabaa", "b")  = 5
     * StringUtils.lastIndexOf("aabaabaa", "ab") = 4
     * StringUtils.lastIndexOf("aabaabaa", "")   = 8
     * 
* * @param str the String to check, may be null * @param searchStr the String to find, may be null * @return the last index of the search String, * -1 if no match or null string input * @since 2.0 */ public static int lastIndexOf(String str, String searchStr) { if (str == null || searchStr == null) { return INDEX_NOT_FOUND; } return str.lastIndexOf(searchStr); } /** *

Finds the n-th last index within a String, handling null. * This method uses {@link String#lastIndexOf(String)}.

* *

A null String will return -1.

* *
     * StringUtils.lastOrdinalIndexOf(null, *, *)          = -1
     * StringUtils.lastOrdinalIndexOf(*, null, *)          = -1
     * StringUtils.lastOrdinalIndexOf("", "", *)           = 0
     * StringUtils.lastOrdinalIndexOf("aabaabaa", "a", 1)  = 7
     * StringUtils.lastOrdinalIndexOf("aabaabaa", "a", 2)  = 6
     * StringUtils.lastOrdinalIndexOf("aabaabaa", "b", 1)  = 5
     * StringUtils.lastOrdinalIndexOf("aabaabaa", "b", 2)  = 2
     * StringUtils.lastOrdinalIndexOf("aabaabaa", "ab", 1) = 4
     * StringUtils.lastOrdinalIndexOf("aabaabaa", "ab", 2) = 1
     * StringUtils.lastOrdinalIndexOf("aabaabaa", "", 1)   = 8
     * StringUtils.lastOrdinalIndexOf("aabaabaa", "", 2)   = 8
     * 
* *

Note that 'tail(String str, int n)' may be implemented as:

* *
     *   str.substring(lastOrdinalIndexOf(str, "\n", n) + 1)
     * 
* * @param str the String to check, may be null * @param searchStr the String to find, may be null * @param ordinal the n-th last searchStr to find * @return the n-th last index of the search String, * -1 (INDEX_NOT_FOUND) if no match or null string input * @since 2.5 */ public static int lastOrdinalIndexOf(String str, String searchStr, int ordinal) { return ordinalIndexOf(str, searchStr, ordinal, true); } /** *

Finds the first index within a String, handling null. * This method uses {@link String#lastIndexOf(String, int)}.

* *

A null String will return -1. * A negative start position returns -1. * An empty ("") search String always matches unless the start position is negative. * A start position greater than the string length searches the whole string.

* *
     * StringUtils.lastIndexOf(null, *, *)          = -1
     * StringUtils.lastIndexOf(*, null, *)          = -1
     * StringUtils.lastIndexOf("aabaabaa", "a", 8)  = 7
     * StringUtils.lastIndexOf("aabaabaa", "b", 8)  = 5
     * StringUtils.lastIndexOf("aabaabaa", "ab", 8) = 4
     * StringUtils.lastIndexOf("aabaabaa", "b", 9)  = 5
     * StringUtils.lastIndexOf("aabaabaa", "b", -1) = -1
     * StringUtils.lastIndexOf("aabaabaa", "a", 0)  = 0
     * StringUtils.lastIndexOf("aabaabaa", "b", 0)  = -1
     * 
* * @param str the String to check, may be null * @param searchStr the String to find, may be null * @param startPos the start position, negative treated as zero * @return the first index of the search String, * -1 if no match or null string input * @since 2.0 */ public static int lastIndexOf(String str, String searchStr, int startPos) { if (str == null || searchStr == null) { return INDEX_NOT_FOUND; } return str.lastIndexOf(searchStr, startPos); } /** *

Case in-sensitive find of the last index within a String.

* *

A null String will return -1. * A negative start position returns -1. * An empty ("") search String always matches unless the start position is negative. * A start position greater than the string length searches the whole string.

* *
     * StringUtils.lastIndexOfIgnoreCase(null, *)          = -1
     * StringUtils.lastIndexOfIgnoreCase(*, null)          = -1
     * StringUtils.lastIndexOfIgnoreCase("aabaabaa", "A")  = 7
     * StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B")  = 5
     * StringUtils.lastIndexOfIgnoreCase("aabaabaa", "AB") = 4
     * 
* * @param str the String to check, may be null * @param searchStr the String to find, may be null * @return the first index of the search String, * -1 if no match or null string input * @since 2.5 */ public static int lastIndexOfIgnoreCase(String str, String searchStr) { if (str == null || searchStr == null) { return INDEX_NOT_FOUND; } return lastIndexOfIgnoreCase(str, searchStr, str.length()); } /** *

Case in-sensitive find of the last index within a String * from the specified position.

* *

A null String will return -1. * A negative start position returns -1. * An empty ("") search String always matches unless the start position is negative. * A start position greater than the string length searches the whole string.

* *
     * StringUtils.lastIndexOfIgnoreCase(null, *, *)          = -1
     * StringUtils.lastIndexOfIgnoreCase(*, null, *)          = -1
     * StringUtils.lastIndexOfIgnoreCase("aabaabaa", "A", 8)  = 7
     * StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B", 8)  = 5
     * StringUtils.lastIndexOfIgnoreCase("aabaabaa", "AB", 8) = 4
     * StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B", 9)  = 5
     * StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B", -1) = -1
     * StringUtils.lastIndexOfIgnoreCase("aabaabaa", "A", 0)  = 0
     * StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B", 0)  = -1
     * 
* * @param str the String to check, may be null * @param searchStr the String to find, may be null * @param startPos the start position * @return the first index of the search String, * -1 if no match or null string input * @since 2.5 */ public static int lastIndexOfIgnoreCase(String str, String searchStr, int startPos) { if (str == null || searchStr == null) { return INDEX_NOT_FOUND; } if (startPos > (str.length() - searchStr.length())) { startPos = str.length() - searchStr.length(); } if (startPos < 0) { return INDEX_NOT_FOUND; } if (searchStr.length() == 0) { return startPos; } for (int i = startPos; i >= 0; i--) { if (str.regionMatches(true, i, searchStr, 0, searchStr.length())) { return i; } } return INDEX_NOT_FOUND; } // Contains //----------------------------------------------------------------------- /** *

Checks if String contains a search character, handling null. * This method uses {@link String#indexOf(int)}.

* *

A null or empty ("") String will return false.

* *
     * StringUtils.contains(null, *)    = false
     * StringUtils.contains("", *)      = false
     * StringUtils.contains("abc", 'a') = true
     * StringUtils.contains("abc", 'z') = false
     * 
* * @param str the String to check, may be null * @param searchChar the character to find * @return true if the String contains the search character, * false if not or null string input * @since 2.0 */ public static boolean contains(String str, char searchChar) { if (isEmpty(str)) { return false; } return str.indexOf(searchChar) >= 0; } /** *

Checks if String contains a search String, handling null. * This method uses {@link String#indexOf(String)}.

* *

A null String will return false.

* *
     * StringUtils.contains(null, *)     = false
     * StringUtils.contains(*, null)     = false
     * StringUtils.contains("", "")      = true
     * StringUtils.contains("abc", "")   = true
     * StringUtils.contains("abc", "a")  = true
     * StringUtils.contains("abc", "z")  = false
     * 
* * @param str the String to check, may be null * @param searchStr the String to find, may be null * @return true if the String contains the search String, * false if not or null string input * @since 2.0 */ public static boolean contains(String str, String searchStr) { if (str == null || searchStr == null) { return false; } return str.indexOf(searchStr) >= 0; } /** *

Checks if String contains a search String irrespective of case, * handling null. Case-insensitivity is defined as by * {@link String#equalsIgnoreCase(String)}. * *

A null String will return false.

* *
     * StringUtils.contains(null, *) = false
     * StringUtils.contains(*, null) = false
     * StringUtils.contains("", "") = true
     * StringUtils.contains("abc", "") = true
     * StringUtils.contains("abc", "a") = true
     * StringUtils.contains("abc", "z") = false
     * StringUtils.contains("abc", "A") = true
     * StringUtils.contains("abc", "Z") = false
     * 
* * @param str the String to check, may be null * @param searchStr the String to find, may be null * @return true if the String contains the search String irrespective of * case or false if not or null string input */ public static boolean containsIgnoreCase(String str, String searchStr) { if (str == null || searchStr == null) { return false; } int len = searchStr.length(); int max = str.length() - len; for (int i = 0; i <= max; i++) { if (str.regionMatches(true, i, searchStr, 0, len)) { return true; } } return false; } // IndexOfAny chars //----------------------------------------------------------------------- /** *

Search a String to find the first index of any * character in the given set of characters.

* *

A null String will return -1. * A null or zero length search array will return -1.

* *
     * StringUtils.indexOfAny(null, *)                = -1
     * StringUtils.indexOfAny("", *)                  = -1
     * StringUtils.indexOfAny(*, null)                = -1
     * StringUtils.indexOfAny(*, [])                  = -1
     * StringUtils.indexOfAny("zzabyycdxx",['z','a']) = 0
     * StringUtils.indexOfAny("zzabyycdxx",['b','y']) = 3
     * StringUtils.indexOfAny("aba", ['z'])           = -1
     * 
* * @param str the String to check, may be null * @param searchChars the chars to search for, may be null * @return the index of any of the chars, -1 if no match or null input * @since 2.0 */ public static int indexOfAny(String str, char[] searchChars) { if (isEmpty(str) || ArrayUtils.isEmpty(searchChars)) { return INDEX_NOT_FOUND; } int csLen = str.length(); int csLast = csLen - 1; int searchLen = searchChars.length; int searchLast = searchLen - 1; for (int i = 0; i < csLen; i++) { char ch = str.charAt(i); for (int j = 0; j < searchLen; j++) { if (searchChars[j] == ch) { if (i < csLast && j < searchLast && CharUtils.isHighSurrogate(ch)) { // ch is a supplementary character if (searchChars[j + 1] == str.charAt(i + 1)) { return i; } } else { return i; } } } } return INDEX_NOT_FOUND; } /** *

Search a String to find the first index of any * character in the given set of characters.

* *

A null String will return -1. * A null search string will return -1.

* *
     * StringUtils.indexOfAny(null, *)            = -1
     * StringUtils.indexOfAny("", *)              = -1
     * StringUtils.indexOfAny(*, null)            = -1
     * StringUtils.indexOfAny(*, "")              = -1
     * StringUtils.indexOfAny("zzabyycdxx", "za") = 0
     * StringUtils.indexOfAny("zzabyycdxx", "by") = 3
     * StringUtils.indexOfAny("aba","z")          = -1
     * 
* * @param str the String to check, may be null * @param searchChars the chars to search for, may be null * @return the index of any of the chars, -1 if no match or null input * @since 2.0 */ public static int indexOfAny(String str, String searchChars) { if (isEmpty(str) || isEmpty(searchChars)) { return INDEX_NOT_FOUND; } return indexOfAny(str, searchChars.toCharArray()); } // ContainsAny //----------------------------------------------------------------------- /** *

Checks if the String contains any character in the given * set of characters.

* *

A null String will return false. * A null or zero length search array will return false.

* *
     * StringUtils.containsAny(null, *)                = false
     * StringUtils.containsAny("", *)                  = false
     * StringUtils.containsAny(*, null)                = false
     * StringUtils.containsAny(*, [])                  = false
     * StringUtils.containsAny("zzabyycdxx",['z','a']) = true
     * StringUtils.containsAny("zzabyycdxx",['b','y']) = true
     * StringUtils.containsAny("aba", ['z'])           = false
     * 
* * @param str the String to check, may be null * @param searchChars the chars to search for, may be null * @return the true if any of the chars are found, * false if no match or null input * @since 2.4 */ public static boolean containsAny(String str, char[] searchChars) { if (isEmpty(str) || ArrayUtils.isEmpty(searchChars)) { return false; } int csLength = str.length(); int searchLength = searchChars.length; int csLast = csLength - 1; int searchLast = searchLength - 1; for (int i = 0; i < csLength; i++) { char ch = str.charAt(i); for (int j = 0; j < searchLength; j++) { if (searchChars[j] == ch) { if (CharUtils.isHighSurrogate(ch)) { if (j == searchLast) { // missing low surrogate, fine, like String.indexOf(String) return true; } if (i < csLast && searchChars[j + 1] == str.charAt(i + 1)) { return true; } } else { // ch is in the Basic Multilingual Plane return true; } } } } return false; } /** *

* Checks if the String contains any character in the given set of characters. *

* *

* A null String will return false. A null search string will return * false. *

* *
     * StringUtils.containsAny(null, *)            = false
     * StringUtils.containsAny("", *)              = false
     * StringUtils.containsAny(*, null)            = false
     * StringUtils.containsAny(*, "")              = false
     * StringUtils.containsAny("zzabyycdxx", "za") = true
     * StringUtils.containsAny("zzabyycdxx", "by") = true
     * StringUtils.containsAny("aba","z")          = false
     * 
* * @param str * the String to check, may be null * @param searchChars * the chars to search for, may be null * @return the true if any of the chars are found, false if no match or null input * @since 2.4 */ public static boolean containsAny(String str, String searchChars) { if (searchChars == null) { return false; } return containsAny(str, searchChars.toCharArray()); } // IndexOfAnyBut chars //----------------------------------------------------------------------- /** *

Search a String to find the first index of any * character not in the given set of characters.

* *

A null String will return -1. * A null or zero length search array will return -1.

* *
     * StringUtils.indexOfAnyBut(null, *)                              = -1
     * StringUtils.indexOfAnyBut("", *)                                = -1
     * StringUtils.indexOfAnyBut(*, null)                              = -1
     * StringUtils.indexOfAnyBut(*, [])                                = -1
     * StringUtils.indexOfAnyBut("zzabyycdxx", new char[] {'z', 'a'} ) = 3
     * StringUtils.indexOfAnyBut("aba", new char[] {'z'} )             = 0
     * StringUtils.indexOfAnyBut("aba", new char[] {'a', 'b'} )        = -1
     * 
* * @param str the String to check, may be null * @param searchChars the chars to search for, may be null * @return the index of any of the chars, -1 if no match or null input * @since 2.0 */ public static int indexOfAnyBut(String str, char[] searchChars) { if (isEmpty(str) || ArrayUtils.isEmpty(searchChars)) { return INDEX_NOT_FOUND; } int csLen = str.length(); int csLast = csLen - 1; int searchLen = searchChars.length; int searchLast = searchLen - 1; outer: for (int i = 0; i < csLen; i++) { char ch = str.charAt(i); for (int j = 0; j < searchLen; j++) { if (searchChars[j] == ch) { if (i < csLast && j < searchLast && CharUtils.isHighSurrogate(ch)) { if (searchChars[j + 1] == str.charAt(i + 1)) { continue outer; } } else { continue outer; } } } return i; } return INDEX_NOT_FOUND; } /** *

Search a String to find the first index of any * character not in the given set of characters.

* *

A null String will return -1. * A null or empty search string will return -1.

* *
     * StringUtils.indexOfAnyBut(null, *)            = -1
     * StringUtils.indexOfAnyBut("", *)              = -1
     * StringUtils.indexOfAnyBut(*, null)            = -1
     * StringUtils.indexOfAnyBut(*, "")              = -1
     * StringUtils.indexOfAnyBut("zzabyycdxx", "za") = 3
     * StringUtils.indexOfAnyBut("zzabyycdxx", "")   = -1
     * StringUtils.indexOfAnyBut("aba","ab")         = -1
     * 
* * @param str the String to check, may be null * @param searchChars the chars to search for, may be null * @return the index of any of the chars, -1 if no match or null input * @since 2.0 */ public static int indexOfAnyBut(String str, String searchChars) { if (isEmpty(str) || isEmpty(searchChars)) { return INDEX_NOT_FOUND; } int strLen = str.length(); for (int i = 0; i < strLen; i++) { char ch = str.charAt(i); boolean chFound = searchChars.indexOf(ch) >= 0; if (i + 1 < strLen && CharUtils.isHighSurrogate(ch)) { char ch2 = str.charAt(i + 1); if (chFound && searchChars.indexOf(ch2) < 0) { return i; } } else { if (!chFound) { return i; } } } return INDEX_NOT_FOUND; } // ContainsOnly //----------------------------------------------------------------------- /** *

Checks if the String contains only certain characters.

* *

A null String will return false. * A null valid character array will return false. * An empty String (length()=0) always returns true.

* *
     * StringUtils.containsOnly(null, *)       = false
     * StringUtils.containsOnly(*, null)       = false
     * StringUtils.containsOnly("", *)         = true
     * StringUtils.containsOnly("ab", '')      = false
     * StringUtils.containsOnly("abab", 'abc') = true
     * StringUtils.containsOnly("ab1", 'abc')  = false
     * StringUtils.containsOnly("abz", 'abc')  = false
     * 
* * @param str the String to check, may be null * @param valid an array of valid chars, may be null * @return true if it only contains valid chars and is non-null */ public static boolean containsOnly(String str, char[] valid) { // All these pre-checks are to maintain API with an older version if ((valid == null) || (str == null)) { return false; } if (str.length() == 0) { return true; } if (valid.length == 0) { return false; } return indexOfAnyBut(str, valid) == INDEX_NOT_FOUND; } /** *

Checks if the String contains only certain characters.

* *

A null String will return false. * A null valid character String will return false. * An empty String (length()=0) always returns true.

* *
     * StringUtils.containsOnly(null, *)       = false
     * StringUtils.containsOnly(*, null)       = false
     * StringUtils.containsOnly("", *)         = true
     * StringUtils.containsOnly("ab", "")      = false
     * StringUtils.containsOnly("abab", "abc") = true
     * StringUtils.containsOnly("ab1", "abc")  = false
     * StringUtils.containsOnly("abz", "abc")  = false
     * 
* * @param str the String to check, may be null * @param validChars a String of valid chars, may be null * @return true if it only contains valid chars and is non-null * @since 2.0 */ public static boolean containsOnly(String str, String validChars) { if (str == null || validChars == null) { return false; } return containsOnly(str, validChars.toCharArray()); } // ContainsNone //----------------------------------------------------------------------- /** *

Checks that the String does not contain certain characters.

* *

A null String will return true. * A null invalid character array will return true. * An empty String (length()=0) always returns true.

* *
     * StringUtils.containsNone(null, *)       = true
     * StringUtils.containsNone(*, null)       = true
     * StringUtils.containsNone("", *)         = true
     * StringUtils.containsNone("ab", '')      = true
     * StringUtils.containsNone("abab", 'xyz') = true
     * StringUtils.containsNone("ab1", 'xyz')  = true
     * StringUtils.containsNone("abz", 'xyz')  = false
     * 
* * @param str the String to check, may be null * @param searchChars an array of invalid chars, may be null * @return true if it contains none of the invalid chars, or is null * @since 2.0 */ public static boolean containsNone(String str, char[] searchChars) { if (str == null || searchChars == null) { return true; } int csLen = str.length(); int csLast = csLen - 1; int searchLen = searchChars.length; int searchLast = searchLen - 1; for (int i = 0; i < csLen; i++) { char ch = str.charAt(i); for (int j = 0; j < searchLen; j++) { if (searchChars[j] == ch) { if (CharUtils.isHighSurrogate(ch)) { if (j == searchLast) { // missing low surrogate, fine, like String.indexOf(String) return false; } if (i < csLast && searchChars[j + 1] == str.charAt(i + 1)) { return false; } } else { // ch is in the Basic Multilingual Plane return false; } } } } return true; } /** *

Checks that the String does not contain certain characters.

* *

A null String will return true. * A null invalid character array will return true. * An empty String ("") always returns true.

* *
     * StringUtils.containsNone(null, *)       = true
     * StringUtils.containsNone(*, null)       = true
     * StringUtils.containsNone("", *)         = true
     * StringUtils.containsNone("ab", "")      = true
     * StringUtils.containsNone("abab", "xyz") = true
     * StringUtils.containsNone("ab1", "xyz")  = true
     * StringUtils.containsNone("abz", "xyz")  = false
     * 
* * @param str the String to check, may be null * @param invalidChars a String of invalid chars, may be null * @return true if it contains none of the invalid chars, or is null * @since 2.0 */ public static boolean containsNone(String str, String invalidChars) { if (str == null || invalidChars == null) { return true; } return containsNone(str, invalidChars.toCharArray()); } // IndexOfAny strings //----------------------------------------------------------------------- /** *

Find the first index of any of a set of potential substrings.

* *

A null String will return -1. * A null or zero length search array will return -1. * A null search array entry will be ignored, but a search * array containing "" will return 0 if str is not * null. This method uses {@link String#indexOf(String)}.

* *
     * StringUtils.indexOfAny(null, *)                     = -1
     * StringUtils.indexOfAny(*, null)                     = -1
     * StringUtils.indexOfAny(*, [])                       = -1
     * StringUtils.indexOfAny("zzabyycdxx", ["ab","cd"])   = 2
     * StringUtils.indexOfAny("zzabyycdxx", ["cd","ab"])   = 2
     * StringUtils.indexOfAny("zzabyycdxx", ["mn","op"])   = -1
     * StringUtils.indexOfAny("zzabyycdxx", ["zab","aby"]) = 1
     * StringUtils.indexOfAny("zzabyycdxx", [""])          = 0
     * StringUtils.indexOfAny("", [""])                    = 0
     * StringUtils.indexOfAny("", ["a"])                   = -1
     * 
* * @param str the String to check, may be null * @param searchStrs the Strings to search for, may be null * @return the first index of any of the searchStrs in str, -1 if no match */ public static int indexOfAny(String str, String[] searchStrs) { if ((str == null) || (searchStrs == null)) { return INDEX_NOT_FOUND; } int sz = searchStrs.length; // String's can't have a MAX_VALUEth index. int ret = Integer.MAX_VALUE; int tmp = 0; for (int i = 0; i < sz; i++) { String search = searchStrs[i]; if (search == null) { continue; } tmp = str.indexOf(search); if (tmp == INDEX_NOT_FOUND) { continue; } if (tmp < ret) { ret = tmp; } } return (ret == Integer.MAX_VALUE) ? INDEX_NOT_FOUND : ret; } /** *

Find the latest index of any of a set of potential substrings.

* *

A null String will return -1. * A null search array will return -1. * A null or zero length search array entry will be ignored, * but a search array containing "" will return the length of str * if str is not null. This method uses {@link String#indexOf(String)}

* *
     * StringUtils.lastIndexOfAny(null, *)                   = -1
     * StringUtils.lastIndexOfAny(*, null)                   = -1
     * StringUtils.lastIndexOfAny(*, [])                     = -1
     * StringUtils.lastIndexOfAny(*, [null])                 = -1
     * StringUtils.lastIndexOfAny("zzabyycdxx", ["ab","cd"]) = 6
     * StringUtils.lastIndexOfAny("zzabyycdxx", ["cd","ab"]) = 6
     * StringUtils.lastIndexOfAny("zzabyycdxx", ["mn","op"]) = -1
     * StringUtils.lastIndexOfAny("zzabyycdxx", ["mn","op"]) = -1
     * StringUtils.lastIndexOfAny("zzabyycdxx", ["mn",""])   = 10
     * 
* * @param str the String to check, may be null * @param searchStrs the Strings to search for, may be null * @return the last index of any of the Strings, -1 if no match */ public static int lastIndexOfAny(String str, String[] searchStrs) { if ((str == null) || (searchStrs == null)) { return INDEX_NOT_FOUND; } int sz = searchStrs.length; int ret = INDEX_NOT_FOUND; int tmp = 0; for (int i = 0; i < sz; i++) { String search = searchStrs[i]; if (search == null) { continue; } tmp = str.lastIndexOf(search); if (tmp > ret) { ret = tmp; } } return ret; } // Substring //----------------------------------------------------------------------- /** *

Gets a substring from the specified String avoiding exceptions.

* *

A negative start position can be used to start n * characters from the end of the String.

* *

A null String will return null. * An empty ("") String will return "".

* *
     * StringUtils.substring(null, *)   = null
     * StringUtils.substring("", *)     = ""
     * StringUtils.substring("abc", 0)  = "abc"
     * StringUtils.substring("abc", 2)  = "c"
     * StringUtils.substring("abc", 4)  = ""
     * StringUtils.substring("abc", -2) = "bc"
     * StringUtils.substring("abc", -4) = "abc"
     * 
* * @param str the String to get the substring from, may be null * @param start the position to start from, negative means * count back from the end of the String by this many characters * @return substring from start position, null if null String input */ public static String substring(String str, int start) { if (str == null) { return null; } // handle negatives, which means last n characters if (start < 0) { start = str.length() + start; // remember start is negative } if (start < 0) { start = 0; } if (start > str.length()) { return EMPTY; } return str.substring(start); } /** *

Gets a substring from the specified String avoiding exceptions.

* *

A negative start position can be used to start/end n * characters from the end of the String.

* *

The returned substring starts with the character in the start * position and ends before the end position. All position counting is * zero-based -- i.e., to start at the beginning of the string use * start = 0. Negative start and end positions can be used to * specify offsets relative to the end of the String.

* *

If start is not strictly to the left of end, "" * is returned.

* *
     * StringUtils.substring(null, *, *)    = null
     * StringUtils.substring("", * ,  *)    = "";
     * StringUtils.substring("abc", 0, 2)   = "ab"
     * StringUtils.substring("abc", 2, 0)   = ""
     * StringUtils.substring("abc", 2, 4)   = "c"
     * StringUtils.substring("abc", 4, 6)   = ""
     * StringUtils.substring("abc", 2, 2)   = ""
     * StringUtils.substring("abc", -2, -1) = "b"
     * StringUtils.substring("abc", -4, 2)  = "ab"
     * 
* * @param str the String to get the substring from, may be null * @param start the position to start from, negative means * count back from the end of the String by this many characters * @param end the position to end at (exclusive), negative means * count back from the end of the String by this many characters * @return substring from start position to end positon, * null if null String input */ public static String substring(String str, int start, int end) { if (str == null) { return null; } // handle negatives if (end < 0) { end = str.length() + end; // remember end is negative } if (start < 0) { start = str.length() + start; // remember start is negative } // check length next if (end > str.length()) { end = str.length(); } // if start is greater than end, return "" if (start > end) { return EMPTY; } if (start < 0) { start = 0; } if (end < 0) { end = 0; } return str.substring(start, end); } // Left/Right/Mid //----------------------------------------------------------------------- /** *

Gets the leftmost len characters of a String.

* *

If len characters are not available, or the * String is null, the String will be returned without * an exception. An empty String is returned if len is negative.

* *
     * StringUtils.left(null, *)    = null
     * StringUtils.left(*, -ve)     = ""
     * StringUtils.left("", *)      = ""
     * StringUtils.left("abc", 0)   = ""
     * StringUtils.left("abc", 2)   = "ab"
     * StringUtils.left("abc", 4)   = "abc"
     * 
* * @param str the String to get the leftmost characters from, may be null * @param len the length of the required String * @return the leftmost characters, null if null String input */ public static String left(String str, int len) { if (str == null) { return null; } if (len < 0) { return EMPTY; } if (str.length() <= len) { return str; } return str.substring(0, len); } /** *

Gets the rightmost len characters of a String.

* *

If len characters are not available, or the String * is null, the String will be returned without an * an exception. An empty String is returned if len is negative.

* *
     * StringUtils.right(null, *)    = null
     * StringUtils.right(*, -ve)     = ""
     * StringUtils.right("", *)      = ""
     * StringUtils.right("abc", 0)   = ""
     * StringUtils.right("abc", 2)   = "bc"
     * StringUtils.right("abc", 4)   = "abc"
     * 
* * @param str the String to get the rightmost characters from, may be null * @param len the length of the required String * @return the rightmost characters, null if null String input */ public static String right(String str, int len) { if (str == null) { return null; } if (len < 0) { return EMPTY; } if (str.length() <= len) { return str; } return str.substring(str.length() - len); } /** *

Gets len characters from the middle of a String.

* *

If len characters are not available, the remainder * of the String will be returned without an exception. If the * String is null, null will be returned. * An empty String is returned if len is negative or exceeds the * length of str.

* *
     * StringUtils.mid(null, *, *)    = null
     * StringUtils.mid(*, *, -ve)     = ""
     * StringUtils.mid("", 0, *)      = ""
     * StringUtils.mid("abc", 0, 2)   = "ab"
     * StringUtils.mid("abc", 0, 4)   = "abc"
     * StringUtils.mid("abc", 2, 4)   = "c"
     * StringUtils.mid("abc", 4, 2)   = ""
     * StringUtils.mid("abc", -2, 2)  = "ab"
     * 
* * @param str the String to get the characters from, may be null * @param pos the position to start from, negative treated as zero * @param len the length of the required String * @return the middle characters, null if null String input */ public static String mid(String str, int pos, int len) { if (str == null) { return null; } if (len < 0 || pos > str.length()) { return EMPTY; } if (pos < 0) { pos = 0; } if (str.length() <= (pos + len)) { return str.substring(pos); } return str.substring(pos, pos + len); } // SubStringAfter/SubStringBefore //----------------------------------------------------------------------- /** *

Gets the substring before the first occurrence of a separator. * The separator is not returned.

* *

A null string input will return null. * An empty ("") string input will return the empty string. * A null separator will return the input string.

* *

If nothing is found, the string input is returned.

* *
     * StringUtils.substringBefore(null, *)      = null
     * StringUtils.substringBefore("", *)        = ""
     * StringUtils.substringBefore("abc", "a")   = ""
     * StringUtils.substringBefore("abcba", "b") = "a"
     * StringUtils.substringBefore("abc", "c")   = "ab"
     * StringUtils.substringBefore("abc", "d")   = "abc"
     * StringUtils.substringBefore("abc", "")    = ""
     * StringUtils.substringBefore("abc", null)  = "abc"
     * 
* * @param str the String to get a substring from, may be null * @param separator the String to search for, may be null * @return the substring before the first occurrence of the separator, * null if null String input * @since 2.0 */ public static String substringBefore(String str, String separator) { if (isEmpty(str) || separator == null) { return str; } if (separator.length() == 0) { return EMPTY; } int pos = str.indexOf(separator); if (pos == INDEX_NOT_FOUND) { return str; } return str.substring(0, pos); } /** *

Gets the substring after the first occurrence of a separator. * The separator is not returned.

* *

A null string input will return null. * An empty ("") string input will return the empty string. * A null separator will return the empty string if the * input string is not null.

* *

If nothing is found, the empty string is returned.

* *
     * StringUtils.substringAfter(null, *)      = null
     * StringUtils.substringAfter("", *)        = ""
     * StringUtils.substringAfter(*, null)      = ""
     * StringUtils.substringAfter("abc", "a")   = "bc"
     * StringUtils.substringAfter("abcba", "b") = "cba"
     * StringUtils.substringAfter("abc", "c")   = ""
     * StringUtils.substringAfter("abc", "d")   = ""
     * StringUtils.substringAfter("abc", "")    = "abc"
     * 
* * @param str the String to get a substring from, may be null * @param separator the String to search for, may be null * @return the substring after the first occurrence of the separator, * null if null String input * @since 2.0 */ public static String substringAfter(String str, String separator) { if (isEmpty(str)) { return str; } if (separator == null) { return EMPTY; } int pos = str.indexOf(separator); if (pos == INDEX_NOT_FOUND) { return EMPTY; } return str.substring(pos + separator.length()); } /** *

Gets the substring before the last occurrence of a separator. * The separator is not returned.

* *

A null string input will return null. * An empty ("") string input will return the empty string. * An empty or null separator will return the input string.

* *

If nothing is found, the string input is returned.

* *
     * StringUtils.substringBeforeLast(null, *)      = null
     * StringUtils.substringBeforeLast("", *)        = ""
     * StringUtils.substringBeforeLast("abcba", "b") = "abc"
     * StringUtils.substringBeforeLast("abc", "c")   = "ab"
     * StringUtils.substringBeforeLast("a", "a")     = ""
     * StringUtils.substringBeforeLast("a", "z")     = "a"
     * StringUtils.substringBeforeLast("a", null)    = "a"
     * StringUtils.substringBeforeLast("a", "")      = "a"
     * 
* * @param str the String to get a substring from, may be null * @param separator the String to search for, may be null * @return the substring before the last occurrence of the separator, * null if null String input * @since 2.0 */ public static String substringBeforeLast(String str, String separator) { if (isEmpty(str) || isEmpty(separator)) { return str; } int pos = str.lastIndexOf(separator); if (pos == INDEX_NOT_FOUND) { return str; } return str.substring(0, pos); } /** *

Gets the substring after the last occurrence of a separator. * The separator is not returned.

* *

A null string input will return null. * An empty ("") string input will return the empty string. * An empty or null separator will return the empty string if * the input string is not null.

* *

If nothing is found, the empty string is returned.

* *
     * StringUtils.substringAfterLast(null, *)      = null
     * StringUtils.substringAfterLast("", *)        = ""
     * StringUtils.substringAfterLast(*, "")        = ""
     * StringUtils.substringAfterLast(*, null)      = ""
     * StringUtils.substringAfterLast("abc", "a")   = "bc"
     * StringUtils.substringAfterLast("abcba", "b") = "a"
     * StringUtils.substringAfterLast("abc", "c")   = ""
     * StringUtils.substringAfterLast("a", "a")     = ""
     * StringUtils.substringAfterLast("a", "z")     = ""
     * 
* * @param str the String to get a substring from, may be null * @param separator the String to search for, may be null * @return the substring after the last occurrence of the separator, * null if null String input * @since 2.0 */ public static String substringAfterLast(String str, String separator) { if (isEmpty(str)) { return str; } if (isEmpty(separator)) { return EMPTY; } int pos = str.lastIndexOf(separator); if (pos == INDEX_NOT_FOUND || pos == (str.length() - separator.length())) { return EMPTY; } return str.substring(pos + separator.length()); } // Substring between //----------------------------------------------------------------------- /** *

Gets the String that is nested in between two instances of the * same String.

* *

A null input String returns null. * A null tag returns null.

* *
     * StringUtils.substringBetween(null, *)            = null
     * StringUtils.substringBetween("", "")             = ""
     * StringUtils.substringBetween("", "tag")          = null
     * StringUtils.substringBetween("tagabctag", null)  = null
     * StringUtils.substringBetween("tagabctag", "")    = ""
     * StringUtils.substringBetween("tagabctag", "tag") = "abc"
     * 
* * @param str the String containing the substring, may be null * @param tag the String before and after the substring, may be null * @return the substring, null if no match * @since 2.0 */ public static String substringBetween(String str, String tag) { return substringBetween(str, tag, tag); } /** *

Gets the String that is nested in between two Strings. * Only the first match is returned.

* *

A null input String returns null. * A null open/close returns null (no match). * An empty ("") open and close returns an empty string.

* *
     * StringUtils.substringBetween("wx[b]yz", "[", "]") = "b"
     * StringUtils.substringBetween(null, *, *)          = null
     * StringUtils.substringBetween(*, null, *)          = null
     * StringUtils.substringBetween(*, *, null)          = null
     * StringUtils.substringBetween("", "", "")          = ""
     * StringUtils.substringBetween("", "", "]")         = null
     * StringUtils.substringBetween("", "[", "]")        = null
     * StringUtils.substringBetween("yabcz", "", "")     = ""
     * StringUtils.substringBetween("yabcz", "y", "z")   = "abc"
     * StringUtils.substringBetween("yabczyabcz", "y", "z")   = "abc"
     * 
* * @param str the String containing the substring, may be null * @param open the String before the substring, may be null * @param close the String after the substring, may be null * @return the substring, null if no match * @since 2.0 */ public static String substringBetween(String str, String open, String close) { if (str == null || open == null || close == null) { return null; } int start = str.indexOf(open); if (start != INDEX_NOT_FOUND) { int end = str.indexOf(close, start + open.length()); if (end != INDEX_NOT_FOUND) { return str.substring(start + open.length(), end); } } return null; } /** *

Searches a String for substrings delimited by a start and end tag, * returning all matching substrings in an array.

* *

A null input String returns null. * A null open/close returns null (no match). * An empty ("") open/close returns null (no match).

* *
     * StringUtils.substringsBetween("[a][b][c]", "[", "]") = ["a","b","c"]
     * StringUtils.substringsBetween(null, *, *)            = null
     * StringUtils.substringsBetween(*, null, *)            = null
     * StringUtils.substringsBetween(*, *, null)            = null
     * StringUtils.substringsBetween("", "[", "]")          = []
     * 
* * @param str the String containing the substrings, null returns null, empty returns empty * @param open the String identifying the start of the substring, empty returns null * @param close the String identifying the end of the substring, empty returns null * @return a String Array of substrings, or null if no match * @since 2.3 */ public static String[] substringsBetween(String str, String open, String close) { if (str == null || isEmpty(open) || isEmpty(close)) { return null; } int strLen = str.length(); if (strLen == 0) { return ArrayUtils.EMPTY_STRING_ARRAY; } int closeLen = close.length(); int openLen = open.length(); List list = new ArrayList(); int pos = 0; while (pos < (strLen - closeLen)) { int start = str.indexOf(open, pos); if (start < 0) { break; } start += openLen; int end = str.indexOf(close, start); if (end < 0) { break; } list.add(str.substring(start, end)); pos = end + closeLen; } if (list.isEmpty()) { return null; } return (String[]) list.toArray(new String [list.size()]); } // Nested extraction //----------------------------------------------------------------------- /** *

Gets the String that is nested in between two instances of the * same String.

* *

A null input String returns null. * A null tag returns null.

* *
     * StringUtils.getNestedString(null, *)            = null
     * StringUtils.getNestedString("", "")             = ""
     * StringUtils.getNestedString("", "tag")          = null
     * StringUtils.getNestedString("tagabctag", null)  = null
     * StringUtils.getNestedString("tagabctag", "")    = ""
     * StringUtils.getNestedString("tagabctag", "tag") = "abc"
     * 
* * @param str the String containing nested-string, may be null * @param tag the String before and after nested-string, may be null * @return the nested String, null if no match * @deprecated Use the better named {@link #substringBetween(String, String)}. * Method will be removed in Commons Lang 3.0. */ public static String getNestedString(String str, String tag) { return substringBetween(str, tag, tag); } /** *

Gets the String that is nested in between two Strings. * Only the first match is returned.

* *

A null input String returns null. * A null open/close returns null (no match). * An empty ("") open/close returns an empty string.

* *
     * StringUtils.getNestedString(null, *, *)          = null
     * StringUtils.getNestedString("", "", "")          = ""
     * StringUtils.getNestedString("", "", "tag")       = null
     * StringUtils.getNestedString("", "tag", "tag")    = null
     * StringUtils.getNestedString("yabcz", null, null) = null
     * StringUtils.getNestedString("yabcz", "", "")     = ""
     * StringUtils.getNestedString("yabcz", "y", "z")   = "abc"
     * StringUtils.getNestedString("yabczyabcz", "y", "z")   = "abc"
     * 
* * @param str the String containing nested-string, may be null * @param open the String before nested-string, may be null * @param close the String after nested-string, may be null * @return the nested String, null if no match * @deprecated Use the better named {@link #substringBetween(String, String, String)}. * Method will be removed in Commons Lang 3.0. */ public static String getNestedString(String str, String open, String close) { return substringBetween(str, open, close); } // Splitting //----------------------------------------------------------------------- /** *

Splits the provided text into an array, using whitespace as the * separator. * Whitespace is defined by {@link Character#isWhitespace(char)}.

* *

The separator is not included in the returned String array. * Adjacent separators are treated as one separator. * For more control over the split use the StrTokenizer class.

* *

A null input String returns null.

* *
     * StringUtils.split(null)       = null
     * StringUtils.split("")         = []
     * StringUtils.split("abc def")  = ["abc", "def"]
     * StringUtils.split("abc  def") = ["abc", "def"]
     * StringUtils.split(" abc ")    = ["abc"]
     * 
* * @param str the String to parse, may be null * @return an array of parsed Strings, null if null String input */ public static String[] split(String str) { return split(str, null, -1); } /** *

Splits the provided text into an array, separator specified. * This is an alternative to using StringTokenizer.

* *

The separator is not included in the returned String array. * Adjacent separators are treated as one separator. * For more control over the split use the StrTokenizer class.

* *

A null input String returns null.

* *
     * StringUtils.split(null, *)         = null
     * StringUtils.split("", *)           = []
     * StringUtils.split("a.b.c", '.')    = ["a", "b", "c"]
     * StringUtils.split("a..b.c", '.')   = ["a", "b", "c"]
     * StringUtils.split("a:b:c", '.')    = ["a:b:c"]
     * StringUtils.split("a b c", ' ')    = ["a", "b", "c"]
     * 
* * @param str the String to parse, may be null * @param separatorChar the character used as the delimiter * @return an array of parsed Strings, null if null String input * @since 2.0 */ public static String[] split(String str, char separatorChar) { return splitWorker(str, separatorChar, false); } /** *

Splits the provided text into an array, separators specified. * This is an alternative to using StringTokenizer.

* *

The separator is not included in the returned String array. * Adjacent separators are treated as one separator. * For more control over the split use the StrTokenizer class.

* *

A null input String returns null. * A null separatorChars splits on whitespace.

* *
     * StringUtils.split(null, *)         = null
     * StringUtils.split("", *)           = []
     * StringUtils.split("abc def", null) = ["abc", "def"]
     * StringUtils.split("abc def", " ")  = ["abc", "def"]
     * StringUtils.split("abc  def", " ") = ["abc", "def"]
     * StringUtils.split("ab:cd:ef", ":") = ["ab", "cd", "ef"]
     * 
* * @param str the String to parse, may be null * @param separatorChars the characters used as the delimiters, * null splits on whitespace * @return an array of parsed Strings, null if null String input */ public static String[] split(String str, String separatorChars) { return splitWorker(str, separatorChars, -1, false); } /** *

Splits the provided text into an array with a maximum length, * separators specified.

* *

The separator is not included in the returned String array. * Adjacent separators are treated as one separator.

* *

A null input String returns null. * A null separatorChars splits on whitespace.

* *

If more than max delimited substrings are found, the last * returned string includes all characters after the first max - 1 * returned strings (including separator characters).

* *
     * StringUtils.split(null, *, *)            = null
     * StringUtils.split("", *, *)              = []
     * StringUtils.split("ab de fg", null, 0)   = ["ab", "cd", "ef"]
     * StringUtils.split("ab   de fg", null, 0) = ["ab", "cd", "ef"]
     * StringUtils.split("ab:cd:ef", ":", 0)    = ["ab", "cd", "ef"]
     * StringUtils.split("ab:cd:ef", ":", 2)    = ["ab", "cd:ef"]
     * 
* * @param str the String to parse, may be null * @param separatorChars the characters used as the delimiters, * null splits on whitespace * @param max the maximum number of elements to include in the * array. A zero or negative value implies no limit * @return an array of parsed Strings, null if null String input */ public static String[] split(String str, String separatorChars, int max) { return splitWorker(str, separatorChars, max, false); } /** *

Splits the provided text into an array, separator string specified.

* *

The separator(s) will not be included in the returned String array. * Adjacent separators are treated as one separator.

* *

A null input String returns null. * A null separator splits on whitespace.

* *
     * StringUtils.splitByWholeSeparator(null, *)               = null
     * StringUtils.splitByWholeSeparator("", *)                 = []
     * StringUtils.splitByWholeSeparator("ab de fg", null)      = ["ab", "de", "fg"]
     * StringUtils.splitByWholeSeparator("ab   de fg", null)    = ["ab", "de", "fg"]
     * StringUtils.splitByWholeSeparator("ab:cd:ef", ":")       = ["ab", "cd", "ef"]
     * StringUtils.splitByWholeSeparator("ab-!-cd-!-ef", "-!-") = ["ab", "cd", "ef"]
     * 
* * @param str the String to parse, may be null * @param separator String containing the String to be used as a delimiter, * null splits on whitespace * @return an array of parsed Strings, null if null String was input */ public static String[] splitByWholeSeparator(String str, String separator) { return splitByWholeSeparatorWorker( str, separator, -1, false ) ; } /** *

Splits the provided text into an array, separator string specified. * Returns a maximum of max substrings.

* *

The separator(s) will not be included in the returned String array. * Adjacent separators are treated as one separator.

* *

A null input String returns null. * A null separator splits on whitespace.

* *
     * StringUtils.splitByWholeSeparator(null, *, *)               = null
     * StringUtils.splitByWholeSeparator("", *, *)                 = []
     * StringUtils.splitByWholeSeparator("ab de fg", null, 0)      = ["ab", "de", "fg"]
     * StringUtils.splitByWholeSeparator("ab   de fg", null, 0)    = ["ab", "de", "fg"]
     * StringUtils.splitByWholeSeparator("ab:cd:ef", ":", 2)       = ["ab", "cd:ef"]
     * StringUtils.splitByWholeSeparator("ab-!-cd-!-ef", "-!-", 5) = ["ab", "cd", "ef"]
     * StringUtils.splitByWholeSeparator("ab-!-cd-!-ef", "-!-", 2) = ["ab", "cd-!-ef"]
     * 
* * @param str the String to parse, may be null * @param separator String containing the String to be used as a delimiter, * null splits on whitespace * @param max the maximum number of elements to include in the returned * array. A zero or negative value implies no limit. * @return an array of parsed Strings, null if null String was input */ public static String[] splitByWholeSeparator( String str, String separator, int max ) { return splitByWholeSeparatorWorker(str, separator, max, false); } /** *

Splits the provided text into an array, separator string specified.

* *

The separator is not included in the returned String array. * Adjacent separators are treated as separators for empty tokens. * For more control over the split use the StrTokenizer class.

* *

A null input String returns null. * A null separator splits on whitespace.

* *
     * StringUtils.splitByWholeSeparatorPreserveAllTokens(null, *)               = null
     * StringUtils.splitByWholeSeparatorPreserveAllTokens("", *)                 = []
     * StringUtils.splitByWholeSeparatorPreserveAllTokens("ab de fg", null)      = ["ab", "de", "fg"]
     * StringUtils.splitByWholeSeparatorPreserveAllTokens("ab   de fg", null)    = ["ab", "", "", "de", "fg"]
     * StringUtils.splitByWholeSeparatorPreserveAllTokens("ab:cd:ef", ":")       = ["ab", "cd", "ef"]
     * StringUtils.splitByWholeSeparatorPreserveAllTokens("ab-!-cd-!-ef", "-!-") = ["ab", "cd", "ef"]
     * 
* * @param str the String to parse, may be null * @param separator String containing the String to be used as a delimiter, * null splits on whitespace * @return an array of parsed Strings, null if null String was input * @since 2.4 */ public static String[] splitByWholeSeparatorPreserveAllTokens(String str, String separator) { return splitByWholeSeparatorWorker(str, separator, -1, true); } /** *

Splits the provided text into an array, separator string specified. * Returns a maximum of max substrings.

* *

The separator is not included in the returned String array. * Adjacent separators are treated as separators for empty tokens. * For more control over the split use the StrTokenizer class.

* *

A null input String returns null. * A null separator splits on whitespace.

* *
     * StringUtils.splitByWholeSeparatorPreserveAllTokens(null, *, *)               = null
     * StringUtils.splitByWholeSeparatorPreserveAllTokens("", *, *)                 = []
     * StringUtils.splitByWholeSeparatorPreserveAllTokens("ab de fg", null, 0)      = ["ab", "de", "fg"]
     * StringUtils.splitByWholeSeparatorPreserveAllTokens("ab   de fg", null, 0)    = ["ab", "", "", "de", "fg"]
     * StringUtils.splitByWholeSeparatorPreserveAllTokens("ab:cd:ef", ":", 2)       = ["ab", "cd:ef"]
     * StringUtils.splitByWholeSeparatorPreserveAllTokens("ab-!-cd-!-ef", "-!-", 5) = ["ab", "cd", "ef"]
     * StringUtils.splitByWholeSeparatorPreserveAllTokens("ab-!-cd-!-ef", "-!-", 2) = ["ab", "cd-!-ef"]
     * 
* * @param str the String to parse, may be null * @param separator String containing the String to be used as a delimiter, * null splits on whitespace * @param max the maximum number of elements to include in the returned * array. A zero or negative value implies no limit. * @return an array of parsed Strings, null if null String was input * @since 2.4 */ public static String[] splitByWholeSeparatorPreserveAllTokens(String str, String separator, int max) { return splitByWholeSeparatorWorker(str, separator, max, true); } /** * Performs the logic for the splitByWholeSeparatorPreserveAllTokens methods. * * @param str the String to parse, may be null * @param separator String containing the String to be used as a delimiter, * null splits on whitespace * @param max the maximum number of elements to include in the returned * array. A zero or negative value implies no limit. * @param preserveAllTokens if true, adjacent separators are * treated as empty token separators; if false, adjacent * separators are treated as one separator. * @return an array of parsed Strings, null if null String input * @since 2.4 */ private static String[] splitByWholeSeparatorWorker(String str, String separator, int max, boolean preserveAllTokens) { if (str == null) { return null; } int len = str.length(); if (len == 0) { return ArrayUtils.EMPTY_STRING_ARRAY; } if ((separator == null) || (EMPTY.equals(separator))) { // Split on whitespace. return splitWorker(str, null, max, preserveAllTokens); } int separatorLength = separator.length(); ArrayList substrings = new ArrayList(); int numberOfSubstrings = 0; int beg = 0; int end = 0; while (end < len) { end = str.indexOf(separator, beg); if (end > -1) { if (end > beg) { numberOfSubstrings += 1; if (numberOfSubstrings == max) { end = len; substrings.add(str.substring(beg)); } else { // The following is OK, because String.substring( beg, end ) excludes // the character at the position 'end'. substrings.add(str.substring(beg, end)); // Set the starting point for the next search. // The following is equivalent to beg = end + (separatorLength - 1) + 1, // which is the right calculation: beg = end + separatorLength; } } else { // We found a consecutive occurrence of the separator, so skip it. if (preserveAllTokens) { numberOfSubstrings += 1; if (numberOfSubstrings == max) { end = len; substrings.add(str.substring(beg)); } else { substrings.add(EMPTY); } } beg = end + separatorLength; } } else { // String.substring( beg ) goes from 'beg' to the end of the String. substrings.add(str.substring(beg)); end = len; } } return (String[]) substrings.toArray(new String[substrings.size()]); } // ----------------------------------------------------------------------- /** *

Splits the provided text into an array, using whitespace as the * separator, preserving all tokens, including empty tokens created by * adjacent separators. This is an alternative to using StringTokenizer. * Whitespace is defined by {@link Character#isWhitespace(char)}.

* *

The separator is not included in the returned String array. * Adjacent separators are treated as separators for empty tokens. * For more control over the split use the StrTokenizer class.

* *

A null input String returns null.

* *
     * StringUtils.splitPreserveAllTokens(null)       = null
     * StringUtils.splitPreserveAllTokens("")         = []
     * StringUtils.splitPreserveAllTokens("abc def")  = ["abc", "def"]
     * StringUtils.splitPreserveAllTokens("abc  def") = ["abc", "", "def"]
     * StringUtils.splitPreserveAllTokens(" abc ")    = ["", "abc", ""]
     * 
* * @param str the String to parse, may be null * @return an array of parsed Strings, null if null String input * @since 2.1 */ public static String[] splitPreserveAllTokens(String str) { return splitWorker(str, null, -1, true); } /** *

Splits the provided text into an array, separator specified, * preserving all tokens, including empty tokens created by adjacent * separators. This is an alternative to using StringTokenizer.

* *

The separator is not included in the returned String array. * Adjacent separators are treated as separators for empty tokens. * For more control over the split use the StrTokenizer class.

* *

A null input String returns null.

* *
     * StringUtils.splitPreserveAllTokens(null, *)         = null
     * StringUtils.splitPreserveAllTokens("", *)           = []
     * StringUtils.splitPreserveAllTokens("a.b.c", '.')    = ["a", "b", "c"]
     * StringUtils.splitPreserveAllTokens("a..b.c", '.')   = ["a", "", "b", "c"]
     * StringUtils.splitPreserveAllTokens("a:b:c", '.')    = ["a:b:c"]
     * StringUtils.splitPreserveAllTokens("a\tb\nc", null) = ["a", "b", "c"]
     * StringUtils.splitPreserveAllTokens("a b c", ' ')    = ["a", "b", "c"]
     * StringUtils.splitPreserveAllTokens("a b c ", ' ')   = ["a", "b", "c", ""]
     * StringUtils.splitPreserveAllTokens("a b c  ", ' ')   = ["a", "b", "c", "", ""]
     * StringUtils.splitPreserveAllTokens(" a b c", ' ')   = ["", a", "b", "c"]
     * StringUtils.splitPreserveAllTokens("  a b c", ' ')  = ["", "", a", "b", "c"]
     * StringUtils.splitPreserveAllTokens(" a b c ", ' ')  = ["", a", "b", "c", ""]
     * 
* * @param str the String to parse, may be null * @param separatorChar the character used as the delimiter, * null splits on whitespace * @return an array of parsed Strings, null if null String input * @since 2.1 */ public static String[] splitPreserveAllTokens(String str, char separatorChar) { return splitWorker(str, separatorChar, true); } /** * Performs the logic for the split and * splitPreserveAllTokens methods that do not return a * maximum array length. * * @param str the String to parse, may be null * @param separatorChar the separate character * @param preserveAllTokens if true, adjacent separators are * treated as empty token separators; if false, adjacent * separators are treated as one separator. * @return an array of parsed Strings, null if null String input */ private static String[] splitWorker(String str, char separatorChar, boolean preserveAllTokens) { // Performance tuned for 2.0 (JDK1.4) if (str == null) { return null; } int len = str.length(); if (len == 0) { return ArrayUtils.EMPTY_STRING_ARRAY; } List list = new ArrayList(); int i = 0, start = 0; boolean match = false; boolean lastMatch = false; while (i < len) { if (str.charAt(i) == separatorChar) { if (match || preserveAllTokens) { list.add(str.substring(start, i)); match = false; lastMatch = true; } start = ++i; continue; } lastMatch = false; match = true; i++; } if (match || (preserveAllTokens && lastMatch)) { list.add(str.substring(start, i)); } return (String[]) list.toArray(new String[list.size()]); } /** *

Splits the provided text into an array, separators specified, * preserving all tokens, including empty tokens created by adjacent * separators. This is an alternative to using StringTokenizer.

* *

The separator is not included in the returned String array. * Adjacent separators are treated as separators for empty tokens. * For more control over the split use the StrTokenizer class.

* *

A null input String returns null. * A null separatorChars splits on whitespace.

* *
     * StringUtils.splitPreserveAllTokens(null, *)           = null
     * StringUtils.splitPreserveAllTokens("", *)             = []
     * StringUtils.splitPreserveAllTokens("abc def", null)   = ["abc", "def"]
     * StringUtils.splitPreserveAllTokens("abc def", " ")    = ["abc", "def"]
     * StringUtils.splitPreserveAllTokens("abc  def", " ")   = ["abc", "", def"]
     * StringUtils.splitPreserveAllTokens("ab:cd:ef", ":")   = ["ab", "cd", "ef"]
     * StringUtils.splitPreserveAllTokens("ab:cd:ef:", ":")  = ["ab", "cd", "ef", ""]
     * StringUtils.splitPreserveAllTokens("ab:cd:ef::", ":") = ["ab", "cd", "ef", "", ""]
     * StringUtils.splitPreserveAllTokens("ab::cd:ef", ":")  = ["ab", "", cd", "ef"]
     * StringUtils.splitPreserveAllTokens(":cd:ef", ":")     = ["", cd", "ef"]
     * StringUtils.splitPreserveAllTokens("::cd:ef", ":")    = ["", "", cd", "ef"]
     * StringUtils.splitPreserveAllTokens(":cd:ef:", ":")    = ["", cd", "ef", ""]
     * 
* * @param str the String to parse, may be null * @param separatorChars the characters used as the delimiters, * null splits on whitespace * @return an array of parsed Strings, null if null String input * @since 2.1 */ public static String[] splitPreserveAllTokens(String str, String separatorChars) { return splitWorker(str, separatorChars, -1, true); } /** *

Splits the provided text into an array with a maximum length, * separators specified, preserving all tokens, including empty tokens * created by adjacent separators.

* *

The separator is not included in the returned String array. * Adjacent separators are treated as separators for empty tokens. * Adjacent separators are treated as one separator.

* *

A null input String returns null. * A null separatorChars splits on whitespace.

* *

If more than max delimited substrings are found, the last * returned string includes all characters after the first max - 1 * returned strings (including separator characters).

* *
     * StringUtils.splitPreserveAllTokens(null, *, *)            = null
     * StringUtils.splitPreserveAllTokens("", *, *)              = []
     * StringUtils.splitPreserveAllTokens("ab de fg", null, 0)   = ["ab", "cd", "ef"]
     * StringUtils.splitPreserveAllTokens("ab   de fg", null, 0) = ["ab", "cd", "ef"]
     * StringUtils.splitPreserveAllTokens("ab:cd:ef", ":", 0)    = ["ab", "cd", "ef"]
     * StringUtils.splitPreserveAllTokens("ab:cd:ef", ":", 2)    = ["ab", "cd:ef"]
     * StringUtils.splitPreserveAllTokens("ab   de fg", null, 2) = ["ab", "  de fg"]
     * StringUtils.splitPreserveAllTokens("ab   de fg", null, 3) = ["ab", "", " de fg"]
     * StringUtils.splitPreserveAllTokens("ab   de fg", null, 4) = ["ab", "", "", "de fg"]
     * 
* * @param str the String to parse, may be null * @param separatorChars the characters used as the delimiters, * null splits on whitespace * @param max the maximum number of elements to include in the * array. A zero or negative value implies no limit * @return an array of parsed Strings, null if null String input * @since 2.1 */ public static String[] splitPreserveAllTokens(String str, String separatorChars, int max) { return splitWorker(str, separatorChars, max, true); } /** * Performs the logic for the split and * splitPreserveAllTokens methods that return a maximum array * length. * * @param str the String to parse, may be null * @param separatorChars the separate character * @param max the maximum number of elements to include in the * array. A zero or negative value implies no limit. * @param preserveAllTokens if true, adjacent separators are * treated as empty token separators; if false, adjacent * separators are treated as one separator. * @return an array of parsed Strings, null if null String input */ private static String[] splitWorker(String str, String separatorChars, int max, boolean preserveAllTokens) { // Performance tuned for 2.0 (JDK1.4) // Direct code is quicker than StringTokenizer. // Also, StringTokenizer uses isSpace() not isWhitespace() if (str == null) { return null; } int len = str.length(); if (len == 0) { return ArrayUtils.EMPTY_STRING_ARRAY; } List list = new ArrayList(); int sizePlus1 = 1; int i = 0, start = 0; boolean match = false; boolean lastMatch = false; if (separatorChars == null) { // Null separator means use whitespace while (i < len) { if (Character.isWhitespace(str.charAt(i))) { if (match || preserveAllTokens) { lastMatch = true; if (sizePlus1++ == max) { i = len; lastMatch = false; } list.add(str.substring(start, i)); match = false; } start = ++i; continue; } lastMatch = false; match = true; i++; } } else if (separatorChars.length() == 1) { // Optimise 1 character case char sep = separatorChars.charAt(0); while (i < len) { if (str.charAt(i) == sep) { if (match || preserveAllTokens) { lastMatch = true; if (sizePlus1++ == max) { i = len; lastMatch = false; } list.add(str.substring(start, i)); match = false; } start = ++i; continue; } lastMatch = false; match = true; i++; } } else { // standard case while (i < len) { if (separatorChars.indexOf(str.charAt(i)) >= 0) { if (match || preserveAllTokens) { lastMatch = true; if (sizePlus1++ == max) { i = len; lastMatch = false; } list.add(str.substring(start, i)); match = false; } start = ++i; continue; } lastMatch = false; match = true; i++; } } if (match || (preserveAllTokens && lastMatch)) { list.add(str.substring(start, i)); } return (String[]) list.toArray(new String[list.size()]); } /** *

Splits a String by Character type as returned by * java.lang.Character.getType(char). Groups of contiguous * characters of the same type are returned as complete tokens. *

     * StringUtils.splitByCharacterType(null)         = null
     * StringUtils.splitByCharacterType("")           = []
     * StringUtils.splitByCharacterType("ab de fg")   = ["ab", " ", "de", " ", "fg"]
     * StringUtils.splitByCharacterType("ab   de fg") = ["ab", "   ", "de", " ", "fg"]
     * StringUtils.splitByCharacterType("ab:cd:ef")   = ["ab", ":", "cd", ":", "ef"]
     * StringUtils.splitByCharacterType("number5")    = ["number", "5"]
     * StringUtils.splitByCharacterType("fooBar")     = ["foo", "B", "ar"]
     * StringUtils.splitByCharacterType("foo200Bar")  = ["foo", "200", "B", "ar"]
     * StringUtils.splitByCharacterType("ASFRules")   = ["ASFR", "ules"]
     * 
* @param str the String to split, may be null * @return an array of parsed Strings, null if null String input * @since 2.4 */ public static String[] splitByCharacterType(String str) { return splitByCharacterType(str, false); } /** *

Splits a String by Character type as returned by * java.lang.Character.getType(char). Groups of contiguous * characters of the same type are returned as complete tokens, with the * following exception: the character of type * Character.UPPERCASE_LETTER, if any, immediately * preceding a token of type Character.LOWERCASE_LETTER * will belong to the following token rather than to the preceding, if any, * Character.UPPERCASE_LETTER token. *

     * StringUtils.splitByCharacterTypeCamelCase(null)         = null
     * StringUtils.splitByCharacterTypeCamelCase("")           = []
     * StringUtils.splitByCharacterTypeCamelCase("ab de fg")   = ["ab", " ", "de", " ", "fg"]
     * StringUtils.splitByCharacterTypeCamelCase("ab   de fg") = ["ab", "   ", "de", " ", "fg"]
     * StringUtils.splitByCharacterTypeCamelCase("ab:cd:ef")   = ["ab", ":", "cd", ":", "ef"]
     * StringUtils.splitByCharacterTypeCamelCase("number5")    = ["number", "5"]
     * StringUtils.splitByCharacterTypeCamelCase("fooBar")     = ["foo", "Bar"]
     * StringUtils.splitByCharacterTypeCamelCase("foo200Bar")  = ["foo", "200", "Bar"]
     * StringUtils.splitByCharacterTypeCamelCase("ASFRules")   = ["ASF", "Rules"]
     * 
* @param str the String to split, may be null * @return an array of parsed Strings, null if null String input * @since 2.4 */ public static String[] splitByCharacterTypeCamelCase(String str) { return splitByCharacterType(str, true); } /** *

Splits a String by Character type as returned by * java.lang.Character.getType(char). Groups of contiguous * characters of the same type are returned as complete tokens, with the * following exception: if camelCase is true, * the character of type Character.UPPERCASE_LETTER, if any, * immediately preceding a token of type Character.LOWERCASE_LETTER * will belong to the following token rather than to the preceding, if any, * Character.UPPERCASE_LETTER token. * @param str the String to split, may be null * @param camelCase whether to use so-called "camel-case" for letter types * @return an array of parsed Strings, null if null String input * @since 2.4 */ private static String[] splitByCharacterType(String str, boolean camelCase) { if (str == null) { return null; } if (str.length() == 0) { return ArrayUtils.EMPTY_STRING_ARRAY; } char[] c = str.toCharArray(); List list = new ArrayList(); int tokenStart = 0; int currentType = Character.getType(c[tokenStart]); for (int pos = tokenStart + 1; pos < c.length; pos++) { int type = Character.getType(c[pos]); if (type == currentType) { continue; } if (camelCase && type == Character.LOWERCASE_LETTER && currentType == Character.UPPERCASE_LETTER) { int newTokenStart = pos - 1; if (newTokenStart != tokenStart) { list.add(new String(c, tokenStart, newTokenStart - tokenStart)); tokenStart = newTokenStart; } } else { list.add(new String(c, tokenStart, pos - tokenStart)); tokenStart = pos; } currentType = type; } list.add(new String(c, tokenStart, c.length - tokenStart)); return (String[]) list.toArray(new String[list.size()]); } // Joining //----------------------------------------------------------------------- /** *

Joins the provided elements into a single String.

* *

No separator is added to the joined String. * Null objects or empty string elements are represented by * empty strings.

* *
     * StringUtils.concatenate(null)            = null
     * StringUtils.concatenate([])              = ""
     * StringUtils.concatenate([null])          = ""
     * StringUtils.concatenate(["a", "b", "c"]) = "abc"
     * StringUtils.concatenate([null, "", "a"]) = "a"
     * 
* * @param array the array of values to concatenate, may be null * @return the concatenated String, null if null array input * @deprecated Use the better named {@link #join(Object[])} instead. * Method will be removed in Commons Lang 3.0. */ public static String concatenate(Object[] array) { return join(array, null); } /** *

Joins the elements of the provided array into a single String * containing the provided list of elements.

* *

No separator is added to the joined String. * Null objects or empty strings within the array are represented by * empty strings.

* *
     * StringUtils.join(null)            = null
     * StringUtils.join([])              = ""
     * StringUtils.join([null])          = ""
     * StringUtils.join(["a", "b", "c"]) = "abc"
     * StringUtils.join([null, "", "a"]) = "a"
     * 
* * @param array the array of values to join together, may be null * @return the joined String, null if null array input * @since 2.0 */ public static String join(Object[] array) { return join(array, null); } /** *

Joins the elements of the provided array into a single String * containing the provided list of elements.

* *

No delimiter is added before or after the list. * Null objects or empty strings within the array are represented by * empty strings.

* *
     * StringUtils.join(null, *)               = null
     * StringUtils.join([], *)                 = ""
     * StringUtils.join([null], *)             = ""
     * StringUtils.join(["a", "b", "c"], ';')  = "a;b;c"
     * StringUtils.join(["a", "b", "c"], null) = "abc"
     * StringUtils.join([null, "", "a"], ';')  = ";;a"
     * 
* * @param array the array of values to join together, may be null * @param separator the separator character to use * @return the joined String, null if null array input * @since 2.0 */ public static String join(Object[] array, char separator) { if (array == null) { return null; } return join(array, separator, 0, array.length); } /** *

Joins the elements of the provided array into a single String * containing the provided list of elements.

* *

No delimiter is added before or after the list. * Null objects or empty strings within the array are represented by * empty strings.

* *
     * StringUtils.join(null, *)               = null
     * StringUtils.join([], *)                 = ""
     * StringUtils.join([null], *)             = ""
     * StringUtils.join(["a", "b", "c"], ';')  = "a;b;c"
     * StringUtils.join(["a", "b", "c"], null) = "abc"
     * StringUtils.join([null, "", "a"], ';')  = ";;a"
     * 
* * @param array the array of values to join together, may be null * @param separator the separator character to use * @param startIndex the first index to start joining from. It is * an error to pass in an end index past the end of the array * @param endIndex the index to stop joining from (exclusive). It is * an error to pass in an end index past the end of the array * @return the joined String, null if null array input * @since 2.0 */ public static String join(Object[] array, char separator, int startIndex, int endIndex) { if (array == null) { return null; } int bufSize = (endIndex - startIndex); if (bufSize <= 0) { return EMPTY; } bufSize *= ((array[startIndex] == null ? 16 : array[startIndex].toString().length()) + 1); StrBuilder buf = new StrBuilder(bufSize); for (int i = startIndex; i < endIndex; i++) { if (i > startIndex) { buf.append(separator); } if (array[i] != null) { buf.append(array[i]); } } return buf.toString(); } /** *

Joins the elements of the provided array into a single String * containing the provided list of elements.

* *

No delimiter is added before or after the list. * A null separator is the same as an empty String (""). * Null objects or empty strings within the array are represented by * empty strings.

* *
     * StringUtils.join(null, *)                = null
     * StringUtils.join([], *)                  = ""
     * StringUtils.join([null], *)              = ""
     * StringUtils.join(["a", "b", "c"], "--")  = "a--b--c"
     * StringUtils.join(["a", "b", "c"], null)  = "abc"
     * StringUtils.join(["a", "b", "c"], "")    = "abc"
     * StringUtils.join([null, "", "a"], ',')   = ",,a"
     * 
* * @param array the array of values to join together, may be null * @param separator the separator character to use, null treated as "" * @return the joined String, null if null array input */ public static String join(Object[] array, String separator) { if (array == null) { return null; } return join(array, separator, 0, array.length); } /** *

Joins the elements of the provided array into a single String * containing the provided list of elements.

* *

No delimiter is added before or after the list. * A null separator is the same as an empty String (""). * Null objects or empty strings within the array are represented by * empty strings.

* *
     * StringUtils.join(null, *)                = null
     * StringUtils.join([], *)                  = ""
     * StringUtils.join([null], *)              = ""
     * StringUtils.join(["a", "b", "c"], "--")  = "a--b--c"
     * StringUtils.join(["a", "b", "c"], null)  = "abc"
     * StringUtils.join(["a", "b", "c"], "")    = "abc"
     * StringUtils.join([null, "", "a"], ',')   = ",,a"
     * 
* * @param array the array of values to join together, may be null * @param separator the separator character to use, null treated as "" * @param startIndex the first index to start joining from. It is * an error to pass in an end index past the end of the array * @param endIndex the index to stop joining from (exclusive). It is * an error to pass in an end index past the end of the array * @return the joined String, null if null array input */ public static String join(Object[] array, String separator, int startIndex, int endIndex) { if (array == null) { return null; } if (separator == null) { separator = EMPTY; } // endIndex - startIndex > 0: Len = NofStrings *(len(firstString) + len(separator)) // (Assuming that all Strings are roughly equally long) int bufSize = (endIndex - startIndex); if (bufSize <= 0) { return EMPTY; } bufSize *= ((array[startIndex] == null ? 16 : array[startIndex].toString().length()) + separator.length()); StrBuilder buf = new StrBuilder(bufSize); for (int i = startIndex; i < endIndex; i++) { if (i > startIndex) { buf.append(separator); } if (array[i] != null) { buf.append(array[i]); } } return buf.toString(); } /** *

Joins the elements of the provided Iterator into * a single String containing the provided elements.

* *

No delimiter is added before or after the list. Null objects or empty * strings within the iteration are represented by empty strings.

* *

See the examples here: {@link #join(Object[],char)}.

* * @param iterator the Iterator of values to join together, may be null * @param separator the separator character to use * @return the joined String, null if null iterator input * @since 2.0 */ public static String join(Iterator iterator, char separator) { // handle null, zero and one elements before building a buffer if (iterator == null) { return null; } if (!iterator.hasNext()) { return EMPTY; } Object first = iterator.next(); if (!iterator.hasNext()) { return ObjectUtils.toString(first); } // two or more elements StrBuilder buf = new StrBuilder(256); // Java default is 16, probably too small if (first != null) { buf.append(first); } while (iterator.hasNext()) { buf.append(separator); Object obj = iterator.next(); if (obj != null) { buf.append(obj); } } return buf.toString(); } /** *

Joins the elements of the provided Iterator into * a single String containing the provided elements.

* *

No delimiter is added before or after the list. * A null separator is the same as an empty String ("").

* *

See the examples here: {@link #join(Object[],String)}.

* * @param iterator the Iterator of values to join together, may be null * @param separator the separator character to use, null treated as "" * @return the joined String, null if null iterator input */ public static String join(Iterator iterator, String separator) { // handle null, zero and one elements before building a buffer if (iterator == null) { return null; } if (!iterator.hasNext()) { return EMPTY; } Object first = iterator.next(); if (!iterator.hasNext()) { return ObjectUtils.toString(first); } // two or more elements StrBuilder buf = new StrBuilder(256); // Java default is 16, probably too small if (first != null) { buf.append(first); } while (iterator.hasNext()) { if (separator != null) { buf.append(separator); } Object obj = iterator.next(); if (obj != null) { buf.append(obj); } } return buf.toString(); } /** *

Joins the elements of the provided Collection into * a single String containing the provided elements.

* *

No delimiter is added before or after the list. Null objects or empty * strings within the iteration are represented by empty strings.

* *

See the examples here: {@link #join(Object[],char)}.

* * @param collection the Collection of values to join together, may be null * @param separator the separator character to use * @return the joined String, null if null iterator input * @since 2.3 */ public static String join(Collection collection, char separator) { if (collection == null) { return null; } return join(collection.iterator(), separator); } /** *

Joins the elements of the provided Collection into * a single String containing the provided elements.

* *

No delimiter is added before or after the list. * A null separator is the same as an empty String ("").

* *

See the examples here: {@link #join(Object[],String)}.

* * @param collection the Collection of values to join together, may be null * @param separator the separator character to use, null treated as "" * @return the joined String, null if null iterator input * @since 2.3 */ public static String join(Collection collection, String separator) { if (collection == null) { return null; } return join(collection.iterator(), separator); } // Delete //----------------------------------------------------------------------- /** *

Deletes all 'space' characters from a String as defined by * {@link Character#isSpace(char)}.

* *

This is the only StringUtils method that uses the * isSpace definition. You are advised to use * {@link #deleteWhitespace(String)} instead as whitespace is much * better localized.

* *
     * StringUtils.deleteSpaces(null)           = null
     * StringUtils.deleteSpaces("")             = ""
     * StringUtils.deleteSpaces("abc")          = "abc"
     * StringUtils.deleteSpaces(" \t  abc \n ") = "abc"
     * StringUtils.deleteSpaces("ab  c")        = "abc"
     * StringUtils.deleteSpaces("a\nb\tc     ") = "abc"
     * 
* *

Spaces are defined as {' ', '\t', '\r', '\n', '\b'} * in line with the deprecated isSpace method.

* * @param str the String to delete spaces from, may be null * @return the String without 'spaces', null if null String input * @deprecated Use the better localized {@link #deleteWhitespace(String)}. * Method will be removed in Commons Lang 3.0. */ public static String deleteSpaces(String str) { if (str == null) { return null; } return CharSetUtils.delete(str, " \t\r\n\b"); } /** *

Deletes all whitespaces from a String as defined by * {@link Character#isWhitespace(char)}.

* *
     * StringUtils.deleteWhitespace(null)         = null
     * StringUtils.deleteWhitespace("")           = ""
     * StringUtils.deleteWhitespace("abc")        = "abc"
     * StringUtils.deleteWhitespace("   ab  c  ") = "abc"
     * 
* * @param str the String to delete whitespace from, may be null * @return the String without whitespaces, null if null String input */ public static String deleteWhitespace(String str) { if (isEmpty(str)) { return str; } int sz = str.length(); char[] chs = new char[sz]; int count = 0; for (int i = 0; i < sz; i++) { if (!Character.isWhitespace(str.charAt(i))) { chs[count++] = str.charAt(i); } } if (count == sz) { return str; } return new String(chs, 0, count); } // Remove //----------------------------------------------------------------------- /** *

Removes a substring only if it is at the begining of a source string, * otherwise returns the source string.

* *

A null source string will return null. * An empty ("") source string will return the empty string. * A null search string will return the source string.

* *
     * StringUtils.removeStart(null, *)      = null
     * StringUtils.removeStart("", *)        = ""
     * StringUtils.removeStart(*, null)      = *
     * StringUtils.removeStart("www.domain.com", "www.")   = "domain.com"
     * StringUtils.removeStart("domain.com", "www.")       = "domain.com"
     * StringUtils.removeStart("www.domain.com", "domain") = "www.domain.com"
     * StringUtils.removeStart("abc", "")    = "abc"
     * 
* * @param str the source String to search, may be null * @param remove the String to search for and remove, may be null * @return the substring with the string removed if found, * null if null String input * @since 2.1 */ public static String removeStart(String str, String remove) { if (isEmpty(str) || isEmpty(remove)) { return str; } if (str.startsWith(remove)){ return str.substring(remove.length()); } return str; } /** *

Case insensitive removal of a substring if it is at the begining of a source string, * otherwise returns the source string.

* *

A null source string will return null. * An empty ("") source string will return the empty string. * A null search string will return the source string.

* *
     * StringUtils.removeStartIgnoreCase(null, *)      = null
     * StringUtils.removeStartIgnoreCase("", *)        = ""
     * StringUtils.removeStartIgnoreCase(*, null)      = *
     * StringUtils.removeStartIgnoreCase("www.domain.com", "www.")   = "domain.com"
     * StringUtils.removeStartIgnoreCase("www.domain.com", "WWW.")   = "domain.com"
     * StringUtils.removeStartIgnoreCase("domain.com", "www.")       = "domain.com"
     * StringUtils.removeStartIgnoreCase("www.domain.com", "domain") = "www.domain.com"
     * StringUtils.removeStartIgnoreCase("abc", "")    = "abc"
     * 
* * @param str the source String to search, may be null * @param remove the String to search for (case insensitive) and remove, may be null * @return the substring with the string removed if found, * null if null String input * @since 2.4 */ public static String removeStartIgnoreCase(String str, String remove) { if (isEmpty(str) || isEmpty(remove)) { return str; } if (startsWithIgnoreCase(str, remove)) { return str.substring(remove.length()); } return str; } /** *

Removes a substring only if it is at the end of a source string, * otherwise returns the source string.

* *

A null source string will return null. * An empty ("") source string will return the empty string. * A null search string will return the source string.

* *
     * StringUtils.removeEnd(null, *)      = null
     * StringUtils.removeEnd("", *)        = ""
     * StringUtils.removeEnd(*, null)      = *
     * StringUtils.removeEnd("www.domain.com", ".com.")  = "www.domain.com"
     * StringUtils.removeEnd("www.domain.com", ".com")   = "www.domain"
     * StringUtils.removeEnd("www.domain.com", "domain") = "www.domain.com"
     * StringUtils.removeEnd("abc", "")    = "abc"
     * 
* * @param str the source String to search, may be null * @param remove the String to search for and remove, may be null * @return the substring with the string removed if found, * null if null String input * @since 2.1 */ public static String removeEnd(String str, String remove) { if (isEmpty(str) || isEmpty(remove)) { return str; } if (str.endsWith(remove)) { return str.substring(0, str.length() - remove.length()); } return str; } /** *

Case insensitive removal of a substring if it is at the end of a source string, * otherwise returns the source string.

* *

A null source string will return null. * An empty ("") source string will return the empty string. * A null search string will return the source string.

* *
     * StringUtils.removeEndIgnoreCase(null, *)      = null
     * StringUtils.removeEndIgnoreCase("", *)        = ""
     * StringUtils.removeEndIgnoreCase(*, null)      = *
     * StringUtils.removeEndIgnoreCase("www.domain.com", ".com.")  = "www.domain.com"
     * StringUtils.removeEndIgnoreCase("www.domain.com", ".com")   = "www.domain"
     * StringUtils.removeEndIgnoreCase("www.domain.com", "domain") = "www.domain.com"
     * StringUtils.removeEndIgnoreCase("abc", "")    = "abc"
     * StringUtils.removeEndIgnoreCase("www.domain.com", ".COM") = "www.domain")
     * StringUtils.removeEndIgnoreCase("www.domain.COM", ".com") = "www.domain")
     * 
* * @param str the source String to search, may be null * @param remove the String to search for (case insensitive) and remove, may be null * @return the substring with the string removed if found, * null if null String input * @since 2.4 */ public static String removeEndIgnoreCase(String str, String remove) { if (isEmpty(str) || isEmpty(remove)) { return str; } if (endsWithIgnoreCase(str, remove)) { return str.substring(0, str.length() - remove.length()); } return str; } /** *

Removes all occurrences of a substring from within the source string.

* *

A null source string will return null. * An empty ("") source string will return the empty string. * A null remove string will return the source string. * An empty ("") remove string will return the source string.

* *
     * StringUtils.remove(null, *)        = null
     * StringUtils.remove("", *)          = ""
     * StringUtils.remove(*, null)        = *
     * StringUtils.remove(*, "")          = *
     * StringUtils.remove("queued", "ue") = "qd"
     * StringUtils.remove("queued", "zz") = "queued"
     * 
* * @param str the source String to search, may be null * @param remove the String to search for and remove, may be null * @return the substring with the string removed if found, * null if null String input * @since 2.1 */ public static String remove(String str, String remove) { if (isEmpty(str) || isEmpty(remove)) { return str; } return replace(str, remove, EMPTY, -1); } /** *

Removes all occurrences of a character from within the source string.

* *

A null source string will return null. * An empty ("") source string will return the empty string.

* *
     * StringUtils.remove(null, *)       = null
     * StringUtils.remove("", *)         = ""
     * StringUtils.remove("queued", 'u') = "qeed"
     * StringUtils.remove("queued", 'z') = "queued"
     * 
* * @param str the source String to search, may be null * @param remove the char to search for and remove, may be null * @return the substring with the char removed if found, * null if null String input * @since 2.1 */ public static String remove(String str, char remove) { if (isEmpty(str) || str.indexOf(remove) == INDEX_NOT_FOUND) { return str; } char[] chars = str.toCharArray(); int pos = 0; for (int i = 0; i < chars.length; i++) { if (chars[i] != remove) { chars[pos++] = chars[i]; } } return new String(chars, 0, pos); } // Replacing //----------------------------------------------------------------------- /** *

Replaces a String with another String inside a larger String, once.

* *

A null reference passed to this method is a no-op.

* *
     * StringUtils.replaceOnce(null, *, *)        = null
     * StringUtils.replaceOnce("", *, *)          = ""
     * StringUtils.replaceOnce("any", null, *)    = "any"
     * StringUtils.replaceOnce("any", *, null)    = "any"
     * StringUtils.replaceOnce("any", "", *)      = "any"
     * StringUtils.replaceOnce("aba", "a", null)  = "aba"
     * StringUtils.replaceOnce("aba", "a", "")    = "ba"
     * StringUtils.replaceOnce("aba", "a", "z")   = "zba"
     * 
* * @see #replace(String text, String searchString, String replacement, int max) * @param text text to search and replace in, may be null * @param searchString the String to search for, may be null * @param replacement the String to replace with, may be null * @return the text with any replacements processed, * null if null String input */ public static String replaceOnce(String text, String searchString, String replacement) { return replace(text, searchString, replacement, 1); } /** *

Replaces all occurrences of a String within another String.

* *

A null reference passed to this method is a no-op.

* *
     * StringUtils.replace(null, *, *)        = null
     * StringUtils.replace("", *, *)          = ""
     * StringUtils.replace("any", null, *)    = "any"
     * StringUtils.replace("any", *, null)    = "any"
     * StringUtils.replace("any", "", *)      = "any"
     * StringUtils.replace("aba", "a", null)  = "aba"
     * StringUtils.replace("aba", "a", "")    = "b"
     * StringUtils.replace("aba", "a", "z")   = "zbz"
     * 
* * @see #replace(String text, String searchString, String replacement, int max) * @param text text to search and replace in, may be null * @param searchString the String to search for, may be null * @param replacement the String to replace it with, may be null * @return the text with any replacements processed, * null if null String input */ public static String replace(String text, String searchString, String replacement) { return replace(text, searchString, replacement, -1); } /** *

Replaces a String with another String inside a larger String, * for the first max values of the search String.

* *

A null reference passed to this method is a no-op.

* *
     * StringUtils.replace(null, *, *, *)         = null
     * StringUtils.replace("", *, *, *)           = ""
     * StringUtils.replace("any", null, *, *)     = "any"
     * StringUtils.replace("any", *, null, *)     = "any"
     * StringUtils.replace("any", "", *, *)       = "any"
     * StringUtils.replace("any", *, *, 0)        = "any"
     * StringUtils.replace("abaa", "a", null, -1) = "abaa"
     * StringUtils.replace("abaa", "a", "", -1)   = "b"
     * StringUtils.replace("abaa", "a", "z", 0)   = "abaa"
     * StringUtils.replace("abaa", "a", "z", 1)   = "zbaa"
     * StringUtils.replace("abaa", "a", "z", 2)   = "zbza"
     * StringUtils.replace("abaa", "a", "z", -1)  = "zbzz"
     * 
* * @param text text to search and replace in, may be null * @param searchString the String to search for, may be null * @param replacement the String to replace it with, may be null * @param max maximum number of values to replace, or -1 if no maximum * @return the text with any replacements processed, * null if null String input */ public static String replace(String text, String searchString, String replacement, int max) { if (isEmpty(text) || isEmpty(searchString) || replacement == null || max == 0) { return text; } int start = 0; int end = text.indexOf(searchString, start); if (end == INDEX_NOT_FOUND) { return text; } int replLength = searchString.length(); int increase = replacement.length() - replLength; increase = (increase < 0 ? 0 : increase); increase *= (max < 0 ? 16 : (max > 64 ? 64 : max)); StrBuilder buf = new StrBuilder(text.length() + increase); while (end != INDEX_NOT_FOUND) { buf.append(text.substring(start, end)).append(replacement); start = end + replLength; if (--max == 0) { break; } end = text.indexOf(searchString, start); } buf.append(text.substring(start)); return buf.toString(); } /** *

* Replaces all occurrences of Strings within another String. *

* *

* A null reference passed to this method is a no-op, or if * any "search string" or "string to replace" is null, that replace will be * ignored. This will not repeat. For repeating replaces, call the * overloaded method. *

* *
     *  StringUtils.replaceEach(null, *, *)        = null
     *  StringUtils.replaceEach("", *, *)          = ""
     *  StringUtils.replaceEach("aba", null, null) = "aba"
     *  StringUtils.replaceEach("aba", new String[0], null) = "aba"
     *  StringUtils.replaceEach("aba", null, new String[0]) = "aba"
     *  StringUtils.replaceEach("aba", new String[]{"a"}, null)  = "aba"
     *  StringUtils.replaceEach("aba", new String[]{"a"}, new String[]{""})  = "b"
     *  StringUtils.replaceEach("aba", new String[]{null}, new String[]{"a"})  = "aba"
     *  StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"w", "t"})  = "wcte"
     *  (example of how it does not repeat)
     *  StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"})  = "dcte"
     * 
* * @param text * text to search and replace in, no-op if null * @param searchList * the Strings to search for, no-op if null * @param replacementList * the Strings to replace them with, no-op if null * @return the text with any replacements processed, null if * null String input * @throws IndexOutOfBoundsException * if the lengths of the arrays are not the same (null is ok, * and/or size 0) * @since 2.4 */ public static String replaceEach(String text, String[] searchList, String[] replacementList) { return replaceEach(text, searchList, replacementList, false, 0); } /** *

* Replaces all occurrences of Strings within another String. *

* *

* A null reference passed to this method is a no-op, or if * any "search string" or "string to replace" is null, that replace will be * ignored. This will not repeat. For repeating replaces, call the * overloaded method. *

* *
     *  StringUtils.replaceEach(null, *, *, *) = null
     *  StringUtils.replaceEach("", *, *, *) = ""
     *  StringUtils.replaceEach("aba", null, null, *) = "aba"
     *  StringUtils.replaceEach("aba", new String[0], null, *) = "aba"
     *  StringUtils.replaceEach("aba", null, new String[0], *) = "aba"
     *  StringUtils.replaceEach("aba", new String[]{"a"}, null, *) = "aba"
     *  StringUtils.replaceEach("aba", new String[]{"a"}, new String[]{""}, *) = "b"
     *  StringUtils.replaceEach("aba", new String[]{null}, new String[]{"a"}, *) = "aba"
     *  StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"w", "t"}, *) = "wcte"
     *  (example of how it repeats)
     *  StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"}, false) = "dcte"
     *  StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"}, true) = "tcte"
     *  StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "ab"}, true) = IllegalArgumentException
     *  StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "ab"}, false) = "dcabe"
     * 
* * @param text * text to search and replace in, no-op if null * @param searchList * the Strings to search for, no-op if null * @param replacementList * the Strings to replace them with, no-op if null * @return the text with any replacements processed, null if * null String input * @throws IllegalArgumentException * if the search is repeating and there is an endless loop due * to outputs of one being inputs to another * @throws IndexOutOfBoundsException * if the lengths of the arrays are not the same (null is ok, * and/or size 0) * @since 2.4 */ public static String replaceEachRepeatedly(String text, String[] searchList, String[] replacementList) { // timeToLive should be 0 if not used or nothing to replace, else it's // the length of the replace array int timeToLive = searchList == null ? 0 : searchList.length; return replaceEach(text, searchList, replacementList, true, timeToLive); } /** *

* Replaces all occurrences of Strings within another String. *

* *

* A null reference passed to this method is a no-op, or if * any "search string" or "string to replace" is null, that replace will be * ignored. *

* *
     *  StringUtils.replaceEach(null, *, *, *) = null
     *  StringUtils.replaceEach("", *, *, *) = ""
     *  StringUtils.replaceEach("aba", null, null, *) = "aba"
     *  StringUtils.replaceEach("aba", new String[0], null, *) = "aba"
     *  StringUtils.replaceEach("aba", null, new String[0], *) = "aba"
     *  StringUtils.replaceEach("aba", new String[]{"a"}, null, *) = "aba"
     *  StringUtils.replaceEach("aba", new String[]{"a"}, new String[]{""}, *) = "b"
     *  StringUtils.replaceEach("aba", new String[]{null}, new String[]{"a"}, *) = "aba"
     *  StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"w", "t"}, *) = "wcte"
     *  (example of how it repeats)
     *  StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"}, false) = "dcte"
     *  StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"}, true) = "tcte"
     *  StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "ab"}, *) = IllegalArgumentException
     * 
* * @param text * text to search and replace in, no-op if null * @param searchList * the Strings to search for, no-op if null * @param replacementList * the Strings to replace them with, no-op if null * @param repeat if true, then replace repeatedly * until there are no more possible replacements or timeToLive < 0 * @param timeToLive * if less than 0 then there is a circular reference and endless * loop * @return the text with any replacements processed, null if * null String input * @throws IllegalArgumentException * if the search is repeating and there is an endless loop due * to outputs of one being inputs to another * @throws IndexOutOfBoundsException * if the lengths of the arrays are not the same (null is ok, * and/or size 0) * @since 2.4 */ private static String replaceEach(String text, String[] searchList, String[] replacementList, boolean repeat, int timeToLive) { // mchyzer Performance note: This creates very few new objects (one major goal) // let me know if there are performance requests, we can create a harness to measure if (text == null || text.length() == 0 || searchList == null || searchList.length == 0 || replacementList == null || replacementList.length == 0) { return text; } // if recursing, this shouldnt be less than 0 if (timeToLive < 0) { throw new IllegalStateException("TimeToLive of " + timeToLive + " is less than 0: " + text); } int searchLength = searchList.length; int replacementLength = replacementList.length; // make sure lengths are ok, these need to be equal if (searchLength != replacementLength) { throw new IllegalArgumentException("Search and Replace array lengths don't match: " + searchLength + " vs " + replacementLength); } // keep track of which still have matches boolean[] noMoreMatchesForReplIndex = new boolean[searchLength]; // index on index that the match was found int textIndex = -1; int replaceIndex = -1; int tempIndex = -1; // index of replace array that will replace the search string found // NOTE: logic duplicated below START for (int i = 0; i < searchLength; i++) { if (noMoreMatchesForReplIndex[i] || searchList[i] == null || searchList[i].length() == 0 || replacementList[i] == null) { continue; } tempIndex = text.indexOf(searchList[i]); // see if we need to keep searching for this if (tempIndex == -1) { noMoreMatchesForReplIndex[i] = true; } else { if (textIndex == -1 || tempIndex < textIndex) { textIndex = tempIndex; replaceIndex = i; } } } // NOTE: logic mostly below END // no search strings found, we are done if (textIndex == -1) { return text; } int start = 0; // get a good guess on the size of the result buffer so it doesnt have to double if it goes over a bit int increase = 0; // count the replacement text elements that are larger than their corresponding text being replaced for (int i = 0; i < searchList.length; i++) { if (searchList[i] == null || replacementList[i] == null) { continue; } int greater = replacementList[i].length() - searchList[i].length(); if (greater > 0) { increase += 3 * greater; // assume 3 matches } } // have upper-bound at 20% increase, then let Java take over increase = Math.min(increase, text.length() / 5); StrBuilder buf = new StrBuilder(text.length() + increase); while (textIndex != -1) { for (int i = start; i < textIndex; i++) { buf.append(text.charAt(i)); } buf.append(replacementList[replaceIndex]); start = textIndex + searchList[replaceIndex].length(); textIndex = -1; replaceIndex = -1; tempIndex = -1; // find the next earliest match // NOTE: logic mostly duplicated above START for (int i = 0; i < searchLength; i++) { if (noMoreMatchesForReplIndex[i] || searchList[i] == null || searchList[i].length() == 0 || replacementList[i] == null) { continue; } tempIndex = text.indexOf(searchList[i], start); // see if we need to keep searching for this if (tempIndex == -1) { noMoreMatchesForReplIndex[i] = true; } else { if (textIndex == -1 || tempIndex < textIndex) { textIndex = tempIndex; replaceIndex = i; } } } // NOTE: logic duplicated above END } int textLength = text.length(); for (int i = start; i < textLength; i++) { buf.append(text.charAt(i)); } String result = buf.toString(); if (!repeat) { return result; } return replaceEach(result, searchList, replacementList, repeat, timeToLive - 1); } // Replace, character based //----------------------------------------------------------------------- /** *

Replaces all occurrences of a character in a String with another. * This is a null-safe version of {@link String#replace(char, char)}.

* *

A null string input returns null. * An empty ("") string input returns an empty string.

* *
     * StringUtils.replaceChars(null, *, *)        = null
     * StringUtils.replaceChars("", *, *)          = ""
     * StringUtils.replaceChars("abcba", 'b', 'y') = "aycya"
     * StringUtils.replaceChars("abcba", 'z', 'y') = "abcba"
     * 
* * @param str String to replace characters in, may be null * @param searchChar the character to search for, may be null * @param replaceChar the character to replace, may be null * @return modified String, null if null string input * @since 2.0 */ public static String replaceChars(String str, char searchChar, char replaceChar) { if (str == null) { return null; } return str.replace(searchChar, replaceChar); } /** *

Replaces multiple characters in a String in one go. * This method can also be used to delete characters.

* *

For example:
* replaceChars("hello", "ho", "jy") = jelly.

* *

A null string input returns null. * An empty ("") string input returns an empty string. * A null or empty set of search characters returns the input string.

* *

The length of the search characters should normally equal the length * of the replace characters. * If the search characters is longer, then the extra search characters * are deleted. * If the search characters is shorter, then the extra replace characters * are ignored.

* *
     * StringUtils.replaceChars(null, *, *)           = null
     * StringUtils.replaceChars("", *, *)             = ""
     * StringUtils.replaceChars("abc", null, *)       = "abc"
     * StringUtils.replaceChars("abc", "", *)         = "abc"
     * StringUtils.replaceChars("abc", "b", null)     = "ac"
     * StringUtils.replaceChars("abc", "b", "")       = "ac"
     * StringUtils.replaceChars("abcba", "bc", "yz")  = "ayzya"
     * StringUtils.replaceChars("abcba", "bc", "y")   = "ayya"
     * StringUtils.replaceChars("abcba", "bc", "yzx") = "ayzya"
     * 
* * @param str String to replace characters in, may be null * @param searchChars a set of characters to search for, may be null * @param replaceChars a set of characters to replace, may be null * @return modified String, null if null string input * @since 2.0 */ public static String replaceChars(String str, String searchChars, String replaceChars) { if (isEmpty(str) || isEmpty(searchChars)) { return str; } if (replaceChars == null) { replaceChars = EMPTY; } boolean modified = false; int replaceCharsLength = replaceChars.length(); int strLength = str.length(); StrBuilder buf = new StrBuilder(strLength); for (int i = 0; i < strLength; i++) { char ch = str.charAt(i); int index = searchChars.indexOf(ch); if (index >= 0) { modified = true; if (index < replaceCharsLength) { buf.append(replaceChars.charAt(index)); } } else { buf.append(ch); } } if (modified) { return buf.toString(); } return str; } // Overlay //----------------------------------------------------------------------- /** *

Overlays part of a String with another String.

* *
     * StringUtils.overlayString(null, *, *, *)           = NullPointerException
     * StringUtils.overlayString(*, null, *, *)           = NullPointerException
     * StringUtils.overlayString("", "abc", 0, 0)         = "abc"
     * StringUtils.overlayString("abcdef", null, 2, 4)    = "abef"
     * StringUtils.overlayString("abcdef", "", 2, 4)      = "abef"
     * StringUtils.overlayString("abcdef", "zzzz", 2, 4)  = "abzzzzef"
     * StringUtils.overlayString("abcdef", "zzzz", 4, 2)  = "abcdzzzzcdef"
     * StringUtils.overlayString("abcdef", "zzzz", -1, 4) = IndexOutOfBoundsException
     * StringUtils.overlayString("abcdef", "zzzz", 2, 8)  = IndexOutOfBoundsException
     * 
* * @param text the String to do overlaying in, may be null * @param overlay the String to overlay, may be null * @param start the position to start overlaying at, must be valid * @param end the position to stop overlaying before, must be valid * @return overlayed String, null if null String input * @throws NullPointerException if text or overlay is null * @throws IndexOutOfBoundsException if either position is invalid * @deprecated Use better named {@link #overlay(String, String, int, int)} instead. * Method will be removed in Commons Lang 3.0. */ public static String overlayString(String text, String overlay, int start, int end) { return new StrBuilder(start + overlay.length() + text.length() - end + 1) .append(text.substring(0, start)) .append(overlay) .append(text.substring(end)) .toString(); } /** *

Overlays part of a String with another String.

* *

A null string input returns null. * A negative index is treated as zero. * An index greater than the string length is treated as the string length. * The start index is always the smaller of the two indices.

* *
     * StringUtils.overlay(null, *, *, *)            = null
     * StringUtils.overlay("", "abc", 0, 0)          = "abc"
     * StringUtils.overlay("abcdef", null, 2, 4)     = "abef"
     * StringUtils.overlay("abcdef", "", 2, 4)       = "abef"
     * StringUtils.overlay("abcdef", "", 4, 2)       = "abef"
     * StringUtils.overlay("abcdef", "zzzz", 2, 4)   = "abzzzzef"
     * StringUtils.overlay("abcdef", "zzzz", 4, 2)   = "abzzzzef"
     * StringUtils.overlay("abcdef", "zzzz", -1, 4)  = "zzzzef"
     * StringUtils.overlay("abcdef", "zzzz", 2, 8)   = "abzzzz"
     * StringUtils.overlay("abcdef", "zzzz", -2, -3) = "zzzzabcdef"
     * StringUtils.overlay("abcdef", "zzzz", 8, 10)  = "abcdefzzzz"
     * 
* * @param str the String to do overlaying in, may be null * @param overlay the String to overlay, may be null * @param start the position to start overlaying at * @param end the position to stop overlaying before * @return overlayed String, null if null String input * @since 2.0 */ public static String overlay(String str, String overlay, int start, int end) { if (str == null) { return null; } if (overlay == null) { overlay = EMPTY; } int len = str.length(); if (start < 0) { start = 0; } if (start > len) { start = len; } if (end < 0) { end = 0; } if (end > len) { end = len; } if (start > end) { int temp = start; start = end; end = temp; } return new StrBuilder(len + start - end + overlay.length() + 1) .append(str.substring(0, start)) .append(overlay) .append(str.substring(end)) .toString(); } // Chomping //----------------------------------------------------------------------- /** *

Removes one newline from end of a String if it's there, * otherwise leave it alone. A newline is "\n", * "\r", or "\r\n".

* *

NOTE: This method changed in 2.0. * It now more closely matches Perl chomp.

* *
     * StringUtils.chomp(null)          = null
     * StringUtils.chomp("")            = ""
     * StringUtils.chomp("abc \r")      = "abc "
     * StringUtils.chomp("abc\n")       = "abc"
     * StringUtils.chomp("abc\r\n")     = "abc"
     * StringUtils.chomp("abc\r\n\r\n") = "abc\r\n"
     * StringUtils.chomp("abc\n\r")     = "abc\n"
     * StringUtils.chomp("abc\n\rabc")  = "abc\n\rabc"
     * StringUtils.chomp("\r")          = ""
     * StringUtils.chomp("\n")          = ""
     * StringUtils.chomp("\r\n")        = ""
     * 
* * @param str the String to chomp a newline from, may be null * @return String without newline, null if null String input */ public static String chomp(String str) { if (isEmpty(str)) { return str; } if (str.length() == 1) { char ch = str.charAt(0); if (ch == CharUtils.CR || ch == CharUtils.LF) { return EMPTY; } return str; } int lastIdx = str.length() - 1; char last = str.charAt(lastIdx); if (last == CharUtils.LF) { if (str.charAt(lastIdx - 1) == CharUtils.CR) { lastIdx--; } } else if (last != CharUtils.CR) { lastIdx++; } return str.substring(0, lastIdx); } /** *

Removes separator from the end of * str if it's there, otherwise leave it alone.

* *

NOTE: This method changed in version 2.0. * It now more closely matches Perl chomp. * For the previous behavior, use {@link #substringBeforeLast(String, String)}. * This method uses {@link String#endsWith(String)}.

* *
     * StringUtils.chomp(null, *)         = null
     * StringUtils.chomp("", *)           = ""
     * StringUtils.chomp("foobar", "bar") = "foo"
     * StringUtils.chomp("foobar", "baz") = "foobar"
     * StringUtils.chomp("foo", "foo")    = ""
     * StringUtils.chomp("foo ", "foo")   = "foo "
     * StringUtils.chomp(" foo", "foo")   = " "
     * StringUtils.chomp("foo", "foooo")  = "foo"
     * StringUtils.chomp("foo", "")       = "foo"
     * StringUtils.chomp("foo", null)     = "foo"
     * 
* * @param str the String to chomp from, may be null * @param separator separator String, may be null * @return String without trailing separator, null if null String input */ public static String chomp(String str, String separator) { if (isEmpty(str) || separator == null) { return str; } if (str.endsWith(separator)) { return str.substring(0, str.length() - separator.length()); } return str; } /** *

Remove any "\n" if and only if it is at the end * of the supplied String.

* * @param str the String to chomp from, must not be null * @return String without chomped ending * @throws NullPointerException if str is null * @deprecated Use {@link #chomp(String)} instead. * Method will be removed in Commons Lang 3.0. */ public static String chompLast(String str) { return chompLast(str, "\n"); } /** *

Remove a value if and only if the String ends with that value.

* * @param str the String to chomp from, must not be null * @param sep the String to chomp, must not be null * @return String without chomped ending * @throws NullPointerException if str or sep is null * @deprecated Use {@link #chomp(String,String)} instead. * Method will be removed in Commons Lang 3.0. */ public static String chompLast(String str, String sep) { if (str.length() == 0) { return str; } String sub = str.substring(str.length() - sep.length()); if (sep.equals(sub)) { return str.substring(0, str.length() - sep.length()); } return str; } /** *

Remove everything and return the last value of a supplied String, and * everything after it from a String.

* * @param str the String to chomp from, must not be null * @param sep the String to chomp, must not be null * @return String chomped * @throws NullPointerException if str or sep is null * @deprecated Use {@link #substringAfterLast(String, String)} instead * (although this doesn't include the separator) * Method will be removed in Commons Lang 3.0. */ public static String getChomp(String str, String sep) { int idx = str.lastIndexOf(sep); if (idx == str.length() - sep.length()) { return sep; } else if (idx != -1) { return str.substring(idx); } else { return EMPTY; } } /** *

Remove the first value of a supplied String, and everything before it * from a String.

* * @param str the String to chomp from, must not be null * @param sep the String to chomp, must not be null * @return String without chomped beginning * @throws NullPointerException if str or sep is null * @deprecated Use {@link #substringAfter(String,String)} instead. * Method will be removed in Commons Lang 3.0. */ public static String prechomp(String str, String sep) { int idx = str.indexOf(sep); if (idx == -1) { return str; } return str.substring(idx + sep.length()); } /** *

Remove and return everything before the first value of a * supplied String from another String.

* * @param str the String to chomp from, must not be null * @param sep the String to chomp, must not be null * @return String prechomped * @throws NullPointerException if str or sep is null * @deprecated Use {@link #substringBefore(String,String)} instead * (although this doesn't include the separator). * Method will be removed in Commons Lang 3.0. */ public static String getPrechomp(String str, String sep) { int idx = str.indexOf(sep); if (idx == -1) { return EMPTY; } return str.substring(0, idx + sep.length()); } // Chopping //----------------------------------------------------------------------- /** *

Remove the last character from a String.

* *

If the String ends in \r\n, then remove both * of them.

* *
     * StringUtils.chop(null)          = null
     * StringUtils.chop("")            = ""
     * StringUtils.chop("abc \r")      = "abc "
     * StringUtils.chop("abc\n")       = "abc"
     * StringUtils.chop("abc\r\n")     = "abc"
     * StringUtils.chop("abc")         = "ab"
     * StringUtils.chop("abc\nabc")    = "abc\nab"
     * StringUtils.chop("a")           = ""
     * StringUtils.chop("\r")          = ""
     * StringUtils.chop("\n")          = ""
     * StringUtils.chop("\r\n")        = ""
     * 
* * @param str the String to chop last character from, may be null * @return String without last character, null if null String input */ public static String chop(String str) { if (str == null) { return null; } int strLen = str.length(); if (strLen < 2) { return EMPTY; } int lastIdx = strLen - 1; String ret = str.substring(0, lastIdx); char last = str.charAt(lastIdx); if (last == CharUtils.LF) { if (ret.charAt(lastIdx - 1) == CharUtils.CR) { return ret.substring(0, lastIdx - 1); } } return ret; } /** *

Removes \n from end of a String if it's there. * If a \r precedes it, then remove that too.

* * @param str the String to chop a newline from, must not be null * @return String without newline * @throws NullPointerException if str is null * @deprecated Use {@link #chomp(String)} instead. * Method will be removed in Commons Lang 3.0. */ public static String chopNewline(String str) { int lastIdx = str.length() - 1; if (lastIdx <= 0) { return EMPTY; } char last = str.charAt(lastIdx); if (last == CharUtils.LF) { if (str.charAt(lastIdx - 1) == CharUtils.CR) { lastIdx--; } } else { lastIdx++; } return str.substring(0, lastIdx); } // Conversion //----------------------------------------------------------------------- /** *

Escapes any values it finds into their String form.

* *

So a tab becomes the characters '\\' and * 't'.

* *

As of Lang 2.0, this calls {@link StringEscapeUtils#escapeJava(String)} * behind the scenes. *

* @see StringEscapeUtils#escapeJava(java.lang.String) * @param str String to escape values in * @return String with escaped values * @throws NullPointerException if str is null * @deprecated Use {@link StringEscapeUtils#escapeJava(String)} * This method will be removed in Commons Lang 3.0 */ public static String escape(String str) { return StringEscapeUtils.escapeJava(str); } // Padding //----------------------------------------------------------------------- /** *

Repeat a String repeat times to form a * new String.

* *
     * StringUtils.repeat(null, 2) = null
     * StringUtils.repeat("", 0)   = ""
     * StringUtils.repeat("", 2)   = ""
     * StringUtils.repeat("a", 3)  = "aaa"
     * StringUtils.repeat("ab", 2) = "abab"
     * StringUtils.repeat("a", -2) = ""
     * 
* * @param str the String to repeat, may be null * @param repeat number of times to repeat str, negative treated as zero * @return a new String consisting of the original String repeated, * null if null String input */ public static String repeat(String str, int repeat) { // Performance tuned for 2.0 (JDK1.4) if (str == null) { return null; } if (repeat <= 0) { return EMPTY; } int inputLength = str.length(); if (repeat == 1 || inputLength == 0) { return str; } if (inputLength == 1 && repeat <= PAD_LIMIT) { return padding(repeat, str.charAt(0)); } int outputLength = inputLength * repeat; switch (inputLength) { case 1 : char ch = str.charAt(0); char[] output1 = new char[outputLength]; for (int i = repeat - 1; i >= 0; i--) { output1[i] = ch; } return new String(output1); case 2 : char ch0 = str.charAt(0); char ch1 = str.charAt(1); char[] output2 = new char[outputLength]; for (int i = repeat * 2 - 2; i >= 0; i--, i--) { output2[i] = ch0; output2[i + 1] = ch1; } return new String(output2); default : StrBuilder buf = new StrBuilder(outputLength); for (int i = 0; i < repeat; i++) { buf.append(str); } return buf.toString(); } } /** *

Repeat a String repeat times to form a * new String, with a String separator injected each time.

* *
     * StringUtils.repeat(null, null, 2) = null
     * StringUtils.repeat(null, "x", 2)  = null
     * StringUtils.repeat("", null, 0)   = ""
     * StringUtils.repeat("", "", 2)     = ""
     * StringUtils.repeat("", "x", 3)    = "xxx"
     * StringUtils.repeat("?", ", ", 3)  = "?, ?, ?"
     * 
* * @param str the String to repeat, may be null * @param separator the String to inject, may be null * @param repeat number of times to repeat str, negative treated as zero * @return a new String consisting of the original String repeated, * null if null String input * @since 2.5 */ public static String repeat(String str, String separator, int repeat) { if(str == null || separator == null) { return repeat(str, repeat); } else { // given that repeat(String, int) is quite optimized, better to rely on it than try and splice this into it String result = repeat(str + separator, repeat); return removeEnd(result, separator); } } /** *

Returns padding using the specified delimiter repeated * to a given length.

* *
     * StringUtils.padding(0, 'e')  = ""
     * StringUtils.padding(3, 'e')  = "eee"
     * StringUtils.padding(-2, 'e') = IndexOutOfBoundsException
     * 
* *

Note: this method doesn't not support padding with * Unicode Supplementary Characters * as they require a pair of chars to be represented. * If you are needing to support full I18N of your applications * consider using {@link #repeat(String, int)} instead. *

* * @param repeat number of times to repeat delim * @param padChar character to repeat * @return String with repeated character * @throws IndexOutOfBoundsException if repeat < 0 * @see #repeat(String, int) */ private static String padding(int repeat, char padChar) throws IndexOutOfBoundsException { if (repeat < 0) { throw new IndexOutOfBoundsException("Cannot pad a negative amount: " + repeat); } final char[] buf = new char[repeat]; for (int i = 0; i < buf.length; i++) { buf[i] = padChar; } return new String(buf); } /** *

Right pad a String with spaces (' ').

* *

The String is padded to the size of size.

* *
     * StringUtils.rightPad(null, *)   = null
     * StringUtils.rightPad("", 3)     = "   "
     * StringUtils.rightPad("bat", 3)  = "bat"
     * StringUtils.rightPad("bat", 5)  = "bat  "
     * StringUtils.rightPad("bat", 1)  = "bat"
     * StringUtils.rightPad("bat", -1) = "bat"
     * 
* * @param str the String to pad out, may be null * @param size the size to pad to * @return right padded String or original String if no padding is necessary, * null if null String input */ public static String rightPad(String str, int size) { return rightPad(str, size, ' '); } /** *

Right pad a String with a specified character.

* *

The String is padded to the size of size.

* *
     * StringUtils.rightPad(null, *, *)     = null
     * StringUtils.rightPad("", 3, 'z')     = "zzz"
     * StringUtils.rightPad("bat", 3, 'z')  = "bat"
     * StringUtils.rightPad("bat", 5, 'z')  = "batzz"
     * StringUtils.rightPad("bat", 1, 'z')  = "bat"
     * StringUtils.rightPad("bat", -1, 'z') = "bat"
     * 
* * @param str the String to pad out, may be null * @param size the size to pad to * @param padChar the character to pad with * @return right padded String or original String if no padding is necessary, * null if null String input * @since 2.0 */ public static String rightPad(String str, int size, char padChar) { if (str == null) { return null; } int pads = size - str.length(); if (pads <= 0) { return str; // returns original String when possible } if (pads > PAD_LIMIT) { return rightPad(str, size, String.valueOf(padChar)); } return str.concat(padding(pads, padChar)); } /** *

Right pad a String with a specified String.

* *

The String is padded to the size of size.

* *
     * StringUtils.rightPad(null, *, *)      = null
     * StringUtils.rightPad("", 3, "z")      = "zzz"
     * StringUtils.rightPad("bat", 3, "yz")  = "bat"
     * StringUtils.rightPad("bat", 5, "yz")  = "batyz"
     * StringUtils.rightPad("bat", 8, "yz")  = "batyzyzy"
     * StringUtils.rightPad("bat", 1, "yz")  = "bat"
     * StringUtils.rightPad("bat", -1, "yz") = "bat"
     * StringUtils.rightPad("bat", 5, null)  = "bat  "
     * StringUtils.rightPad("bat", 5, "")    = "bat  "
     * 
* * @param str the String to pad out, may be null * @param size the size to pad to * @param padStr the String to pad with, null or empty treated as single space * @return right padded String or original String if no padding is necessary, * null if null String input */ public static String rightPad(String str, int size, String padStr) { if (str == null) { return null; } if (isEmpty(padStr)) { padStr = " "; } int padLen = padStr.length(); int strLen = str.length(); int pads = size - strLen; if (pads <= 0) { return str; // returns original String when possible } if (padLen == 1 && pads <= PAD_LIMIT) { return rightPad(str, size, padStr.charAt(0)); } if (pads == padLen) { return str.concat(padStr); } else if (pads < padLen) { return str.concat(padStr.substring(0, pads)); } else { char[] padding = new char[pads]; char[] padChars = padStr.toCharArray(); for (int i = 0; i < pads; i++) { padding[i] = padChars[i % padLen]; } return str.concat(new String(padding)); } } /** *

Left pad a String with spaces (' ').

* *

The String is padded to the size of size.

* *
     * StringUtils.leftPad(null, *)   = null
     * StringUtils.leftPad("", 3)     = "   "
     * StringUtils.leftPad("bat", 3)  = "bat"
     * StringUtils.leftPad("bat", 5)  = "  bat"
     * StringUtils.leftPad("bat", 1)  = "bat"
     * StringUtils.leftPad("bat", -1) = "bat"
     * 
* * @param str the String to pad out, may be null * @param size the size to pad to * @return left padded String or original String if no padding is necessary, * null if null String input */ public static String leftPad(String str, int size) { return leftPad(str, size, ' '); } /** *

Left pad a String with a specified character.

* *

Pad to a size of size.

* *
     * StringUtils.leftPad(null, *, *)     = null
     * StringUtils.leftPad("", 3, 'z')     = "zzz"
     * StringUtils.leftPad("bat", 3, 'z')  = "bat"
     * StringUtils.leftPad("bat", 5, 'z')  = "zzbat"
     * StringUtils.leftPad("bat", 1, 'z')  = "bat"
     * StringUtils.leftPad("bat", -1, 'z') = "bat"
     * 
* * @param str the String to pad out, may be null * @param size the size to pad to * @param padChar the character to pad with * @return left padded String or original String if no padding is necessary, * null if null String input * @since 2.0 */ public static String leftPad(String str, int size, char padChar) { if (str == null) { return null; } int pads = size - str.length(); if (pads <= 0) { return str; // returns original String when possible } if (pads > PAD_LIMIT) { return leftPad(str, size, String.valueOf(padChar)); } return padding(pads, padChar).concat(str); } /** *

Left pad a String with a specified String.

* *

Pad to a size of size.

* *
     * StringUtils.leftPad(null, *, *)      = null
     * StringUtils.leftPad("", 3, "z")      = "zzz"
     * StringUtils.leftPad("bat", 3, "yz")  = "bat"
     * StringUtils.leftPad("bat", 5, "yz")  = "yzbat"
     * StringUtils.leftPad("bat", 8, "yz")  = "yzyzybat"
     * StringUtils.leftPad("bat", 1, "yz")  = "bat"
     * StringUtils.leftPad("bat", -1, "yz") = "bat"
     * StringUtils.leftPad("bat", 5, null)  = "  bat"
     * StringUtils.leftPad("bat", 5, "")    = "  bat"
     * 
* * @param str the String to pad out, may be null * @param size the size to pad to * @param padStr the String to pad with, null or empty treated as single space * @return left padded String or original String if no padding is necessary, * null if null String input */ public static String leftPad(String str, int size, String padStr) { if (str == null) { return null; } if (isEmpty(padStr)) { padStr = " "; } int padLen = padStr.length(); int strLen = str.length(); int pads = size - strLen; if (pads <= 0) { return str; // returns original String when possible } if (padLen == 1 && pads <= PAD_LIMIT) { return leftPad(str, size, padStr.charAt(0)); } if (pads == padLen) { return padStr.concat(str); } else if (pads < padLen) { return padStr.substring(0, pads).concat(str); } else { char[] padding = new char[pads]; char[] padChars = padStr.toCharArray(); for (int i = 0; i < pads; i++) { padding[i] = padChars[i % padLen]; } return new String(padding).concat(str); } } /** * Gets a String's length or 0 if the String is null. * * @param str * a String or null * @return String length or 0 if the String is null. * @since 2.4 */ public static int length(String str) { return str == null ? 0 : str.length(); } // Centering //----------------------------------------------------------------------- /** *

Centers a String in a larger String of size size * using the space character (' ').

* *

If the size is less than the String length, the String is returned. * A null String returns null. * A negative size is treated as zero.

* *

Equivalent to center(str, size, " ").

* *
     * StringUtils.center(null, *)   = null
     * StringUtils.center("", 4)     = "    "
     * StringUtils.center("ab", -1)  = "ab"
     * StringUtils.center("ab", 4)   = " ab "
     * StringUtils.center("abcd", 2) = "abcd"
     * StringUtils.center("a", 4)    = " a  "
     * 
* * @param str the String to center, may be null * @param size the int size of new String, negative treated as zero * @return centered String, null if null String input */ public static String center(String str, int size) { return center(str, size, ' '); } /** *

Centers a String in a larger String of size size. * Uses a supplied character as the value to pad the String with.

* *

If the size is less than the String length, the String is returned. * A null String returns null. * A negative size is treated as zero.

* *
     * StringUtils.center(null, *, *)     = null
     * StringUtils.center("", 4, ' ')     = "    "
     * StringUtils.center("ab", -1, ' ')  = "ab"
     * StringUtils.center("ab", 4, ' ')   = " ab"
     * StringUtils.center("abcd", 2, ' ') = "abcd"
     * StringUtils.center("a", 4, ' ')    = " a  "
     * StringUtils.center("a", 4, 'y')    = "yayy"
     * 
* * @param str the String to center, may be null * @param size the int size of new String, negative treated as zero * @param padChar the character to pad the new String with * @return centered String, null if null String input * @since 2.0 */ public static String center(String str, int size, char padChar) { if (str == null || size <= 0) { return str; } int strLen = str.length(); int pads = size - strLen; if (pads <= 0) { return str; } str = leftPad(str, strLen + pads / 2, padChar); str = rightPad(str, size, padChar); return str; } /** *

Centers a String in a larger String of size size. * Uses a supplied String as the value to pad the String with.

* *

If the size is less than the String length, the String is returned. * A null String returns null. * A negative size is treated as zero.

* *
     * StringUtils.center(null, *, *)     = null
     * StringUtils.center("", 4, " ")     = "    "
     * StringUtils.center("ab", -1, " ")  = "ab"
     * StringUtils.center("ab", 4, " ")   = " ab"
     * StringUtils.center("abcd", 2, " ") = "abcd"
     * StringUtils.center("a", 4, " ")    = " a  "
     * StringUtils.center("a", 4, "yz")   = "yayz"
     * StringUtils.center("abc", 7, null) = "  abc  "
     * StringUtils.center("abc", 7, "")   = "  abc  "
     * 
* * @param str the String to center, may be null * @param size the int size of new String, negative treated as zero * @param padStr the String to pad the new String with, must not be null or empty * @return centered String, null if null String input * @throws IllegalArgumentException if padStr is null or empty */ public static String center(String str, int size, String padStr) { if (str == null || size <= 0) { return str; } if (isEmpty(padStr)) { padStr = " "; } int strLen = str.length(); int pads = size - strLen; if (pads <= 0) { return str; } str = leftPad(str, strLen + pads / 2, padStr); str = rightPad(str, size, padStr); return str; } // Case conversion //----------------------------------------------------------------------- /** *

Converts a String to upper case as per {@link String#toUpperCase()}.

* *

A null input String returns null.

* *
     * StringUtils.upperCase(null)  = null
     * StringUtils.upperCase("")    = ""
     * StringUtils.upperCase("aBc") = "ABC"
     * 
* *

Note: As described in the documentation for {@link String#toUpperCase()}, * the result of this method is affected by the current locale. * For platform-independent case transformations, the method {@link #lowerCase(String, Locale)} * should be used with a specific locale (e.g. {@link Locale#ENGLISH}).

* * @param str the String to upper case, may be null * @return the upper cased String, null if null String input */ public static String upperCase(String str) { if (str == null) { return null; } return str.toUpperCase(); } /** *

Converts a String to upper case as per {@link String#toUpperCase(Locale)}.

* *

A null input String returns null.

* *
     * StringUtils.upperCase(null, Locale.ENGLISH)  = null
     * StringUtils.upperCase("", Locale.ENGLISH)    = ""
     * StringUtils.upperCase("aBc", Locale.ENGLISH) = "ABC"
     * 
* * @param str the String to upper case, may be null * @param locale the locale that defines the case transformation rules, must not be null * @return the upper cased String, null if null String input * @since 2.5 */ public static String upperCase(String str, Locale locale) { if (str == null) { return null; } return str.toUpperCase(locale); } /** *

Converts a String to lower case as per {@link String#toLowerCase()}.

* *

A null input String returns null.

* *
     * StringUtils.lowerCase(null)  = null
     * StringUtils.lowerCase("")    = ""
     * StringUtils.lowerCase("aBc") = "abc"
     * 
* *

Note: As described in the documentation for {@link String#toLowerCase()}, * the result of this method is affected by the current locale. * For platform-independent case transformations, the method {@link #lowerCase(String, Locale)} * should be used with a specific locale (e.g. {@link Locale#ENGLISH}).

* * @param str the String to lower case, may be null * @return the lower cased String, null if null String input */ public static String lowerCase(String str) { if (str == null) { return null; } return str.toLowerCase(); } /** *

Converts a String to lower case as per {@link String#toLowerCase(Locale)}.

* *

A null input String returns null.

* *
     * StringUtils.lowerCase(null, Locale.ENGLISH)  = null
     * StringUtils.lowerCase("", Locale.ENGLISH)    = ""
     * StringUtils.lowerCase("aBc", Locale.ENGLISH) = "abc"
     * 
* * @param str the String to lower case, may be null * @param locale the locale that defines the case transformation rules, must not be null * @return the lower cased String, null if null String input * @since 2.5 */ public static String lowerCase(String str, Locale locale) { if (str == null) { return null; } return str.toLowerCase(locale); } /** *

Capitalizes a String changing the first letter to title case as * per {@link Character#toTitleCase(char)}. No other letters are changed.

* *

For a word based algorithm, see {@link WordUtils#capitalize(String)}. * A null input String returns null.

* *
     * StringUtils.capitalize(null)  = null
     * StringUtils.capitalize("")    = ""
     * StringUtils.capitalize("cat") = "Cat"
     * StringUtils.capitalize("cAt") = "CAt"
     * 
* * @param str the String to capitalize, may be null * @return the capitalized String, null if null String input * @see WordUtils#capitalize(String) * @see #uncapitalize(String) * @since 2.0 */ public static String capitalize(String str) { int strLen; if (str == null || (strLen = str.length()) == 0) { return str; } return new StrBuilder(strLen) .append(Character.toTitleCase(str.charAt(0))) .append(str.substring(1)) .toString(); } /** *

Capitalizes a String changing the first letter to title case as * per {@link Character#toTitleCase(char)}. No other letters are changed.

* * @param str the String to capitalize, may be null * @return the capitalized String, null if null String input * @deprecated Use the standardly named {@link #capitalize(String)}. * Method will be removed in Commons Lang 3.0. */ public static String capitalise(String str) { return capitalize(str); } /** *

Uncapitalizes a String changing the first letter to title case as * per {@link Character#toLowerCase(char)}. No other letters are changed.

* *

For a word based algorithm, see {@link WordUtils#uncapitalize(String)}. * A null input String returns null.

* *
     * StringUtils.uncapitalize(null)  = null
     * StringUtils.uncapitalize("")    = ""
     * StringUtils.uncapitalize("Cat") = "cat"
     * StringUtils.uncapitalize("CAT") = "cAT"
     * 
* * @param str the String to uncapitalize, may be null * @return the uncapitalized String, null if null String input * @see WordUtils#uncapitalize(String) * @see #capitalize(String) * @since 2.0 */ public static String uncapitalize(String str) { int strLen; if (str == null || (strLen = str.length()) == 0) { return str; } return new StrBuilder(strLen) .append(Character.toLowerCase(str.charAt(0))) .append(str.substring(1)) .toString(); } /** *

Uncapitalizes a String changing the first letter to title case as * per {@link Character#toLowerCase(char)}. No other letters are changed.

* * @param str the String to uncapitalize, may be null * @return the uncapitalized String, null if null String input * @deprecated Use the standardly named {@link #uncapitalize(String)}. * Method will be removed in Commons Lang 3.0. */ public static String uncapitalise(String str) { return uncapitalize(str); } /** *

Swaps the case of a String changing upper and title case to * lower case, and lower case to upper case.

* *
    *
  • Upper case character converts to Lower case
  • *
  • Title case character converts to Lower case
  • *
  • Lower case character converts to Upper case
  • *
* *

For a word based algorithm, see {@link WordUtils#swapCase(String)}. * A null input String returns null.

* *
     * StringUtils.swapCase(null)                 = null
     * StringUtils.swapCase("")                   = ""
     * StringUtils.swapCase("The dog has a BONE") = "tHE DOG HAS A bone"
     * 
* *

NOTE: This method changed in Lang version 2.0. * It no longer performs a word based algorithm. * If you only use ASCII, you will notice no change. * That functionality is available in WordUtils.

* * @param str the String to swap case, may be null * @return the changed String, null if null String input */ public static String swapCase(String str) { int strLen; if (str == null || (strLen = str.length()) == 0) { return str; } StrBuilder buffer = new StrBuilder(strLen); char ch = 0; for (int i = 0; i < strLen; i++) { ch = str.charAt(i); if (Character.isUpperCase(ch)) { ch = Character.toLowerCase(ch); } else if (Character.isTitleCase(ch)) { ch = Character.toLowerCase(ch); } else if (Character.isLowerCase(ch)) { ch = Character.toUpperCase(ch); } buffer.append(ch); } return buffer.toString(); } /** *

Capitalizes all the whitespace separated words in a String. * Only the first letter of each word is changed.

* *

Whitespace is defined by {@link Character#isWhitespace(char)}. * A null input String returns null.

* * @param str the String to capitalize, may be null * @return capitalized String, null if null String input * @deprecated Use the relocated {@link WordUtils#capitalize(String)}. * Method will be removed in Commons Lang 3.0. */ public static String capitaliseAllWords(String str) { return WordUtils.capitalize(str); } // Count matches //----------------------------------------------------------------------- /** *

Counts how many times the substring appears in the larger String.

* *

A null or empty ("") String input returns 0.

* *
     * StringUtils.countMatches(null, *)       = 0
     * StringUtils.countMatches("", *)         = 0
     * StringUtils.countMatches("abba", null)  = 0
     * StringUtils.countMatches("abba", "")    = 0
     * StringUtils.countMatches("abba", "a")   = 2
     * StringUtils.countMatches("abba", "ab")  = 1
     * StringUtils.countMatches("abba", "xxx") = 0
     * 
* * @param str the String to check, may be null * @param sub the substring to count, may be null * @return the number of occurrences, 0 if either String is null */ public static int countMatches(String str, String sub) { if (isEmpty(str) || isEmpty(sub)) { return 0; } int count = 0; int idx = 0; while ((idx = str.indexOf(sub, idx)) != INDEX_NOT_FOUND) { count++; idx += sub.length(); } return count; } // Character Tests //----------------------------------------------------------------------- /** *

Checks if the String contains only unicode letters.

* *

null will return false. * An empty String (length()=0) will return true.

* *
     * StringUtils.isAlpha(null)   = false
     * StringUtils.isAlpha("")     = true
     * StringUtils.isAlpha("  ")   = false
     * StringUtils.isAlpha("abc")  = true
     * StringUtils.isAlpha("ab2c") = false
     * StringUtils.isAlpha("ab-c") = false
     * 
* * @param str the String to check, may be null * @return true if only contains letters, and is non-null */ public static boolean isAlpha(String str) { if (str == null) { return false; } int sz = str.length(); for (int i = 0; i < sz; i++) { if (Character.isLetter(str.charAt(i)) == false) { return false; } } return true; } /** *

Checks if the String contains only unicode letters and * space (' ').

* *

null will return false * An empty String (length()=0) will return true.

* *
     * StringUtils.isAlphaSpace(null)   = false
     * StringUtils.isAlphaSpace("")     = true
     * StringUtils.isAlphaSpace("  ")   = true
     * StringUtils.isAlphaSpace("abc")  = true
     * StringUtils.isAlphaSpace("ab c") = true
     * StringUtils.isAlphaSpace("ab2c") = false
     * StringUtils.isAlphaSpace("ab-c") = false
     * 
* * @param str the String to check, may be null * @return true if only contains letters and space, * and is non-null */ public static boolean isAlphaSpace(String str) { if (str == null) { return false; } int sz = str.length(); for (int i = 0; i < sz; i++) { if ((Character.isLetter(str.charAt(i)) == false) && (str.charAt(i) != ' ')) { return false; } } return true; } /** *

Checks if the String contains only unicode letters or digits.

* *

null will return false. * An empty String (length()=0) will return true.

* *
     * StringUtils.isAlphanumeric(null)   = false
     * StringUtils.isAlphanumeric("")     = true
     * StringUtils.isAlphanumeric("  ")   = false
     * StringUtils.isAlphanumeric("abc")  = true
     * StringUtils.isAlphanumeric("ab c") = false
     * StringUtils.isAlphanumeric("ab2c") = true
     * StringUtils.isAlphanumeric("ab-c") = false
     * 
* * @param str the String to check, may be null * @return true if only contains letters or digits, * and is non-null */ public static boolean isAlphanumeric(String str) { if (str == null) { return false; } int sz = str.length(); for (int i = 0; i < sz; i++) { if (Character.isLetterOrDigit(str.charAt(i)) == false) { return false; } } return true; } /** *

Checks if the String contains only unicode letters, digits * or space (' ').

* *

null will return false. * An empty String (length()=0) will return true.

* *
     * StringUtils.isAlphanumeric(null)   = false
     * StringUtils.isAlphanumeric("")     = true
     * StringUtils.isAlphanumeric("  ")   = true
     * StringUtils.isAlphanumeric("abc")  = true
     * StringUtils.isAlphanumeric("ab c") = true
     * StringUtils.isAlphanumeric("ab2c") = true
     * StringUtils.isAlphanumeric("ab-c") = false
     * 
* * @param str the String to check, may be null * @return true if only contains letters, digits or space, * and is non-null */ public static boolean isAlphanumericSpace(String str) { if (str == null) { return false; } int sz = str.length(); for (int i = 0; i < sz; i++) { if ((Character.isLetterOrDigit(str.charAt(i)) == false) && (str.charAt(i) != ' ')) { return false; } } return true; } /** *

Checks if the string contains only ASCII printable characters.

* *

null will return false. * An empty String (length()=0) will return true.

* *
     * StringUtils.isAsciiPrintable(null)     = false
     * StringUtils.isAsciiPrintable("")       = true
     * StringUtils.isAsciiPrintable(" ")      = true
     * StringUtils.isAsciiPrintable("Ceki")   = true
     * StringUtils.isAsciiPrintable("ab2c")   = true
     * StringUtils.isAsciiPrintable("!ab-c~") = true
     * StringUtils.isAsciiPrintable("\u0020") = true
     * StringUtils.isAsciiPrintable("\u0021") = true
     * StringUtils.isAsciiPrintable("\u007e") = true
     * StringUtils.isAsciiPrintable("\u007f") = false
     * StringUtils.isAsciiPrintable("Ceki G\u00fclc\u00fc") = false
     * 
* * @param str the string to check, may be null * @return true if every character is in the range * 32 thru 126 * @since 2.1 */ public static boolean isAsciiPrintable(String str) { if (str == null) { return false; } int sz = str.length(); for (int i = 0; i < sz; i++) { if (CharUtils.isAsciiPrintable(str.charAt(i)) == false) { return false; } } return true; } /** *

Checks if the String contains only unicode digits. * A decimal point is not a unicode digit and returns false.

* *

null will return false. * An empty String (length()=0) will return true.

* *
     * StringUtils.isNumeric(null)   = false
     * StringUtils.isNumeric("")     = true
     * StringUtils.isNumeric("  ")   = false
     * StringUtils.isNumeric("123")  = true
     * StringUtils.isNumeric("12 3") = false
     * StringUtils.isNumeric("ab2c") = false
     * StringUtils.isNumeric("12-3") = false
     * StringUtils.isNumeric("12.3") = false
     * 
* * @param str the String to check, may be null * @return true if only contains digits, and is non-null */ public static boolean isNumeric(String str) { if (str == null) { return false; } int sz = str.length(); for (int i = 0; i < sz; i++) { if (Character.isDigit(str.charAt(i)) == false) { return false; } } return true; } /** *

Checks if the String contains only unicode digits or space * (' '). * A decimal point is not a unicode digit and returns false.

* *

null will return false. * An empty String (length()=0) will return true.

* *
     * StringUtils.isNumeric(null)   = false
     * StringUtils.isNumeric("")     = true
     * StringUtils.isNumeric("  ")   = true
     * StringUtils.isNumeric("123")  = true
     * StringUtils.isNumeric("12 3") = true
     * StringUtils.isNumeric("ab2c") = false
     * StringUtils.isNumeric("12-3") = false
     * StringUtils.isNumeric("12.3") = false
     * 
* * @param str the String to check, may be null * @return true if only contains digits or space, * and is non-null */ public static boolean isNumericSpace(String str) { if (str == null) { return false; } int sz = str.length(); for (int i = 0; i < sz; i++) { if ((Character.isDigit(str.charAt(i)) == false) && (str.charAt(i) != ' ')) { return false; } } return true; } /** *

Checks if the String contains only whitespace.

* *

null will return false. * An empty String (length()=0) will return true.

* *
     * StringUtils.isWhitespace(null)   = false
     * StringUtils.isWhitespace("")     = true
     * StringUtils.isWhitespace("  ")   = true
     * StringUtils.isWhitespace("abc")  = false
     * StringUtils.isWhitespace("ab2c") = false
     * StringUtils.isWhitespace("ab-c") = false
     * 
* * @param str the String to check, may be null * @return true if only contains whitespace, and is non-null * @since 2.0 */ public static boolean isWhitespace(String str) { if (str == null) { return false; } int sz = str.length(); for (int i = 0; i < sz; i++) { if ((Character.isWhitespace(str.charAt(i)) == false)) { return false; } } return true; } /** *

Checks if the String contains only lowercase characters.

* *

null will return false. * An empty String (length()=0) will return false.

* *
     * StringUtils.isAllLowerCase(null)   = false
     * StringUtils.isAllLowerCase("")     = false
     * StringUtils.isAllLowerCase("  ")   = false
     * StringUtils.isAllLowerCase("abc")  = true
     * StringUtils.isAllLowerCase("abC") = false
     * 
* * @param str the String to check, may be null * @return true if only contains lowercase characters, and is non-null * @since 2.5 */ public static boolean isAllLowerCase(String str) { if (str == null || isEmpty(str)) { return false; } int sz = str.length(); for (int i = 0; i < sz; i++) { if (Character.isLowerCase(str.charAt(i)) == false) { return false; } } return true; } /** *

Checks if the String contains only uppercase characters.

* *

null will return false. * An empty String (length()=0) will return false.

* *
     * StringUtils.isAllUpperCase(null)   = false
     * StringUtils.isAllUpperCase("")     = false
     * StringUtils.isAllUpperCase("  ")   = false
     * StringUtils.isAllUpperCase("ABC")  = true
     * StringUtils.isAllUpperCase("aBC") = false
     * 
* * @param str the String to check, may be null * @return true if only contains uppercase characters, and is non-null * @since 2.5 */ public static boolean isAllUpperCase(String str) { if (str == null || isEmpty(str)) { return false; } int sz = str.length(); for (int i = 0; i < sz; i++) { if (Character.isUpperCase(str.charAt(i)) == false) { return false; } } return true; } // Defaults //----------------------------------------------------------------------- /** *

Returns either the passed in String, * or if the String is null, an empty String ("").

* *
     * StringUtils.defaultString(null)  = ""
     * StringUtils.defaultString("")    = ""
     * StringUtils.defaultString("bat") = "bat"
     * 
* * @see ObjectUtils#toString(Object) * @see String#valueOf(Object) * @param str the String to check, may be null * @return the passed in String, or the empty String if it * was null */ public static String defaultString(String str) { return str == null ? EMPTY : str; } /** *

Returns either the passed in String, or if the String is * null, the value of defaultStr.

* *
     * StringUtils.defaultString(null, "NULL")  = "NULL"
     * StringUtils.defaultString("", "NULL")    = ""
     * StringUtils.defaultString("bat", "NULL") = "bat"
     * 
* * @see ObjectUtils#toString(Object,String) * @see String#valueOf(Object) * @param str the String to check, may be null * @param defaultStr the default String to return * if the input is null, may be null * @return the passed in String, or the default if it was null */ public static String defaultString(String str, String defaultStr) { return str == null ? defaultStr : str; } /** *

Returns either the passed in String, or if the String is * whitespace, empty ("") or null, the value of defaultStr.

* *
     * StringUtils.defaultIfBlank(null, "NULL")  = "NULL"
     * StringUtils.defaultIfBlank("", "NULL")    = "NULL"
     * StringUtils.defaultIfBlank(" ", "NULL")   = "NULL"
     * StringUtils.defaultIfBlank("bat", "NULL") = "bat"
     * StringUtils.defaultIfBlank("", null)      = null
     * 
* @param str the String to check, may be null * @param defaultStr the default String to return * if the input is whitespace, empty ("") or null, may be null * @return the passed in String, or the default * @see StringUtils#defaultString(String, String) * @since 2.6 */ public static String defaultIfBlank(String str, String defaultStr) { return StringUtils.isBlank(str) ? defaultStr : str; } /** *

Returns either the passed in String, or if the String is * empty or null, the value of defaultStr.

* *
     * StringUtils.defaultIfEmpty(null, "NULL")  = "NULL"
     * StringUtils.defaultIfEmpty("", "NULL")    = "NULL"
     * StringUtils.defaultIfEmpty("bat", "NULL") = "bat"
     * StringUtils.defaultIfEmpty("", null)      = null
     * 
* * @param str the String to check, may be null * @param defaultStr the default String to return * if the input is empty ("") or null, may be null * @return the passed in String, or the default * @see StringUtils#defaultString(String, String) */ public static String defaultIfEmpty(String str, String defaultStr) { return StringUtils.isEmpty(str) ? defaultStr : str; } // Reversing //----------------------------------------------------------------------- /** *

Reverses a String as per {@link StrBuilder#reverse()}.

* *

A null String returns null.

* *
     * StringUtils.reverse(null)  = null
     * StringUtils.reverse("")    = ""
     * StringUtils.reverse("bat") = "tab"
     * 
* * @param str the String to reverse, may be null * @return the reversed String, null if null String input */ public static String reverse(String str) { if (str == null) { return null; } return new StrBuilder(str).reverse().toString(); } /** *

Reverses a String that is delimited by a specific character.

* *

The Strings between the delimiters are not reversed. * Thus java.lang.String becomes String.lang.java (if the delimiter * is '.').

* *
     * StringUtils.reverseDelimited(null, *)      = null
     * StringUtils.reverseDelimited("", *)        = ""
     * StringUtils.reverseDelimited("a.b.c", 'x') = "a.b.c"
     * StringUtils.reverseDelimited("a.b.c", ".") = "c.b.a"
     * 
* * @param str the String to reverse, may be null * @param separatorChar the separator character to use * @return the reversed String, null if null String input * @since 2.0 */ public static String reverseDelimited(String str, char separatorChar) { if (str == null) { return null; } // could implement manually, but simple way is to reuse other, // probably slower, methods. String[] strs = split(str, separatorChar); ArrayUtils.reverse(strs); return join(strs, separatorChar); } /** *

Reverses a String that is delimited by a specific character.

* *

The Strings between the delimiters are not reversed. * Thus java.lang.String becomes String.lang.java (if the delimiter * is ".").

* *
     * StringUtils.reverseDelimitedString(null, *)       = null
     * StringUtils.reverseDelimitedString("",*)          = ""
     * StringUtils.reverseDelimitedString("a.b.c", null) = "a.b.c"
     * StringUtils.reverseDelimitedString("a.b.c", ".")  = "c.b.a"
     * 
* * @param str the String to reverse, may be null * @param separatorChars the separator characters to use, null treated as whitespace * @return the reversed String, null if null String input * @deprecated Use {@link #reverseDelimited(String, char)} instead. * This method is broken as the join doesn't know which char to use. * Method will be removed in Commons Lang 3.0. * */ public static String reverseDelimitedString(String str, String separatorChars) { if (str == null) { return null; } // could implement manually, but simple way is to reuse other, // probably slower, methods. String[] strs = split(str, separatorChars); ArrayUtils.reverse(strs); if (separatorChars == null) { return join(strs, ' '); } return join(strs, separatorChars); } // Abbreviating //----------------------------------------------------------------------- /** *

Abbreviates a String using ellipses. This will turn * "Now is the time for all good men" into "Now is the time for..."

* *

Specifically: *

    *
  • If str is less than maxWidth characters * long, return it.
  • *
  • Else abbreviate it to (substring(str, 0, max-3) + "...").
  • *
  • If maxWidth is less than 4, throw an * IllegalArgumentException.
  • *
  • In no case will it return a String of length greater than * maxWidth.
  • *
*

* *
     * StringUtils.abbreviate(null, *)      = null
     * StringUtils.abbreviate("", 4)        = ""
     * StringUtils.abbreviate("abcdefg", 6) = "abc..."
     * StringUtils.abbreviate("abcdefg", 7) = "abcdefg"
     * StringUtils.abbreviate("abcdefg", 8) = "abcdefg"
     * StringUtils.abbreviate("abcdefg", 4) = "a..."
     * StringUtils.abbreviate("abcdefg", 3) = IllegalArgumentException
     * 
* * @param str the String to check, may be null * @param maxWidth maximum length of result String, must be at least 4 * @return abbreviated String, null if null String input * @throws IllegalArgumentException if the width is too small * @since 2.0 */ public static String abbreviate(String str, int maxWidth) { return abbreviate(str, 0, maxWidth); } /** *

Abbreviates a String using ellipses. This will turn * "Now is the time for all good men" into "...is the time for..."

* *

Works like abbreviate(String, int), but allows you to specify * a "left edge" offset. Note that this left edge is not necessarily going to * be the leftmost character in the result, or the first character following the * ellipses, but it will appear somewhere in the result. * *

In no case will it return a String of length greater than * maxWidth.

* *
     * StringUtils.abbreviate(null, *, *)                = null
     * StringUtils.abbreviate("", 0, 4)                  = ""
     * StringUtils.abbreviate("abcdefghijklmno", -1, 10) = "abcdefg..."
     * StringUtils.abbreviate("abcdefghijklmno", 0, 10)  = "abcdefg..."
     * StringUtils.abbreviate("abcdefghijklmno", 1, 10)  = "abcdefg..."
     * StringUtils.abbreviate("abcdefghijklmno", 4, 10)  = "abcdefg..."
     * StringUtils.abbreviate("abcdefghijklmno", 5, 10)  = "...fghi..."
     * StringUtils.abbreviate("abcdefghijklmno", 6, 10)  = "...ghij..."
     * StringUtils.abbreviate("abcdefghijklmno", 8, 10)  = "...ijklmno"
     * StringUtils.abbreviate("abcdefghijklmno", 10, 10) = "...ijklmno"
     * StringUtils.abbreviate("abcdefghijklmno", 12, 10) = "...ijklmno"
     * StringUtils.abbreviate("abcdefghij", 0, 3)        = IllegalArgumentException
     * StringUtils.abbreviate("abcdefghij", 5, 6)        = IllegalArgumentException
     * 
* * @param str the String to check, may be null * @param offset left edge of source String * @param maxWidth maximum length of result String, must be at least 4 * @return abbreviated String, null if null String input * @throws IllegalArgumentException if the width is too small * @since 2.0 */ public static String abbreviate(String str, int offset, int maxWidth) { if (str == null) { return null; } if (maxWidth < 4) { throw new IllegalArgumentException("Minimum abbreviation width is 4"); } if (str.length() <= maxWidth) { return str; } if (offset > str.length()) { offset = str.length(); } if ((str.length() - offset) < (maxWidth - 3)) { offset = str.length() - (maxWidth - 3); } if (offset <= 4) { return str.substring(0, maxWidth - 3) + "..."; } if (maxWidth < 7) { throw new IllegalArgumentException("Minimum abbreviation width with offset is 7"); } if ((offset + (maxWidth - 3)) < str.length()) { return "..." + abbreviate(str.substring(offset), maxWidth - 3); } return "..." + str.substring(str.length() - (maxWidth - 3)); } /** *

Abbreviates a String to the length passed, replacing the middle characters with the supplied * replacement String.

* *

This abbreviation only occurs if the following criteria is met: *

    *
  • Neither the String for abbreviation nor the replacement String are null or empty
  • *
  • The length to truncate to is less than the length of the supplied String
  • *
  • The length to truncate to is greater than 0
  • *
  • The abbreviated String will have enough room for the length supplied replacement String * and the first and last characters of the supplied String for abbreviation
  • *
* Otherwise, the returned String will be the same as the supplied String for abbreviation. *

* *
     * StringUtils.abbreviateMiddle(null, null, 0)      = null
     * StringUtils.abbreviateMiddle("abc", null, 0)      = "abc"
     * StringUtils.abbreviateMiddle("abc", ".", 0)      = "abc"
     * StringUtils.abbreviateMiddle("abc", ".", 3)      = "abc"
     * StringUtils.abbreviateMiddle("abcdef", ".", 4)     = "ab.f"
     * 
* * @param str the String to abbreviate, may be null * @param middle the String to replace the middle characters with, may be null * @param length the length to abbreviate str to. * @return the abbreviated String if the above criteria is met, or the original String supplied for abbreviation. * @since 2.5 */ public static String abbreviateMiddle(String str, String middle, int length) { if (isEmpty(str) || isEmpty(middle)) { return str; } if (length >= str.length() || length < (middle.length()+2)) { return str; } int targetSting = length-middle.length(); int startOffset = targetSting/2+targetSting%2; int endOffset = str.length()-targetSting/2; StrBuilder builder = new StrBuilder(length); builder.append(str.substring(0,startOffset)); builder.append(middle); builder.append(str.substring(endOffset)); return builder.toString(); } // Difference //----------------------------------------------------------------------- /** *

Compares two Strings, and returns the portion where they differ. * (More precisely, return the remainder of the second String, * starting from where it's different from the first.)

* *

For example, * difference("i am a machine", "i am a robot") -> "robot".

* *
     * StringUtils.difference(null, null) = null
     * StringUtils.difference("", "") = ""
     * StringUtils.difference("", "abc") = "abc"
     * StringUtils.difference("abc", "") = ""
     * StringUtils.difference("abc", "abc") = ""
     * StringUtils.difference("ab", "abxyz") = "xyz"
     * StringUtils.difference("abcde", "abxyz") = "xyz"
     * StringUtils.difference("abcde", "xyz") = "xyz"
     * 
* * @param str1 the first String, may be null * @param str2 the second String, may be null * @return the portion of str2 where it differs from str1; returns the * empty String if they are equal * @since 2.0 */ public static String difference(String str1, String str2) { if (str1 == null) { return str2; } if (str2 == null) { return str1; } int at = indexOfDifference(str1, str2); if (at == INDEX_NOT_FOUND) { return EMPTY; } return str2.substring(at); } /** *

Compares two Strings, and returns the index at which the * Strings begin to differ.

* *

For example, * indexOfDifference("i am a machine", "i am a robot") -> 7

* *
     * StringUtils.indexOfDifference(null, null) = -1
     * StringUtils.indexOfDifference("", "") = -1
     * StringUtils.indexOfDifference("", "abc") = 0
     * StringUtils.indexOfDifference("abc", "") = 0
     * StringUtils.indexOfDifference("abc", "abc") = -1
     * StringUtils.indexOfDifference("ab", "abxyz") = 2
     * StringUtils.indexOfDifference("abcde", "abxyz") = 2
     * StringUtils.indexOfDifference("abcde", "xyz") = 0
     * 
* * @param str1 the first String, may be null * @param str2 the second String, may be null * @return the index where str2 and str1 begin to differ; -1 if they are equal * @since 2.0 */ public static int indexOfDifference(String str1, String str2) { if (str1 == str2) { return INDEX_NOT_FOUND; } if (str1 == null || str2 == null) { return 0; } int i; for (i = 0; i < str1.length() && i < str2.length(); ++i) { if (str1.charAt(i) != str2.charAt(i)) { break; } } if (i < str2.length() || i < str1.length()) { return i; } return INDEX_NOT_FOUND; } /** *

Compares all Strings in an array and returns the index at which the * Strings begin to differ.

* *

For example, * indexOfDifference(new String[] {"i am a machine", "i am a robot"}) -> 7

* *
     * StringUtils.indexOfDifference(null) = -1
     * StringUtils.indexOfDifference(new String[] {}) = -1
     * StringUtils.indexOfDifference(new String[] {"abc"}) = -1
     * StringUtils.indexOfDifference(new String[] {null, null}) = -1
     * StringUtils.indexOfDifference(new String[] {"", ""}) = -1
     * StringUtils.indexOfDifference(new String[] {"", null}) = 0
     * StringUtils.indexOfDifference(new String[] {"abc", null, null}) = 0
     * StringUtils.indexOfDifference(new String[] {null, null, "abc"}) = 0
     * StringUtils.indexOfDifference(new String[] {"", "abc"}) = 0
     * StringUtils.indexOfDifference(new String[] {"abc", ""}) = 0
     * StringUtils.indexOfDifference(new String[] {"abc", "abc"}) = -1
     * StringUtils.indexOfDifference(new String[] {"abc", "a"}) = 1
     * StringUtils.indexOfDifference(new String[] {"ab", "abxyz"}) = 2
     * StringUtils.indexOfDifference(new String[] {"abcde", "abxyz"}) = 2
     * StringUtils.indexOfDifference(new String[] {"abcde", "xyz"}) = 0
     * StringUtils.indexOfDifference(new String[] {"xyz", "abcde"}) = 0
     * StringUtils.indexOfDifference(new String[] {"i am a machine", "i am a robot"}) = 7
     * 
* * @param strs array of strings, entries may be null * @return the index where the strings begin to differ; -1 if they are all equal * @since 2.4 */ public static int indexOfDifference(String[] strs) { if (strs == null || strs.length <= 1) { return INDEX_NOT_FOUND; } boolean anyStringNull = false; boolean allStringsNull = true; int arrayLen = strs.length; int shortestStrLen = Integer.MAX_VALUE; int longestStrLen = 0; // find the min and max string lengths; this avoids checking to make // sure we are not exceeding the length of the string each time through // the bottom loop. for (int i = 0; i < arrayLen; i++) { if (strs[i] == null) { anyStringNull = true; shortestStrLen = 0; } else { allStringsNull = false; shortestStrLen = Math.min(strs[i].length(), shortestStrLen); longestStrLen = Math.max(strs[i].length(), longestStrLen); } } // handle lists containing all nulls or all empty strings if (allStringsNull || (longestStrLen == 0 && !anyStringNull)) { return INDEX_NOT_FOUND; } // handle lists containing some nulls or some empty strings if (shortestStrLen == 0) { return 0; } // find the position with the first difference across all strings int firstDiff = -1; for (int stringPos = 0; stringPos < shortestStrLen; stringPos++) { char comparisonChar = strs[0].charAt(stringPos); for (int arrayPos = 1; arrayPos < arrayLen; arrayPos++) { if (strs[arrayPos].charAt(stringPos) != comparisonChar) { firstDiff = stringPos; break; } } if (firstDiff != -1) { break; } } if (firstDiff == -1 && shortestStrLen != longestStrLen) { // we compared all of the characters up to the length of the // shortest string and didn't find a match, but the string lengths // vary, so return the length of the shortest string. return shortestStrLen; } return firstDiff; } /** *

Compares all Strings in an array and returns the initial sequence of * characters that is common to all of them.

* *

For example, * getCommonPrefix(new String[] {"i am a machine", "i am a robot"}) -> "i am a "

* *
     * StringUtils.getCommonPrefix(null) = ""
     * StringUtils.getCommonPrefix(new String[] {}) = ""
     * StringUtils.getCommonPrefix(new String[] {"abc"}) = "abc"
     * StringUtils.getCommonPrefix(new String[] {null, null}) = ""
     * StringUtils.getCommonPrefix(new String[] {"", ""}) = ""
     * StringUtils.getCommonPrefix(new String[] {"", null}) = ""
     * StringUtils.getCommonPrefix(new String[] {"abc", null, null}) = ""
     * StringUtils.getCommonPrefix(new String[] {null, null, "abc"}) = ""
     * StringUtils.getCommonPrefix(new String[] {"", "abc"}) = ""
     * StringUtils.getCommonPrefix(new String[] {"abc", ""}) = ""
     * StringUtils.getCommonPrefix(new String[] {"abc", "abc"}) = "abc"
     * StringUtils.getCommonPrefix(new String[] {"abc", "a"}) = "a"
     * StringUtils.getCommonPrefix(new String[] {"ab", "abxyz"}) = "ab"
     * StringUtils.getCommonPrefix(new String[] {"abcde", "abxyz"}) = "ab"
     * StringUtils.getCommonPrefix(new String[] {"abcde", "xyz"}) = ""
     * StringUtils.getCommonPrefix(new String[] {"xyz", "abcde"}) = ""
     * StringUtils.getCommonPrefix(new String[] {"i am a machine", "i am a robot"}) = "i am a "
     * 
* * @param strs array of String objects, entries may be null * @return the initial sequence of characters that are common to all Strings * in the array; empty String if the array is null, the elements are all null * or if there is no common prefix. * @since 2.4 */ public static String getCommonPrefix(String[] strs) { if (strs == null || strs.length == 0) { return EMPTY; } int smallestIndexOfDiff = indexOfDifference(strs); if (smallestIndexOfDiff == INDEX_NOT_FOUND) { // all strings were identical if (strs[0] == null) { return EMPTY; } return strs[0]; } else if (smallestIndexOfDiff == 0) { // there were no common initial characters return EMPTY; } else { // we found a common initial character sequence return strs[0].substring(0, smallestIndexOfDiff); } } // Misc //----------------------------------------------------------------------- /** *

Find the Levenshtein distance between two Strings.

* *

This is the number of changes needed to change one String into * another, where each change is a single character modification (deletion, * insertion or substitution).

* *

The previous implementation of the Levenshtein distance algorithm * was from http://www.merriampark.com/ld.htm

* *

Chas Emerick has written an implementation in Java, which avoids an OutOfMemoryError * which can occur when my Java implementation is used with very large strings.
* This implementation of the Levenshtein distance algorithm * is from http://www.merriampark.com/ldjava.htm

* *
     * StringUtils.getLevenshteinDistance(null, *)             = IllegalArgumentException
     * StringUtils.getLevenshteinDistance(*, null)             = IllegalArgumentException
     * StringUtils.getLevenshteinDistance("","")               = 0
     * StringUtils.getLevenshteinDistance("","a")              = 1
     * StringUtils.getLevenshteinDistance("aaapppp", "")       = 7
     * StringUtils.getLevenshteinDistance("frog", "fog")       = 1
     * StringUtils.getLevenshteinDistance("fly", "ant")        = 3
     * StringUtils.getLevenshteinDistance("elephant", "hippo") = 7
     * StringUtils.getLevenshteinDistance("hippo", "elephant") = 7
     * StringUtils.getLevenshteinDistance("hippo", "zzzzzzzz") = 8
     * StringUtils.getLevenshteinDistance("hello", "hallo")    = 1
     * 
* * @param s the first String, must not be null * @param t the second String, must not be null * @return result distance * @throws IllegalArgumentException if either String input null */ public static int getLevenshteinDistance(String s, String t) { if (s == null || t == null) { throw new IllegalArgumentException("Strings must not be null"); } /* The difference between this impl. and the previous is that, rather than creating and retaining a matrix of size s.length()+1 by t.length()+1, we maintain two single-dimensional arrays of length s.length()+1. The first, d, is the 'current working' distance array that maintains the newest distance cost counts as we iterate through the characters of String s. Each time we increment the index of String t we are comparing, d is copied to p, the second int[]. Doing so allows us to retain the previous cost counts as required by the algorithm (taking the minimum of the cost count to the left, up one, and diagonally up and to the left of the current cost count being calculated). (Note that the arrays aren't really copied anymore, just switched...this is clearly much better than cloning an array or doing a System.arraycopy() each time through the outer loop.) Effectively, the difference between the two implementations is this one does not cause an out of memory condition when calculating the LD over two very large strings. */ int n = s.length(); // length of s int m = t.length(); // length of t if (n == 0) { return m; } else if (m == 0) { return n; } if (n > m) { // swap the input strings to consume less memory String tmp = s; s = t; t = tmp; n = m; m = t.length(); } int p[] = new int[n+1]; //'previous' cost array, horizontally int d[] = new int[n+1]; // cost array, horizontally int _d[]; //placeholder to assist in swapping p and d // indexes into strings s and t int i; // iterates through s int j; // iterates through t char t_j; // jth character of t int cost; // cost for (i = 0; i<=n; i++) { p[i] = i; } for (j = 1; j<=m; j++) { t_j = t.charAt(j-1); d[0] = j; for (i=1; i<=n; i++) { cost = s.charAt(i-1)==t_j ? 0 : 1; // minimum of cell to the left+1, to the top+1, diagonally left and up +cost d[i] = Math.min(Math.min(d[i-1]+1, p[i]+1), p[i-1]+cost); } // copy current distance counts to 'previous row' distance counts _d = p; p = d; d = _d; } // our last action in the above loop was to switch d and p, so p now // actually has the most recent cost counts return p[n]; } // startsWith //----------------------------------------------------------------------- /** *

Check if a String starts with a specified prefix.

* *

nulls are handled without exceptions. Two null * references are considered to be equal. The comparison is case sensitive.

* *
     * StringUtils.startsWith(null, null)      = true
     * StringUtils.startsWith(null, "abc")     = false
     * StringUtils.startsWith("abcdef", null)  = false
     * StringUtils.startsWith("abcdef", "abc") = true
     * StringUtils.startsWith("ABCDEF", "abc") = false
     * 
* * @see java.lang.String#startsWith(String) * @param str the String to check, may be null * @param prefix the prefix to find, may be null * @return true if the String starts with the prefix, case sensitive, or * both null * @since 2.4 */ public static boolean startsWith(String str, String prefix) { return startsWith(str, prefix, false); } /** *

Case insensitive check if a String starts with a specified prefix.

* *

nulls are handled without exceptions. Two null * references are considered to be equal. The comparison is case insensitive.

* *
     * StringUtils.startsWithIgnoreCase(null, null)      = true
     * StringUtils.startsWithIgnoreCase(null, "abc")     = false
     * StringUtils.startsWithIgnoreCase("abcdef", null)  = false
     * StringUtils.startsWithIgnoreCase("abcdef", "abc") = true
     * StringUtils.startsWithIgnoreCase("ABCDEF", "abc") = true
     * 
* * @see java.lang.String#startsWith(String) * @param str the String to check, may be null * @param prefix the prefix to find, may be null * @return true if the String starts with the prefix, case insensitive, or * both null * @since 2.4 */ public static boolean startsWithIgnoreCase(String str, String prefix) { return startsWith(str, prefix, true); } /** *

Check if a String starts with a specified prefix (optionally case insensitive).

* * @see java.lang.String#startsWith(String) * @param str the String to check, may be null * @param prefix the prefix to find, may be null * @param ignoreCase inidicates whether the compare should ignore case * (case insensitive) or not. * @return true if the String starts with the prefix or * both null */ private static boolean startsWith(String str, String prefix, boolean ignoreCase) { if (str == null || prefix == null) { return (str == null && prefix == null); } if (prefix.length() > str.length()) { return false; } return str.regionMatches(ignoreCase, 0, prefix, 0, prefix.length()); } /** *

Check if a String starts with any of an array of specified strings.

* *
     * StringUtils.startsWithAny(null, null)      = false
     * StringUtils.startsWithAny(null, new String[] {"abc"})  = false
     * StringUtils.startsWithAny("abcxyz", null)     = false
     * StringUtils.startsWithAny("abcxyz", new String[] {""}) = false
     * StringUtils.startsWithAny("abcxyz", new String[] {"abc"}) = true
     * StringUtils.startsWithAny("abcxyz", new String[] {null, "xyz", "abc"}) = true
     * 
* * @see #startsWith(String, String) * @param string the String to check, may be null * @param searchStrings the Strings to find, may be null or empty * @return true if the String starts with any of the the prefixes, case insensitive, or * both null * @since 2.5 */ public static boolean startsWithAny(String string, String[] searchStrings) { if (isEmpty(string) || ArrayUtils.isEmpty(searchStrings)) { return false; } for (int i = 0; i < searchStrings.length; i++) { String searchString = searchStrings[i]; if (StringUtils.startsWith(string, searchString)) { return true; } } return false; } // endsWith //----------------------------------------------------------------------- /** *

Check if a String ends with a specified suffix.

* *

nulls are handled without exceptions. Two null * references are considered to be equal. The comparison is case sensitive.

* *
     * StringUtils.endsWith(null, null)      = true
     * StringUtils.endsWith(null, "def")     = false
     * StringUtils.endsWith("abcdef", null)  = false
     * StringUtils.endsWith("abcdef", "def") = true
     * StringUtils.endsWith("ABCDEF", "def") = false
     * StringUtils.endsWith("ABCDEF", "cde") = false
     * 
* * @see java.lang.String#endsWith(String) * @param str the String to check, may be null * @param suffix the suffix to find, may be null * @return true if the String ends with the suffix, case sensitive, or * both null * @since 2.4 */ public static boolean endsWith(String str, String suffix) { return endsWith(str, suffix, false); } /** *

Case insensitive check if a String ends with a specified suffix.

* *

nulls are handled without exceptions. Two null * references are considered to be equal. The comparison is case insensitive.

* *
     * StringUtils.endsWithIgnoreCase(null, null)      = true
     * StringUtils.endsWithIgnoreCase(null, "def")     = false
     * StringUtils.endsWithIgnoreCase("abcdef", null)  = false
     * StringUtils.endsWithIgnoreCase("abcdef", "def") = true
     * StringUtils.endsWithIgnoreCase("ABCDEF", "def") = true
     * StringUtils.endsWithIgnoreCase("ABCDEF", "cde") = false
     * 
* * @see java.lang.String#endsWith(String) * @param str the String to check, may be null * @param suffix the suffix to find, may be null * @return true if the String ends with the suffix, case insensitive, or * both null * @since 2.4 */ public static boolean endsWithIgnoreCase(String str, String suffix) { return endsWith(str, suffix, true); } /** *

Check if a String ends with a specified suffix (optionally case insensitive).

* * @see java.lang.String#endsWith(String) * @param str the String to check, may be null * @param suffix the suffix to find, may be null * @param ignoreCase inidicates whether the compare should ignore case * (case insensitive) or not. * @return true if the String starts with the prefix or * both null */ private static boolean endsWith(String str, String suffix, boolean ignoreCase) { if (str == null || suffix == null) { return (str == null && suffix == null); } if (suffix.length() > str.length()) { return false; } int strOffset = str.length() - suffix.length(); return str.regionMatches(ignoreCase, strOffset, suffix, 0, suffix.length()); } /** *

* Similar to http://www.w3.org/TR/xpath/#function-normalize * -space *

*

* The function returns the argument string with whitespace normalized by using * {@link #trim(String)} to remove leading and trailing whitespace * and then replacing sequences of whitespace characters by a single space. *

* In XML Whitespace characters are the same as those allowed by the S production, which is S ::= (#x20 | #x9 | #xD | #xA)+ *

* See Java's {@link Character#isWhitespace(char)} for which characters are considered whitespace. *

* The difference is that Java's whitespace includes vertical tab and form feed, which this functional will also * normalize. Additonally {@link #trim(String)} removes control characters (char <= 32) from both * ends of this String. *

* * @see Character#isWhitespace(char) * @see #trim(String) * @see * http://www.w3.org/TR/xpath/#function-normalize-space * @param str the source String to normalize whitespaces from, may be null * @return the modified string with whitespace normalized, null if null String input * * @since 2.6 */ public static String normalizeSpace(String str) { str = strip(str); if(str == null || str.length() <= 2) { return str; } StrBuilder b = new StrBuilder(str.length()); for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); if (Character.isWhitespace(c)) { if (i > 0 && !Character.isWhitespace(str.charAt(i - 1))) { b.append(' '); } } else { b.append(c); } } return b.toString(); } /** *

Check if a String ends with any of an array of specified strings.

* *
     * StringUtils.endsWithAny(null, null)      = false
     * StringUtils.endsWithAny(null, new String[] {"abc"})  = false
     * StringUtils.endsWithAny("abcxyz", null)     = false
     * StringUtils.endsWithAny("abcxyz", new String[] {""}) = true
     * StringUtils.endsWithAny("abcxyz", new String[] {"xyz"}) = true
     * StringUtils.endsWithAny("abcxyz", new String[] {null, "xyz", "abc"}) = true
     * 
* * @param string the String to check, may be null * @param searchStrings the Strings to find, may be null or empty * @return true if the String ends with any of the the prefixes, case insensitive, or * both null * @since 2.6 */ public static boolean endsWithAny(String string, String[] searchStrings) { if (isEmpty(string) || ArrayUtils.isEmpty(searchStrings)) { return false; } for (int i = 0; i < searchStrings.length; i++) { String searchString = searchStrings[i]; if (StringUtils.endsWith(string, searchString)) { return true; } } return false; } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/SystemUtils.java100644 0 0 173574 11513702446 24163 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang; import java.io.File; /** *

* Helpers for java.lang.System. *

* *

* If a system property cannot be read due to security restrictions, * the corresponding field in this class will be set to null * and a message will be written to System.err. *

* *

* #ThreadSafe# *

* * @author Apache Software Foundation * @author Based on code from Avalon Excalibur * @author Based on code from Lucene * @author Steve Downey * @author Gary Gregory * @author Michael Becke * @author Tetsuya Kaneuchi * @author Rafal Krupinski * @author Jason Gritman * @since 1.0 * @version $Id: SystemUtils.java 1056988 2011-01-09 17:58:53Z niallp $ */ public class SystemUtils { private static final int JAVA_VERSION_TRIM_SIZE = 3; /** * The prefix String for all Windows OS. */ private static final String OS_NAME_WINDOWS_PREFIX = "Windows"; // System property constants // ----------------------------------------------------------------------- // These MUST be declared first. Other constants depend on this. /** * The System property key for the user home directory. */ private static final String USER_HOME_KEY = "user.home"; /** * The System property key for the user directory. */ private static final String USER_DIR_KEY = "user.dir"; /** * The System property key for the Java IO temporary directory. */ private static final String JAVA_IO_TMPDIR_KEY = "java.io.tmpdir"; /** * The System property key for the Java home directory. */ private static final String JAVA_HOME_KEY = "java.home"; /** *

* The awt.toolkit System Property. *

*

* Holds a class name, on Windows XP this is sun.awt.windows.WToolkit. *

*

* On platforms without a GUI, this value is null. *

* *

* Defaults to null if the runtime does not have * security access to read this property or the property does not exist. *

* *

* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will * be out of sync with that System property. *

* * @since 2.1 */ public static final String AWT_TOOLKIT = getSystemProperty("awt.toolkit"); /** *

* The file.encoding System Property. *

*

* File encoding, such as Cp1252. *

* *

* Defaults to null if the runtime does not have * security access to read this property or the property does not exist. *

* *

* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. *

* * @since 2.0 * @since Java 1.2 */ public static final String FILE_ENCODING = getSystemProperty("file.encoding"); /** *

* The file.separator System Property. File separator ("/" on UNIX). *

* *

* Defaults to null if the runtime does not have * security access to read this property or the property does not exist. *

* *

* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. *

* * @since Java 1.1 */ public static final String FILE_SEPARATOR = getSystemProperty("file.separator"); /** *

* The java.awt.fonts System Property. *

* *

* Defaults to null if the runtime does not have * security access to read this property or the property does not exist. *

* *

* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. *

* * @since 2.1 */ public static final String JAVA_AWT_FONTS = getSystemProperty("java.awt.fonts"); /** *

* The java.awt.graphicsenv System Property. *

* *

* Defaults to null if the runtime does not have * security access to read this property or the property does not exist. *

* *

* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. *

* * @since 2.1 */ public static final String JAVA_AWT_GRAPHICSENV = getSystemProperty("java.awt.graphicsenv"); /** *

* The java.awt.headless System Property. * The value of this property is the String "true" or "false". *

* *

* Defaults to null if the runtime does not have * security access to read this property or the property does not exist. *

* *

* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. *

* * @see #isJavaAwtHeadless() * @since 2.1 * @since Java 1.4 */ public static final String JAVA_AWT_HEADLESS = getSystemProperty("java.awt.headless"); /** *

* The java.awt.printerjob System Property. *

* *

* Defaults to null if the runtime does not have * security access to read this property or the property does not exist. *

* *

* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. *

* * @since 2.1 */ public static final String JAVA_AWT_PRINTERJOB = getSystemProperty("java.awt.printerjob"); /** *

* The java.class.path System Property. Java class path. *

* *

* Defaults to null if the runtime does not have * security access to read this property or the property does not exist. *

* *

* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. *

* * @since Java 1.1 */ public static final String JAVA_CLASS_PATH = getSystemProperty("java.class.path"); /** *

* The java.class.version System Property. Java class format version number. *

* *

* Defaults to null if the runtime does not have * security access to read this property or the property does not exist. *

* *

* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. *

* * @since Java 1.1 */ public static final String JAVA_CLASS_VERSION = getSystemProperty("java.class.version"); /** *

* The java.compiler System Property. Name of JIT compiler to use. * First in JDK version 1.2. Not used in Sun JDKs after 1.2. *

* *

* Defaults to null if the runtime does not have * security access to read this property or the property does not exist. *

* *

* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. *

* * @since Java 1.2. Not used in Sun versions after 1.2. */ public static final String JAVA_COMPILER = getSystemProperty("java.compiler"); /** *

* The java.endorsed.dirs System Property. Path of endorsed directory or directories. *

* *

* Defaults to null if the runtime does not have * security access to read this property or the property does not exist. *

* *

* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. *

* * @since Java 1.4 */ public static final String JAVA_ENDORSED_DIRS = getSystemProperty("java.endorsed.dirs"); /** *

* The java.ext.dirs System Property. Path of extension directory or directories. *

* *

* Defaults to null if the runtime does not have * security access to read this property or the property does not exist. *

* *

* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. *

* * @since Java 1.3 */ public static final String JAVA_EXT_DIRS = getSystemProperty("java.ext.dirs"); /** *

* The java.home System Property. Java installation directory. *

* *

* Defaults to null if the runtime does not have * security access to read this property or the property does not exist. *

* *

* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. *

* * @since Java 1.1 */ public static final String JAVA_HOME = getSystemProperty(JAVA_HOME_KEY); /** *

* The java.io.tmpdir System Property. Default temp file path. *

* *

* Defaults to null if the runtime does not have * security access to read this property or the property does not exist. *

* *

* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. *

* * @since Java 1.2 */ public static final String JAVA_IO_TMPDIR = getSystemProperty(JAVA_IO_TMPDIR_KEY); /** *

* The java.library.path System Property. List of paths to search when loading libraries. *

* *

* Defaults to null if the runtime does not have * security access to read this property or the property does not exist. *

* *

* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. *

* * @since Java 1.2 */ public static final String JAVA_LIBRARY_PATH = getSystemProperty("java.library.path"); /** *

* The java.runtime.name System Property. Java Runtime Environment name. *

* *

* Defaults to null if the runtime does not have * security access to read this property or the property does not exist. *

* *

* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. *

* * @since 2.0 * @since Java 1.3 */ public static final String JAVA_RUNTIME_NAME = getSystemProperty("java.runtime.name"); /** *

* The java.runtime.version System Property. Java Runtime Environment version. *

* *

* Defaults to null if the runtime does not have * security access to read this property or the property does not exist. *

* *

* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. *

* * @since 2.0 * @since Java 1.3 */ public static final String JAVA_RUNTIME_VERSION = getSystemProperty("java.runtime.version"); /** *

* The java.specification.name System Property. Java Runtime Environment specification name. *

* *

* Defaults to null if the runtime does not have * security access to read this property or the property does not exist. *

* *

* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. *

* * @since Java 1.2 */ public static final String JAVA_SPECIFICATION_NAME = getSystemProperty("java.specification.name"); /** *

* The java.specification.vendor System Property. Java Runtime Environment specification vendor. *

* *

* Defaults to null if the runtime does not have * security access to read this property or the property does not exist. *

* *

* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. *

* * @since Java 1.2 */ public static final String JAVA_SPECIFICATION_VENDOR = getSystemProperty("java.specification.vendor"); /** *

* The java.specification.version System Property. Java Runtime Environment specification version. *

* *

* Defaults to null if the runtime does not have * security access to read this property or the property does not exist. *

* *

* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. *

* * @since Java 1.3 */ public static final String JAVA_SPECIFICATION_VERSION = getSystemProperty("java.specification.version"); /** *

* The java.util.prefs.PreferencesFactory System Property. A class name. *

* *

* Defaults to null if the runtime does not have * security access to read this property or the property does not exist. *

* *

* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. *

* * @since 2.1 * @since Java 1.4 */ public static final String JAVA_UTIL_PREFS_PREFERENCES_FACTORY = getSystemProperty("java.util.prefs.PreferencesFactory"); /** *

* The java.vendor System Property. Java vendor-specific string. *

* *

* Defaults to null if the runtime does not have * security access to read this property or the property does not exist. *

* *

* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. *

* * @since Java 1.1 */ public static final String JAVA_VENDOR = getSystemProperty("java.vendor"); /** *

* The java.vendor.url System Property. Java vendor URL. *

* *

* Defaults to null if the runtime does not have * security access to read this property or the property does not exist. *

* *

* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. *

* * @since Java 1.1 */ public static final String JAVA_VENDOR_URL = getSystemProperty("java.vendor.url"); /** *

* The java.version System Property. Java version number. *

* *

* Defaults to null if the runtime does not have * security access to read this property or the property does not exist. *

* *

* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. *

* * @since Java 1.1 */ public static final String JAVA_VERSION = getSystemProperty("java.version"); /** *

* The java.vm.info System Property. Java Virtual Machine implementation info. *

* *

* Defaults to null if the runtime does not have * security access to read this property or the property does not exist. *

* *

* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. *

* * @since 2.0 * @since Java 1.2 */ public static final String JAVA_VM_INFO = getSystemProperty("java.vm.info"); /** *

* The java.vm.name System Property. Java Virtual Machine implementation name. *

* *

* Defaults to null if the runtime does not have * security access to read this property or the property does not exist. *

* *

* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. *

* * @since Java 1.2 */ public static final String JAVA_VM_NAME = getSystemProperty("java.vm.name"); /** *

* The java.vm.specification.name System Property. Java Virtual Machine specification name. *

* *

* Defaults to null if the runtime does not have * security access to read this property or the property does not exist. *

* *

* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. *

* * @since Java 1.2 */ public static final String JAVA_VM_SPECIFICATION_NAME = getSystemProperty("java.vm.specification.name"); /** *

* The java.vm.specification.vendor System Property. Java Virtual Machine specification vendor. *

* *

* Defaults to null if the runtime does not have * security access to read this property or the property does not exist. *

* *

* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. *

* * @since Java 1.2 */ public static final String JAVA_VM_SPECIFICATION_VENDOR = getSystemProperty("java.vm.specification.vendor"); /** *

* The java.vm.specification.version System Property. Java Virtual Machine specification version. *

* *

* Defaults to null if the runtime does not have * security access to read this property or the property does not exist. *

* *

* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. *

* * @since Java 1.2 */ public static final String JAVA_VM_SPECIFICATION_VERSION = getSystemProperty("java.vm.specification.version"); /** *

* The java.vm.vendor System Property. Java Virtual Machine implementation vendor. *

* *

* Defaults to null if the runtime does not have * security access to read this property or the property does not exist. *

* *

* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. *

* * @since Java 1.2 */ public static final String JAVA_VM_VENDOR = getSystemProperty("java.vm.vendor"); /** *

* The java.vm.version System Property. Java Virtual Machine implementation version. *

* *

* Defaults to null if the runtime does not have * security access to read this property or the property does not exist. *

* *

* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. *

* * @since Java 1.2 */ public static final String JAVA_VM_VERSION = getSystemProperty("java.vm.version"); /** *

* The line.separator System Property. Line separator ("\n" on UNIX). *

* *

* Defaults to null if the runtime does not have * security access to read this property or the property does not exist. *

* *

* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. *

* * @since Java 1.1 */ public static final String LINE_SEPARATOR = getSystemProperty("line.separator"); /** *

* The os.arch System Property. Operating system architecture. *

* *

* Defaults to null if the runtime does not have * security access to read this property or the property does not exist. *

* *

* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. *

* * @since Java 1.1 */ public static final String OS_ARCH = getSystemProperty("os.arch"); /** *

* The os.name System Property. Operating system name. *

* *

* Defaults to null if the runtime does not have * security access to read this property or the property does not exist. *

* *

* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. *

* * @since Java 1.1 */ public static final String OS_NAME = getSystemProperty("os.name"); /** *

* The os.version System Property. Operating system version. *

* *

* Defaults to null if the runtime does not have * security access to read this property or the property does not exist. *

* *

* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. *

* * @since Java 1.1 */ public static final String OS_VERSION = getSystemProperty("os.version"); /** *

* The path.separator System Property. Path separator (":" on UNIX). *

* *

* Defaults to null if the runtime does not have * security access to read this property or the property does not exist. *

* *

* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. *

* * @since Java 1.1 */ public static final String PATH_SEPARATOR = getSystemProperty("path.separator"); /** *

* The user.country or user.region System Property. * User's country code, such as GB. First in * Java version 1.2 as user.region. Renamed to user.country in 1.4 *

* *

* Defaults to null if the runtime does not have * security access to read this property or the property does not exist. *

* *

* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. *

* * @since 2.0 * @since Java 1.2 */ public static final String USER_COUNTRY = getSystemProperty("user.country") == null ? getSystemProperty("user.region") : getSystemProperty("user.country"); /** *

* The user.dir System Property. User's current working directory. *

* *

* Defaults to null if the runtime does not have * security access to read this property or the property does not exist. *

* *

* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. *

* * @since Java 1.1 */ public static final String USER_DIR = getSystemProperty(USER_DIR_KEY); /** *

* The user.home System Property. User's home directory. *

* *

* Defaults to null if the runtime does not have * security access to read this property or the property does not exist. *

* *

* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. *

* * @since Java 1.1 */ public static final String USER_HOME = getSystemProperty(USER_HOME_KEY); /** *

* The user.language System Property. User's language code, such as "en". *

* *

* Defaults to null if the runtime does not have * security access to read this property or the property does not exist. *

* *

* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. *

* * @since 2.0 * @since Java 1.2 */ public static final String USER_LANGUAGE = getSystemProperty("user.language"); /** *

* The user.name System Property. User's account name. *

* *

* Defaults to null if the runtime does not have * security access to read this property or the property does not exist. *

* *

* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. *

* * @since Java 1.1 */ public static final String USER_NAME = getSystemProperty("user.name"); /** *

* The user.timezone System Property. For example: "America/Los_Angeles". *

* *

* Defaults to null if the runtime does not have * security access to read this property or the property does not exist. *

* *

* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value * will be out of sync with that System property. *

* * @since 2.1 */ public static final String USER_TIMEZONE = getSystemProperty("user.timezone"); // Java version // ----------------------------------------------------------------------- // This MUST be declared after those above as it depends on the // values being set up /** *

* Gets the Java version as a String trimming leading letters. *

* *

* The field will return null if {@link #JAVA_VERSION} is null. *

* * @since 2.1 */ public static final String JAVA_VERSION_TRIMMED = getJavaVersionTrimmed(); // Java version values // ----------------------------------------------------------------------- // These MUST be declared after the trim above as they depend on the // value being set up /** *

* Gets the Java version as a float. *

* *

* Example return values: *

*
    *
  • 1.2f for Java 1.2 *
  • 1.31f for Java 1.3.1 *
* *

* The field will return zero if {@link #JAVA_VERSION} is null. *

* * @since 2.0 */ public static final float JAVA_VERSION_FLOAT = getJavaVersionAsFloat(); /** *

* Gets the Java version as an int. *

* *

* Example return values: *

*
    *
  • 120 for Java 1.2 *
  • 131 for Java 1.3.1 *
* *

* The field will return zero if {@link #JAVA_VERSION} is null. *

* * @since 2.0 */ public static final int JAVA_VERSION_INT = getJavaVersionAsInt(); // Java version checks // ----------------------------------------------------------------------- // These MUST be declared after those above as they depend on the // values being set up /** *

* Is true if this is Java version 1.1 (also 1.1.x versions). *

* *

* The field will return false if {@link #JAVA_VERSION} is null. *

*/ public static final boolean IS_JAVA_1_1 = getJavaVersionMatches("1.1"); /** *

* Is true if this is Java version 1.2 (also 1.2.x versions). *

* *

* The field will return false if {@link #JAVA_VERSION} is null. *

*/ public static final boolean IS_JAVA_1_2 = getJavaVersionMatches("1.2"); /** *

* Is true if this is Java version 1.3 (also 1.3.x versions). *

* *

* The field will return false if {@link #JAVA_VERSION} is null. *

*/ public static final boolean IS_JAVA_1_3 = getJavaVersionMatches("1.3"); /** *

* Is true if this is Java version 1.4 (also 1.4.x versions). *

* *

* The field will return false if {@link #JAVA_VERSION} is null. *

*/ public static final boolean IS_JAVA_1_4 = getJavaVersionMatches("1.4"); /** *

* Is true if this is Java version 1.5 (also 1.5.x versions). *

* *

* The field will return false if {@link #JAVA_VERSION} is null. *

*/ public static final boolean IS_JAVA_1_5 = getJavaVersionMatches("1.5"); /** *

* Is true if this is Java version 1.6 (also 1.6.x versions). *

* *

* The field will return false if {@link #JAVA_VERSION} is null. *

*/ public static final boolean IS_JAVA_1_6 = getJavaVersionMatches("1.6"); /** *

* Is true if this is Java version 1.7 (also 1.7.x versions). *

* *

* The field will return false if {@link #JAVA_VERSION} is null. *

* * @since 2.5 */ public static final boolean IS_JAVA_1_7 = getJavaVersionMatches("1.7"); // Operating system checks // ----------------------------------------------------------------------- // These MUST be declared after those above as they depend on the // values being set up // OS names from http://www.vamphq.com/os.html // Selected ones included - please advise dev@commons.apache.org // if you want another added or a mistake corrected /** *

* Is true if this is AIX. *

* *

* The field will return false if OS_NAME is null. *

* * @since 2.0 */ public static final boolean IS_OS_AIX = getOSMatchesName("AIX"); /** *

* Is true if this is HP-UX. *

* *

* The field will return false if OS_NAME is null. *

* * @since 2.0 */ public static final boolean IS_OS_HP_UX = getOSMatchesName("HP-UX"); /** *

* Is true if this is Irix. *

* *

* The field will return false if OS_NAME is null. *

* * @since 2.0 */ public static final boolean IS_OS_IRIX = getOSMatchesName("Irix"); /** *

* Is true if this is Linux. *

* *

* The field will return false if OS_NAME is null. *

* * @since 2.0 */ public static final boolean IS_OS_LINUX = getOSMatchesName("Linux") || getOSMatchesName("LINUX"); /** *

* Is true if this is Mac. *

* *

* The field will return false if OS_NAME is null. *

* * @since 2.0 */ public static final boolean IS_OS_MAC = getOSMatchesName("Mac"); /** *

* Is true if this is Mac. *

* *

* The field will return false if OS_NAME is null. *

* * @since 2.0 */ public static final boolean IS_OS_MAC_OSX = getOSMatchesName("Mac OS X"); /** *

* Is true if this is OS/2. *

* *

* The field will return false if OS_NAME is null. *

* * @since 2.0 */ public static final boolean IS_OS_OS2 = getOSMatchesName("OS/2"); /** *

* Is true if this is Solaris. *

* *

* The field will return false if OS_NAME is null. *

* * @since 2.0 */ public static final boolean IS_OS_SOLARIS = getOSMatchesName("Solaris"); /** *

* Is true if this is SunOS. *

* *

* The field will return false if OS_NAME is null. *

* * @since 2.0 */ public static final boolean IS_OS_SUN_OS = getOSMatchesName("SunOS"); /** *

* Is true if this is a UNIX like system, * as in any of AIX, HP-UX, Irix, Linux, MacOSX, Solaris or SUN OS. *

* *

* The field will return false if OS_NAME is null. *

* * @since 2.1 */ public static final boolean IS_OS_UNIX = IS_OS_AIX || IS_OS_HP_UX || IS_OS_IRIX || IS_OS_LINUX || IS_OS_MAC_OSX || IS_OS_SOLARIS || IS_OS_SUN_OS; /** *

* Is true if this is Windows. *

* *

* The field will return false if OS_NAME is null. *

* * @since 2.0 */ public static final boolean IS_OS_WINDOWS = getOSMatchesName(OS_NAME_WINDOWS_PREFIX); /** *

* Is true if this is Windows 2000. *

* *

* The field will return false if OS_NAME is null. *

* * @since 2.0 */ public static final boolean IS_OS_WINDOWS_2000 = getOSMatches(OS_NAME_WINDOWS_PREFIX, "5.0"); /** *

* Is true if this is Windows 95. *

* *

* The field will return false if OS_NAME is null. *

* * @since 2.0 */ public static final boolean IS_OS_WINDOWS_95 = getOSMatches(OS_NAME_WINDOWS_PREFIX + " 9", "4.0"); // Java 1.2 running on Windows98 returns 'Windows 95', hence the above /** *

* Is true if this is Windows 98. *

* *

* The field will return false if OS_NAME is null. *

* * @since 2.0 */ public static final boolean IS_OS_WINDOWS_98 = getOSMatches(OS_NAME_WINDOWS_PREFIX + " 9", "4.1"); // Java 1.2 running on Windows98 returns 'Windows 95', hence the above /** *

* Is true if this is Windows ME. *

* *

* The field will return false if OS_NAME is null. *

* * @since 2.0 */ public static final boolean IS_OS_WINDOWS_ME = getOSMatches(OS_NAME_WINDOWS_PREFIX, "4.9"); // Java 1.2 running on WindowsME may return 'Windows 95', hence the above /** *

* Is true if this is Windows NT. *

* *

* The field will return false if OS_NAME is null. *

* * @since 2.0 */ public static final boolean IS_OS_WINDOWS_NT = getOSMatchesName(OS_NAME_WINDOWS_PREFIX + " NT"); // Windows 2000 returns 'Windows 2000' but may suffer from same Java1.2 problem /** *

* Is true if this is Windows XP. *

* *

* The field will return false if OS_NAME is null. *

* * @since 2.0 */ public static final boolean IS_OS_WINDOWS_XP = getOSMatches(OS_NAME_WINDOWS_PREFIX, "5.1"); // ----------------------------------------------------------------------- /** *

* Is true if this is Windows Vista. *

* *

* The field will return false if OS_NAME is null. *

* * @since 2.4 */ public static final boolean IS_OS_WINDOWS_VISTA = getOSMatches(OS_NAME_WINDOWS_PREFIX, "6.0"); /** *

* Is true if this is Windows 7. *

* *

* The field will return false if OS_NAME is null. *

* * @since 2.5 */ public static final boolean IS_OS_WINDOWS_7 = getOSMatches(OS_NAME_WINDOWS_PREFIX, "6.1"); /** *

* Gets the Java home directory as a File. *

* * @return a directory * @throws SecurityException if a security manager exists and its * checkPropertyAccess method doesn't allow access to the specified system property. * @see System#getProperty(String) * @since 2.1 */ public static File getJavaHome() { return new File(System.getProperty(JAVA_HOME_KEY)); } /** *

* Gets the Java IO temporary directory as a File. *

* * @return a directory * @throws SecurityException if a security manager exists and its * checkPropertyAccess method doesn't allow access to the specified system * property. * @see System#getProperty(String) * @since 2.1 */ public static File getJavaIoTmpDir() { return new File(System.getProperty(JAVA_IO_TMPDIR_KEY)); } /** *

Gets the Java version number as a float.

* *

Example return values:

*
    *
  • 1.2f for JDK 1.2 *
  • 1.31f for JDK 1.3.1 *
* * @return the version, for example 1.31f for JDK 1.3.1 * @deprecated Use {@link #JAVA_VERSION_FLOAT} instead. * Method will be removed in Commons Lang 3.0. */ public static float getJavaVersion() { return JAVA_VERSION_FLOAT; } /** *

* Gets the Java version number as a float. *

* *

* Example return values: *

*
    *
  • 1.2f for Java 1.2
  • *
  • 1.31f for Java 1.3.1
  • *
  • 1.6f for Java 1.6.0_20
  • *
* *

* Patch releases are not reported. *

* * @return the version, for example 1.31f for Java 1.3.1 */ private static float getJavaVersionAsFloat() { return toVersionFloat(toJavaVersionIntArray(SystemUtils.JAVA_VERSION, JAVA_VERSION_TRIM_SIZE)); } /** *

* Gets the Java version number as an int. *

* *

* Example return values: *

*
    *
  • 120 for Java 1.2
  • *
  • 131 for Java 1.3.1
  • *
  • 160 for Java 1.6.0_20
  • *
* *

* Patch releases are not reported. *

* * @return the version, for example 131 for Java 1.3.1 */ private static int getJavaVersionAsInt() { return toVersionInt(toJavaVersionIntArray(SystemUtils.JAVA_VERSION, JAVA_VERSION_TRIM_SIZE)); } /** *

* Decides if the Java version matches. *

* * @param versionPrefix * the prefix for the java version * @return true if matches, or false if not or can't determine */ private static boolean getJavaVersionMatches(String versionPrefix) { return isJavaVersionMatch(JAVA_VERSION_TRIMMED, versionPrefix); } /** * Trims the text of the java version to start with numbers. * * @return the trimmed java version */ private static String getJavaVersionTrimmed() { if (JAVA_VERSION != null) { for (int i = 0; i < JAVA_VERSION.length(); i++) { char ch = JAVA_VERSION.charAt(i); if (ch >= '0' && ch <= '9') { return JAVA_VERSION.substring(i); } } } return null; } /** * Decides if the operating system matches. * * @param osNamePrefix * the prefix for the os name * @param osVersionPrefix * the prefix for the version * @return true if matches, or false if not or can't determine */ private static boolean getOSMatches(String osNamePrefix, String osVersionPrefix) { return isOSMatch(OS_NAME, OS_VERSION, osNamePrefix, osVersionPrefix); } /** * Decides if the operating system matches. * * @param osNamePrefix * the prefix for the os name * @return true if matches, or false if not or can't determine */ private static boolean getOSMatchesName(String osNamePrefix) { return isOSNameMatch(OS_NAME, osNamePrefix); } // ----------------------------------------------------------------------- /** *

* Gets a System property, defaulting to null if the property cannot be read. *

* *

* If a SecurityException is caught, the return value is null and a message is written to * System.err. *

* * @param property * the system property name * @return the system property value or null if a security problem occurs */ private static String getSystemProperty(String property) { try { return System.getProperty(property); } catch (SecurityException ex) { // we are not allowed to look at this property System.err.println("Caught a SecurityException reading the system property '" + property + "'; the SystemUtils property value will default to null."); return null; } } /** *

* Gets the user directory as a File. *

* * @return a directory * @throws SecurityException if a security manager exists and its * checkPropertyAccess method doesn't allow access to the specified system property. * @see System#getProperty(String) * @since 2.1 */ public static File getUserDir() { return new File(System.getProperty(USER_DIR_KEY)); } /** *

* Gets the user home directory as a File. *

* * @return a directory * @throws SecurityException if a security manager exists and its * checkPropertyAccess method doesn't allow access to the specified system property. * @see System#getProperty(String) * @since 2.1 */ public static File getUserHome() { return new File(System.getProperty(USER_HOME_KEY)); } /** * Returns whether the {@link #JAVA_AWT_HEADLESS} value is true. * * @return true if JAVA_AWT_HEADLESS is "true", false otherwise. * * @see #JAVA_AWT_HEADLESS * @since 2.1 * @since Java 1.4 */ public static boolean isJavaAwtHeadless() { return JAVA_AWT_HEADLESS != null ? JAVA_AWT_HEADLESS.equals(Boolean.TRUE.toString()) : false; } /** *

* Is the Java version at least the requested version. *

* *

* Example input: *

*
    *
  • 1.2f to test for Java 1.2
  • *
  • 1.31f to test for Java 1.3.1
  • *
* * @param requiredVersion * the required version, for example 1.31f * @return true if the actual version is equal or greater than the required version */ public static boolean isJavaVersionAtLeast(float requiredVersion) { return JAVA_VERSION_FLOAT >= requiredVersion; } /** *

* Is the Java version at least the requested version. *

* *

* Example input: *

*
    *
  • 120 to test for Java 1.2 or greater
  • *
  • 131 to test for Java 1.3.1 or greater
  • *
* * @param requiredVersion * the required version, for example 131 * @return true if the actual version is equal or greater than the required version * @since 2.0 */ public static boolean isJavaVersionAtLeast(int requiredVersion) { return JAVA_VERSION_INT >= requiredVersion; } /** *

* Decides if the Java version matches. *

*

* This method is package private instead of private to support unit test invocation. *

* * @param version * the actual Java version * @param versionPrefix * the prefix for the expected Java version * @return true if matches, or false if not or can't determine */ static boolean isJavaVersionMatch(String version, String versionPrefix) { if (version == null) { return false; } return version.startsWith(versionPrefix); } /** * Decides if the operating system matches. *

* This method is package private instead of private to support unit test invocation. *

* * @param osName * the actual OS name * @param osVersion * the actual OS version * @param osNamePrefix * the prefix for the expected OS name * @param osVersionPrefix * the prefix for the expected OS version * @return true if matches, or false if not or can't determine */ static boolean isOSMatch(String osName, String osVersion, String osNamePrefix, String osVersionPrefix) { if (osName == null || osVersion == null) { return false; } return osName.startsWith(osNamePrefix) && osVersion.startsWith(osVersionPrefix); } /** * Decides if the operating system matches. *

* This method is package private instead of private to support unit test invocation. *

* * @param osName * the actual OS name * @param osNamePrefix * the prefix for the expected OS name * @return true if matches, or false if not or can't determine */ static boolean isOSNameMatch(String osName, String osNamePrefix) { if (osName == null) { return false; } return osName.startsWith(osNamePrefix); } /** *

* Converts the given Java version string to a float. *

* *

* Example return values: *

*
    *
  • 1.2f for Java 1.2
  • *
  • 1.31f for Java 1.3.1
  • *
  • 1.6f for Java 1.6.0_20
  • *
* *

* Patch releases are not reported. *

*

* This method is package private instead of private to support unit test invocation. *

* * @param version The string version * @return the version, for example 1.31f for Java 1.3.1 */ static float toJavaVersionFloat(String version) { return toVersionFloat(toJavaVersionIntArray(version, JAVA_VERSION_TRIM_SIZE)); } /** *

* Converts the given Java version string to an int. *

* *

* Example return values: *

*
    *
  • 120 for Java 1.2
  • *
  • 131 for Java 1.3.1
  • *
  • 160 for Java 1.6.0_20
  • *
* *

* Patch releases are not reported. *

*

* This method is package private instead of private to support unit test invocation. *

* * @param version The string version * @return the version, for example 131 for Java 1.3.1 */ static int toJavaVersionInt(String version) { return toVersionInt(toJavaVersionIntArray(version, JAVA_VERSION_TRIM_SIZE)); } /** *

* Converts the given Java version string to an int[] of maximum size 3. *

* *

* Example return values: *

*
    *
  • [1, 2, 0] for Java 1.2
  • *
  • [1, 3, 1] for Java 1.3.1
  • *
  • [1, 5, 0] for Java 1.5.0_21
  • *
*

* This method is package private instead of private to support unit test invocation. *

* * @param version The string version * @return the version, for example [1, 5, 0] for Java 1.5.0_21 */ static int[] toJavaVersionIntArray(String version) { return toJavaVersionIntArray(version, Integer.MAX_VALUE); } /** *

* Converts the given Java version string to an int[] of maximum size limit. *

* *

* Example return values: *

*
    *
  • [1, 2, 0] for Java 1.2
  • *
  • [1, 3, 1] for Java 1.3.1
  • *
  • [1, 5, 0, 21] for Java 1.5.0_21
  • *
* * @param version The string version * @param limit version limit * @return the version, for example [1, 5, 0, 21] for Java 1.5.0_21 */ private static int[] toJavaVersionIntArray(String version, int limit) { if (version == null) { return ArrayUtils.EMPTY_INT_ARRAY; } String[] strings = StringUtils.split(version, "._- "); int[] ints = new int[Math.min(limit, strings.length)]; int j = 0; for (int i = 0; i < strings.length && j < limit; i++) { String s = strings[i]; if (s.length() > 0) { try { ints[j] = Integer.parseInt(s); j++; } catch (Exception e) { } } } if (ints.length > j) { int[] newInts = new int[j]; System.arraycopy(ints, 0, newInts, 0, j); ints = newInts; } return ints; } /** *

* Converts given the Java version array to a float. *

* *

* Example return values: *

*
    *
  • 1.2f for Java 1.2
  • *
  • 1.31f for Java 1.3.1
  • *
  • 1.6f for Java 1.6.0_20
  • *
* *

* Patch releases are not reported. *

* * @param javaVersions The version numbers * @return the version, for example 1.31f for Java 1.3.1 */ private static float toVersionFloat(int[] javaVersions) { if (javaVersions == null || javaVersions.length == 0) { return 0f; } if (javaVersions.length == 1) { return javaVersions[0]; } StringBuffer builder = new StringBuffer(); builder.append(javaVersions[0]); builder.append('.'); for (int i = 1; i < javaVersions.length; i++) { builder.append(javaVersions[i]); } try { return Float.parseFloat(builder.toString()); } catch (Exception ex) { return 0f; } } /** *

* Converts given the Java version array to an int. *

* *

* Example return values: *

*
    *
  • 120 for Java 1.2
  • *
  • 131 for Java 1.3.1
  • *
  • 160 for Java 1.6.0_20
  • *
* *

* Patch releases are not reported. *

* * @param javaVersions The version numbers * @return the version, for example 1.31f for Java 1.3.1 */ private static int toVersionInt(int[] javaVersions) { if (javaVersions == null) { return 0; } int intVersion = 0; int len = javaVersions.length; if (len >= 1) { intVersion = javaVersions[0] * 100; } if (len >= 2) { intVersion += javaVersions[1] * 10; } if (len >= 3) { intVersion += javaVersions[2]; } return intVersion; } // ----------------------------------------------------------------------- /** *

* SystemUtils instances should NOT be constructed in standard programming. Instead, the class should be used as * SystemUtils.FILE_SEPARATOR. *

* *

* This constructor is public to permit tools that require a JavaBean instance to operate. *

*/ public SystemUtils() { super(); } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/text/CompositeFormat.java100644 0 0 7432 11513702441 25675 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.text; import java.text.FieldPosition; import java.text.Format; import java.text.ParseException; import java.text.ParsePosition; /** * Formats using one formatter and parses using a different formatter. An * example of use for this would be a webapp where data is taken in one way and * stored in a database another way. * * @author Apache Software Foundation * @author Archimedes Trajano * @version $Id: CompositeFormat.java 905636 2010-02-02 14:03:32Z niallp $ */ public class CompositeFormat extends Format { /** * Required for serialization support. * * @see java.io.Serializable */ private static final long serialVersionUID = -4329119827877627683L; /** The parser to use. */ private final Format parser; /** The formatter to use. */ private final Format formatter; /** * Create a format that points its parseObject method to one implementation * and its format method to another. * * @param parser implementation * @param formatter implementation */ public CompositeFormat(Format parser, Format formatter) { this.parser = parser; this.formatter = formatter; } /** * Uses the formatter Format instance. * * @param obj the object to format * @param toAppendTo the {@link StringBuffer} to append to * @param pos the FieldPosition to use (or ignore). * @return toAppendTo * @see Format#format(Object, StringBuffer, FieldPosition) */ public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) { return formatter.format(obj, toAppendTo, pos); } /** * Uses the parser Format instance. * * @param source the String source * @param pos the ParsePosition containing the position to parse from, will * be updated according to parsing success (index) or failure * (error index) * @return the parsed Object * @see Format#parseObject(String, ParsePosition) */ public Object parseObject(String source, ParsePosition pos) { return parser.parseObject(source, pos); } /** * Provides access to the parser Format implementation. * * @return parser Format implementation */ public Format getParser() { return this.parser; } /** * Provides access to the parser Format implementation. * * @return formatter Format implementation */ public Format getFormatter() { return this.formatter; } /** * Utility method to parse and then reformat a String. * * @param input String to reformat * @return A reformatted String * @throws ParseException thrown by parseObject(String) call */ public String reformat(String input) throws ParseException { return format(parseObject(input)); } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/text/ExtendedMessageFormat.java100644 0 0 46156 11513702441 27026 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.text; import java.text.Format; import java.text.MessageFormat; import java.text.ParsePosition; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.Locale; import java.util.Map; import org.apache.commons.lang.ObjectUtils; import org.apache.commons.lang.Validate; /** * Extends java.text.MessageFormat to allow pluggable/additional formatting * options for embedded format elements. Client code should specify a registry * of FormatFactory instances associated with String * format names. This registry will be consulted when the format elements are * parsed from the message pattern. In this way custom patterns can be specified, * and the formats supported by java.text.MessageFormat can be overridden * at the format and/or format style level (see MessageFormat). A "format element" * embedded in the message pattern is specified (()? signifies optionality):
* {argument-number(,format-name(,format-style)?)?} * *

* format-name and format-style values are trimmed of surrounding whitespace * in the manner of java.text.MessageFormat. If format-name denotes * FormatFactory formatFactoryInstance in registry, a Format * matching format-name and format-style is requested from * formatFactoryInstance. If this is successful, the Format * found is used for this format element. *

* *

NOTICE:: The various subformat mutator methods are considered unnecessary; they exist on the parent * class to allow the type of customization which it is the job of this class to provide in * a configurable fashion. These methods have thus been disabled and will throw * UnsupportedOperationException if called. *

* *

Limitations inherited from java.text.MessageFormat: *

    *
  • When using "choice" subformats, support for nested formatting instructions is limited * to that provided by the base class.
  • *
  • Thread-safety of Formats, including MessageFormat and thus * ExtendedMessageFormat, is not guaranteed.
  • *
*

* * @author Apache Software Foundation * @author Matt Benson * @since 2.4 * @version $Id: ExtendedMessageFormat.java 1057427 2011-01-11 00:28:01Z niallp $ */ public class ExtendedMessageFormat extends MessageFormat { private static final long serialVersionUID = -2362048321261811743L; private static final int HASH_SEED = 31; private static final String DUMMY_PATTERN = ""; private static final String ESCAPED_QUOTE = "''"; private static final char START_FMT = ','; private static final char END_FE = '}'; private static final char START_FE = '{'; private static final char QUOTE = '\''; private String toPattern; private final Map registry; /** * Create a new ExtendedMessageFormat for the default locale. * * @param pattern the pattern to use, not null * @throws IllegalArgumentException in case of a bad pattern. */ public ExtendedMessageFormat(String pattern) { this(pattern, Locale.getDefault()); } /** * Create a new ExtendedMessageFormat. * * @param pattern the pattern to use, not null * @param locale the locale to use, not null * @throws IllegalArgumentException in case of a bad pattern. */ public ExtendedMessageFormat(String pattern, Locale locale) { this(pattern, locale, null); } /** * Create a new ExtendedMessageFormat for the default locale. * * @param pattern the pattern to use, not null * @param registry the registry of format factories, may be null * @throws IllegalArgumentException in case of a bad pattern. */ public ExtendedMessageFormat(String pattern, Map registry) { this(pattern, Locale.getDefault(), registry); } /** * Create a new ExtendedMessageFormat. * * @param pattern the pattern to use, not null * @param locale the locale to use, not null * @param registry the registry of format factories, may be null * @throws IllegalArgumentException in case of a bad pattern. */ public ExtendedMessageFormat(String pattern, Locale locale, Map registry) { super(DUMMY_PATTERN); setLocale(locale); this.registry = registry; applyPattern(pattern); } /** * {@inheritDoc} */ public String toPattern() { return toPattern; } /** * Apply the specified pattern. * * @param pattern String */ public final void applyPattern(String pattern) { if (registry == null) { super.applyPattern(pattern); toPattern = super.toPattern(); return; } ArrayList foundFormats = new ArrayList(); ArrayList foundDescriptions = new ArrayList(); StrBuilder stripCustom = new StrBuilder(pattern.length()); ParsePosition pos = new ParsePosition(0); char[] c = pattern.toCharArray(); int fmtCount = 0; while (pos.getIndex() < pattern.length()) { switch (c[pos.getIndex()]) { case QUOTE: appendQuotedString(pattern, pos, stripCustom, true); break; case START_FE: fmtCount++; seekNonWs(pattern, pos); int start = pos.getIndex(); int index = readArgumentIndex(pattern, next(pos)); stripCustom.append(START_FE).append(index); seekNonWs(pattern, pos); Format format = null; String formatDescription = null; if (c[pos.getIndex()] == START_FMT) { formatDescription = parseFormatDescription(pattern, next(pos)); format = getFormat(formatDescription); if (format == null) { stripCustom.append(START_FMT).append(formatDescription); } } foundFormats.add(format); foundDescriptions.add(format == null ? null : formatDescription); Validate.isTrue(foundFormats.size() == fmtCount); Validate.isTrue(foundDescriptions.size() == fmtCount); if (c[pos.getIndex()] != END_FE) { throw new IllegalArgumentException( "Unreadable format element at position " + start); } //$FALL-THROUGH$ default: stripCustom.append(c[pos.getIndex()]); next(pos); } } super.applyPattern(stripCustom.toString()); toPattern = insertFormats(super.toPattern(), foundDescriptions); if (containsElements(foundFormats)) { Format[] origFormats = getFormats(); // only loop over what we know we have, as MessageFormat on Java 1.3 // seems to provide an extra format element: int i = 0; for (Iterator it = foundFormats.iterator(); it.hasNext(); i++) { Format f = (Format) it.next(); if (f != null) { origFormats[i] = f; } } super.setFormats(origFormats); } } /** * Throws UnsupportedOperationException - see class Javadoc for details. * * @param formatElementIndex format element index * @param newFormat the new format * @throws UnsupportedOperationException */ public void setFormat(int formatElementIndex, Format newFormat) { throw new UnsupportedOperationException(); } /** * Throws UnsupportedOperationException - see class Javadoc for details. * * @param argumentIndex argument index * @param newFormat the new format * @throws UnsupportedOperationException */ public void setFormatByArgumentIndex(int argumentIndex, Format newFormat) { throw new UnsupportedOperationException(); } /** * Throws UnsupportedOperationException - see class Javadoc for details. * * @param newFormats new formats * @throws UnsupportedOperationException */ public void setFormats(Format[] newFormats) { throw new UnsupportedOperationException(); } /** * Throws UnsupportedOperationException - see class Javadoc for details. * * @param newFormats new formats * @throws UnsupportedOperationException */ public void setFormatsByArgumentIndex(Format[] newFormats) { throw new UnsupportedOperationException(); } /** * Check if this extended message format is equal to another object. * * @param obj the object to compare to * @return true if this object equals the other, otherwise false * @since 2.6 */ public boolean equals(Object obj) { if (obj == this) { return true; } if (obj == null) { return false; } if (!super.equals(obj)) { return false; } if (ObjectUtils.notEqual(getClass(), obj.getClass())) { return false; } ExtendedMessageFormat rhs = (ExtendedMessageFormat)obj; if (ObjectUtils.notEqual(toPattern, rhs.toPattern)) { return false; } if (ObjectUtils.notEqual(registry, rhs.registry)) { return false; } return true; } /** * Return the hashcode. * * @return the hashcode * @since 2.6 */ public int hashCode() { int result = super.hashCode(); result = HASH_SEED * result + ObjectUtils.hashCode(registry); result = HASH_SEED * result + ObjectUtils.hashCode(toPattern); return result; } /** * Get a custom format from a format description. * * @param desc String * @return Format */ private Format getFormat(String desc) { if (registry != null) { String name = desc; String args = null; int i = desc.indexOf(START_FMT); if (i > 0) { name = desc.substring(0, i).trim(); args = desc.substring(i + 1).trim(); } FormatFactory factory = (FormatFactory) registry.get(name); if (factory != null) { return factory.getFormat(name, args, getLocale()); } } return null; } /** * Read the argument index from the current format element * * @param pattern pattern to parse * @param pos current parse position * @return argument index */ private int readArgumentIndex(String pattern, ParsePosition pos) { int start = pos.getIndex(); seekNonWs(pattern, pos); StrBuilder result = new StrBuilder(); boolean error = false; for (; !error && pos.getIndex() < pattern.length(); next(pos)) { char c = pattern.charAt(pos.getIndex()); if (Character.isWhitespace(c)) { seekNonWs(pattern, pos); c = pattern.charAt(pos.getIndex()); if (c != START_FMT && c != END_FE) { error = true; continue; } } if ((c == START_FMT || c == END_FE) && result.length() > 0) { try { return Integer.parseInt(result.toString()); } catch (NumberFormatException e) { // we've already ensured only digits, so unless something // outlandishly large was specified we should be okay. } } error = !Character.isDigit(c); result.append(c); } if (error) { throw new IllegalArgumentException( "Invalid format argument index at position " + start + ": " + pattern.substring(start, pos.getIndex())); } throw new IllegalArgumentException( "Unterminated format element at position " + start); } /** * Parse the format component of a format element. * * @param pattern string to parse * @param pos current parse position * @return Format description String */ private String parseFormatDescription(String pattern, ParsePosition pos) { int start = pos.getIndex(); seekNonWs(pattern, pos); int text = pos.getIndex(); int depth = 1; for (; pos.getIndex() < pattern.length(); next(pos)) { switch (pattern.charAt(pos.getIndex())) { case START_FE: depth++; break; case END_FE: depth--; if (depth == 0) { return pattern.substring(text, pos.getIndex()); } break; case QUOTE: getQuotedString(pattern, pos, false); break; } } throw new IllegalArgumentException( "Unterminated format element at position " + start); } /** * Insert formats back into the pattern for toPattern() support. * * @param pattern source * @param customPatterns The custom patterns to re-insert, if any * @return full pattern */ private String insertFormats(String pattern, ArrayList customPatterns) { if (!containsElements(customPatterns)) { return pattern; } StrBuilder sb = new StrBuilder(pattern.length() * 2); ParsePosition pos = new ParsePosition(0); int fe = -1; int depth = 0; while (pos.getIndex() < pattern.length()) { char c = pattern.charAt(pos.getIndex()); switch (c) { case QUOTE: appendQuotedString(pattern, pos, sb, false); break; case START_FE: depth++; if (depth == 1) { fe++; sb.append(START_FE).append( readArgumentIndex(pattern, next(pos))); String customPattern = (String) customPatterns.get(fe); if (customPattern != null) { sb.append(START_FMT).append(customPattern); } } break; case END_FE: depth--; //$FALL-THROUGH$ default: sb.append(c); next(pos); } } return sb.toString(); } /** * Consume whitespace from the current parse position. * * @param pattern String to read * @param pos current position */ private void seekNonWs(String pattern, ParsePosition pos) { int len = 0; char[] buffer = pattern.toCharArray(); do { len = StrMatcher.splitMatcher().isMatch(buffer, pos.getIndex()); pos.setIndex(pos.getIndex() + len); } while (len > 0 && pos.getIndex() < pattern.length()); } /** * Convenience method to advance parse position by 1 * * @param pos ParsePosition * @return pos */ private ParsePosition next(ParsePosition pos) { pos.setIndex(pos.getIndex() + 1); return pos; } /** * Consume a quoted string, adding it to appendTo if * specified. * * @param pattern pattern to parse * @param pos current parse position * @param appendTo optional StringBuffer to append * @param escapingOn whether to process escaped quotes * @return appendTo */ private StrBuilder appendQuotedString(String pattern, ParsePosition pos, StrBuilder appendTo, boolean escapingOn) { int start = pos.getIndex(); char[] c = pattern.toCharArray(); if (escapingOn && c[start] == QUOTE) { next(pos); return appendTo == null ? null : appendTo.append(QUOTE); } int lastHold = start; for (int i = pos.getIndex(); i < pattern.length(); i++) { if (escapingOn && pattern.substring(i).startsWith(ESCAPED_QUOTE)) { appendTo.append(c, lastHold, pos.getIndex() - lastHold).append( QUOTE); pos.setIndex(i + ESCAPED_QUOTE.length()); lastHold = pos.getIndex(); continue; } switch (c[pos.getIndex()]) { case QUOTE: next(pos); return appendTo == null ? null : appendTo.append(c, lastHold, pos.getIndex() - lastHold); default: next(pos); } } throw new IllegalArgumentException( "Unterminated quoted string at position " + start); } /** * Consume quoted string only * * @param pattern pattern to parse * @param pos current parse position * @param escapingOn whether to process escaped quotes */ private void getQuotedString(String pattern, ParsePosition pos, boolean escapingOn) { appendQuotedString(pattern, pos, null, escapingOn); } /** * Learn whether the specified Collection contains non-null elements. * @param coll to check * @return true if some Object was found, false otherwise. */ private boolean containsElements(Collection coll) { if (coll == null || coll.size() == 0) { return false; } for (Iterator iter = coll.iterator(); iter.hasNext();) { if (iter.next() != null) { return true; } } return false; } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/text/FormatFactory.java100644 0 0 3137 11513702441 25340 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.text; import java.text.Format; import java.util.Locale; /** * Format factory. * * @author Apache Software Foundation * @since 2.4 * @version $Id: FormatFactory.java 905636 2010-02-02 14:03:32Z niallp $ */ public interface FormatFactory { /** * Create or retrieve a format instance. * * @param name The format type name * @param arguments Arguments used to create the format instance. This allows the * FormatFactory to implement the "format style" * concept from java.text.MessageFormat. * @param locale The locale, may be null * @return The format instance */ Format getFormat(String name, String arguments, Locale locale); } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/text/package.html100644 0 0 2073 11513702441 24174 0ustar 0 0

Provides classes for handling and manipulating text, partly as an extension to {@link java.text}. The classes in this package are, for the most part, intended to be instantiated. (ie. they are not utility classes with lots of static methods)

@since 2.1 commons-lang-2.6-src/src/main/java/org/apache/commons/lang/text/StrBuilder.java100644 0 0 276700 11513702441 24707 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.text; import java.io.Reader; import java.io.Writer; import java.util.Collection; import java.util.Iterator; import java.util.List; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.SystemUtils; /** * Builds a string from constituent parts providing a more flexible and powerful API * than StringBuffer. *

* The main differences from StringBuffer/StringBuilder are: *

    *
  • Not synchronized
  • *
  • Not final
  • *
  • Subclasses have direct access to character array
  • *
  • Additional methods *
      *
    • appendWithSeparators - adds an array of values, with a separator
    • *
    • appendPadding - adds a length padding characters
    • *
    • appendFixedLength - adds a fixed width field to the builder
    • *
    • toCharArray/getChars - simpler ways to get a range of the character array
    • *
    • delete - delete char or string
    • *
    • replace - search and replace for a char or string
    • *
    • leftString/rightString/midString - substring without exceptions
    • *
    • contains - whether the builder contains a char or string
    • *
    • size/clear/isEmpty - collections style API methods
    • *
    *
  • *
*
  • Views *
      *
    • asTokenizer - uses the internal buffer as the source of a StrTokenizer
    • *
    • asReader - uses the internal buffer as the source of a Reader
    • *
    • asWriter - allows a Writer to write directly to the internal buffer
    • *
    *
  • * *

    * The aim has been to provide an API that mimics very closely what StringBuffer * provides, but with additional methods. It should be noted that some edge cases, * with invalid indices or null input, have been altered - see individual methods. * The biggest of these changes is that by default, null will not output the text * 'null'. This can be controlled by a property, {@link #setNullText(String)}. *

    * Prior to 3.0, this class implemented Cloneable but did not implement the * clone method so could not be used. From 3.0 onwards it no longer implements * the interface. * * @author Apache Software Foundation * @since 2.2 * @version $Id: StrBuilder.java 1057349 2011-01-10 20:40:49Z niallp $ */ public class StrBuilder implements Cloneable { /** * The extra capacity for new builders. */ static final int CAPACITY = 32; /** * Required for serialization support. * * @see java.io.Serializable */ private static final long serialVersionUID = 7628716375283629643L; /** Internal data storage. */ protected char[] buffer; // TODO make private? /** Current size of the buffer. */ protected int size; // TODO make private? /** The new line. */ private String newLine; /** The null text. */ private String nullText; //----------------------------------------------------------------------- /** * Constructor that creates an empty builder initial capacity 32 characters. */ public StrBuilder() { this(CAPACITY); } /** * Constructor that creates an empty builder the specified initial capacity. * * @param initialCapacity the initial capacity, zero or less will be converted to 32 */ public StrBuilder(int initialCapacity) { super(); if (initialCapacity <= 0) { initialCapacity = CAPACITY; } buffer = new char[initialCapacity]; } /** * Constructor that creates a builder from the string, allocating * 32 extra characters for growth. * * @param str the string to copy, null treated as blank string */ public StrBuilder(String str) { super(); if (str == null) { buffer = new char[CAPACITY]; } else { buffer = new char[str.length() + CAPACITY]; append(str); } } //----------------------------------------------------------------------- /** * Gets the text to be appended when a new line is added. * * @return the new line text, null means use system default */ public String getNewLineText() { return newLine; } /** * Sets the text to be appended when a new line is added. * * @param newLine the new line text, null means use system default * @return this, to enable chaining */ public StrBuilder setNewLineText(String newLine) { this.newLine = newLine; return this; } //----------------------------------------------------------------------- /** * Gets the text to be appended when null is added. * * @return the null text, null means no append */ public String getNullText() { return nullText; } /** * Sets the text to be appended when null is added. * * @param nullText the null text, null means no append * @return this, to enable chaining */ public StrBuilder setNullText(String nullText) { if (nullText != null && nullText.length() == 0) { nullText = null; } this.nullText = nullText; return this; } //----------------------------------------------------------------------- /** * Gets the length of the string builder. * * @return the length */ public int length() { return size; } /** * Updates the length of the builder by either dropping the last characters * or adding filler of unicode zero. * * @param length the length to set to, must be zero or positive * @return this, to enable chaining * @throws IndexOutOfBoundsException if the length is negative */ public StrBuilder setLength(int length) { if (length < 0) { throw new StringIndexOutOfBoundsException(length); } if (length < size) { size = length; } else if (length > size) { ensureCapacity(length); int oldEnd = size; int newEnd = length; size = length; for (int i = oldEnd; i < newEnd; i++) { buffer[i] = '\0'; } } return this; } //----------------------------------------------------------------------- /** * Gets the current size of the internal character array buffer. * * @return the capacity */ public int capacity() { return buffer.length; } /** * Checks the capacity and ensures that it is at least the size specified. * * @param capacity the capacity to ensure * @return this, to enable chaining */ public StrBuilder ensureCapacity(int capacity) { if (capacity > buffer.length) { char[] old = buffer; buffer = new char[capacity * 2]; System.arraycopy(old, 0, buffer, 0, size); } return this; } /** * Minimizes the capacity to the actual length of the string. * * @return this, to enable chaining */ public StrBuilder minimizeCapacity() { if (buffer.length > length()) { char[] old = buffer; buffer = new char[length()]; System.arraycopy(old, 0, buffer, 0, size); } return this; } //----------------------------------------------------------------------- /** * Gets the length of the string builder. *

    * This method is the same as {@link #length()} and is provided to match the * API of Collections. * * @return the length */ public int size() { return size; } /** * Checks is the string builder is empty (convenience Collections API style method). *

    * This method is the same as checking {@link #length()} and is provided to match the * API of Collections. * * @return true if the size is 0. */ public boolean isEmpty() { return size == 0; } /** * Clears the string builder (convenience Collections API style method). *

    * This method does not reduce the size of the internal character buffer. * To do that, call clear() followed by {@link #minimizeCapacity()}. *

    * This method is the same as {@link #setLength(int)} called with zero * and is provided to match the API of Collections. * * @return this, to enable chaining */ public StrBuilder clear() { size = 0; return this; } //----------------------------------------------------------------------- /** * Gets the character at the specified index. * * @see #setCharAt(int, char) * @see #deleteCharAt(int) * @param index the index to retrieve, must be valid * @return the character at the index * @throws IndexOutOfBoundsException if the index is invalid */ public char charAt(int index) { if (index < 0 || index >= length()) { throw new StringIndexOutOfBoundsException(index); } return buffer[index]; } /** * Sets the character at the specified index. * * @see #charAt(int) * @see #deleteCharAt(int) * @param index the index to set * @param ch the new character * @return this, to enable chaining * @throws IndexOutOfBoundsException if the index is invalid */ public StrBuilder setCharAt(int index, char ch) { if (index < 0 || index >= length()) { throw new StringIndexOutOfBoundsException(index); } buffer[index] = ch; return this; } /** * Deletes the character at the specified index. * * @see #charAt(int) * @see #setCharAt(int, char) * @param index the index to delete * @return this, to enable chaining * @throws IndexOutOfBoundsException if the index is invalid */ public StrBuilder deleteCharAt(int index) { if (index < 0 || index >= size) { throw new StringIndexOutOfBoundsException(index); } deleteImpl(index, index + 1, 1); return this; } //----------------------------------------------------------------------- /** * Copies the builder's character array into a new character array. * * @return a new array that represents the contents of the builder */ public char[] toCharArray() { if (size == 0) { return ArrayUtils.EMPTY_CHAR_ARRAY; } char chars[] = new char[size]; System.arraycopy(buffer, 0, chars, 0, size); return chars; } /** * Copies part of the builder's character array into a new character array. * * @param startIndex the start index, inclusive, must be valid * @param endIndex the end index, exclusive, must be valid except that * if too large it is treated as end of string * @return a new array that holds part of the contents of the builder * @throws IndexOutOfBoundsException if startIndex is invalid, * or if endIndex is invalid (but endIndex greater than size is valid) */ public char[] toCharArray(int startIndex, int endIndex) { endIndex = validateRange(startIndex, endIndex); int len = endIndex - startIndex; if (len == 0) { return ArrayUtils.EMPTY_CHAR_ARRAY; } char chars[] = new char[len]; System.arraycopy(buffer, startIndex, chars, 0, len); return chars; } /** * Copies the character array into the specified array. * * @param destination the destination array, null will cause an array to be created * @return the input array, unless that was null or too small */ public char[] getChars(char[] destination) { int len = length(); if (destination == null || destination.length < len) { destination = new char[len]; } System.arraycopy(buffer, 0, destination, 0, len); return destination; } /** * Copies the character array into the specified array. * * @param startIndex first index to copy, inclusive, must be valid * @param endIndex last index, exclusive, must be valid * @param destination the destination array, must not be null or too small * @param destinationIndex the index to start copying in destination * @throws NullPointerException if the array is null * @throws IndexOutOfBoundsException if any index is invalid */ public void getChars(int startIndex, int endIndex, char destination[], int destinationIndex) { if (startIndex < 0) { throw new StringIndexOutOfBoundsException(startIndex); } if (endIndex < 0 || endIndex > length()) { throw new StringIndexOutOfBoundsException(endIndex); } if (startIndex > endIndex) { throw new StringIndexOutOfBoundsException("end < start"); } System.arraycopy(buffer, startIndex, destination, destinationIndex, endIndex - startIndex); } //----------------------------------------------------------------------- /** * Appends the new line string to this string builder. *

    * The new line string can be altered using {@link #setNewLineText(String)}. * This might be used to force the output to always use Unix line endings * even when on Windows. * * @return this, to enable chaining */ public StrBuilder appendNewLine() { if (newLine == null) { append(SystemUtils.LINE_SEPARATOR); return this; } return append(newLine); } /** * Appends the text representing null to this string builder. * * @return this, to enable chaining */ public StrBuilder appendNull() { if (nullText == null) { return this; } return append(nullText); } /** * Appends an object to this string builder. * Appending null will call {@link #appendNull()}. * * @param obj the object to append * @return this, to enable chaining */ public StrBuilder append(Object obj) { if (obj == null) { return appendNull(); } return append(obj.toString()); } /** * Appends a string to this string builder. * Appending null will call {@link #appendNull()}. * * @param str the string to append * @return this, to enable chaining */ public StrBuilder append(String str) { if (str == null) { return appendNull(); } int strLen = str.length(); if (strLen > 0) { int len = length(); ensureCapacity(len + strLen); str.getChars(0, strLen, buffer, len); size += strLen; } return this; } /** * Appends part of a string to this string builder. * Appending null will call {@link #appendNull()}. * * @param str the string to append * @param startIndex the start index, inclusive, must be valid * @param length the length to append, must be valid * @return this, to enable chaining */ public StrBuilder append(String str, int startIndex, int length) { if (str == null) { return appendNull(); } if (startIndex < 0 || startIndex > str.length()) { throw new StringIndexOutOfBoundsException("startIndex must be valid"); } if (length < 0 || (startIndex + length) > str.length()) { throw new StringIndexOutOfBoundsException("length must be valid"); } if (length > 0) { int len = length(); ensureCapacity(len + length); str.getChars(startIndex, startIndex + length, buffer, len); size += length; } return this; } /** * Appends a string buffer to this string builder. * Appending null will call {@link #appendNull()}. * * @param str the string buffer to append * @return this, to enable chaining */ public StrBuilder append(StringBuffer str) { if (str == null) { return appendNull(); } int strLen = str.length(); if (strLen > 0) { int len = length(); ensureCapacity(len + strLen); str.getChars(0, strLen, buffer, len); size += strLen; } return this; } /** * Appends part of a string buffer to this string builder. * Appending null will call {@link #appendNull()}. * * @param str the string to append * @param startIndex the start index, inclusive, must be valid * @param length the length to append, must be valid * @return this, to enable chaining */ public StrBuilder append(StringBuffer str, int startIndex, int length) { if (str == null) { return appendNull(); } if (startIndex < 0 || startIndex > str.length()) { throw new StringIndexOutOfBoundsException("startIndex must be valid"); } if (length < 0 || (startIndex + length) > str.length()) { throw new StringIndexOutOfBoundsException("length must be valid"); } if (length > 0) { int len = length(); ensureCapacity(len + length); str.getChars(startIndex, startIndex + length, buffer, len); size += length; } return this; } /** * Appends another string builder to this string builder. * Appending null will call {@link #appendNull()}. * * @param str the string builder to append * @return this, to enable chaining */ public StrBuilder append(StrBuilder str) { if (str == null) { return appendNull(); } int strLen = str.length(); if (strLen > 0) { int len = length(); ensureCapacity(len + strLen); System.arraycopy(str.buffer, 0, buffer, len, strLen); size += strLen; } return this; } /** * Appends part of a string builder to this string builder. * Appending null will call {@link #appendNull()}. * * @param str the string to append * @param startIndex the start index, inclusive, must be valid * @param length the length to append, must be valid * @return this, to enable chaining */ public StrBuilder append(StrBuilder str, int startIndex, int length) { if (str == null) { return appendNull(); } if (startIndex < 0 || startIndex > str.length()) { throw new StringIndexOutOfBoundsException("startIndex must be valid"); } if (length < 0 || (startIndex + length) > str.length()) { throw new StringIndexOutOfBoundsException("length must be valid"); } if (length > 0) { int len = length(); ensureCapacity(len + length); str.getChars(startIndex, startIndex + length, buffer, len); size += length; } return this; } /** * Appends a char array to the string builder. * Appending null will call {@link #appendNull()}. * * @param chars the char array to append * @return this, to enable chaining */ public StrBuilder append(char[] chars) { if (chars == null) { return appendNull(); } int strLen = chars.length; if (strLen > 0) { int len = length(); ensureCapacity(len + strLen); System.arraycopy(chars, 0, buffer, len, strLen); size += strLen; } return this; } /** * Appends a char array to the string builder. * Appending null will call {@link #appendNull()}. * * @param chars the char array to append * @param startIndex the start index, inclusive, must be valid * @param length the length to append, must be valid * @return this, to enable chaining */ public StrBuilder append(char[] chars, int startIndex, int length) { if (chars == null) { return appendNull(); } if (startIndex < 0 || startIndex > chars.length) { throw new StringIndexOutOfBoundsException("Invalid startIndex: " + length); } if (length < 0 || (startIndex + length) > chars.length) { throw new StringIndexOutOfBoundsException("Invalid length: " + length); } if (length > 0) { int len = length(); ensureCapacity(len + length); System.arraycopy(chars, startIndex, buffer, len, length); size += length; } return this; } /** * Appends a boolean value to the string builder. * * @param value the value to append * @return this, to enable chaining */ public StrBuilder append(boolean value) { if (value) { ensureCapacity(size + 4); buffer[size++] = 't'; buffer[size++] = 'r'; buffer[size++] = 'u'; buffer[size++] = 'e'; } else { ensureCapacity(size + 5); buffer[size++] = 'f'; buffer[size++] = 'a'; buffer[size++] = 'l'; buffer[size++] = 's'; buffer[size++] = 'e'; } return this; } /** * Appends a char value to the string builder. * * @param ch the value to append * @return this, to enable chaining */ public StrBuilder append(char ch) { int len = length(); ensureCapacity(len + 1); buffer[size++] = ch; return this; } /** * Appends an int value to the string builder using String.valueOf. * * @param value the value to append * @return this, to enable chaining */ public StrBuilder append(int value) { return append(String.valueOf(value)); } /** * Appends a long value to the string builder using String.valueOf. * * @param value the value to append * @return this, to enable chaining */ public StrBuilder append(long value) { return append(String.valueOf(value)); } /** * Appends a float value to the string builder using String.valueOf. * * @param value the value to append * @return this, to enable chaining */ public StrBuilder append(float value) { return append(String.valueOf(value)); } /** * Appends a double value to the string builder using String.valueOf. * * @param value the value to append * @return this, to enable chaining */ public StrBuilder append(double value) { return append(String.valueOf(value)); } //----------------------------------------------------------------------- /** * Appends an object followed by a new line to this string builder. * Appending null will call {@link #appendNull()}. * * @param obj the object to append * @return this, to enable chaining * @since 2.3 */ public StrBuilder appendln(Object obj) { return append(obj).appendNewLine(); } /** * Appends a string followed by a new line to this string builder. * Appending null will call {@link #appendNull()}. * * @param str the string to append * @return this, to enable chaining * @since 2.3 */ public StrBuilder appendln(String str) { return append(str).appendNewLine(); } /** * Appends part of a string followed by a new line to this string builder. * Appending null will call {@link #appendNull()}. * * @param str the string to append * @param startIndex the start index, inclusive, must be valid * @param length the length to append, must be valid * @return this, to enable chaining * @since 2.3 */ public StrBuilder appendln(String str, int startIndex, int length) { return append(str, startIndex, length).appendNewLine(); } /** * Appends a string buffer followed by a new line to this string builder. * Appending null will call {@link #appendNull()}. * * @param str the string buffer to append * @return this, to enable chaining * @since 2.3 */ public StrBuilder appendln(StringBuffer str) { return append(str).appendNewLine(); } /** * Appends part of a string buffer followed by a new line to this string builder. * Appending null will call {@link #appendNull()}. * * @param str the string to append * @param startIndex the start index, inclusive, must be valid * @param length the length to append, must be valid * @return this, to enable chaining * @since 2.3 */ public StrBuilder appendln(StringBuffer str, int startIndex, int length) { return append(str, startIndex, length).appendNewLine(); } /** * Appends another string builder followed by a new line to this string builder. * Appending null will call {@link #appendNull()}. * * @param str the string builder to append * @return this, to enable chaining * @since 2.3 */ public StrBuilder appendln(StrBuilder str) { return append(str).appendNewLine(); } /** * Appends part of a string builder followed by a new line to this string builder. * Appending null will call {@link #appendNull()}. * * @param str the string to append * @param startIndex the start index, inclusive, must be valid * @param length the length to append, must be valid * @return this, to enable chaining * @since 2.3 */ public StrBuilder appendln(StrBuilder str, int startIndex, int length) { return append(str, startIndex, length).appendNewLine(); } /** * Appends a char array followed by a new line to the string builder. * Appending null will call {@link #appendNull()}. * * @param chars the char array to append * @return this, to enable chaining * @since 2.3 */ public StrBuilder appendln(char[] chars) { return append(chars).appendNewLine(); } /** * Appends a char array followed by a new line to the string builder. * Appending null will call {@link #appendNull()}. * * @param chars the char array to append * @param startIndex the start index, inclusive, must be valid * @param length the length to append, must be valid * @return this, to enable chaining * @since 2.3 */ public StrBuilder appendln(char[] chars, int startIndex, int length) { return append(chars, startIndex, length).appendNewLine(); } /** * Appends a boolean value followed by a new line to the string builder. * * @param value the value to append * @return this, to enable chaining * @since 2.3 */ public StrBuilder appendln(boolean value) { return append(value).appendNewLine(); } /** * Appends a char value followed by a new line to the string builder. * * @param ch the value to append * @return this, to enable chaining * @since 2.3 */ public StrBuilder appendln(char ch) { return append(ch).appendNewLine(); } /** * Appends an int value followed by a new line to the string builder using String.valueOf. * * @param value the value to append * @return this, to enable chaining * @since 2.3 */ public StrBuilder appendln(int value) { return append(value).appendNewLine(); } /** * Appends a long value followed by a new line to the string builder using String.valueOf. * * @param value the value to append * @return this, to enable chaining * @since 2.3 */ public StrBuilder appendln(long value) { return append(value).appendNewLine(); } /** * Appends a float value followed by a new line to the string builder using String.valueOf. * * @param value the value to append * @return this, to enable chaining * @since 2.3 */ public StrBuilder appendln(float value) { return append(value).appendNewLine(); } /** * Appends a double value followed by a new line to the string builder using String.valueOf. * * @param value the value to append * @return this, to enable chaining * @since 2.3 */ public StrBuilder appendln(double value) { return append(value).appendNewLine(); } //----------------------------------------------------------------------- /** * Appends each item in an array to the builder without any separators. * Appending a null array will have no effect. * Each object is appended using {@link #append(Object)}. * * @param array the array to append * @return this, to enable chaining * @since 2.3 */ public StrBuilder appendAll(Object[] array) { if (array != null && array.length > 0) { for (int i = 0; i < array.length; i++) { append(array[i]); } } return this; } /** * Appends each item in a collection to the builder without any separators. * Appending a null collection will have no effect. * Each object is appended using {@link #append(Object)}. * * @param coll the collection to append * @return this, to enable chaining * @since 2.3 */ public StrBuilder appendAll(Collection coll) { if (coll != null && coll.size() > 0) { Iterator it = coll.iterator(); while (it.hasNext()) { append(it.next()); } } return this; } /** * Appends each item in an iterator to the builder without any separators. * Appending a null iterator will have no effect. * Each object is appended using {@link #append(Object)}. * * @param it the iterator to append * @return this, to enable chaining * @since 2.3 */ public StrBuilder appendAll(Iterator it) { if (it != null) { while (it.hasNext()) { append(it.next()); } } return this; } //----------------------------------------------------------------------- /** * Appends an array placing separators between each value, but * not before the first or after the last. * Appending a null array will have no effect. * Each object is appended using {@link #append(Object)}. * * @param array the array to append * @param separator the separator to use, null means no separator * @return this, to enable chaining */ public StrBuilder appendWithSeparators(Object[] array, String separator) { if (array != null && array.length > 0) { separator = (separator == null ? "" : separator); append(array[0]); for (int i = 1; i < array.length; i++) { append(separator); append(array[i]); } } return this; } /** * Appends a collection placing separators between each value, but * not before the first or after the last. * Appending a null collection will have no effect. * Each object is appended using {@link #append(Object)}. * * @param coll the collection to append * @param separator the separator to use, null means no separator * @return this, to enable chaining */ public StrBuilder appendWithSeparators(Collection coll, String separator) { if (coll != null && coll.size() > 0) { separator = (separator == null ? "" : separator); Iterator it = coll.iterator(); while (it.hasNext()) { append(it.next()); if (it.hasNext()) { append(separator); } } } return this; } /** * Appends an iterator placing separators between each value, but * not before the first or after the last. * Appending a null iterator will have no effect. * Each object is appended using {@link #append(Object)}. * * @param it the iterator to append * @param separator the separator to use, null means no separator * @return this, to enable chaining */ public StrBuilder appendWithSeparators(Iterator it, String separator) { if (it != null) { separator = (separator == null ? "" : separator); while (it.hasNext()) { append(it.next()); if (it.hasNext()) { append(separator); } } } return this; } //----------------------------------------------------------------------- /** * Appends a separator if the builder is currently non-empty. * Appending a null separator will have no effect. * The separator is appended using {@link #append(String)}. *

    * This method is useful for adding a separator each time around the * loop except the first. *

         * for (Iterator it = list.iterator(); it.hasNext(); ) {
         *   appendSeparator(",");
         *   append(it.next());
         * }
         * 
    * Note that for this simple example, you should use * {@link #appendWithSeparators(Collection, String)}. * * @param separator the separator to use, null means no separator * @return this, to enable chaining * @since 2.3 */ public StrBuilder appendSeparator(String separator) { return appendSeparator(separator, null); } /** * Appends one of both separators to the StrBuilder. * If the builder is currently empty it will append the defaultIfEmpty-separator * Otherwise it will append the standard-separator * * Appending a null separator will have no effect. * The separator is appended using {@link #append(String)}. *

    * This method is for example useful for constructing queries *

         * StrBuilder whereClause = new StrBuilder();
         * if(searchCommand.getPriority() != null) {
         *  whereClause.appendSeparator(" and", " where");
         *  whereClause.append(" priority = ?")
         * }
         * if(searchCommand.getComponent() != null) {
         *  whereClause.appendSeparator(" and", " where");
         *  whereClause.append(" component = ?")
         * }
         * selectClause.append(whereClause)
         * 
    * * @param standard the separator if builder is not empty, null means no separator * @param defaultIfEmpty the separator if builder is empty, null means no separator * @return this, to enable chaining * @since 2.5 */ public StrBuilder appendSeparator(String standard, String defaultIfEmpty) { String str = isEmpty() ? defaultIfEmpty : standard; if (str != null) { append(str); } return this; } /** * Appends a separator if the builder is currently non-empty. * The separator is appended using {@link #append(char)}. *

    * This method is useful for adding a separator each time around the * loop except the first. *

         * for (Iterator it = list.iterator(); it.hasNext(); ) {
         *   appendSeparator(',');
         *   append(it.next());
         * }
         * 
    * Note that for this simple example, you should use * {@link #appendWithSeparators(Collection, String)}. * * @param separator the separator to use * @return this, to enable chaining * @since 2.3 */ public StrBuilder appendSeparator(char separator) { if (size() > 0) { append(separator); } return this; } /** * Append one of both separators to the builder * If the builder is currently empty it will append the defaultIfEmpty-separator * Otherwise it will append the standard-separator * * The separator is appended using {@link #append(char)}. * @param standard the separator if builder is not empty * @param defaultIfEmpty the separator if builder is empty * @return this, to enable chaining * @since 2.5 */ public StrBuilder appendSeparator(char standard, char defaultIfEmpty) { if (size() > 0) { append(standard); } else { append(defaultIfEmpty); } return this; } /** * Appends a separator to the builder if the loop index is greater than zero. * Appending a null separator will have no effect. * The separator is appended using {@link #append(String)}. *

    * This method is useful for adding a separator each time around the * loop except the first. *

         * for (int i = 0; i < list.size(); i++) {
         *   appendSeparator(",", i);
         *   append(list.get(i));
         * }
         * 
    * Note that for this simple example, you should use * {@link #appendWithSeparators(Collection, String)}. * * @param separator the separator to use, null means no separator * @param loopIndex the loop index * @return this, to enable chaining * @since 2.3 */ public StrBuilder appendSeparator(String separator, int loopIndex) { if (separator != null && loopIndex > 0) { append(separator); } return this; } /** * Appends a separator to the builder if the loop index is greater than zero. * The separator is appended using {@link #append(char)}. *

    * This method is useful for adding a separator each time around the * loop except the first. *

         * for (int i = 0; i < list.size(); i++) {
         *   appendSeparator(",", i);
         *   append(list.get(i));
         * }
         * 
    * Note that for this simple example, you should use * {@link #appendWithSeparators(Collection, String)}. * * @param separator the separator to use * @param loopIndex the loop index * @return this, to enable chaining * @since 2.3 */ public StrBuilder appendSeparator(char separator, int loopIndex) { if (loopIndex > 0) { append(separator); } return this; } //----------------------------------------------------------------------- /** * Appends the pad character to the builder the specified number of times. * * @param length the length to append, negative means no append * @param padChar the character to append * @return this, to enable chaining */ public StrBuilder appendPadding(int length, char padChar) { if (length >= 0) { ensureCapacity(size + length); for (int i = 0; i < length; i++) { buffer[size++] = padChar; } } return this; } //----------------------------------------------------------------------- /** * Appends an object to the builder padding on the left to a fixed width. * The toString of the object is used. * If the object is larger than the length, the left hand side is lost. * If the object is null, the null text value is used. * * @param obj the object to append, null uses null text * @param width the fixed field width, zero or negative has no effect * @param padChar the pad character to use * @return this, to enable chaining */ public StrBuilder appendFixedWidthPadLeft(Object obj, int width, char padChar) { if (width > 0) { ensureCapacity(size + width); String str = (obj == null ? getNullText() : obj.toString()); if (str == null) { str = ""; } int strLen = str.length(); if (strLen >= width) { str.getChars(strLen - width, strLen, buffer, size); } else { int padLen = width - strLen; for (int i = 0; i < padLen; i++) { buffer[size + i] = padChar; } str.getChars(0, strLen, buffer, size + padLen); } size += width; } return this; } /** * Appends an object to the builder padding on the left to a fixed width. * The String.valueOf of the int value is used. * If the formatted value is larger than the length, the left hand side is lost. * * @param value the value to append * @param width the fixed field width, zero or negative has no effect * @param padChar the pad character to use * @return this, to enable chaining */ public StrBuilder appendFixedWidthPadLeft(int value, int width, char padChar) { return appendFixedWidthPadLeft(String.valueOf(value), width, padChar); } /** * Appends an object to the builder padding on the right to a fixed length. * The toString of the object is used. * If the object is larger than the length, the right hand side is lost. * If the object is null, null text value is used. * * @param obj the object to append, null uses null text * @param width the fixed field width, zero or negative has no effect * @param padChar the pad character to use * @return this, to enable chaining */ public StrBuilder appendFixedWidthPadRight(Object obj, int width, char padChar) { if (width > 0) { ensureCapacity(size + width); String str = (obj == null ? getNullText() : obj.toString()); if (str == null) { str = ""; } int strLen = str.length(); if (strLen >= width) { str.getChars(0, width, buffer, size); } else { int padLen = width - strLen; str.getChars(0, strLen, buffer, size); for (int i = 0; i < padLen; i++) { buffer[size + strLen + i] = padChar; } } size += width; } return this; } /** * Appends an object to the builder padding on the right to a fixed length. * The String.valueOf of the int value is used. * If the object is larger than the length, the right hand side is lost. * * @param value the value to append * @param width the fixed field width, zero or negative has no effect * @param padChar the pad character to use * @return this, to enable chaining */ public StrBuilder appendFixedWidthPadRight(int value, int width, char padChar) { return appendFixedWidthPadRight(String.valueOf(value), width, padChar); } //----------------------------------------------------------------------- /** * Inserts the string representation of an object into this builder. * Inserting null will use the stored null text value. * * @param index the index to add at, must be valid * @param obj the object to insert * @return this, to enable chaining * @throws IndexOutOfBoundsException if the index is invalid */ public StrBuilder insert(int index, Object obj) { if (obj == null) { return insert(index, nullText); } return insert(index, obj.toString()); } /** * Inserts the string into this builder. * Inserting null will use the stored null text value. * * @param index the index to add at, must be valid * @param str the string to insert * @return this, to enable chaining * @throws IndexOutOfBoundsException if the index is invalid */ public StrBuilder insert(int index, String str) { validateIndex(index); if (str == null) { str = nullText; } int strLen = (str == null ? 0 : str.length()); if (strLen > 0) { int newSize = size + strLen; ensureCapacity(newSize); System.arraycopy(buffer, index, buffer, index + strLen, size - index); size = newSize; str.getChars(0, strLen, buffer, index); // str cannot be null here } return this; } /** * Inserts the character array into this builder. * Inserting null will use the stored null text value. * * @param index the index to add at, must be valid * @param chars the char array to insert * @return this, to enable chaining * @throws IndexOutOfBoundsException if the index is invalid */ public StrBuilder insert(int index, char chars[]) { validateIndex(index); if (chars == null) { return insert(index, nullText); } int len = chars.length; if (len > 0) { ensureCapacity(size + len); System.arraycopy(buffer, index, buffer, index + len, size - index); System.arraycopy(chars, 0, buffer, index, len); size += len; } return this; } /** * Inserts part of the character array into this builder. * Inserting null will use the stored null text value. * * @param index the index to add at, must be valid * @param chars the char array to insert * @param offset the offset into the character array to start at, must be valid * @param length the length of the character array part to copy, must be positive * @return this, to enable chaining * @throws IndexOutOfBoundsException if any index is invalid */ public StrBuilder insert(int index, char chars[], int offset, int length) { validateIndex(index); if (chars == null) { return insert(index, nullText); } if (offset < 0 || offset > chars.length) { throw new StringIndexOutOfBoundsException("Invalid offset: " + offset); } if (length < 0 || offset + length > chars.length) { throw new StringIndexOutOfBoundsException("Invalid length: " + length); } if (length > 0) { ensureCapacity(size + length); System.arraycopy(buffer, index, buffer, index + length, size - index); System.arraycopy(chars, offset, buffer, index, length); size += length; } return this; } /** * Inserts the value into this builder. * * @param index the index to add at, must be valid * @param value the value to insert * @return this, to enable chaining * @throws IndexOutOfBoundsException if the index is invalid */ public StrBuilder insert(int index, boolean value) { validateIndex(index); if (value) { ensureCapacity(size + 4); System.arraycopy(buffer, index, buffer, index + 4, size - index); buffer[index++] = 't'; buffer[index++] = 'r'; buffer[index++] = 'u'; buffer[index] = 'e'; size += 4; } else { ensureCapacity(size + 5); System.arraycopy(buffer, index, buffer, index + 5, size - index); buffer[index++] = 'f'; buffer[index++] = 'a'; buffer[index++] = 'l'; buffer[index++] = 's'; buffer[index] = 'e'; size += 5; } return this; } /** * Inserts the value into this builder. * * @param index the index to add at, must be valid * @param value the value to insert * @return this, to enable chaining * @throws IndexOutOfBoundsException if the index is invalid */ public StrBuilder insert(int index, char value) { validateIndex(index); ensureCapacity(size + 1); System.arraycopy(buffer, index, buffer, index + 1, size - index); buffer[index] = value; size++; return this; } /** * Inserts the value into this builder. * * @param index the index to add at, must be valid * @param value the value to insert * @return this, to enable chaining * @throws IndexOutOfBoundsException if the index is invalid */ public StrBuilder insert(int index, int value) { return insert(index, String.valueOf(value)); } /** * Inserts the value into this builder. * * @param index the index to add at, must be valid * @param value the value to insert * @return this, to enable chaining * @throws IndexOutOfBoundsException if the index is invalid */ public StrBuilder insert(int index, long value) { return insert(index, String.valueOf(value)); } /** * Inserts the value into this builder. * * @param index the index to add at, must be valid * @param value the value to insert * @return this, to enable chaining * @throws IndexOutOfBoundsException if the index is invalid */ public StrBuilder insert(int index, float value) { return insert(index, String.valueOf(value)); } /** * Inserts the value into this builder. * * @param index the index to add at, must be valid * @param value the value to insert * @return this, to enable chaining * @throws IndexOutOfBoundsException if the index is invalid */ public StrBuilder insert(int index, double value) { return insert(index, String.valueOf(value)); } //----------------------------------------------------------------------- /** * Internal method to delete a range without validation. * * @param startIndex the start index, must be valid * @param endIndex the end index (exclusive), must be valid * @param len the length, must be valid * @throws IndexOutOfBoundsException if any index is invalid */ private void deleteImpl(int startIndex, int endIndex, int len) { System.arraycopy(buffer, endIndex, buffer, startIndex, size - endIndex); size -= len; } /** * Deletes the characters between the two specified indices. * * @param startIndex the start index, inclusive, must be valid * @param endIndex the end index, exclusive, must be valid except * that if too large it is treated as end of string * @return this, to enable chaining * @throws IndexOutOfBoundsException if the index is invalid */ public StrBuilder delete(int startIndex, int endIndex) { endIndex = validateRange(startIndex, endIndex); int len = endIndex - startIndex; if (len > 0) { deleteImpl(startIndex, endIndex, len); } return this; } //----------------------------------------------------------------------- /** * Deletes the character wherever it occurs in the builder. * * @param ch the character to delete * @return this, to enable chaining */ public StrBuilder deleteAll(char ch) { for (int i = 0; i < size; i++) { if (buffer[i] == ch) { int start = i; while (++i < size) { if (buffer[i] != ch) { break; } } int len = i - start; deleteImpl(start, i, len); i -= len; } } return this; } /** * Deletes the character wherever it occurs in the builder. * * @param ch the character to delete * @return this, to enable chaining */ public StrBuilder deleteFirst(char ch) { for (int i = 0; i < size; i++) { if (buffer[i] == ch) { deleteImpl(i, i + 1, 1); break; } } return this; } //----------------------------------------------------------------------- /** * Deletes the string wherever it occurs in the builder. * * @param str the string to delete, null causes no action * @return this, to enable chaining */ public StrBuilder deleteAll(String str) { int len = (str == null ? 0 : str.length()); if (len > 0) { int index = indexOf(str, 0); while (index >= 0) { deleteImpl(index, index + len, len); index = indexOf(str, index); } } return this; } /** * Deletes the string wherever it occurs in the builder. * * @param str the string to delete, null causes no action * @return this, to enable chaining */ public StrBuilder deleteFirst(String str) { int len = (str == null ? 0 : str.length()); if (len > 0) { int index = indexOf(str, 0); if (index >= 0) { deleteImpl(index, index + len, len); } } return this; } //----------------------------------------------------------------------- /** * Deletes all parts of the builder that the matcher matches. *

    * Matchers can be used to perform advanced deletion behaviour. * For example you could write a matcher to delete all occurances * where the character 'a' is followed by a number. * * @param matcher the matcher to use to find the deletion, null causes no action * @return this, to enable chaining */ public StrBuilder deleteAll(StrMatcher matcher) { return replace(matcher, null, 0, size, -1); } /** * Deletes the first match within the builder using the specified matcher. *

    * Matchers can be used to perform advanced deletion behaviour. * For example you could write a matcher to delete * where the character 'a' is followed by a number. * * @param matcher the matcher to use to find the deletion, null causes no action * @return this, to enable chaining */ public StrBuilder deleteFirst(StrMatcher matcher) { return replace(matcher, null, 0, size, 1); } //----------------------------------------------------------------------- /** * Internal method to delete a range without validation. * * @param startIndex the start index, must be valid * @param endIndex the end index (exclusive), must be valid * @param removeLen the length to remove (endIndex - startIndex), must be valid * @param insertStr the string to replace with, null means delete range * @param insertLen the length of the insert string, must be valid * @throws IndexOutOfBoundsException if any index is invalid */ private void replaceImpl(int startIndex, int endIndex, int removeLen, String insertStr, int insertLen) { int newSize = size - removeLen + insertLen; if (insertLen != removeLen) { ensureCapacity(newSize); System.arraycopy(buffer, endIndex, buffer, startIndex + insertLen, size - endIndex); size = newSize; } if (insertLen > 0) { insertStr.getChars(0, insertLen, buffer, startIndex); } } /** * Replaces a portion of the string builder with another string. * The length of the inserted string does not have to match the removed length. * * @param startIndex the start index, inclusive, must be valid * @param endIndex the end index, exclusive, must be valid except * that if too large it is treated as end of string * @param replaceStr the string to replace with, null means delete range * @return this, to enable chaining * @throws IndexOutOfBoundsException if the index is invalid */ public StrBuilder replace(int startIndex, int endIndex, String replaceStr) { endIndex = validateRange(startIndex, endIndex); int insertLen = (replaceStr == null ? 0 : replaceStr.length()); replaceImpl(startIndex, endIndex, endIndex - startIndex, replaceStr, insertLen); return this; } //----------------------------------------------------------------------- /** * Replaces the search character with the replace character * throughout the builder. * * @param search the search character * @param replace the replace character * @return this, to enable chaining */ public StrBuilder replaceAll(char search, char replace) { if (search != replace) { for (int i = 0; i < size; i++) { if (buffer[i] == search) { buffer[i] = replace; } } } return this; } /** * Replaces the first instance of the search character with the * replace character in the builder. * * @param search the search character * @param replace the replace character * @return this, to enable chaining */ public StrBuilder replaceFirst(char search, char replace) { if (search != replace) { for (int i = 0; i < size; i++) { if (buffer[i] == search) { buffer[i] = replace; break; } } } return this; } //----------------------------------------------------------------------- /** * Replaces the search string with the replace string throughout the builder. * * @param searchStr the search string, null causes no action to occur * @param replaceStr the replace string, null is equivalent to an empty string * @return this, to enable chaining */ public StrBuilder replaceAll(String searchStr, String replaceStr) { int searchLen = (searchStr == null ? 0 : searchStr.length()); if (searchLen > 0) { int replaceLen = (replaceStr == null ? 0 : replaceStr.length()); int index = indexOf(searchStr, 0); while (index >= 0) { replaceImpl(index, index + searchLen, searchLen, replaceStr, replaceLen); index = indexOf(searchStr, index + replaceLen); } } return this; } /** * Replaces the first instance of the search string with the replace string. * * @param searchStr the search string, null causes no action to occur * @param replaceStr the replace string, null is equivalent to an empty string * @return this, to enable chaining */ public StrBuilder replaceFirst(String searchStr, String replaceStr) { int searchLen = (searchStr == null ? 0 : searchStr.length()); if (searchLen > 0) { int index = indexOf(searchStr, 0); if (index >= 0) { int replaceLen = (replaceStr == null ? 0 : replaceStr.length()); replaceImpl(index, index + searchLen, searchLen, replaceStr, replaceLen); } } return this; } //----------------------------------------------------------------------- /** * Replaces all matches within the builder with the replace string. *

    * Matchers can be used to perform advanced replace behaviour. * For example you could write a matcher to replace all occurances * where the character 'a' is followed by a number. * * @param matcher the matcher to use to find the deletion, null causes no action * @param replaceStr the replace string, null is equivalent to an empty string * @return this, to enable chaining */ public StrBuilder replaceAll(StrMatcher matcher, String replaceStr) { return replace(matcher, replaceStr, 0, size, -1); } /** * Replaces the first match within the builder with the replace string. *

    * Matchers can be used to perform advanced replace behaviour. * For example you could write a matcher to replace * where the character 'a' is followed by a number. * * @param matcher the matcher to use to find the deletion, null causes no action * @param replaceStr the replace string, null is equivalent to an empty string * @return this, to enable chaining */ public StrBuilder replaceFirst(StrMatcher matcher, String replaceStr) { return replace(matcher, replaceStr, 0, size, 1); } // ----------------------------------------------------------------------- /** * Advanced search and replaces within the builder using a matcher. *

    * Matchers can be used to perform advanced behaviour. * For example you could write a matcher to delete all occurances * where the character 'a' is followed by a number. * * @param matcher the matcher to use to find the deletion, null causes no action * @param replaceStr the string to replace the match with, null is a delete * @param startIndex the start index, inclusive, must be valid * @param endIndex the end index, exclusive, must be valid except * that if too large it is treated as end of string * @param replaceCount the number of times to replace, -1 for replace all * @return this, to enable chaining * @throws IndexOutOfBoundsException if start index is invalid */ public StrBuilder replace( StrMatcher matcher, String replaceStr, int startIndex, int endIndex, int replaceCount) { endIndex = validateRange(startIndex, endIndex); return replaceImpl(matcher, replaceStr, startIndex, endIndex, replaceCount); } /** * Replaces within the builder using a matcher. *

    * Matchers can be used to perform advanced behaviour. * For example you could write a matcher to delete all occurances * where the character 'a' is followed by a number. * * @param matcher the matcher to use to find the deletion, null causes no action * @param replaceStr the string to replace the match with, null is a delete * @param from the start index, must be valid * @param to the end index (exclusive), must be valid * @param replaceCount the number of times to replace, -1 for replace all * @return this, to enable chaining * @throws IndexOutOfBoundsException if any index is invalid */ private StrBuilder replaceImpl( StrMatcher matcher, String replaceStr, int from, int to, int replaceCount) { if (matcher == null || size == 0) { return this; } int replaceLen = (replaceStr == null ? 0 : replaceStr.length()); char[] buf = buffer; for (int i = from; i < to && replaceCount != 0; i++) { int removeLen = matcher.isMatch(buf, i, from, to); if (removeLen > 0) { replaceImpl(i, i + removeLen, removeLen, replaceStr, replaceLen); to = to - removeLen + replaceLen; i = i + replaceLen - 1; if (replaceCount > 0) { replaceCount--; } } } return this; } //----------------------------------------------------------------------- /** * Reverses the string builder placing each character in the opposite index. * * @return this, to enable chaining */ public StrBuilder reverse() { if (size == 0) { return this; } int half = size / 2; char[] buf = buffer; for (int leftIdx = 0, rightIdx = size - 1; leftIdx < half; leftIdx++,rightIdx--) { char swap = buf[leftIdx]; buf[leftIdx] = buf[rightIdx]; buf[rightIdx] = swap; } return this; } //----------------------------------------------------------------------- /** * Trims the builder by removing characters less than or equal to a space * from the beginning and end. * * @return this, to enable chaining */ public StrBuilder trim() { if (size == 0) { return this; } int len = size; char[] buf = buffer; int pos = 0; while (pos < len && buf[pos] <= ' ') { pos++; } while (pos < len && buf[len - 1] <= ' ') { len--; } if (len < size) { delete(len, size); } if (pos > 0) { delete(0, pos); } return this; } //----------------------------------------------------------------------- /** * Checks whether this builder starts with the specified string. *

    * Note that this method handles null input quietly, unlike String. * * @param str the string to search for, null returns false * @return true if the builder starts with the string */ public boolean startsWith(String str) { if (str == null) { return false; } int len = str.length(); if (len == 0) { return true; } if (len > size) { return false; } for (int i = 0; i < len; i++) { if (buffer[i] != str.charAt(i)) { return false; } } return true; } /** * Checks whether this builder ends with the specified string. *

    * Note that this method handles null input quietly, unlike String. * * @param str the string to search for, null returns false * @return true if the builder ends with the string */ public boolean endsWith(String str) { if (str == null) { return false; } int len = str.length(); if (len == 0) { return true; } if (len > size) { return false; } int pos = size - len; for (int i = 0; i < len; i++,pos++) { if (buffer[pos] != str.charAt(i)) { return false; } } return true; } //----------------------------------------------------------------------- /** * Extracts a portion of this string builder as a string. * * @param start the start index, inclusive, must be valid * @return the new string * @throws IndexOutOfBoundsException if the index is invalid */ public String substring(int start) { return substring(start, size); } /** * Extracts a portion of this string builder as a string. *

    * Note: This method treats an endIndex greater than the length of the * builder as equal to the length of the builder, and continues * without error, unlike StringBuffer or String. * * @param startIndex the start index, inclusive, must be valid * @param endIndex the end index, exclusive, must be valid except * that if too large it is treated as end of string * @return the new string * @throws IndexOutOfBoundsException if the index is invalid */ public String substring(int startIndex, int endIndex) { endIndex = validateRange(startIndex, endIndex); return new String(buffer, startIndex, endIndex - startIndex); } /** * Extracts the leftmost characters from the string builder without * throwing an exception. *

    * This method extracts the left length characters from * the builder. If this many characters are not available, the whole * builder is returned. Thus the returned string may be shorter than the * length requested. * * @param length the number of characters to extract, negative returns empty string * @return the new string */ public String leftString(int length) { if (length <= 0) { return ""; } else if (length >= size) { return new String(buffer, 0, size); } else { return new String(buffer, 0, length); } } /** * Extracts the rightmost characters from the string builder without * throwing an exception. *

    * This method extracts the right length characters from * the builder. If this many characters are not available, the whole * builder is returned. Thus the returned string may be shorter than the * length requested. * * @param length the number of characters to extract, negative returns empty string * @return the new string */ public String rightString(int length) { if (length <= 0) { return ""; } else if (length >= size) { return new String(buffer, 0, size); } else { return new String(buffer, size - length, length); } } /** * Extracts some characters from the middle of the string builder without * throwing an exception. *

    * This method extracts length characters from the builder * at the specified index. * If the index is negative it is treated as zero. * If the index is greater than the builder size, it is treated as the builder size. * If the length is negative, the empty string is returned. * If insufficient characters are available in the builder, as much as possible is returned. * Thus the returned string may be shorter than the length requested. * * @param index the index to start at, negative means zero * @param length the number of characters to extract, negative returns empty string * @return the new string */ public String midString(int index, int length) { if (index < 0) { index = 0; } if (length <= 0 || index >= size) { return ""; } if (size <= index + length) { return new String(buffer, index, size - index); } else { return new String(buffer, index, length); } } //----------------------------------------------------------------------- /** * Checks if the string builder contains the specified char. * * @param ch the character to find * @return true if the builder contains the character */ public boolean contains(char ch) { char[] thisBuf = buffer; for (int i = 0; i < this.size; i++) { if (thisBuf[i] == ch) { return true; } } return false; } /** * Checks if the string builder contains the specified string. * * @param str the string to find * @return true if the builder contains the string */ public boolean contains(String str) { return indexOf(str, 0) >= 0; } /** * Checks if the string builder contains a string matched using the * specified matcher. *

    * Matchers can be used to perform advanced searching behaviour. * For example you could write a matcher to search for the character * 'a' followed by a number. * * @param matcher the matcher to use, null returns -1 * @return true if the matcher finds a match in the builder */ public boolean contains(StrMatcher matcher) { return indexOf(matcher, 0) >= 0; } //----------------------------------------------------------------------- /** * Searches the string builder to find the first reference to the specified char. * * @param ch the character to find * @return the first index of the character, or -1 if not found */ public int indexOf(char ch) { return indexOf(ch, 0); } /** * Searches the string builder to find the first reference to the specified char. * * @param ch the character to find * @param startIndex the index to start at, invalid index rounded to edge * @return the first index of the character, or -1 if not found */ public int indexOf(char ch, int startIndex) { startIndex = (startIndex < 0 ? 0 : startIndex); if (startIndex >= size) { return -1; } char[] thisBuf = buffer; for (int i = startIndex; i < size; i++) { if (thisBuf[i] == ch) { return i; } } return -1; } /** * Searches the string builder to find the first reference to the specified string. *

    * Note that a null input string will return -1, whereas the JDK throws an exception. * * @param str the string to find, null returns -1 * @return the first index of the string, or -1 if not found */ public int indexOf(String str) { return indexOf(str, 0); } /** * Searches the string builder to find the first reference to the specified * string starting searching from the given index. *

    * Note that a null input string will return -1, whereas the JDK throws an exception. * * @param str the string to find, null returns -1 * @param startIndex the index to start at, invalid index rounded to edge * @return the first index of the string, or -1 if not found */ public int indexOf(String str, int startIndex) { startIndex = (startIndex < 0 ? 0 : startIndex); if (str == null || startIndex >= size) { return -1; } int strLen = str.length(); if (strLen == 1) { return indexOf(str.charAt(0), startIndex); } if (strLen == 0) { return startIndex; } if (strLen > size) { return -1; } char[] thisBuf = buffer; int len = size - strLen + 1; outer: for (int i = startIndex; i < len; i++) { for (int j = 0; j < strLen; j++) { if (str.charAt(j) != thisBuf[i + j]) { continue outer; } } return i; } return -1; } /** * Searches the string builder using the matcher to find the first match. *

    * Matchers can be used to perform advanced searching behaviour. * For example you could write a matcher to find the character 'a' * followed by a number. * * @param matcher the matcher to use, null returns -1 * @return the first index matched, or -1 if not found */ public int indexOf(StrMatcher matcher) { return indexOf(matcher, 0); } /** * Searches the string builder using the matcher to find the first * match searching from the given index. *

    * Matchers can be used to perform advanced searching behaviour. * For example you could write a matcher to find the character 'a' * followed by a number. * * @param matcher the matcher to use, null returns -1 * @param startIndex the index to start at, invalid index rounded to edge * @return the first index matched, or -1 if not found */ public int indexOf(StrMatcher matcher, int startIndex) { startIndex = (startIndex < 0 ? 0 : startIndex); if (matcher == null || startIndex >= size) { return -1; } int len = size; char[] buf = buffer; for (int i = startIndex; i < len; i++) { if (matcher.isMatch(buf, i, startIndex, len) > 0) { return i; } } return -1; } //----------------------------------------------------------------------- /** * Searches the string builder to find the last reference to the specified char. * * @param ch the character to find * @return the last index of the character, or -1 if not found */ public int lastIndexOf(char ch) { return lastIndexOf(ch, size - 1); } /** * Searches the string builder to find the last reference to the specified char. * * @param ch the character to find * @param startIndex the index to start at, invalid index rounded to edge * @return the last index of the character, or -1 if not found */ public int lastIndexOf(char ch, int startIndex) { startIndex = (startIndex >= size ? size - 1 : startIndex); if (startIndex < 0) { return -1; } for (int i = startIndex; i >= 0; i--) { if (buffer[i] == ch) { return i; } } return -1; } /** * Searches the string builder to find the last reference to the specified string. *

    * Note that a null input string will return -1, whereas the JDK throws an exception. * * @param str the string to find, null returns -1 * @return the last index of the string, or -1 if not found */ public int lastIndexOf(String str) { return lastIndexOf(str, size - 1); } /** * Searches the string builder to find the last reference to the specified * string starting searching from the given index. *

    * Note that a null input string will return -1, whereas the JDK throws an exception. * * @param str the string to find, null returns -1 * @param startIndex the index to start at, invalid index rounded to edge * @return the last index of the string, or -1 if not found */ public int lastIndexOf(String str, int startIndex) { startIndex = (startIndex >= size ? size - 1 : startIndex); if (str == null || startIndex < 0) { return -1; } int strLen = str.length(); if (strLen > 0 && strLen <= size) { if (strLen == 1) { return lastIndexOf(str.charAt(0), startIndex); } outer: for (int i = startIndex - strLen + 1; i >= 0; i--) { for (int j = 0; j < strLen; j++) { if (str.charAt(j) != buffer[i + j]) { continue outer; } } return i; } } else if (strLen == 0) { return startIndex; } return -1; } /** * Searches the string builder using the matcher to find the last match. *

    * Matchers can be used to perform advanced searching behaviour. * For example you could write a matcher to find the character 'a' * followed by a number. * * @param matcher the matcher to use, null returns -1 * @return the last index matched, or -1 if not found */ public int lastIndexOf(StrMatcher matcher) { return lastIndexOf(matcher, size); } /** * Searches the string builder using the matcher to find the last * match searching from the given index. *

    * Matchers can be used to perform advanced searching behaviour. * For example you could write a matcher to find the character 'a' * followed by a number. * * @param matcher the matcher to use, null returns -1 * @param startIndex the index to start at, invalid index rounded to edge * @return the last index matched, or -1 if not found */ public int lastIndexOf(StrMatcher matcher, int startIndex) { startIndex = (startIndex >= size ? size - 1 : startIndex); if (matcher == null || startIndex < 0) { return -1; } char[] buf = buffer; int endIndex = startIndex + 1; for (int i = startIndex; i >= 0; i--) { if (matcher.isMatch(buf, i, 0, endIndex) > 0) { return i; } } return -1; } //----------------------------------------------------------------------- /** * Creates a tokenizer that can tokenize the contents of this builder. *

    * This method allows the contents of this builder to be tokenized. * The tokenizer will be setup by default to tokenize on space, tab, * newline and formfeed (as per StringTokenizer). These values can be * changed on the tokenizer class, before retrieving the tokens. *

    * The returned tokenizer is linked to this builder. You may intermix * calls to the buider and tokenizer within certain limits, however * there is no synchronization. Once the tokenizer has been used once, * it must be {@link StrTokenizer#reset() reset} to pickup the latest * changes in the builder. For example: *

         * StrBuilder b = new StrBuilder();
         * b.append("a b ");
         * StrTokenizer t = b.asTokenizer();
         * String[] tokens1 = t.getTokenArray();  // returns a,b
         * b.append("c d ");
         * String[] tokens2 = t.getTokenArray();  // returns a,b (c and d ignored)
         * t.reset();              // reset causes builder changes to be picked up
         * String[] tokens3 = t.getTokenArray();  // returns a,b,c,d
         * 
    * In addition to simply intermixing appends and tokenization, you can also * call the set methods on the tokenizer to alter how it tokenizes. Just * remember to call reset when you want to pickup builder changes. *

    * Calling {@link StrTokenizer#reset(String)} or {@link StrTokenizer#reset(char[])} * with a non-null value will break the link with the builder. * * @return a tokenizer that is linked to this builder */ public StrTokenizer asTokenizer() { return new StrBuilderTokenizer(); } //----------------------------------------------------------------------- /** * Gets the contents of this builder as a Reader. *

    * This method allows the contents of the builder to be read * using any standard method that expects a Reader. *

    * To use, simply create a StrBuilder, populate it with * data, call asReader, and then read away. *

    * The internal character array is shared between the builder and the reader. * This allows you to append to the builder after creating the reader, * and the changes will be picked up. * Note however, that no synchronization occurs, so you must perform * all operations with the builder and the reader in one thread. *

    * The returned reader supports marking, and ignores the flush method. * * @return a reader that reads from this builder */ public Reader asReader() { return new StrBuilderReader(); } //----------------------------------------------------------------------- /** * Gets this builder as a Writer that can be written to. *

    * This method allows you to populate the contents of the builder * using any standard method that takes a Writer. *

    * To use, simply create a StrBuilder, * call asWriter, and populate away. The data is available * at any time using the methods of the StrBuilder. *

    * The internal character array is shared between the builder and the writer. * This allows you to intermix calls that append to the builder and * write using the writer and the changes will be occur correctly. * Note however, that no synchronization occurs, so you must perform * all operations with the builder and the writer in one thread. *

    * The returned writer ignores the close and flush methods. * * @return a writer that populates this builder */ public Writer asWriter() { return new StrBuilderWriter(); } //----------------------------------------------------------------------- // /** // * Gets a String version of the string builder by calling the internal // * constructor of String by reflection. // *

    // * WARNING: You must not use the StrBuilder after calling this method // * as the buffer is now shared with the String object. To ensure this, // * the internal character array is set to null, so you will get // * NullPointerExceptions on all method calls. // * // * @return the builder as a String // */ // public String toSharedString() { // try { // Constructor con = String.class.getDeclaredConstructor( // new Class[] {int.class, int.class, char[].class}); // con.setAccessible(true); // char[] buffer = buf; // buf = null; // size = -1; // nullText = null; // return (String) con.newInstance( // new Object[] {new Integer(0), new Integer(size), buffer}); // // } catch (Exception ex) { // ex.printStackTrace(); // throw new UnsupportedOperationException("StrBuilder.toSharedString is unsupported: " + ex.getMessage()); // } // } //----------------------------------------------------------------------- /** * Checks the contents of this builder against another to see if they * contain the same character content ignoring case. * * @param other the object to check, null returns false * @return true if the builders contain the same characters in the same order */ public boolean equalsIgnoreCase(StrBuilder other) { if (this == other) { return true; } if (this.size != other.size) { return false; } char thisBuf[] = this.buffer; char otherBuf[] = other.buffer; for (int i = size - 1; i >= 0; i--) { char c1 = thisBuf[i]; char c2 = otherBuf[i]; if (c1 != c2 && Character.toUpperCase(c1) != Character.toUpperCase(c2)) { return false; } } return true; } /** * Checks the contents of this builder against another to see if they * contain the same character content. * * @param other the object to check, null returns false * @return true if the builders contain the same characters in the same order */ public boolean equals(StrBuilder other) { if (this == other) { return true; } if (this.size != other.size) { return false; } char thisBuf[] = this.buffer; char otherBuf[] = other.buffer; for (int i = size - 1; i >= 0; i--) { if (thisBuf[i] != otherBuf[i]) { return false; } } return true; } /** * Checks the contents of this builder against another to see if they * contain the same character content. * * @param obj the object to check, null returns false * @return true if the builders contain the same characters in the same order */ public boolean equals(Object obj) { if (obj instanceof StrBuilder) { return equals((StrBuilder) obj); } return false; } /** * Gets a suitable hash code for this builder. * * @return a hash code */ public int hashCode() { char buf[] = buffer; int hash = 0; for (int i = size - 1; i >= 0; i--) { hash = 31 * hash + buf[i]; } return hash; } //----------------------------------------------------------------------- /** * Gets a String version of the string builder, creating a new instance * each time the method is called. *

    * Note that unlike StringBuffer, the string version returned is * independent of the string builder. * * @return the builder as a String */ public String toString() { return new String(buffer, 0, size); } /** * Gets a StringBuffer version of the string builder, creating a * new instance each time the method is called. * * @return the builder as a StringBuffer */ public StringBuffer toStringBuffer() { return new StringBuffer(size).append(buffer, 0, size); } /** * Clone this object. * * @return a clone of this object * @throws CloneNotSupportedException if clone is not supported * @since 2.6 */ public Object clone() throws CloneNotSupportedException { StrBuilder clone = (StrBuilder)super.clone(); clone.buffer = new char[buffer.length]; System.arraycopy(buffer, 0, clone.buffer, 0, buffer.length); return clone; } //----------------------------------------------------------------------- /** * Validates parameters defining a range of the builder. * * @param startIndex the start index, inclusive, must be valid * @param endIndex the end index, exclusive, must be valid except * that if too large it is treated as end of string * @return the new string * @throws IndexOutOfBoundsException if the index is invalid */ protected int validateRange(int startIndex, int endIndex) { if (startIndex < 0) { throw new StringIndexOutOfBoundsException(startIndex); } if (endIndex > size) { endIndex = size; } if (startIndex > endIndex) { throw new StringIndexOutOfBoundsException("end < start"); } return endIndex; } /** * Validates parameters defining a single index in the builder. * * @param index the index, must be valid * @throws IndexOutOfBoundsException if the index is invalid */ protected void validateIndex(int index) { if (index < 0 || index > size) { throw new StringIndexOutOfBoundsException(index); } } //----------------------------------------------------------------------- /** * Inner class to allow StrBuilder to operate as a tokenizer. */ class StrBuilderTokenizer extends StrTokenizer { /** * Default constructor. */ StrBuilderTokenizer() { super(); } /** {@inheritDoc} */ protected List tokenize(char[] chars, int offset, int count) { if (chars == null) { return super.tokenize(StrBuilder.this.buffer, 0, StrBuilder.this.size()); } else { return super.tokenize(chars, offset, count); } } /** {@inheritDoc} */ public String getContent() { String str = super.getContent(); if (str == null) { return StrBuilder.this.toString(); } else { return str; } } } //----------------------------------------------------------------------- /** * Inner class to allow StrBuilder to operate as a writer. */ class StrBuilderReader extends Reader { /** The current stream position. */ private int pos; /** The last mark position. */ private int mark; /** * Default constructor. */ StrBuilderReader() { super(); } /** {@inheritDoc} */ public void close() { // do nothing } /** {@inheritDoc} */ public int read() { if (ready() == false) { return -1; } return StrBuilder.this.charAt(pos++); } /** {@inheritDoc} */ public int read(char b[], int off, int len) { if (off < 0 || len < 0 || off > b.length || (off + len) > b.length || (off + len) < 0) { throw new IndexOutOfBoundsException(); } if (len == 0) { return 0; } if (pos >= StrBuilder.this.size()) { return -1; } if (pos + len > size()) { len = StrBuilder.this.size() - pos; } StrBuilder.this.getChars(pos, pos + len, b, off); pos += len; return len; } /** {@inheritDoc} */ public long skip(long n) { if (pos + n > StrBuilder.this.size()) { n = StrBuilder.this.size() - pos; } if (n < 0) { return 0; } pos += n; return n; } /** {@inheritDoc} */ public boolean ready() { return pos < StrBuilder.this.size(); } /** {@inheritDoc} */ public boolean markSupported() { return true; } /** {@inheritDoc} */ public void mark(int readAheadLimit) { mark = pos; } /** {@inheritDoc} */ public void reset() { pos = mark; } } //----------------------------------------------------------------------- /** * Inner class to allow StrBuilder to operate as a writer. */ class StrBuilderWriter extends Writer { /** * Default constructor. */ StrBuilderWriter() { super(); } /** {@inheritDoc} */ public void close() { // do nothing } /** {@inheritDoc} */ public void flush() { // do nothing } /** {@inheritDoc} */ public void write(int c) { StrBuilder.this.append((char) c); } /** {@inheritDoc} */ public void write(char[] cbuf) { StrBuilder.this.append(cbuf); } /** {@inheritDoc} */ public void write(char[] cbuf, int off, int len) { StrBuilder.this.append(cbuf, off, len); } /** {@inheritDoc} */ public void write(String str) { StrBuilder.this.append(str); } /** {@inheritDoc} */ public void write(String str, int off, int len) { StrBuilder.this.append(str, off, len); } } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/text/StrLookup.java100644 0 0 13437 11513702441 24546 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.text; import java.util.Map; /** * Lookup a String key to a String value. *

    * This class represents the simplest form of a string to string map. * It has a benefit over a map in that it can create the result on * demand based on the key. *

    * This class comes complete with various factory methods. * If these do not suffice, you can subclass and implement your own matcher. *

    * For example, it would be possible to implement a lookup that used the * key as a primary key, and looked up the value on demand from the database * * @author Apache Software Foundation * @since 2.2 * @version $Id: StrLookup.java 905636 2010-02-02 14:03:32Z niallp $ */ public abstract class StrLookup { /** * Lookup that always returns null. */ private static final StrLookup NONE_LOOKUP; /** * Lookup that uses System properties. */ private static final StrLookup SYSTEM_PROPERTIES_LOOKUP; static { NONE_LOOKUP = new MapStrLookup(null); StrLookup lookup = null; try { lookup = new MapStrLookup(System.getProperties()); } catch (SecurityException ex) { lookup = NONE_LOOKUP; } SYSTEM_PROPERTIES_LOOKUP = lookup; } //----------------------------------------------------------------------- /** * Returns a lookup which always returns null. * * @return a lookup that always returns null, not null */ public static StrLookup noneLookup() { return NONE_LOOKUP; } /** * Returns a lookup which uses {@link System#getProperties() System properties} * to lookup the key to value. *

    * If a security manager blocked access to system properties, then null will * be returned from every lookup. *

    * If a null key is used, this lookup will throw a NullPointerException. * * @return a lookup using system properties, not null */ public static StrLookup systemPropertiesLookup() { return SYSTEM_PROPERTIES_LOOKUP; } /** * Returns a lookup which looks up values using a map. *

    * If the map is null, then null will be returned from every lookup. * The map result object is converted to a string using toString(). * * @param map the map of keys to values, may be null * @return a lookup using the map, not null */ public static StrLookup mapLookup(Map map) { return new MapStrLookup(map); } //----------------------------------------------------------------------- /** * Constructor. */ protected StrLookup() { super(); } /** * Looks up a String key to a String value. *

    * The internal implementation may use any mechanism to return the value. * The simplest implementation is to use a Map. However, virtually any * implementation is possible. *

    * For example, it would be possible to implement a lookup that used the * key as a primary key, and looked up the value on demand from the database * Or, a numeric based implementation could be created that treats the key * as an integer, increments the value and return the result as a string - * converting 1 to 2, 15 to 16 etc. *

    * The {@link #lookup(String)} method always returns a String, regardless of * the underlying data, by converting it as necessary. For example: *

         * Map map = new HashMap();
         * map.put("number", new Integer(2));
         * assertEquals("2", StrLookup.mapLookup(map).lookup("number"));
         * 
    * @param key the key to be looked up, may be null * @return the matching value, null if no match */ public abstract String lookup(String key); //----------------------------------------------------------------------- /** * Lookup implementation that uses a Map. */ static class MapStrLookup extends StrLookup { /** Map keys are variable names and value. */ private final Map map; /** * Creates a new instance backed by a Map. * * @param map the map of keys to values, may be null */ MapStrLookup(Map map) { this.map = map; } /** * Looks up a String key to a String value using the map. *

    * If the map is null, then null is returned. * The map result object is converted to a string using toString(). * * @param key the key to be looked up, may be null * @return the matching value, null if no match */ public String lookup(String key) { if (map == null) { return null; } Object obj = map.get(key); if (obj == null) { return null; } return obj.toString(); } } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/text/StrMatcher.java100644 0 0 35706 11513702441 24663 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.text; import java.util.Arrays; /** * A matcher class that can be queried to determine if a character array * portion matches. *

    * This class comes complete with various factory methods. * If these do not suffice, you can subclass and implement your own matcher. * * @author Apache Software Foundation * @since 2.2 * @version $Id: StrMatcher.java 905636 2010-02-02 14:03:32Z niallp $ */ public abstract class StrMatcher { /** * Matches the comma character. */ private static final StrMatcher COMMA_MATCHER = new CharMatcher(','); /** * Matches the tab character. */ private static final StrMatcher TAB_MATCHER = new CharMatcher('\t'); /** * Matches the space character. */ private static final StrMatcher SPACE_MATCHER = new CharMatcher(' '); /** * Matches the same characters as StringTokenizer, * namely space, tab, newline, formfeed. */ private static final StrMatcher SPLIT_MATCHER = new CharSetMatcher(" \t\n\r\f".toCharArray()); /** * Matches the String trim() whitespace characters. */ private static final StrMatcher TRIM_MATCHER = new TrimMatcher(); /** * Matches the double quote character. */ private static final StrMatcher SINGLE_QUOTE_MATCHER = new CharMatcher('\''); /** * Matches the double quote character. */ private static final StrMatcher DOUBLE_QUOTE_MATCHER = new CharMatcher('"'); /** * Matches the single or double quote character. */ private static final StrMatcher QUOTE_MATCHER = new CharSetMatcher("'\"".toCharArray()); /** * Matches no characters. */ private static final StrMatcher NONE_MATCHER = new NoMatcher(); // ----------------------------------------------------------------------- /** * Returns a matcher which matches the comma character. * * @return a matcher for a comma */ public static StrMatcher commaMatcher() { return COMMA_MATCHER; } /** * Returns a matcher which matches the tab character. * * @return a matcher for a tab */ public static StrMatcher tabMatcher() { return TAB_MATCHER; } /** * Returns a matcher which matches the space character. * * @return a matcher for a space */ public static StrMatcher spaceMatcher() { return SPACE_MATCHER; } /** * Matches the same characters as StringTokenizer, * namely space, tab, newline and formfeed. * * @return the split matcher */ public static StrMatcher splitMatcher() { return SPLIT_MATCHER; } /** * Matches the String trim() whitespace characters. * * @return the trim matcher */ public static StrMatcher trimMatcher() { return TRIM_MATCHER; } /** * Returns a matcher which matches the single quote character. * * @return a matcher for a single quote */ public static StrMatcher singleQuoteMatcher() { return SINGLE_QUOTE_MATCHER; } /** * Returns a matcher which matches the double quote character. * * @return a matcher for a double quote */ public static StrMatcher doubleQuoteMatcher() { return DOUBLE_QUOTE_MATCHER; } /** * Returns a matcher which matches the single or double quote character. * * @return a matcher for a single or double quote */ public static StrMatcher quoteMatcher() { return QUOTE_MATCHER; } /** * Matches no characters. * * @return a matcher that matches nothing */ public static StrMatcher noneMatcher() { return NONE_MATCHER; } /** * Constructor that creates a matcher from a character. * * @param ch the character to match, must not be null * @return a new Matcher for the given char */ public static StrMatcher charMatcher(char ch) { return new CharMatcher(ch); } /** * Constructor that creates a matcher from a set of characters. * * @param chars the characters to match, null or empty matches nothing * @return a new matcher for the given char[] */ public static StrMatcher charSetMatcher(char[] chars) { if (chars == null || chars.length == 0) { return NONE_MATCHER; } if (chars.length == 1) { return new CharMatcher(chars[0]); } return new CharSetMatcher(chars); } /** * Constructor that creates a matcher from a string representing a set of characters. * * @param chars the characters to match, null or empty matches nothing * @return a new Matcher for the given characters */ public static StrMatcher charSetMatcher(String chars) { if (chars == null || chars.length() == 0) { return NONE_MATCHER; } if (chars.length() == 1) { return new CharMatcher(chars.charAt(0)); } return new CharSetMatcher(chars.toCharArray()); } /** * Constructor that creates a matcher from a string. * * @param str the string to match, null or empty matches nothing * @return a new Matcher for the given String */ public static StrMatcher stringMatcher(String str) { if (str == null || str.length() == 0) { return NONE_MATCHER; } return new StringMatcher(str); } //----------------------------------------------------------------------- /** * Constructor. */ protected StrMatcher() { super(); } /** * Returns the number of matching characters, zero for no match. *

    * This method is called to check for a match. * The parameter pos represents the current position to be * checked in the string buffer (a character array which must * not be changed). * The API guarantees that pos is a valid index for buffer. *

    * The character array may be larger than the active area to be matched. * Only values in the buffer between the specifed indices may be accessed. *

    * The matching code may check one character or many. * It may check characters preceeding pos as well as those * after, so long as no checks exceed the bounds specified. *

    * It must return zero for no match, or a positive number if a match was found. * The number indicates the number of characters that matched. * * @param buffer the text content to match against, do not change * @param pos the starting position for the match, valid for buffer * @param bufferStart the first active index in the buffer, valid for buffer * @param bufferEnd the end index (exclusive) of the active buffer, valid for buffer * @return the number of matching characters, zero for no match */ public abstract int isMatch(char[] buffer, int pos, int bufferStart, int bufferEnd); /** * Returns the number of matching characters, zero for no match. *

    * This method is called to check for a match. * The parameter pos represents the current position to be * checked in the string buffer (a character array which must * not be changed). * The API guarantees that pos is a valid index for buffer. *

    * The matching code may check one character or many. * It may check characters preceeding pos as well as those after. *

    * It must return zero for no match, or a positive number if a match was found. * The number indicates the number of characters that matched. * * @param buffer the text content to match against, do not change * @param pos the starting position for the match, valid for buffer * @return the number of matching characters, zero for no match * @since 2.4 */ public int isMatch(char[] buffer, int pos) { return isMatch(buffer, pos, 0, buffer.length); } //----------------------------------------------------------------------- /** * Class used to define a set of characters for matching purposes. */ static final class CharSetMatcher extends StrMatcher { /** The set of characters to match. */ private final char[] chars; /** * Constructor that creates a matcher from a character array. * * @param chars the characters to match, must not be null */ CharSetMatcher(char chars[]) { super(); this.chars = (char[]) chars.clone(); Arrays.sort(this.chars); } /** * Returns whether or not the given character matches. * * @param buffer the text content to match against, do not change * @param pos the starting position for the match, valid for buffer * @param bufferStart the first active index in the buffer, valid for buffer * @param bufferEnd the end index of the active buffer, valid for buffer * @return the number of matching characters, zero for no match */ public int isMatch(char[] buffer, int pos, int bufferStart, int bufferEnd) { return Arrays.binarySearch(chars, buffer[pos]) >= 0 ? 1 : 0; } } //----------------------------------------------------------------------- /** * Class used to define a character for matching purposes. */ static final class CharMatcher extends StrMatcher { /** The character to match. */ private final char ch; /** * Constructor that creates a matcher that matches a single character. * * @param ch the character to match */ CharMatcher(char ch) { super(); this.ch = ch; } /** * Returns whether or not the given character matches. * * @param buffer the text content to match against, do not change * @param pos the starting position for the match, valid for buffer * @param bufferStart the first active index in the buffer, valid for buffer * @param bufferEnd the end index of the active buffer, valid for buffer * @return the number of matching characters, zero for no match */ public int isMatch(char[] buffer, int pos, int bufferStart, int bufferEnd) { return ch == buffer[pos] ? 1 : 0; } } //----------------------------------------------------------------------- /** * Class used to define a set of characters for matching purposes. */ static final class StringMatcher extends StrMatcher { /** The string to match, as a character array. */ private final char[] chars; /** * Constructor that creates a matcher from a String. * * @param str the string to match, must not be null */ StringMatcher(String str) { super(); chars = str.toCharArray(); } /** * Returns whether or not the given text matches the stored string. * * @param buffer the text content to match against, do not change * @param pos the starting position for the match, valid for buffer * @param bufferStart the first active index in the buffer, valid for buffer * @param bufferEnd the end index of the active buffer, valid for buffer * @return the number of matching characters, zero for no match */ public int isMatch(char[] buffer, int pos, int bufferStart, int bufferEnd) { int len = chars.length; if (pos + len > bufferEnd) { return 0; } for (int i = 0; i < chars.length; i++, pos++) { if (chars[i] != buffer[pos]) { return 0; } } return len; } } //----------------------------------------------------------------------- /** * Class used to match no characters. */ static final class NoMatcher extends StrMatcher { /** * Constructs a new instance of NoMatcher. */ NoMatcher() { super(); } /** * Always returns false. * * @param buffer the text content to match against, do not change * @param pos the starting position for the match, valid for buffer * @param bufferStart the first active index in the buffer, valid for buffer * @param bufferEnd the end index of the active buffer, valid for buffer * @return the number of matching characters, zero for no match */ public int isMatch(char[] buffer, int pos, int bufferStart, int bufferEnd) { return 0; } } //----------------------------------------------------------------------- /** * Class used to match whitespace as per trim(). */ static final class TrimMatcher extends StrMatcher { /** * Constructs a new instance of TrimMatcher. */ TrimMatcher() { super(); } /** * Returns whether or not the given character matches. * * @param buffer the text content to match against, do not change * @param pos the starting position for the match, valid for buffer * @param bufferStart the first active index in the buffer, valid for buffer * @param bufferEnd the end index of the active buffer, valid for buffer * @return the number of matching characters, zero for no match */ public int isMatch(char[] buffer, int pos, int bufferStart, int bufferEnd) { return buffer[pos] <= 32 ? 1 : 0; } } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/text/StrSubstitutor.java100644 0 0 113024 11513702441 25655 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.text; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; /** * Substitutes variables within a string by values. *

    * This class takes a piece of text and substitutes all the variables within it. * The default definition of a variable is ${variableName}. * The prefix and suffix can be changed via constructors and set methods. *

    * Variable values are typically resolved from a map, but could also be resolved * from system properties, or by supplying a custom variable resolver. *

    * The simplest example is to use this class to replace Java System properties. For example: *

     * StrSubstitutor.replaceSystemProperties(
     *      "You are running with java.version = ${java.version} and os.name = ${os.name}.");
     * 
    *

    * Typical usage of this class follows the following pattern: First an instance is created * and initialized with the map that contains the values for the available variables. * If a prefix and/or suffix for variables should be used other than the default ones, * the appropriate settings can be performed. After that the replace() * method can be called passing in the source text for interpolation. In the returned * text all variable references (as long as their values are known) will be resolved. * The following example demonstrates this: *

     * Map valuesMap = HashMap();
     * valuesMap.put("animal", "quick brown fox");
     * valuesMap.put("target", "lazy dog");
     * String templateString = "The ${animal} jumped over the ${target}.";
     * StrSubstitutor sub = new StrSubstitutor(valuesMap);
     * String resolvedString = sub.replace(templateString);
     * 
    * yielding: *
     *      The quick brown fox jumped over the lazy dog.
     * 
    *

    * In addition to this usage pattern there are some static convenience methods that * cover the most common use cases. These methods can be used without the need of * manually creating an instance. However if multiple replace operations are to be * performed, creating and reusing an instance of this class will be more efficient. *

    * Variable replacement works in a recursive way. Thus, if a variable value contains * a variable then that variable will also be replaced. Cyclic replacements are * detected and will cause an exception to be thrown. *

    * Sometimes the interpolation's result must contain a variable prefix. As an example * take the following source text: *

     *   The variable ${${name}} must be used.
     * 
    * Here only the variable's name referred to in the text should be replaced resulting * in the text (assuming that the value of the name variable is x): *
     *   The variable ${x} must be used.
     * 
    * To achieve this effect there are two possibilities: Either set a different prefix * and suffix for variables which do not conflict with the result text you want to * produce. The other possibility is to use the escape character, by default '$'. * If this character is placed before a variable reference, this reference is ignored * and won't be replaced. For example: *
     *   The variable $${${name}} must be used.
     * 
    *

    * In some complex scenarios you might even want to perform substitution in the * names of variables, for instance *

     * ${jre-${java.specification.version}}
     * 
    * StrSubstitutor supports this recursive substitution in variable * names, but it has to be enabled explicitly by setting the * {@link #setEnableSubstitutionInVariables(boolean) enableSubstitutionInVariables} * property to true. * * @author Apache Software Foundation * @author Oliver Heger * @version $Id: StrSubstitutor.java 1057354 2011-01-10 20:48:47Z niallp $ * @since 2.2 */ public class StrSubstitutor { /** * Constant for the default escape character. */ public static final char DEFAULT_ESCAPE = '$'; /** * Constant for the default variable prefix. */ public static final StrMatcher DEFAULT_PREFIX = StrMatcher.stringMatcher("${"); /** * Constant for the default variable suffix. */ public static final StrMatcher DEFAULT_SUFFIX = StrMatcher.stringMatcher("}"); /** * Stores the escape character. */ private char escapeChar; /** * Stores the variable prefix. */ private StrMatcher prefixMatcher; /** * Stores the variable suffix. */ private StrMatcher suffixMatcher; /** * Variable resolution is delegated to an implementor of VariableResolver. */ private StrLookup variableResolver; /** * The flag whether substitution in variable names is enabled. */ private boolean enableSubstitutionInVariables; //----------------------------------------------------------------------- /** * Replaces all the occurrences of variables in the given source object with * their matching values from the map. * * @param source the source text containing the variables to substitute, null returns null * @param valueMap the map with the values, may be null * @return the result of the replace operation */ public static String replace(Object source, Map valueMap) { return new StrSubstitutor(valueMap).replace(source); } /** * Replaces all the occurrences of variables in the given source object with * their matching values from the map. This method allows to specifiy a * custom variable prefix and suffix * * @param source the source text containing the variables to substitute, null returns null * @param valueMap the map with the values, may be null * @param prefix the prefix of variables, not null * @param suffix the suffix of variables, not null * @return the result of the replace operation * @throws IllegalArgumentException if the prefix or suffix is null */ public static String replace(Object source, Map valueMap, String prefix, String suffix) { return new StrSubstitutor(valueMap, prefix, suffix).replace(source); } /** * Replaces all the occurrences of variables in the given source object with their matching * values from the properties. * * @param source the source text containing the variables to substitute, null returns null * @param valueProperties the properties with values, may be null * @return the result of the replace operation * @since 2.6 */ public static String replace(Object source, Properties valueProperties) { if (valueProperties == null) { return source.toString(); } Map valueMap = new HashMap(); Enumeration propNames = valueProperties.propertyNames(); while (propNames.hasMoreElements()) { String propName = (String)propNames.nextElement(); String propValue = valueProperties.getProperty(propName); valueMap.put(propName, propValue); } return StrSubstitutor.replace(source, valueMap); } /** * Replaces all the occurrences of variables in the given source object with * their matching values from the system properties. * * @param source the source text containing the variables to substitute, null returns null * @return the result of the replace operation */ public static String replaceSystemProperties(Object source) { return new StrSubstitutor(StrLookup.systemPropertiesLookup()).replace(source); } //----------------------------------------------------------------------- /** * Creates a new instance with defaults for variable prefix and suffix * and the escaping character. */ public StrSubstitutor() { this((StrLookup) null, DEFAULT_PREFIX, DEFAULT_SUFFIX, DEFAULT_ESCAPE); } /** * Creates a new instance and initializes it. Uses defaults for variable * prefix and suffix and the escaping character. * * @param valueMap the map with the variables' values, may be null */ public StrSubstitutor(Map valueMap) { this(StrLookup.mapLookup(valueMap), DEFAULT_PREFIX, DEFAULT_SUFFIX, DEFAULT_ESCAPE); } /** * Creates a new instance and initializes it. Uses a default escaping character. * * @param valueMap the map with the variables' values, may be null * @param prefix the prefix for variables, not null * @param suffix the suffix for variables, not null * @throws IllegalArgumentException if the prefix or suffix is null */ public StrSubstitutor(Map valueMap, String prefix, String suffix) { this(StrLookup.mapLookup(valueMap), prefix, suffix, DEFAULT_ESCAPE); } /** * Creates a new instance and initializes it. * * @param valueMap the map with the variables' values, may be null * @param prefix the prefix for variables, not null * @param suffix the suffix for variables, not null * @param escape the escape character * @throws IllegalArgumentException if the prefix or suffix is null */ public StrSubstitutor(Map valueMap, String prefix, String suffix, char escape) { this(StrLookup.mapLookup(valueMap), prefix, suffix, escape); } /** * Creates a new instance and initializes it. * * @param variableResolver the variable resolver, may be null */ public StrSubstitutor(StrLookup variableResolver) { this(variableResolver, DEFAULT_PREFIX, DEFAULT_SUFFIX, DEFAULT_ESCAPE); } /** * Creates a new instance and initializes it. * * @param variableResolver the variable resolver, may be null * @param prefix the prefix for variables, not null * @param suffix the suffix for variables, not null * @param escape the escape character * @throws IllegalArgumentException if the prefix or suffix is null */ public StrSubstitutor(StrLookup variableResolver, String prefix, String suffix, char escape) { this.setVariableResolver(variableResolver); this.setVariablePrefix(prefix); this.setVariableSuffix(suffix); this.setEscapeChar(escape); } /** * Creates a new instance and initializes it. * * @param variableResolver the variable resolver, may be null * @param prefixMatcher the prefix for variables, not null * @param suffixMatcher the suffix for variables, not null * @param escape the escape character * @throws IllegalArgumentException if the prefix or suffix is null */ public StrSubstitutor( StrLookup variableResolver, StrMatcher prefixMatcher, StrMatcher suffixMatcher, char escape) { this.setVariableResolver(variableResolver); this.setVariablePrefixMatcher(prefixMatcher); this.setVariableSuffixMatcher(suffixMatcher); this.setEscapeChar(escape); } //----------------------------------------------------------------------- /** * Replaces all the occurrences of variables with their matching values * from the resolver using the given source string as a template. * * @param source the string to replace in, null returns null * @return the result of the replace operation */ public String replace(String source) { if (source == null) { return null; } StrBuilder buf = new StrBuilder(source); if (substitute(buf, 0, source.length()) == false) { return source; } return buf.toString(); } /** * Replaces all the occurrences of variables with their matching values * from the resolver using the given source string as a template. *

    * Only the specified portion of the string will be processed. * The rest of the string is not processed, and is not returned. * * @param source the string to replace in, null returns null * @param offset the start offset within the array, must be valid * @param length the length within the array to be processed, must be valid * @return the result of the replace operation */ public String replace(String source, int offset, int length) { if (source == null) { return null; } StrBuilder buf = new StrBuilder(length).append(source, offset, length); if (substitute(buf, 0, length) == false) { return source.substring(offset, offset + length); } return buf.toString(); } //----------------------------------------------------------------------- /** * Replaces all the occurrences of variables with their matching values * from the resolver using the given source array as a template. * The array is not altered by this method. * * @param source the character array to replace in, not altered, null returns null * @return the result of the replace operation */ public String replace(char[] source) { if (source == null) { return null; } StrBuilder buf = new StrBuilder(source.length).append(source); substitute(buf, 0, source.length); return buf.toString(); } /** * Replaces all the occurrences of variables with their matching values * from the resolver using the given source array as a template. * The array is not altered by this method. *

    * Only the specified portion of the array will be processed. * The rest of the array is not processed, and is not returned. * * @param source the character array to replace in, not altered, null returns null * @param offset the start offset within the array, must be valid * @param length the length within the array to be processed, must be valid * @return the result of the replace operation */ public String replace(char[] source, int offset, int length) { if (source == null) { return null; } StrBuilder buf = new StrBuilder(length).append(source, offset, length); substitute(buf, 0, length); return buf.toString(); } //----------------------------------------------------------------------- /** * Replaces all the occurrences of variables with their matching values * from the resolver using the given source buffer as a template. * The buffer is not altered by this method. * * @param source the buffer to use as a template, not changed, null returns null * @return the result of the replace operation */ public String replace(StringBuffer source) { if (source == null) { return null; } StrBuilder buf = new StrBuilder(source.length()).append(source); substitute(buf, 0, buf.length()); return buf.toString(); } /** * Replaces all the occurrences of variables with their matching values * from the resolver using the given source buffer as a template. * The buffer is not altered by this method. *

    * Only the specified portion of the buffer will be processed. * The rest of the buffer is not processed, and is not returned. * * @param source the buffer to use as a template, not changed, null returns null * @param offset the start offset within the array, must be valid * @param length the length within the array to be processed, must be valid * @return the result of the replace operation */ public String replace(StringBuffer source, int offset, int length) { if (source == null) { return null; } StrBuilder buf = new StrBuilder(length).append(source, offset, length); substitute(buf, 0, length); return buf.toString(); } //----------------------------------------------------------------------- /** * Replaces all the occurrences of variables with their matching values * from the resolver using the given source builder as a template. * The builder is not altered by this method. * * @param source the builder to use as a template, not changed, null returns null * @return the result of the replace operation */ public String replace(StrBuilder source) { if (source == null) { return null; } StrBuilder buf = new StrBuilder(source.length()).append(source); substitute(buf, 0, buf.length()); return buf.toString(); } /** * Replaces all the occurrences of variables with their matching values * from the resolver using the given source builder as a template. * The builder is not altered by this method. *

    * Only the specified portion of the builder will be processed. * The rest of the builder is not processed, and is not returned. * * @param source the builder to use as a template, not changed, null returns null * @param offset the start offset within the array, must be valid * @param length the length within the array to be processed, must be valid * @return the result of the replace operation */ public String replace(StrBuilder source, int offset, int length) { if (source == null) { return null; } StrBuilder buf = new StrBuilder(length).append(source, offset, length); substitute(buf, 0, length); return buf.toString(); } //----------------------------------------------------------------------- /** * Replaces all the occurrences of variables in the given source object with * their matching values from the resolver. The input source object is * converted to a string using toString and is not altered. * * @param source the source to replace in, null returns null * @return the result of the replace operation */ public String replace(Object source) { if (source == null) { return null; } StrBuilder buf = new StrBuilder().append(source); substitute(buf, 0, buf.length()); return buf.toString(); } //----------------------------------------------------------------------- /** * Replaces all the occurrences of variables within the given source buffer * with their matching values from the resolver. * The buffer is updated with the result. * * @param source the buffer to replace in, updated, null returns zero * @return true if altered */ public boolean replaceIn(StringBuffer source) { if (source == null) { return false; } return replaceIn(source, 0, source.length()); } /** * Replaces all the occurrences of variables within the given source buffer * with their matching values from the resolver. * The buffer is updated with the result. *

    * Only the specified portion of the buffer will be processed. * The rest of the buffer is not processed, but it is not deleted. * * @param source the buffer to replace in, updated, null returns zero * @param offset the start offset within the array, must be valid * @param length the length within the buffer to be processed, must be valid * @return true if altered */ public boolean replaceIn(StringBuffer source, int offset, int length) { if (source == null) { return false; } StrBuilder buf = new StrBuilder(length).append(source, offset, length); if (substitute(buf, 0, length) == false) { return false; } source.replace(offset, offset + length, buf.toString()); return true; } //----------------------------------------------------------------------- /** * Replaces all the occurrences of variables within the given source * builder with their matching values from the resolver. * * @param source the builder to replace in, updated, null returns zero * @return true if altered */ public boolean replaceIn(StrBuilder source) { if (source == null) { return false; } return substitute(source, 0, source.length()); } /** * Replaces all the occurrences of variables within the given source * builder with their matching values from the resolver. *

    * Only the specified portion of the builder will be processed. * The rest of the builder is not processed, but it is not deleted. * * @param source the builder to replace in, null returns zero * @param offset the start offset within the array, must be valid * @param length the length within the builder to be processed, must be valid * @return true if altered */ public boolean replaceIn(StrBuilder source, int offset, int length) { if (source == null) { return false; } return substitute(source, offset, length); } //----------------------------------------------------------------------- /** * Internal method that substitutes the variables. *

    * Most users of this class do not need to call this method. This method will * be called automatically by another (public) method. *

    * Writers of subclasses can override this method if they need access to * the substitution process at the start or end. * * @param buf the string builder to substitute into, not null * @param offset the start offset within the builder, must be valid * @param length the length within the builder to be processed, must be valid * @return true if altered */ protected boolean substitute(StrBuilder buf, int offset, int length) { return substitute(buf, offset, length, null) > 0; } /** * Recursive handler for multiple levels of interpolation. This is the main * interpolation method, which resolves the values of all variable references * contained in the passed in text. * * @param buf the string builder to substitute into, not null * @param offset the start offset within the builder, must be valid * @param length the length within the builder to be processed, must be valid * @param priorVariables the stack keeping track of the replaced variables, may be null * @return the length change that occurs, unless priorVariables is null when the int * represents a boolean flag as to whether any change occurred. */ private int substitute(StrBuilder buf, int offset, int length, List priorVariables) { StrMatcher prefixMatcher = getVariablePrefixMatcher(); StrMatcher suffixMatcher = getVariableSuffixMatcher(); char escape = getEscapeChar(); boolean top = (priorVariables == null); boolean altered = false; int lengthChange = 0; char[] chars = buf.buffer; int bufEnd = offset + length; int pos = offset; while (pos < bufEnd) { int startMatchLen = prefixMatcher.isMatch(chars, pos, offset, bufEnd); if (startMatchLen == 0) { pos++; } else { // found variable start marker if (pos > offset && chars[pos - 1] == escape) { // escaped buf.deleteCharAt(pos - 1); chars = buf.buffer; // in case buffer was altered lengthChange--; altered = true; bufEnd--; } else { // find suffix int startPos = pos; pos += startMatchLen; int endMatchLen = 0; int nestedVarCount = 0; while (pos < bufEnd) { if (isEnableSubstitutionInVariables() && (endMatchLen = prefixMatcher.isMatch(chars, pos, offset, bufEnd)) != 0) { // found a nested variable start nestedVarCount++; pos += endMatchLen; continue; } endMatchLen = suffixMatcher.isMatch(chars, pos, offset, bufEnd); if (endMatchLen == 0) { pos++; } else { // found variable end marker if (nestedVarCount == 0) { String varName = new String(chars, startPos + startMatchLen, pos - startPos - startMatchLen); if (isEnableSubstitutionInVariables()) { StrBuilder bufName = new StrBuilder(varName); substitute(bufName, 0, bufName.length()); varName = bufName.toString(); } pos += endMatchLen; int endPos = pos; // on the first call initialize priorVariables if (priorVariables == null) { priorVariables = new ArrayList(); priorVariables.add(new String(chars, offset, length)); } // handle cyclic substitution checkCyclicSubstitution(varName, priorVariables); priorVariables.add(varName); // resolve the variable String varValue = resolveVariable(varName, buf, startPos, endPos); if (varValue != null) { // recursive replace int varLen = varValue.length(); buf.replace(startPos, endPos, varValue); altered = true; int change = substitute(buf, startPos, varLen, priorVariables); change = change + (varLen - (endPos - startPos)); pos += change; bufEnd += change; lengthChange += change; chars = buf.buffer; // in case buffer was // altered } // remove variable from the cyclic stack priorVariables .remove(priorVariables.size() - 1); break; } else { nestedVarCount--; pos += endMatchLen; } } } } } } if (top) { return (altered ? 1 : 0); } return lengthChange; } /** * Checks if the specified variable is already in the stack (list) of variables. * * @param varName the variable name to check * @param priorVariables the list of prior variables */ private void checkCyclicSubstitution(String varName, List priorVariables) { if (priorVariables.contains(varName) == false) { return; } StrBuilder buf = new StrBuilder(256); buf.append("Infinite loop in property interpolation of "); buf.append(priorVariables.remove(0)); buf.append(": "); buf.appendWithSeparators(priorVariables, "->"); throw new IllegalStateException(buf.toString()); } /** * Internal method that resolves the value of a variable. *

    * Most users of this class do not need to call this method. This method is * called automatically by the substitution process. *

    * Writers of subclasses can override this method if they need to alter * how each substitution occurs. The method is passed the variable's name * and must return the corresponding value. This implementation uses the * {@link #getVariableResolver()} with the variable's name as the key. * * @param variableName the name of the variable, not null * @param buf the buffer where the substitution is occurring, not null * @param startPos the start position of the variable including the prefix, valid * @param endPos the end position of the variable including the suffix, valid * @return the variable's value or null if the variable is unknown */ protected String resolveVariable(String variableName, StrBuilder buf, int startPos, int endPos) { StrLookup resolver = getVariableResolver(); if (resolver == null) { return null; } return resolver.lookup(variableName); } // Escape //----------------------------------------------------------------------- /** * Returns the escape character. * * @return the character used for escaping variable references */ public char getEscapeChar() { return this.escapeChar; } /** * Sets the escape character. * If this character is placed before a variable reference in the source * text, this variable will be ignored. * * @param escapeCharacter the escape character (0 for disabling escaping) */ public void setEscapeChar(char escapeCharacter) { this.escapeChar = escapeCharacter; } // Prefix //----------------------------------------------------------------------- /** * Gets the variable prefix matcher currently in use. *

    * The variable prefix is the characer or characters that identify the * start of a variable. This prefix is expressed in terms of a matcher * allowing advanced prefix matches. * * @return the prefix matcher in use */ public StrMatcher getVariablePrefixMatcher() { return prefixMatcher; } /** * Sets the variable prefix matcher currently in use. *

    * The variable prefix is the characer or characters that identify the * start of a variable. This prefix is expressed in terms of a matcher * allowing advanced prefix matches. * * @param prefixMatcher the prefix matcher to use, null ignored * @return this, to enable chaining * @throws IllegalArgumentException if the prefix matcher is null */ public StrSubstitutor setVariablePrefixMatcher(StrMatcher prefixMatcher) { if (prefixMatcher == null) { throw new IllegalArgumentException("Variable prefix matcher must not be null!"); } this.prefixMatcher = prefixMatcher; return this; } /** * Sets the variable prefix to use. *

    * The variable prefix is the character or characters that identify the * start of a variable. This method allows a single character prefix to * be easily set. * * @param prefix the prefix character to use * @return this, to enable chaining */ public StrSubstitutor setVariablePrefix(char prefix) { return setVariablePrefixMatcher(StrMatcher.charMatcher(prefix)); } /** * Sets the variable prefix to use. *

    * The variable prefix is the characer or characters that identify the * start of a variable. This method allows a string prefix to be easily set. * * @param prefix the prefix for variables, not null * @return this, to enable chaining * @throws IllegalArgumentException if the prefix is null */ public StrSubstitutor setVariablePrefix(String prefix) { if (prefix == null) { throw new IllegalArgumentException("Variable prefix must not be null!"); } return setVariablePrefixMatcher(StrMatcher.stringMatcher(prefix)); } // Suffix //----------------------------------------------------------------------- /** * Gets the variable suffix matcher currently in use. *

    * The variable suffix is the characer or characters that identify the * end of a variable. This suffix is expressed in terms of a matcher * allowing advanced suffix matches. * * @return the suffix matcher in use */ public StrMatcher getVariableSuffixMatcher() { return suffixMatcher; } /** * Sets the variable suffix matcher currently in use. *

    * The variable suffix is the characer or characters that identify the * end of a variable. This suffix is expressed in terms of a matcher * allowing advanced suffix matches. * * @param suffixMatcher the suffix matcher to use, null ignored * @return this, to enable chaining * @throws IllegalArgumentException if the suffix matcher is null */ public StrSubstitutor setVariableSuffixMatcher(StrMatcher suffixMatcher) { if (suffixMatcher == null) { throw new IllegalArgumentException("Variable suffix matcher must not be null!"); } this.suffixMatcher = suffixMatcher; return this; } /** * Sets the variable suffix to use. *

    * The variable suffix is the characer or characters that identify the * end of a variable. This method allows a single character suffix to * be easily set. * * @param suffix the suffix character to use * @return this, to enable chaining */ public StrSubstitutor setVariableSuffix(char suffix) { return setVariableSuffixMatcher(StrMatcher.charMatcher(suffix)); } /** * Sets the variable suffix to use. *

    * The variable suffix is the character or characters that identify the * end of a variable. This method allows a string suffix to be easily set. * * @param suffix the suffix for variables, not null * @return this, to enable chaining * @throws IllegalArgumentException if the suffix is null */ public StrSubstitutor setVariableSuffix(String suffix) { if (suffix == null) { throw new IllegalArgumentException("Variable suffix must not be null!"); } return setVariableSuffixMatcher(StrMatcher.stringMatcher(suffix)); } // Resolver //----------------------------------------------------------------------- /** * Gets the VariableResolver that is used to lookup variables. * * @return the VariableResolver */ public StrLookup getVariableResolver() { return this.variableResolver; } /** * Sets the VariableResolver that is used to lookup variables. * * @param variableResolver the VariableResolver */ public void setVariableResolver(StrLookup variableResolver) { this.variableResolver = variableResolver; } // Substitution support in variable names //----------------------------------------------------------------------- /** * Returns a flag whether substitution is done in variable names. * * @return the substitution in variable names flag * @since 2.6 */ public boolean isEnableSubstitutionInVariables() { return enableSubstitutionInVariables; } /** * Sets a flag whether substitution is done in variable names. If set to * true, the names of variables can contain other variables which are * processed first before the original variable is evaluated, e.g. * ${jre-${java.version}}. The default value is false. * * @param enableSubstitutionInVariables the new value of the flag * @since 2.6 */ public void setEnableSubstitutionInVariables( boolean enableSubstitutionInVariables) { this.enableSubstitutionInVariables = enableSubstitutionInVariables; } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/text/StrTokenizer.java100644 0 0 115051 11513702441 25262 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.text; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.ListIterator; import java.util.NoSuchElementException; /** * Tokenizes a string based based on delimiters (separators) * and supporting quoting and ignored character concepts. *

    * This class can split a String into many smaller strings. It aims * to do a similar job to {@link java.util.StringTokenizer StringTokenizer}, * however it offers much more control and flexibility including implementing * the ListIterator interface. By default, it is set up * like StringTokenizer. *

    * The input String is split into a number of tokens. * Each token is separated from the next String by a delimiter. * One or more delimiter characters must be specified. *

    * Each token may be surrounded by quotes. * The quote matcher specifies the quote character(s). * A quote may be escaped within a quoted section by duplicating itself. *

    * Between each token and the delimiter are potentially characters that need trimming. * The trimmer matcher specifies these characters. * One usage might be to trim whitespace characters. *

    * At any point outside the quotes there might potentially be invalid characters. * The ignored matcher specifies these characters to be removed. * One usage might be to remove new line characters. *

    * Empty tokens may be removed or returned as null. *

     * "a,b,c"         - Three tokens "a","b","c"   (comma delimiter)
     * " a, b , c "    - Three tokens "a","b","c"   (default CSV processing trims whitespace)
     * "a, ", b ,", c" - Three tokens "a, " , " b ", ", c" (quoted text untouched)
     * 
    *

    * * This tokenizer has the following properties and options: * * * * * * * * * * * * * * * * * * * * *
    PropertyTypeDefault
    delimCharSetMatcher{ \t\n\r\f}
    quoteNoneMatcher{}
    ignoreNoneMatcher{}
    emptyTokenAsNullbooleanfalse
    ignoreEmptyTokensbooleantrue
    * * @author Apache Software Foundation * @author Matthew Inger * @author Gary D. Gregory * @since 2.2 * @version $Id: StrTokenizer.java 907631 2010-02-08 12:22:48Z sebb $ */ public class StrTokenizer implements ListIterator, Cloneable { private static final StrTokenizer CSV_TOKENIZER_PROTOTYPE; private static final StrTokenizer TSV_TOKENIZER_PROTOTYPE; static { CSV_TOKENIZER_PROTOTYPE = new StrTokenizer(); CSV_TOKENIZER_PROTOTYPE.setDelimiterMatcher(StrMatcher.commaMatcher()); CSV_TOKENIZER_PROTOTYPE.setQuoteMatcher(StrMatcher.doubleQuoteMatcher()); CSV_TOKENIZER_PROTOTYPE.setIgnoredMatcher(StrMatcher.noneMatcher()); CSV_TOKENIZER_PROTOTYPE.setTrimmerMatcher(StrMatcher.trimMatcher()); CSV_TOKENIZER_PROTOTYPE.setEmptyTokenAsNull(false); CSV_TOKENIZER_PROTOTYPE.setIgnoreEmptyTokens(false); TSV_TOKENIZER_PROTOTYPE = new StrTokenizer(); TSV_TOKENIZER_PROTOTYPE.setDelimiterMatcher(StrMatcher.tabMatcher()); TSV_TOKENIZER_PROTOTYPE.setQuoteMatcher(StrMatcher.doubleQuoteMatcher()); TSV_TOKENIZER_PROTOTYPE.setIgnoredMatcher(StrMatcher.noneMatcher()); TSV_TOKENIZER_PROTOTYPE.setTrimmerMatcher(StrMatcher.trimMatcher()); TSV_TOKENIZER_PROTOTYPE.setEmptyTokenAsNull(false); TSV_TOKENIZER_PROTOTYPE.setIgnoreEmptyTokens(false); } /** The text to work on. */ private char chars[]; /** The parsed tokens */ private String tokens[]; /** The current iteration position */ private int tokenPos; /** The delimiter matcher */ private StrMatcher delimMatcher = StrMatcher.splitMatcher(); /** The quote matcher */ private StrMatcher quoteMatcher = StrMatcher.noneMatcher(); /** The ignored matcher */ private StrMatcher ignoredMatcher = StrMatcher.noneMatcher(); /** The trimmer matcher */ private StrMatcher trimmerMatcher = StrMatcher.noneMatcher(); /** Whether to return empty tokens as null */ private boolean emptyAsNull = false; /** Whether to ignore empty tokens */ private boolean ignoreEmptyTokens = true; //----------------------------------------------------------------------- /** * Returns a clone of CSV_TOKENIZER_PROTOTYPE. * * @return a clone of CSV_TOKENIZER_PROTOTYPE. */ private static StrTokenizer getCSVClone() { return (StrTokenizer) CSV_TOKENIZER_PROTOTYPE.clone(); } /** * Gets a new tokenizer instance which parses Comma Separated Value strings * initializing it with the given input. The default for CSV processing * will be trim whitespace from both ends (which can be overridden with * the setTrimmer method). *

    * You must call a "reset" method to set the string which you want to parse. * @return a new tokenizer instance which parses Comma Separated Value strings */ public static StrTokenizer getCSVInstance() { return getCSVClone(); } /** * Gets a new tokenizer instance which parses Comma Separated Value strings * initializing it with the given input. The default for CSV processing * will be trim whitespace from both ends (which can be overridden with * the setTrimmer method). * * @param input the text to parse * @return a new tokenizer instance which parses Comma Separated Value strings */ public static StrTokenizer getCSVInstance(String input) { StrTokenizer tok = getCSVClone(); tok.reset(input); return tok; } /** * Gets a new tokenizer instance which parses Comma Separated Value strings * initializing it with the given input. The default for CSV processing * will be trim whitespace from both ends (which can be overridden with * the setTrimmer method). * * @param input the text to parse * @return a new tokenizer instance which parses Comma Separated Value strings */ public static StrTokenizer getCSVInstance(char[] input) { StrTokenizer tok = getCSVClone(); tok.reset(input); return tok; } /** * Returns a clone of TSV_TOKENIZER_PROTOTYPE. * * @return a clone of TSV_TOKENIZER_PROTOTYPE. */ private static StrTokenizer getTSVClone() { return (StrTokenizer) TSV_TOKENIZER_PROTOTYPE.clone(); } /** * Gets a new tokenizer instance which parses Tab Separated Value strings. * The default for CSV processing will be trim whitespace from both ends * (which can be overridden with the setTrimmer method). *

    * You must call a "reset" method to set the string which you want to parse. * @return a new tokenizer instance which parses Tab Separated Value strings. */ public static StrTokenizer getTSVInstance() { return getTSVClone(); } /** * Gets a new tokenizer instance which parses Tab Separated Value strings. * The default for CSV processing will be trim whitespace from both ends * (which can be overridden with the setTrimmer method). * @param input the string to parse * @return a new tokenizer instance which parses Tab Separated Value strings. */ public static StrTokenizer getTSVInstance(String input) { StrTokenizer tok = getTSVClone(); tok.reset(input); return tok; } /** * Gets a new tokenizer instance which parses Tab Separated Value strings. * The default for CSV processing will be trim whitespace from both ends * (which can be overridden with the setTrimmer method). * @param input the string to parse * @return a new tokenizer instance which parses Tab Separated Value strings. */ public static StrTokenizer getTSVInstance(char[] input) { StrTokenizer tok = getTSVClone(); tok.reset(input); return tok; } //----------------------------------------------------------------------- /** * Constructs a tokenizer splitting on space, tab, newline and formfeed * as per StringTokenizer, but with no text to tokenize. *

    * This constructor is normally used with {@link #reset(String)}. */ public StrTokenizer() { super(); this.chars = null; } /** * Constructs a tokenizer splitting on space, tab, newline and formfeed * as per StringTokenizer. * * @param input the string which is to be parsed */ public StrTokenizer(String input) { super(); if (input != null) { chars = input.toCharArray(); } else { chars = null; } } /** * Constructs a tokenizer splitting on the specified delimiter character. * * @param input the string which is to be parsed * @param delim the field delimiter character */ public StrTokenizer(String input, char delim) { this(input); setDelimiterChar(delim); } /** * Constructs a tokenizer splitting on the specified delimiter string. * * @param input the string which is to be parsed * @param delim the field delimiter string */ public StrTokenizer(String input, String delim) { this(input); setDelimiterString(delim); } /** * Constructs a tokenizer splitting using the specified delimiter matcher. * * @param input the string which is to be parsed * @param delim the field delimiter matcher */ public StrTokenizer(String input, StrMatcher delim) { this(input); setDelimiterMatcher(delim); } /** * Constructs a tokenizer splitting on the specified delimiter character * and handling quotes using the specified quote character. * * @param input the string which is to be parsed * @param delim the field delimiter character * @param quote the field quoted string character */ public StrTokenizer(String input, char delim, char quote) { this(input, delim); setQuoteChar(quote); } /** * Constructs a tokenizer splitting using the specified delimiter matcher * and handling quotes using the specified quote matcher. * * @param input the string which is to be parsed * @param delim the field delimiter matcher * @param quote the field quoted string matcher */ public StrTokenizer(String input, StrMatcher delim, StrMatcher quote) { this(input, delim); setQuoteMatcher(quote); } /** * Constructs a tokenizer splitting on space, tab, newline and formfeed * as per StringTokenizer. *

    * The input character array is not cloned, and must not be altered after * passing in to this method. * * @param input the string which is to be parsed, not cloned */ public StrTokenizer(char[] input) { super(); this.chars = input; } /** * Constructs a tokenizer splitting on the specified character. *

    * The input character array is not cloned, and must not be altered after * passing in to this method. * * @param input the string which is to be parsed, not cloned * @param delim the field delimiter character */ public StrTokenizer(char[] input, char delim) { this(input); setDelimiterChar(delim); } /** * Constructs a tokenizer splitting on the specified string. *

    * The input character array is not cloned, and must not be altered after * passing in to this method. * * @param input the string which is to be parsed, not cloned * @param delim the field delimiter string */ public StrTokenizer(char[] input, String delim) { this(input); setDelimiterString(delim); } /** * Constructs a tokenizer splitting using the specified delimiter matcher. *

    * The input character array is not cloned, and must not be altered after * passing in to this method. * * @param input the string which is to be parsed, not cloned * @param delim the field delimiter matcher */ public StrTokenizer(char[] input, StrMatcher delim) { this(input); setDelimiterMatcher(delim); } /** * Constructs a tokenizer splitting on the specified delimiter character * and handling quotes using the specified quote character. *

    * The input character array is not cloned, and must not be altered after * passing in to this method. * * @param input the string which is to be parsed, not cloned * @param delim the field delimiter character * @param quote the field quoted string character */ public StrTokenizer(char[] input, char delim, char quote) { this(input, delim); setQuoteChar(quote); } /** * Constructs a tokenizer splitting using the specified delimiter matcher * and handling quotes using the specified quote matcher. *

    * The input character array is not cloned, and must not be altered after * passing in to this method. * * @param input the string which is to be parsed, not cloned * @param delim the field delimiter character * @param quote the field quoted string character */ public StrTokenizer(char[] input, StrMatcher delim, StrMatcher quote) { this(input, delim); setQuoteMatcher(quote); } // API //----------------------------------------------------------------------- /** * Gets the number of tokens found in the String. * * @return the number of matched tokens */ public int size() { checkTokenized(); return tokens.length; } /** * Gets the next token from the String. * Equivalent to {@link #next()} except it returns null rather than * throwing {@link NoSuchElementException} when no tokens remain. * * @return the next sequential token, or null when no more tokens are found */ public String nextToken() { if (hasNext()) { return tokens[tokenPos++]; } return null; } /** * Gets the previous token from the String. * * @return the previous sequential token, or null when no more tokens are found */ public String previousToken() { if (hasPrevious()) { return tokens[--tokenPos]; } return null; } /** * Gets a copy of the full token list as an independent modifiable array. * * @return the tokens as a String array */ public String[] getTokenArray() { checkTokenized(); return (String[]) tokens.clone(); } /** * Gets a copy of the full token list as an independent modifiable list. * * @return the tokens as a String array */ public List getTokenList() { checkTokenized(); List list = new ArrayList(tokens.length); for (int i = 0; i < tokens.length; i++) { list.add(tokens[i]); } return list; } /** * Resets this tokenizer, forgetting all parsing and iteration already completed. *

    * This method allows the same tokenizer to be reused for the same String. * * @return this, to enable chaining */ public StrTokenizer reset() { tokenPos = 0; tokens = null; return this; } /** * Reset this tokenizer, giving it a new input string to parse. * In this manner you can re-use a tokenizer with the same settings * on multiple input lines. * * @param input the new string to tokenize, null sets no text to parse * @return this, to enable chaining */ public StrTokenizer reset(String input) { reset(); if (input != null) { this.chars = input.toCharArray(); } else { this.chars = null; } return this; } /** * Reset this tokenizer, giving it a new input string to parse. * In this manner you can re-use a tokenizer with the same settings * on multiple input lines. *

    * The input character array is not cloned, and must not be altered after * passing in to this method. * * @param input the new character array to tokenize, not cloned, null sets no text to parse * @return this, to enable chaining */ public StrTokenizer reset(char[] input) { reset(); this.chars = input; return this; } // ListIterator //----------------------------------------------------------------------- /** * Checks whether there are any more tokens. * * @return true if there are more tokens */ public boolean hasNext() { checkTokenized(); return tokenPos < tokens.length; } /** * Gets the next token. * * @return the next String token * @throws NoSuchElementException if there are no more elements */ public Object next() { if (hasNext()) { return tokens[tokenPos++]; } throw new NoSuchElementException(); } /** * Gets the index of the next token to return. * * @return the next token index */ public int nextIndex() { return tokenPos; } /** * Checks whether there are any previous tokens that can be iterated to. * * @return true if there are previous tokens */ public boolean hasPrevious() { checkTokenized(); return tokenPos > 0; } /** * Gets the token previous to the last returned token. * * @return the previous token */ public Object previous() { if (hasPrevious()) { return tokens[--tokenPos]; } throw new NoSuchElementException(); } /** * Gets the index of the previous token. * * @return the previous token index */ public int previousIndex() { return tokenPos - 1; } /** * Unsupported ListIterator operation. * * @throws UnsupportedOperationException always */ public void remove() { throw new UnsupportedOperationException("remove() is unsupported"); } /** * Unsupported ListIterator operation. * @param obj this parameter ignored. * @throws UnsupportedOperationException always */ public void set(Object obj) { throw new UnsupportedOperationException("set() is unsupported"); } /** * Unsupported ListIterator operation. * @param obj this parameter ignored. * @throws UnsupportedOperationException always */ public void add(Object obj) { throw new UnsupportedOperationException("add() is unsupported"); } // Implementation //----------------------------------------------------------------------- /** * Checks if tokenization has been done, and if not then do it. */ private void checkTokenized() { if (tokens == null) { if (chars == null) { // still call tokenize as subclass may do some work List split = tokenize(null, 0, 0); tokens = (String[]) split.toArray(new String[split.size()]); } else { List split = tokenize(chars, 0, chars.length); tokens = (String[]) split.toArray(new String[split.size()]); } } } /** * Internal method to performs the tokenization. *

    * Most users of this class do not need to call this method. This method * will be called automatically by other (public) methods when required. *

    * This method exists to allow subclasses to add code before or after the * tokenization. For example, a subclass could alter the character array, * offset or count to be parsed, or call the tokenizer multiple times on * multiple strings. It is also be possible to filter the results. *

    * StrTokenizer will always pass a zero offset and a count * equal to the length of the array to this method, however a subclass * may pass other values, or even an entirely different array. * * @param chars the character array being tokenized, may be null * @param offset the start position within the character array, must be valid * @param count the number of characters to tokenize, must be valid * @return the modifiable list of String tokens, unmodifiable if null array or zero count */ protected List tokenize(char[] chars, int offset, int count) { if (chars == null || count == 0) { return Collections.EMPTY_LIST; } StrBuilder buf = new StrBuilder(); List tokens = new ArrayList(); int pos = offset; // loop around the entire buffer while (pos >= 0 && pos < count) { // find next token pos = readNextToken(chars, pos, count, buf, tokens); // handle case where end of string is a delimiter if (pos >= count) { addToken(tokens, ""); } } return tokens; } /** * Adds a token to a list, paying attention to the parameters we've set. * * @param list the list to add to * @param tok the token to add */ private void addToken(List list, String tok) { if (tok == null || tok.length() == 0) { if (isIgnoreEmptyTokens()) { return; } if (isEmptyTokenAsNull()) { tok = null; } } list.add(tok); } /** * Reads character by character through the String to get the next token. * * @param chars the character array being tokenized * @param start the first character of field * @param len the length of the character array being tokenized * @param workArea a temporary work area * @param tokens the list of parsed tokens * @return the starting position of the next field (the character * immediately after the delimiter), or -1 if end of string found */ private int readNextToken(char[] chars, int start, int len, StrBuilder workArea, List tokens) { // skip all leading whitespace, unless it is the // field delimiter or the quote character while (start < len) { int removeLen = Math.max( getIgnoredMatcher().isMatch(chars, start, start, len), getTrimmerMatcher().isMatch(chars, start, start, len)); if (removeLen == 0 || getDelimiterMatcher().isMatch(chars, start, start, len) > 0 || getQuoteMatcher().isMatch(chars, start, start, len) > 0) { break; } start += removeLen; } // handle reaching end if (start >= len) { addToken(tokens, ""); return -1; } // handle empty token int delimLen = getDelimiterMatcher().isMatch(chars, start, start, len); if (delimLen > 0) { addToken(tokens, ""); return start + delimLen; } // handle found token int quoteLen = getQuoteMatcher().isMatch(chars, start, start, len); if (quoteLen > 0) { return readWithQuotes(chars, start + quoteLen, len, workArea, tokens, start, quoteLen); } return readWithQuotes(chars, start, len, workArea, tokens, 0, 0); } /** * Reads a possibly quoted string token. * * @param chars the character array being tokenized * @param start the first character of field * @param len the length of the character array being tokenized * @param workArea a temporary work area * @param tokens the list of parsed tokens * @param quoteStart the start position of the matched quote, 0 if no quoting * @param quoteLen the length of the matched quote, 0 if no quoting * @return the starting position of the next field (the character * immediately after the delimiter, or if end of string found, * then the length of string */ private int readWithQuotes(char[] chars, int start, int len, StrBuilder workArea, List tokens, int quoteStart, int quoteLen) { // Loop until we've found the end of the quoted // string or the end of the input workArea.clear(); int pos = start; boolean quoting = (quoteLen > 0); int trimStart = 0; while (pos < len) { // quoting mode can occur several times throughout a string // we must switch between quoting and non-quoting until we // encounter a non-quoted delimiter, or end of string if (quoting) { // In quoting mode // If we've found a quote character, see if it's // followed by a second quote. If so, then we need // to actually put the quote character into the token // rather than end the token. if (isQuote(chars, pos, len, quoteStart, quoteLen)) { if (isQuote(chars, pos + quoteLen, len, quoteStart, quoteLen)) { // matched pair of quotes, thus an escaped quote workArea.append(chars, pos, quoteLen); pos += (quoteLen * 2); trimStart = workArea.size(); continue; } // end of quoting quoting = false; pos += quoteLen; continue; } // copy regular character from inside quotes workArea.append(chars[pos++]); trimStart = workArea.size(); } else { // Not in quoting mode // check for delimiter, and thus end of token int delimLen = getDelimiterMatcher().isMatch(chars, pos, start, len); if (delimLen > 0) { // return condition when end of token found addToken(tokens, workArea.substring(0, trimStart)); return pos + delimLen; } // check for quote, and thus back into quoting mode if (quoteLen > 0) { if (isQuote(chars, pos, len, quoteStart, quoteLen)) { quoting = true; pos += quoteLen; continue; } } // check for ignored (outside quotes), and ignore int ignoredLen = getIgnoredMatcher().isMatch(chars, pos, start, len); if (ignoredLen > 0) { pos += ignoredLen; continue; } // check for trimmed character // don't yet know if its at the end, so copy to workArea // use trimStart to keep track of trim at the end int trimmedLen = getTrimmerMatcher().isMatch(chars, pos, start, len); if (trimmedLen > 0) { workArea.append(chars, pos, trimmedLen); pos += trimmedLen; continue; } // copy regular character from outside quotes workArea.append(chars[pos++]); trimStart = workArea.size(); } } // return condition when end of string found addToken(tokens, workArea.substring(0, trimStart)); return -1; } /** * Checks if the characters at the index specified match the quote * already matched in readNextToken(). * * @param chars the character array being tokenized * @param pos the position to check for a quote * @param len the length of the character array being tokenized * @param quoteStart the start position of the matched quote, 0 if no quoting * @param quoteLen the length of the matched quote, 0 if no quoting * @return true if a quote is matched */ private boolean isQuote(char[] chars, int pos, int len, int quoteStart, int quoteLen) { for (int i = 0; i < quoteLen; i++) { if ((pos + i) >= len || chars[pos + i] != chars[quoteStart + i]) { return false; } } return true; } // Delimiter //----------------------------------------------------------------------- /** * Gets the field delimiter matcher. * * @return the delimiter matcher in use */ public StrMatcher getDelimiterMatcher() { return this.delimMatcher; } /** * Sets the field delimiter matcher. *

    * The delimitier is used to separate one token from another. * * @param delim the delimiter matcher to use * @return this, to enable chaining */ public StrTokenizer setDelimiterMatcher(StrMatcher delim) { if (delim == null) { this.delimMatcher = StrMatcher.noneMatcher(); } else { this.delimMatcher = delim; } return this; } /** * Sets the field delimiter character. * * @param delim the delimiter character to use * @return this, to enable chaining */ public StrTokenizer setDelimiterChar(char delim) { return setDelimiterMatcher(StrMatcher.charMatcher(delim)); } /** * Sets the field delimiter string. * * @param delim the delimiter string to use * @return this, to enable chaining */ public StrTokenizer setDelimiterString(String delim) { return setDelimiterMatcher(StrMatcher.stringMatcher(delim)); } // Quote //----------------------------------------------------------------------- /** * Gets the quote matcher currently in use. *

    * The quote character is used to wrap data between the tokens. * This enables delimiters to be entered as data. * The default value is '"' (double quote). * * @return the quote matcher in use */ public StrMatcher getQuoteMatcher() { return quoteMatcher; } /** * Set the quote matcher to use. *

    * The quote character is used to wrap data between the tokens. * This enables delimiters to be entered as data. * * @param quote the quote matcher to use, null ignored * @return this, to enable chaining */ public StrTokenizer setQuoteMatcher(StrMatcher quote) { if (quote != null) { this.quoteMatcher = quote; } return this; } /** * Sets the quote character to use. *

    * The quote character is used to wrap data between the tokens. * This enables delimiters to be entered as data. * * @param quote the quote character to use * @return this, to enable chaining */ public StrTokenizer setQuoteChar(char quote) { return setQuoteMatcher(StrMatcher.charMatcher(quote)); } // Ignored //----------------------------------------------------------------------- /** * Gets the ignored character matcher. *

    * These characters are ignored when parsing the String, unless they are * within a quoted region. * The default value is not to ignore anything. * * @return the ignored matcher in use */ public StrMatcher getIgnoredMatcher() { return ignoredMatcher; } /** * Set the matcher for characters to ignore. *

    * These characters are ignored when parsing the String, unless they are * within a quoted region. * * @param ignored the ignored matcher to use, null ignored * @return this, to enable chaining */ public StrTokenizer setIgnoredMatcher(StrMatcher ignored) { if (ignored != null) { this.ignoredMatcher = ignored; } return this; } /** * Set the character to ignore. *

    * This character is ignored when parsing the String, unless it is * within a quoted region. * * @param ignored the ignored character to use * @return this, to enable chaining */ public StrTokenizer setIgnoredChar(char ignored) { return setIgnoredMatcher(StrMatcher.charMatcher(ignored)); } // Trimmer //----------------------------------------------------------------------- /** * Gets the trimmer character matcher. *

    * These characters are trimmed off on each side of the delimiter * until the token or quote is found. * The default value is not to trim anything. * * @return the trimmer matcher in use */ public StrMatcher getTrimmerMatcher() { return trimmerMatcher; } /** * Sets the matcher for characters to trim. *

    * These characters are trimmed off on each side of the delimiter * until the token or quote is found. * * @param trimmer the trimmer matcher to use, null ignored * @return this, to enable chaining */ public StrTokenizer setTrimmerMatcher(StrMatcher trimmer) { if (trimmer != null) { this.trimmerMatcher = trimmer; } return this; } //----------------------------------------------------------------------- /** * Gets whether the tokenizer currently returns empty tokens as null. * The default for this property is false. * * @return true if empty tokens are returned as null */ public boolean isEmptyTokenAsNull() { return this.emptyAsNull; } /** * Sets whether the tokenizer should return empty tokens as null. * The default for this property is false. * * @param emptyAsNull whether empty tokens are returned as null * @return this, to enable chaining */ public StrTokenizer setEmptyTokenAsNull(boolean emptyAsNull) { this.emptyAsNull = emptyAsNull; return this; } //----------------------------------------------------------------------- /** * Gets whether the tokenizer currently ignores empty tokens. * The default for this property is true. * * @return true if empty tokens are not returned */ public boolean isIgnoreEmptyTokens() { return ignoreEmptyTokens; } /** * Sets whether the tokenizer should ignore and not return empty tokens. * The default for this property is true. * * @param ignoreEmptyTokens whether empty tokens are not returned * @return this, to enable chaining */ public StrTokenizer setIgnoreEmptyTokens(boolean ignoreEmptyTokens) { this.ignoreEmptyTokens = ignoreEmptyTokens; return this; } //----------------------------------------------------------------------- /** * Gets the String content that the tokenizer is parsing. * * @return the string content being parsed */ public String getContent() { if (chars == null) { return null; } return new String(chars); } //----------------------------------------------------------------------- /** * Creates a new instance of this Tokenizer. The new instance is reset so * that it will be at the start of the token list. * If a {@link CloneNotSupportedException} is caught, return null. * * @return a new instance of this Tokenizer which has been reset. */ public Object clone() { try { return cloneReset(); } catch (CloneNotSupportedException ex) { return null; } } /** * Creates a new instance of this Tokenizer. The new instance is reset so that * it will be at the start of the token list. * * @return a new instance of this Tokenizer which has been reset. * @throws CloneNotSupportedException if there is a problem cloning */ Object cloneReset() throws CloneNotSupportedException { // this method exists to enable 100% test coverage StrTokenizer cloned = (StrTokenizer) super.clone(); if (cloned.chars != null) { cloned.chars = (char[]) cloned.chars.clone(); } cloned.reset(); return cloned; } //----------------------------------------------------------------------- /** * Gets the String content that the tokenizer is parsing. * * @return the string content being parsed */ public String toString() { if (tokens == null) { return "StrTokenizer[not tokenized yet]"; } return "StrTokenizer" + getTokenList(); } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/time/DateFormatUtils.java100644 0 0 30345 11513702443 25624 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.time; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.TimeZone; /** *

    Date and time formatting utilities and constants.

    * *

    Formatting is performed using the * {@link org.apache.commons.lang.time.FastDateFormat} class.

    * * @author Apache Software Foundation * @author Apache Ant - DateUtils * @author Stephane Bailliez * @author Stefan Bodewig * @author Gary Gregory * @since 2.0 * @version $Id: DateFormatUtils.java 905636 2010-02-02 14:03:32Z niallp $ */ public class DateFormatUtils { /** * ISO8601 formatter for date-time without time zone. * The format used is yyyy-MM-dd'T'HH:mm:ss. */ public static final FastDateFormat ISO_DATETIME_FORMAT = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ss"); /** * ISO8601 formatter for date-time with time zone. * The format used is yyyy-MM-dd'T'HH:mm:ssZZ. */ public static final FastDateFormat ISO_DATETIME_TIME_ZONE_FORMAT = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ssZZ"); /** * ISO8601 formatter for date without time zone. * The format used is yyyy-MM-dd. */ public static final FastDateFormat ISO_DATE_FORMAT = FastDateFormat.getInstance("yyyy-MM-dd"); /** * ISO8601-like formatter for date with time zone. * The format used is yyyy-MM-ddZZ. * This pattern does not comply with the formal ISO8601 specification * as the standard does not allow a time zone without a time. */ public static final FastDateFormat ISO_DATE_TIME_ZONE_FORMAT = FastDateFormat.getInstance("yyyy-MM-ddZZ"); /** * ISO8601 formatter for time without time zone. * The format used is 'T'HH:mm:ss. */ public static final FastDateFormat ISO_TIME_FORMAT = FastDateFormat.getInstance("'T'HH:mm:ss"); /** * ISO8601 formatter for time with time zone. * The format used is 'T'HH:mm:ssZZ. */ public static final FastDateFormat ISO_TIME_TIME_ZONE_FORMAT = FastDateFormat.getInstance("'T'HH:mm:ssZZ"); /** * ISO8601-like formatter for time without time zone. * The format used is HH:mm:ss. * This pattern does not comply with the formal ISO8601 specification * as the standard requires the 'T' prefix for times. */ public static final FastDateFormat ISO_TIME_NO_T_FORMAT = FastDateFormat.getInstance("HH:mm:ss"); /** * ISO8601-like formatter for time with time zone. * The format used is HH:mm:ssZZ. * This pattern does not comply with the formal ISO8601 specification * as the standard requires the 'T' prefix for times. */ public static final FastDateFormat ISO_TIME_NO_T_TIME_ZONE_FORMAT = FastDateFormat.getInstance("HH:mm:ssZZ"); /** * SMTP (and probably other) date headers. * The format used is EEE, dd MMM yyyy HH:mm:ss Z in US locale. */ public static final FastDateFormat SMTP_DATETIME_FORMAT = FastDateFormat.getInstance("EEE, dd MMM yyyy HH:mm:ss Z", Locale.US); //----------------------------------------------------------------------- /** *

    DateFormatUtils instances should NOT be constructed in standard programming.

    * *

    This constructor is public to permit tools that require a JavaBean instance * to operate.

    */ public DateFormatUtils() { super(); } /** *

    Formats a date/time into a specific pattern using the UTC time zone.

    * * @param millis the date to format expressed in milliseconds * @param pattern the pattern to use to format the date * @return the formatted date */ public static String formatUTC(long millis, String pattern) { return format(new Date(millis), pattern, DateUtils.UTC_TIME_ZONE, null); } /** *

    Formats a date/time into a specific pattern using the UTC time zone.

    * * @param date the date to format * @param pattern the pattern to use to format the date * @return the formatted date */ public static String formatUTC(Date date, String pattern) { return format(date, pattern, DateUtils.UTC_TIME_ZONE, null); } /** *

    Formats a date/time into a specific pattern using the UTC time zone.

    * * @param millis the date to format expressed in milliseconds * @param pattern the pattern to use to format the date * @param locale the locale to use, may be null * @return the formatted date */ public static String formatUTC(long millis, String pattern, Locale locale) { return format(new Date(millis), pattern, DateUtils.UTC_TIME_ZONE, locale); } /** *

    Formats a date/time into a specific pattern using the UTC time zone.

    * * @param date the date to format * @param pattern the pattern to use to format the date * @param locale the locale to use, may be null * @return the formatted date */ public static String formatUTC(Date date, String pattern, Locale locale) { return format(date, pattern, DateUtils.UTC_TIME_ZONE, locale); } /** *

    Formats a date/time into a specific pattern.

    * * @param millis the date to format expressed in milliseconds * @param pattern the pattern to use to format the date * @return the formatted date */ public static String format(long millis, String pattern) { return format(new Date(millis), pattern, null, null); } /** *

    Formats a date/time into a specific pattern.

    * * @param date the date to format * @param pattern the pattern to use to format the date * @return the formatted date */ public static String format(Date date, String pattern) { return format(date, pattern, null, null); } /** *

    Formats a calendar into a specific pattern.

    * * @param calendar the calendar to format * @param pattern the pattern to use to format the calendar * @return the formatted calendar * @see FastDateFormat#format(Calendar) * @since 2.4 */ public static String format(Calendar calendar, String pattern) { return format(calendar, pattern, null, null); } /** *

    Formats a date/time into a specific pattern in a time zone.

    * * @param millis the time expressed in milliseconds * @param pattern the pattern to use to format the date * @param timeZone the time zone to use, may be null * @return the formatted date */ public static String format(long millis, String pattern, TimeZone timeZone) { return format(new Date(millis), pattern, timeZone, null); } /** *

    Formats a date/time into a specific pattern in a time zone.

    * * @param date the date to format * @param pattern the pattern to use to format the date * @param timeZone the time zone to use, may be null * @return the formatted date */ public static String format(Date date, String pattern, TimeZone timeZone) { return format(date, pattern, timeZone, null); } /** *

    Formats a calendar into a specific pattern in a time zone.

    * * @param calendar the calendar to format * @param pattern the pattern to use to format the calendar * @param timeZone the time zone to use, may be null * @return the formatted calendar * @see FastDateFormat#format(Calendar) * @since 2.4 */ public static String format(Calendar calendar, String pattern, TimeZone timeZone) { return format(calendar, pattern, timeZone, null); } /** *

    Formats a date/time into a specific pattern in a locale.

    * * @param millis the date to format expressed in milliseconds * @param pattern the pattern to use to format the date * @param locale the locale to use, may be null * @return the formatted date */ public static String format(long millis, String pattern, Locale locale) { return format(new Date(millis), pattern, null, locale); } /** *

    Formats a date/time into a specific pattern in a locale.

    * * @param date the date to format * @param pattern the pattern to use to format the date * @param locale the locale to use, may be null * @return the formatted date */ public static String format(Date date, String pattern, Locale locale) { return format(date, pattern, null, locale); } /** *

    Formats a calendar into a specific pattern in a locale.

    * * @param calendar the calendar to format * @param pattern the pattern to use to format the calendar * @param locale the locale to use, may be null * @return the formatted calendar * @see FastDateFormat#format(Calendar) * @since 2.4 */ public static String format(Calendar calendar, String pattern, Locale locale) { return format(calendar, pattern, null, locale); } /** *

    Formats a date/time into a specific pattern in a time zone and locale.

    * * @param millis the date to format expressed in milliseconds * @param pattern the pattern to use to format the date * @param timeZone the time zone to use, may be null * @param locale the locale to use, may be null * @return the formatted date */ public static String format(long millis, String pattern, TimeZone timeZone, Locale locale) { return format(new Date(millis), pattern, timeZone, locale); } /** *

    Formats a date/time into a specific pattern in a time zone and locale.

    * * @param date the date to format * @param pattern the pattern to use to format the date * @param timeZone the time zone to use, may be null * @param locale the locale to use, may be null * @return the formatted date */ public static String format(Date date, String pattern, TimeZone timeZone, Locale locale) { FastDateFormat df = FastDateFormat.getInstance(pattern, timeZone, locale); return df.format(date); } /** *

    Formats a calendar into a specific pattern in a time zone and locale.

    * * @param calendar the calendar to format * @param pattern the pattern to use to format the calendar * @param timeZone the time zone to use, may be null * @param locale the locale to use, may be null * @return the formatted calendar * @see FastDateFormat#format(Calendar) * @since 2.4 */ public static String format(Calendar calendar, String pattern, TimeZone timeZone, Locale locale) { FastDateFormat df = FastDateFormat.getInstance(pattern, timeZone, locale); return df.format(calendar); } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/time/DateUtils.java100644 0 0 243404 11513702443 24475 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.time; import java.text.ParseException; import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.TimeZone; import org.apache.commons.lang.StringUtils; /** *

    A suite of utilities surrounding the use of the * {@link java.util.Calendar} and {@link java.util.Date} object.

    * *

    DateUtils contains a lot of common methods considering manipulations * of Dates or Calendars. Some methods require some extra explanation. * The truncate, ceiling and round methods could be considered the Math.floor(), * Math.ceil() or Math.round versions for dates * This way date-fields will be ignored in bottom-up order. * As a complement to these methods we've introduced some fragment-methods. * With these methods the Date-fields will be ignored in top-down order. * Since a date without a year is not a valid date, you have to decide in what * kind of date-field you want your result, for instance milliseconds or days. *

    * * * * @author Apache Software Foundation * @author Serge Knystautas * @author Janek Bogucki * @author Gary Gregory * @author Phil Steitz * @author Robert Scholte * @since 2.0 * @version $Id: DateUtils.java 1056840 2011-01-09 00:12:23Z niallp $ */ public class DateUtils { /** * The UTC time zone (often referred to as GMT). */ public static final TimeZone UTC_TIME_ZONE = TimeZone.getTimeZone("GMT"); /** * Number of milliseconds in a standard second. * @since 2.1 */ public static final long MILLIS_PER_SECOND = 1000; /** * Number of milliseconds in a standard minute. * @since 2.1 */ public static final long MILLIS_PER_MINUTE = 60 * MILLIS_PER_SECOND; /** * Number of milliseconds in a standard hour. * @since 2.1 */ public static final long MILLIS_PER_HOUR = 60 * MILLIS_PER_MINUTE; /** * Number of milliseconds in a standard day. * @since 2.1 */ public static final long MILLIS_PER_DAY = 24 * MILLIS_PER_HOUR; /** * This is half a month, so this represents whether a date is in the top * or bottom half of the month. */ public final static int SEMI_MONTH = 1001; private static final int[][] fields = { {Calendar.MILLISECOND}, {Calendar.SECOND}, {Calendar.MINUTE}, {Calendar.HOUR_OF_DAY, Calendar.HOUR}, {Calendar.DATE, Calendar.DAY_OF_MONTH, Calendar.AM_PM /* Calendar.DAY_OF_YEAR, Calendar.DAY_OF_WEEK, Calendar.DAY_OF_WEEK_IN_MONTH */ }, {Calendar.MONTH, DateUtils.SEMI_MONTH}, {Calendar.YEAR}, {Calendar.ERA}}; /** * A week range, starting on Sunday. */ public final static int RANGE_WEEK_SUNDAY = 1; /** * A week range, starting on Monday. */ public final static int RANGE_WEEK_MONDAY = 2; /** * A week range, starting on the day focused. */ public final static int RANGE_WEEK_RELATIVE = 3; /** * A week range, centered around the day focused. */ public final static int RANGE_WEEK_CENTER = 4; /** * A month range, the week starting on Sunday. */ public final static int RANGE_MONTH_SUNDAY = 5; /** * A month range, the week starting on Monday. */ public final static int RANGE_MONTH_MONDAY = 6; /** * Constant marker for truncating */ private final static int MODIFY_TRUNCATE = 0; /** * Constant marker for rounding */ private final static int MODIFY_ROUND = 1; /** * Constant marker for ceiling */ private final static int MODIFY_CEILING= 2; /** *

    DateUtils instances should NOT be constructed in * standard programming. Instead, the class should be used as * DateUtils.parse(str);.

    * *

    This constructor is public to permit tools that require a JavaBean * instance to operate.

    */ public DateUtils() { super(); } //----------------------------------------------------------------------- /** *

    Checks if two date objects are on the same day ignoring time.

    * *

    28 Mar 2002 13:45 and 28 Mar 2002 06:01 would return true. * 28 Mar 2002 13:45 and 12 Mar 2002 13:45 would return false. *

    * * @param date1 the first date, not altered, not null * @param date2 the second date, not altered, not null * @return true if they represent the same day * @throws IllegalArgumentException if either date is null * @since 2.1 */ public static boolean isSameDay(Date date1, Date date2) { if (date1 == null || date2 == null) { throw new IllegalArgumentException("The date must not be null"); } Calendar cal1 = Calendar.getInstance(); cal1.setTime(date1); Calendar cal2 = Calendar.getInstance(); cal2.setTime(date2); return isSameDay(cal1, cal2); } /** *

    Checks if two calendar objects are on the same day ignoring time.

    * *

    28 Mar 2002 13:45 and 28 Mar 2002 06:01 would return true. * 28 Mar 2002 13:45 and 12 Mar 2002 13:45 would return false. *

    * * @param cal1 the first calendar, not altered, not null * @param cal2 the second calendar, not altered, not null * @return true if they represent the same day * @throws IllegalArgumentException if either calendar is null * @since 2.1 */ public static boolean isSameDay(Calendar cal1, Calendar cal2) { if (cal1 == null || cal2 == null) { throw new IllegalArgumentException("The date must not be null"); } return (cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA) && cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) && cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR)); } //----------------------------------------------------------------------- /** *

    Checks if two date objects represent the same instant in time.

    * *

    This method compares the long millisecond time of the two objects.

    * * @param date1 the first date, not altered, not null * @param date2 the second date, not altered, not null * @return true if they represent the same millisecond instant * @throws IllegalArgumentException if either date is null * @since 2.1 */ public static boolean isSameInstant(Date date1, Date date2) { if (date1 == null || date2 == null) { throw new IllegalArgumentException("The date must not be null"); } return date1.getTime() == date2.getTime(); } /** *

    Checks if two calendar objects represent the same instant in time.

    * *

    This method compares the long millisecond time of the two objects.

    * * @param cal1 the first calendar, not altered, not null * @param cal2 the second calendar, not altered, not null * @return true if they represent the same millisecond instant * @throws IllegalArgumentException if either date is null * @since 2.1 */ public static boolean isSameInstant(Calendar cal1, Calendar cal2) { if (cal1 == null || cal2 == null) { throw new IllegalArgumentException("The date must not be null"); } return cal1.getTime().getTime() == cal2.getTime().getTime(); } //----------------------------------------------------------------------- /** *

    Checks if two calendar objects represent the same local time.

    * *

    This method compares the values of the fields of the two objects. * In addition, both calendars must be the same of the same type.

    * * @param cal1 the first calendar, not altered, not null * @param cal2 the second calendar, not altered, not null * @return true if they represent the same millisecond instant * @throws IllegalArgumentException if either date is null * @since 2.1 */ public static boolean isSameLocalTime(Calendar cal1, Calendar cal2) { if (cal1 == null || cal2 == null) { throw new IllegalArgumentException("The date must not be null"); } return (cal1.get(Calendar.MILLISECOND) == cal2.get(Calendar.MILLISECOND) && cal1.get(Calendar.SECOND) == cal2.get(Calendar.SECOND) && cal1.get(Calendar.MINUTE) == cal2.get(Calendar.MINUTE) && cal1.get(Calendar.HOUR) == cal2.get(Calendar.HOUR) && cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR) && cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) && cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA) && cal1.getClass() == cal2.getClass()); } //----------------------------------------------------------------------- /** *

    Parses a string representing a date by trying a variety of different parsers.

    * *

    The parse will try each parse pattern in turn. * A parse is only deemed successful if it parses the whole of the input string. * If no parse patterns match, a ParseException is thrown.

    * The parser will be lenient toward the parsed date. * * @param str the date to parse, not null * @param parsePatterns the date format patterns to use, see SimpleDateFormat, not null * @return the parsed date * @throws IllegalArgumentException if the date string or pattern array is null * @throws ParseException if none of the date patterns were suitable (or there were none) */ public static Date parseDate(String str, String[] parsePatterns) throws ParseException { return parseDateWithLeniency(str, parsePatterns, true); } //----------------------------------------------------------------------- /** *

    Parses a string representing a date by trying a variety of different parsers.

    * *

    The parse will try each parse pattern in turn. * A parse is only deemed successful if it parses the whole of the input string. * If no parse patterns match, a ParseException is thrown.

    * The parser parses strictly - it does not allow for dates such as "February 942, 1996". * * @param str the date to parse, not null * @param parsePatterns the date format patterns to use, see SimpleDateFormat, not null * @return the parsed date * @throws IllegalArgumentException if the date string or pattern array is null * @throws ParseException if none of the date patterns were suitable * @since 2.5 */ public static Date parseDateStrictly(String str, String[] parsePatterns) throws ParseException { return parseDateWithLeniency(str, parsePatterns, false); } /** *

    Parses a string representing a date by trying a variety of different parsers.

    * *

    The parse will try each parse pattern in turn. * A parse is only deemed successful if it parses the whole of the input string. * If no parse patterns match, a ParseException is thrown.

    * * @param str the date to parse, not null * @param parsePatterns the date format patterns to use, see SimpleDateFormat, not null * @param lenient Specify whether or not date/time parsing is to be lenient. * @return the parsed date * @throws IllegalArgumentException if the date string or pattern array is null * @throws ParseException if none of the date patterns were suitable * @see java.util.Calender#isLenient() */ private static Date parseDateWithLeniency(String str, String[] parsePatterns, boolean lenient) throws ParseException { if (str == null || parsePatterns == null) { throw new IllegalArgumentException("Date and Patterns must not be null"); } SimpleDateFormat parser = new SimpleDateFormat(); parser.setLenient(lenient); ParsePosition pos = new ParsePosition(0); for (int i = 0; i < parsePatterns.length; i++) { String pattern = parsePatterns[i]; // LANG-530 - need to make sure 'ZZ' output doesn't get passed to SimpleDateFormat if (parsePatterns[i].endsWith("ZZ")) { pattern = pattern.substring(0, pattern.length() - 1); } parser.applyPattern(pattern); pos.setIndex(0); String str2 = str; // LANG-530 - need to make sure 'ZZ' output doesn't hit SimpleDateFormat as it will ParseException if (parsePatterns[i].endsWith("ZZ")) { int signIdx = indexOfSignChars(str2, 0); while (signIdx >=0) { str2 = reformatTimezone(str2, signIdx); signIdx = indexOfSignChars(str2, ++signIdx); } } Date date = parser.parse(str2, pos); if (date != null && pos.getIndex() == str2.length()) { return date; } } throw new ParseException("Unable to parse the date: " + str, -1); } /** * Index of sign charaters (i.e. '+' or '-'). * * @param str The string to search * @param startPos The start position * @return the index of the first sign character or -1 if not found */ private static int indexOfSignChars(String str, int startPos) { int idx = StringUtils.indexOf(str, '+', startPos); if (idx < 0) { idx = StringUtils.indexOf(str, '-', startPos); } return idx; } /** * Reformat the timezone in a date string. * * @param str The input string * @param signIdx The index position of the sign characters * @return The reformatted string */ private static String reformatTimezone(String str, int signIdx) { String str2 = str; if (signIdx >= 0 && signIdx + 5 < str.length() && Character.isDigit(str.charAt(signIdx + 1)) && Character.isDigit(str.charAt(signIdx + 2)) && str.charAt(signIdx + 3) == ':' && Character.isDigit(str.charAt(signIdx + 4)) && Character.isDigit(str.charAt(signIdx + 5))) { str2 = str.substring(0, signIdx + 3) + str.substring(signIdx + 4); } return str2; } //----------------------------------------------------------------------- /** * Adds a number of years to a date returning a new object. * The original date object is unchanged. * * @param date the date, not null * @param amount the amount to add, may be negative * @return the new date object with the amount added * @throws IllegalArgumentException if the date is null */ public static Date addYears(Date date, int amount) { return add(date, Calendar.YEAR, amount); } //----------------------------------------------------------------------- /** * Adds a number of months to a date returning a new object. * The original date object is unchanged. * * @param date the date, not null * @param amount the amount to add, may be negative * @return the new date object with the amount added * @throws IllegalArgumentException if the date is null */ public static Date addMonths(Date date, int amount) { return add(date, Calendar.MONTH, amount); } //----------------------------------------------------------------------- /** * Adds a number of weeks to a date returning a new object. * The original date object is unchanged. * * @param date the date, not null * @param amount the amount to add, may be negative * @return the new date object with the amount added * @throws IllegalArgumentException if the date is null */ public static Date addWeeks(Date date, int amount) { return add(date, Calendar.WEEK_OF_YEAR, amount); } //----------------------------------------------------------------------- /** * Adds a number of days to a date returning a new object. * The original date object is unchanged. * * @param date the date, not null * @param amount the amount to add, may be negative * @return the new date object with the amount added * @throws IllegalArgumentException if the date is null */ public static Date addDays(Date date, int amount) { return add(date, Calendar.DAY_OF_MONTH, amount); } //----------------------------------------------------------------------- /** * Adds a number of hours to a date returning a new object. * The original date object is unchanged. * * @param date the date, not null * @param amount the amount to add, may be negative * @return the new date object with the amount added * @throws IllegalArgumentException if the date is null */ public static Date addHours(Date date, int amount) { return add(date, Calendar.HOUR_OF_DAY, amount); } //----------------------------------------------------------------------- /** * Adds a number of minutes to a date returning a new object. * The original date object is unchanged. * * @param date the date, not null * @param amount the amount to add, may be negative * @return the new date object with the amount added * @throws IllegalArgumentException if the date is null */ public static Date addMinutes(Date date, int amount) { return add(date, Calendar.MINUTE, amount); } //----------------------------------------------------------------------- /** * Adds a number of seconds to a date returning a new object. * The original date object is unchanged. * * @param date the date, not null * @param amount the amount to add, may be negative * @return the new date object with the amount added * @throws IllegalArgumentException if the date is null */ public static Date addSeconds(Date date, int amount) { return add(date, Calendar.SECOND, amount); } //----------------------------------------------------------------------- /** * Adds a number of milliseconds to a date returning a new object. * The original date object is unchanged. * * @param date the date, not null * @param amount the amount to add, may be negative * @return the new date object with the amount added * @throws IllegalArgumentException if the date is null */ public static Date addMilliseconds(Date date, int amount) { return add(date, Calendar.MILLISECOND, amount); } //----------------------------------------------------------------------- /** * Adds to a date returning a new object. * The original date object is unchanged. * * @param date the date, not null * @param calendarField the calendar field to add to * @param amount the amount to add, may be negative * @return the new date object with the amount added * @throws IllegalArgumentException if the date is null * @deprecated Will become privately scoped in 3.0 */ public static Date add(Date date, int calendarField, int amount) { if (date == null) { throw new IllegalArgumentException("The date must not be null"); } Calendar c = Calendar.getInstance(); c.setTime(date); c.add(calendarField, amount); return c.getTime(); } //----------------------------------------------------------------------- /** * Sets the years field to a date returning a new object. * The original date object is unchanged. * * @param date the date, not null * @param amount the amount to set * @return a new Date object set with the specified value * @throws IllegalArgumentException if the date is null * @since 2.4 */ public static Date setYears(Date date, int amount) { return set(date, Calendar.YEAR, amount); } //----------------------------------------------------------------------- /** * Sets the months field to a date returning a new object. * The original date object is unchanged. * * @param date the date, not null * @param amount the amount to set * @return a new Date object set with the specified value * @throws IllegalArgumentException if the date is null * @since 2.4 */ public static Date setMonths(Date date, int amount) { return set(date, Calendar.MONTH, amount); } //----------------------------------------------------------------------- /** * Sets the day of month field to a date returning a new object. * The original date object is unchanged. * * @param date the date, not null * @param amount the amount to set * @return a new Date object set with the specified value * @throws IllegalArgumentException if the date is null * @since 2.4 */ public static Date setDays(Date date, int amount) { return set(date, Calendar.DAY_OF_MONTH, amount); } //----------------------------------------------------------------------- /** * Sets the hours field to a date returning a new object. Hours range * from 0-23. * The original date object is unchanged. * * @param date the date, not null * @param amount the amount to set * @return a new Date object set with the specified value * @throws IllegalArgumentException if the date is null * @since 2.4 */ public static Date setHours(Date date, int amount) { return set(date, Calendar.HOUR_OF_DAY, amount); } //----------------------------------------------------------------------- /** * Sets the minute field to a date returning a new object. * The original date object is unchanged. * * @param date the date, not null * @param amount the amount to set * @return a new Date object set with the specified value * @throws IllegalArgumentException if the date is null * @since 2.4 */ public static Date setMinutes(Date date, int amount) { return set(date, Calendar.MINUTE, amount); } //----------------------------------------------------------------------- /** * Sets the seconds field to a date returning a new object. * The original date object is unchanged. * * @param date the date, not null * @param amount the amount to set * @return a new Date object set with the specified value * @throws IllegalArgumentException if the date is null * @since 2.4 */ public static Date setSeconds(Date date, int amount) { return set(date, Calendar.SECOND, amount); } //----------------------------------------------------------------------- /** * Sets the miliseconds field to a date returning a new object. * The original date object is unchanged. * * @param date the date, not null * @param amount the amount to set * @return a new Date object set with the specified value * @throws IllegalArgumentException if the date is null * @since 2.4 */ public static Date setMilliseconds(Date date, int amount) { return set(date, Calendar.MILLISECOND, amount); } //----------------------------------------------------------------------- /** * Sets the specified field to a date returning a new object. * This does not use a lenient calendar. * The original date object is unchanged. * * @param date the date, not null * @param calendarField the calendar field to set the amount to * @param amount the amount to set * @return a new Date object set with the specified value * @throws IllegalArgumentException if the date is null * @since 2.4 */ private static Date set(Date date, int calendarField, int amount) { if (date == null) { throw new IllegalArgumentException("The date must not be null"); } // getInstance() returns a new object, so this method is thread safe. Calendar c = Calendar.getInstance(); c.setLenient(false); c.setTime(date); c.set(calendarField, amount); return c.getTime(); } //----------------------------------------------------------------------- /** * Convert a Date into a Calendar object. * * @param date the date to convert to a Calendar * @return the created Calendar * @throws NullPointerException if null is passed in * @since 2.6 */ public static Calendar toCalendar(Date date) { Calendar c = Calendar.getInstance(); c.setTime(date); return c; } //----------------------------------------------------------------------- /** *

    Round this date, leaving the field specified as the most * significant field.

    * *

    For example, if you had the datetime of 28 Mar 2002 * 13:45:01.231, if this was passed with HOUR, it would return * 28 Mar 2002 14:00:00.000. If this was passed with MONTH, it * would return 1 April 2002 0:00:00.000.

    * *

    For a date in a timezone that handles the change to daylight * saving time, rounding to Calendar.HOUR_OF_DAY will behave as follows. * Suppose daylight saving time begins at 02:00 on March 30. Rounding a * date that crosses this time would produce the following values: *

      *
    • March 30, 2003 01:10 rounds to March 30, 2003 01:00
    • *
    • March 30, 2003 01:40 rounds to March 30, 2003 03:00
    • *
    • March 30, 2003 02:10 rounds to March 30, 2003 03:00
    • *
    • March 30, 2003 02:40 rounds to March 30, 2003 04:00
    • *
    *

    * * @param date the date to work with * @param field the field from Calendar * or SEMI_MONTH * @return the rounded date * @throws IllegalArgumentException if the date is null * @throws ArithmeticException if the year is over 280 million */ public static Date round(Date date, int field) { if (date == null) { throw new IllegalArgumentException("The date must not be null"); } Calendar gval = Calendar.getInstance(); gval.setTime(date); modify(gval, field, MODIFY_ROUND); return gval.getTime(); } /** *

    Round this date, leaving the field specified as the most * significant field.

    * *

    For example, if you had the datetime of 28 Mar 2002 * 13:45:01.231, if this was passed with HOUR, it would return * 28 Mar 2002 14:00:00.000. If this was passed with MONTH, it * would return 1 April 2002 0:00:00.000.

    * *

    For a date in a timezone that handles the change to daylight * saving time, rounding to Calendar.HOUR_OF_DAY will behave as follows. * Suppose daylight saving time begins at 02:00 on March 30. Rounding a * date that crosses this time would produce the following values: *

      *
    • March 30, 2003 01:10 rounds to March 30, 2003 01:00
    • *
    • March 30, 2003 01:40 rounds to March 30, 2003 03:00
    • *
    • March 30, 2003 02:10 rounds to March 30, 2003 03:00
    • *
    • March 30, 2003 02:40 rounds to March 30, 2003 04:00
    • *
    *

    * * @param date the date to work with * @param field the field from Calendar * or SEMI_MONTH * @return the rounded date (a different object) * @throws IllegalArgumentException if the date is null * @throws ArithmeticException if the year is over 280 million */ public static Calendar round(Calendar date, int field) { if (date == null) { throw new IllegalArgumentException("The date must not be null"); } Calendar rounded = (Calendar) date.clone(); modify(rounded, field, MODIFY_ROUND); return rounded; } /** *

    Round this date, leaving the field specified as the most * significant field.

    * *

    For example, if you had the datetime of 28 Mar 2002 * 13:45:01.231, if this was passed with HOUR, it would return * 28 Mar 2002 14:00:00.000. If this was passed with MONTH, it * would return 1 April 2002 0:00:00.000.

    * *

    For a date in a timezone that handles the change to daylight * saving time, rounding to Calendar.HOUR_OF_DAY will behave as follows. * Suppose daylight saving time begins at 02:00 on March 30. Rounding a * date that crosses this time would produce the following values: *

      *
    • March 30, 2003 01:10 rounds to March 30, 2003 01:00
    • *
    • March 30, 2003 01:40 rounds to March 30, 2003 03:00
    • *
    • March 30, 2003 02:10 rounds to March 30, 2003 03:00
    • *
    • March 30, 2003 02:40 rounds to March 30, 2003 04:00
    • *
    *

    * * @param date the date to work with, either Date or Calendar * @param field the field from Calendar * or SEMI_MONTH * @return the rounded date * @throws IllegalArgumentException if the date is null * @throws ClassCastException if the object type is not a Date * or Calendar * @throws ArithmeticException if the year is over 280 million */ public static Date round(Object date, int field) { if (date == null) { throw new IllegalArgumentException("The date must not be null"); } if (date instanceof Date) { return round((Date) date, field); } else if (date instanceof Calendar) { return round((Calendar) date, field).getTime(); } else { throw new ClassCastException("Could not round " + date); } } //----------------------------------------------------------------------- /** *

    Truncate this date, leaving the field specified as the most * significant field.

    * *

    For example, if you had the datetime of 28 Mar 2002 * 13:45:01.231, if you passed with HOUR, it would return 28 Mar * 2002 13:00:00.000. If this was passed with MONTH, it would * return 1 Mar 2002 0:00:00.000.

    * * @param date the date to work with * @param field the field from Calendar * or SEMI_MONTH * @return the rounded date * @throws IllegalArgumentException if the date is null * @throws ArithmeticException if the year is over 280 million */ public static Date truncate(Date date, int field) { if (date == null) { throw new IllegalArgumentException("The date must not be null"); } Calendar gval = Calendar.getInstance(); gval.setTime(date); modify(gval, field, MODIFY_TRUNCATE); return gval.getTime(); } /** *

    Truncate this date, leaving the field specified as the most * significant field.

    * *

    For example, if you had the datetime of 28 Mar 2002 * 13:45:01.231, if you passed with HOUR, it would return 28 Mar * 2002 13:00:00.000. If this was passed with MONTH, it would * return 1 Mar 2002 0:00:00.000.

    * * @param date the date to work with * @param field the field from Calendar * or SEMI_MONTH * @return the rounded date (a different object) * @throws IllegalArgumentException if the date is null * @throws ArithmeticException if the year is over 280 million */ public static Calendar truncate(Calendar date, int field) { if (date == null) { throw new IllegalArgumentException("The date must not be null"); } Calendar truncated = (Calendar) date.clone(); modify(truncated, field, MODIFY_TRUNCATE); return truncated; } /** *

    Truncate this date, leaving the field specified as the most * significant field.

    * *

    For example, if you had the datetime of 28 Mar 2002 * 13:45:01.231, if you passed with HOUR, it would return 28 Mar * 2002 13:00:00.000. If this was passed with MONTH, it would * return 1 Mar 2002 0:00:00.000.

    * * @param date the date to work with, either Date * or Calendar * @param field the field from Calendar * or SEMI_MONTH * @return the rounded date * @throws IllegalArgumentException if the date * is null * @throws ClassCastException if the object type is not a * Date or Calendar * @throws ArithmeticException if the year is over 280 million */ public static Date truncate(Object date, int field) { if (date == null) { throw new IllegalArgumentException("The date must not be null"); } if (date instanceof Date) { return truncate((Date) date, field); } else if (date instanceof Calendar) { return truncate((Calendar) date, field).getTime(); } else { throw new ClassCastException("Could not truncate " + date); } } //----------------------------------------------------------------------- /** *

    Ceil this date, leaving the field specified as the most * significant field.

    * *

    For example, if you had the datetime of 28 Mar 2002 * 13:45:01.231, if you passed with HOUR, it would return 28 Mar * 2002 13:00:00.000. If this was passed with MONTH, it would * return 1 Mar 2002 0:00:00.000.

    * * @param date the date to work with * @param field the field from Calendar * or SEMI_MONTH * @return the rounded date * @throws IllegalArgumentException if the date is null * @throws ArithmeticException if the year is over 280 million * @since 2.5 */ public static Date ceiling(Date date, int field) { if (date == null) { throw new IllegalArgumentException("The date must not be null"); } Calendar gval = Calendar.getInstance(); gval.setTime(date); modify(gval, field, MODIFY_CEILING); return gval.getTime(); } /** *

    Ceil this date, leaving the field specified as the most * significant field.

    * *

    For example, if you had the datetime of 28 Mar 2002 * 13:45:01.231, if you passed with HOUR, it would return 28 Mar * 2002 13:00:00.000. If this was passed with MONTH, it would * return 1 Mar 2002 0:00:00.000.

    * * @param date the date to work with * @param field the field from Calendar * or SEMI_MONTH * @return the rounded date (a different object) * @throws IllegalArgumentException if the date is null * @throws ArithmeticException if the year is over 280 million * @since 2.5 */ public static Calendar ceiling(Calendar date, int field) { if (date == null) { throw new IllegalArgumentException("The date must not be null"); } Calendar ceiled = (Calendar) date.clone(); modify(ceiled, field, MODIFY_CEILING); return ceiled; } /** *

    Ceil this date, leaving the field specified as the most * significant field.

    * *

    For example, if you had the datetime of 28 Mar 2002 * 13:45:01.231, if you passed with HOUR, it would return 28 Mar * 2002 13:00:00.000. If this was passed with MONTH, it would * return 1 Mar 2002 0:00:00.000.

    * * @param date the date to work with, either Date * or Calendar * @param field the field from Calendar * or SEMI_MONTH * @return the rounded date * @throws IllegalArgumentException if the date * is null * @throws ClassCastException if the object type is not a * Date or Calendar * @throws ArithmeticException if the year is over 280 million * @since 2.5 */ public static Date ceiling(Object date, int field) { if (date == null) { throw new IllegalArgumentException("The date must not be null"); } if (date instanceof Date) { return ceiling((Date) date, field); } else if (date instanceof Calendar) { return ceiling((Calendar) date, field).getTime(); } else { throw new ClassCastException("Could not find ceiling of for type: " + date.getClass()); } } //----------------------------------------------------------------------- /** *

    Internal calculation method.

    * * @param val the calendar * @param field the field constant * @param modType type to truncate, round or ceiling * @throws ArithmeticException if the year is over 280 million */ private static void modify(Calendar val, int field, int modType) { if (val.get(Calendar.YEAR) > 280000000) { throw new ArithmeticException("Calendar value too large for accurate calculations"); } if (field == Calendar.MILLISECOND) { return; } // ----------------- Fix for LANG-59 ---------------------- START --------------- // see http://issues.apache.org/jira/browse/LANG-59 // // Manually truncate milliseconds, seconds and minutes, rather than using // Calendar methods. Date date = val.getTime(); long time = date.getTime(); boolean done = false; // truncate milliseconds int millisecs = val.get(Calendar.MILLISECOND); if (MODIFY_TRUNCATE == modType || millisecs < 500) { time = time - millisecs; } if (field == Calendar.SECOND) { done = true; } // truncate seconds int seconds = val.get(Calendar.SECOND); if (!done && (MODIFY_TRUNCATE == modType || seconds < 30)) { time = time - (seconds * 1000L); } if (field == Calendar.MINUTE) { done = true; } // truncate minutes int minutes = val.get(Calendar.MINUTE); if (!done && (MODIFY_TRUNCATE == modType || minutes < 30)) { time = time - (minutes * 60000L); } // reset time if (date.getTime() != time) { date.setTime(time); val.setTime(date); } // ----------------- Fix for LANG-59 ----------------------- END ---------------- boolean roundUp = false; for (int i = 0; i < fields.length; i++) { for (int j = 0; j < fields[i].length; j++) { if (fields[i][j] == field) { //This is our field... we stop looping if (modType == MODIFY_CEILING || (modType == MODIFY_ROUND && roundUp)) { if (field == DateUtils.SEMI_MONTH) { //This is a special case that's hard to generalize //If the date is 1, we round up to 16, otherwise // we subtract 15 days and add 1 month if (val.get(Calendar.DATE) == 1) { val.add(Calendar.DATE, 15); } else { val.add(Calendar.DATE, -15); val.add(Calendar.MONTH, 1); } // ----------------- Fix for LANG-440 ---------------------- START --------------- } else if (field == Calendar.AM_PM) { // This is a special case // If the time is 0, we round up to 12, otherwise // we subtract 12 hours and add 1 day if (val.get(Calendar.HOUR_OF_DAY) == 0) { val.add(Calendar.HOUR_OF_DAY, 12); } else { val.add(Calendar.HOUR_OF_DAY, -12); val.add(Calendar.DATE, 1); } // ----------------- Fix for LANG-440 ---------------------- END --------------- } else { //We need at add one to this field since the // last number causes us to round up val.add(fields[i][0], 1); } } return; } } //We have various fields that are not easy roundings int offset = 0; boolean offsetSet = false; //These are special types of fields that require different rounding rules switch (field) { case DateUtils.SEMI_MONTH: if (fields[i][0] == Calendar.DATE) { //If we're going to drop the DATE field's value, // we want to do this our own way. //We need to subtrace 1 since the date has a minimum of 1 offset = val.get(Calendar.DATE) - 1; //If we're above 15 days adjustment, that means we're in the // bottom half of the month and should stay accordingly. if (offset >= 15) { offset -= 15; } //Record whether we're in the top or bottom half of that range roundUp = offset > 7; offsetSet = true; } break; case Calendar.AM_PM: if (fields[i][0] == Calendar.HOUR_OF_DAY) { //If we're going to drop the HOUR field's value, // we want to do this our own way. offset = val.get(Calendar.HOUR_OF_DAY); if (offset >= 12) { offset -= 12; } roundUp = offset >= 6; offsetSet = true; } break; } if (!offsetSet) { int min = val.getActualMinimum(fields[i][0]); int max = val.getActualMaximum(fields[i][0]); //Calculate the offset from the minimum allowed value offset = val.get(fields[i][0]) - min; //Set roundUp if this is more than half way between the minimum and maximum roundUp = offset > ((max - min) / 2); } //We need to remove this field if (offset != 0) { val.set(fields[i][0], val.get(fields[i][0]) - offset); } } throw new IllegalArgumentException("The field " + field + " is not supported"); } //----------------------------------------------------------------------- /** *

    This constructs an Iterator over each day in a date * range defined by a focus date and range style.

    * *

    For instance, passing Thursday, July 4, 2002 and a * RANGE_MONTH_SUNDAY will return an Iterator * that starts with Sunday, June 30, 2002 and ends with Saturday, August 3, * 2002, returning a Calendar instance for each intermediate day.

    * *

    This method provides an iterator that returns Calendar objects. * The days are progressed using {@link Calendar#add(int, int)}.

    * * @param focus the date to work with, not null * @param rangeStyle the style constant to use. Must be one of * {@link DateUtils#RANGE_MONTH_SUNDAY}, * {@link DateUtils#RANGE_MONTH_MONDAY}, * {@link DateUtils#RANGE_WEEK_SUNDAY}, * {@link DateUtils#RANGE_WEEK_MONDAY}, * {@link DateUtils#RANGE_WEEK_RELATIVE}, * {@link DateUtils#RANGE_WEEK_CENTER} * @return the date iterator, which always returns Calendar instances * @throws IllegalArgumentException if the date is null * @throws IllegalArgumentException if the rangeStyle is invalid */ public static Iterator iterator(Date focus, int rangeStyle) { if (focus == null) { throw new IllegalArgumentException("The date must not be null"); } Calendar gval = Calendar.getInstance(); gval.setTime(focus); return iterator(gval, rangeStyle); } /** *

    This constructs an Iterator over each day in a date * range defined by a focus date and range style.

    * *

    For instance, passing Thursday, July 4, 2002 and a * RANGE_MONTH_SUNDAY will return an Iterator * that starts with Sunday, June 30, 2002 and ends with Saturday, August 3, * 2002, returning a Calendar instance for each intermediate day.

    * *

    This method provides an iterator that returns Calendar objects. * The days are progressed using {@link Calendar#add(int, int)}.

    * * @param focus the date to work with * @param rangeStyle the style constant to use. Must be one of * {@link DateUtils#RANGE_MONTH_SUNDAY}, * {@link DateUtils#RANGE_MONTH_MONDAY}, * {@link DateUtils#RANGE_WEEK_SUNDAY}, * {@link DateUtils#RANGE_WEEK_MONDAY}, * {@link DateUtils#RANGE_WEEK_RELATIVE}, * {@link DateUtils#RANGE_WEEK_CENTER} * @return the date iterator * @throws IllegalArgumentException if the date is null * @throws IllegalArgumentException if the rangeStyle is invalid */ public static Iterator iterator(Calendar focus, int rangeStyle) { if (focus == null) { throw new IllegalArgumentException("The date must not be null"); } Calendar start = null; Calendar end = null; int startCutoff = Calendar.SUNDAY; int endCutoff = Calendar.SATURDAY; switch (rangeStyle) { case RANGE_MONTH_SUNDAY: case RANGE_MONTH_MONDAY: //Set start to the first of the month start = truncate(focus, Calendar.MONTH); //Set end to the last of the month end = (Calendar) start.clone(); end.add(Calendar.MONTH, 1); end.add(Calendar.DATE, -1); //Loop start back to the previous sunday or monday if (rangeStyle == RANGE_MONTH_MONDAY) { startCutoff = Calendar.MONDAY; endCutoff = Calendar.SUNDAY; } break; case RANGE_WEEK_SUNDAY: case RANGE_WEEK_MONDAY: case RANGE_WEEK_RELATIVE: case RANGE_WEEK_CENTER: //Set start and end to the current date start = truncate(focus, Calendar.DATE); end = truncate(focus, Calendar.DATE); switch (rangeStyle) { case RANGE_WEEK_SUNDAY: //already set by default break; case RANGE_WEEK_MONDAY: startCutoff = Calendar.MONDAY; endCutoff = Calendar.SUNDAY; break; case RANGE_WEEK_RELATIVE: startCutoff = focus.get(Calendar.DAY_OF_WEEK); endCutoff = startCutoff - 1; break; case RANGE_WEEK_CENTER: startCutoff = focus.get(Calendar.DAY_OF_WEEK) - 3; endCutoff = focus.get(Calendar.DAY_OF_WEEK) + 3; break; } break; default: throw new IllegalArgumentException("The range style " + rangeStyle + " is not valid."); } if (startCutoff < Calendar.SUNDAY) { startCutoff += 7; } if (startCutoff > Calendar.SATURDAY) { startCutoff -= 7; } if (endCutoff < Calendar.SUNDAY) { endCutoff += 7; } if (endCutoff > Calendar.SATURDAY) { endCutoff -= 7; } while (start.get(Calendar.DAY_OF_WEEK) != startCutoff) { start.add(Calendar.DATE, -1); } while (end.get(Calendar.DAY_OF_WEEK) != endCutoff) { end.add(Calendar.DATE, 1); } return new DateIterator(start, end); } /** *

    This constructs an Iterator over each day in a date * range defined by a focus date and range style.

    * *

    For instance, passing Thursday, July 4, 2002 and a * RANGE_MONTH_SUNDAY will return an Iterator * that starts with Sunday, June 30, 2002 and ends with Saturday, August 3, * 2002, returning a Calendar instance for each intermediate day.

    * * @param focus the date to work with, either * Date or Calendar * @param rangeStyle the style constant to use. Must be one of the range * styles listed for the {@link #iterator(Calendar, int)} method. * @return the date iterator * @throws IllegalArgumentException if the date * is null * @throws ClassCastException if the object type is * not a Date or Calendar */ public static Iterator iterator(Object focus, int rangeStyle) { if (focus == null) { throw new IllegalArgumentException("The date must not be null"); } if (focus instanceof Date) { return iterator((Date) focus, rangeStyle); } else if (focus instanceof Calendar) { return iterator((Calendar) focus, rangeStyle); } else { throw new ClassCastException("Could not iterate based on " + focus); } } /** *

    Returns the number of milliseconds within the * fragment. All datefields greater than the fragment will be ignored.

    * *

    Asking the milliseconds of any date will only return the number of milliseconds * of the current second (resulting in a number between 0 and 999). This * method will retrieve the number of milliseconds for any fragment. * For example, if you want to calculate the number of milliseconds past today, * your fragment is Calendar.DATE or Calendar.DAY_OF_YEAR. The result will * be all milliseconds of the past hour(s), minutes(s) and second(s).

    * *

    Valid fragments are: Calendar.YEAR, Calendar.MONTH, both * Calendar.DAY_OF_YEAR and Calendar.DATE, Calendar.HOUR_OF_DAY, * Calendar.MINUTE, Calendar.SECOND and Calendar.MILLISECOND * A fragment less than or equal to a SECOND field will return 0.

    * *

    *

      *
    • January 1, 2008 7:15:10.538 with Calendar.SECOND as fragment will return 538
    • *
    • January 6, 2008 7:15:10.538 with Calendar.SECOND as fragment will return 538
    • *
    • January 6, 2008 7:15:10.538 with Calendar.MINUTE as fragment will return 10538 (10*1000 + 538)
    • *
    • January 16, 2008 7:15:10.538 with Calendar.MILLISECOND as fragment will return 0 * (a millisecond cannot be split in milliseconds)
    • *
    *

    * * @param date the date to work with, not null * @param fragment the Calendar field part of date to calculate * @return number of milliseconds within the fragment of date * @throws IllegalArgumentException if the date is null or * fragment is not supported * @since 2.4 */ public static long getFragmentInMilliseconds(Date date, int fragment) { return getFragment(date, fragment, Calendar.MILLISECOND); } /** *

    Returns the number of seconds within the * fragment. All datefields greater than the fragment will be ignored.

    * *

    Asking the seconds of any date will only return the number of seconds * of the current minute (resulting in a number between 0 and 59). This * method will retrieve the number of seconds for any fragment. * For example, if you want to calculate the number of seconds past today, * your fragment is Calendar.DATE or Calendar.DAY_OF_YEAR. The result will * be all seconds of the past hour(s) and minutes(s).

    * *

    Valid fragments are: Calendar.YEAR, Calendar.MONTH, both * Calendar.DAY_OF_YEAR and Calendar.DATE, Calendar.HOUR_OF_DAY, * Calendar.MINUTE, Calendar.SECOND and Calendar.MILLISECOND * A fragment less than or equal to a SECOND field will return 0.

    * *

    *

      *
    • January 1, 2008 7:15:10.538 with Calendar.MINUTE as fragment will return 10 * (equivalent to deprecated date.getSeconds())
    • *
    • January 6, 2008 7:15:10.538 with Calendar.MINUTE as fragment will return 10 * (equivalent to deprecated date.getSeconds())
    • *
    • January 6, 2008 7:15:10.538 with Calendar.DAY_OF_YEAR as fragment will return 26110 * (7*3600 + 15*60 + 10)
    • *
    • January 16, 2008 7:15:10.538 with Calendar.MILLISECOND as fragment will return 0 * (a millisecond cannot be split in seconds)
    • *
    *

    * * @param date the date to work with, not null * @param fragment the Calendar field part of date to calculate * @return number of seconds within the fragment of date * @throws IllegalArgumentException if the date is null or * fragment is not supported * @since 2.4 */ public static long getFragmentInSeconds(Date date, int fragment) { return getFragment(date, fragment, Calendar.SECOND); } /** *

    Returns the number of minutes within the * fragment. All datefields greater than the fragment will be ignored.

    * *

    Asking the minutes of any date will only return the number of minutes * of the current hour (resulting in a number between 0 and 59). This * method will retrieve the number of minutes for any fragment. * For example, if you want to calculate the number of minutes past this month, * your fragment is Calendar.MONTH. The result will be all minutes of the * past day(s) and hour(s).

    * *

    Valid fragments are: Calendar.YEAR, Calendar.MONTH, both * Calendar.DAY_OF_YEAR and Calendar.DATE, Calendar.HOUR_OF_DAY, * Calendar.MINUTE, Calendar.SECOND and Calendar.MILLISECOND * A fragment less than or equal to a MINUTE field will return 0.

    * *

    *

      *
    • January 1, 2008 7:15:10.538 with Calendar.HOUR_OF_DAY as fragment will return 15 * (equivalent to deprecated date.getMinutes())
    • *
    • January 6, 2008 7:15:10.538 with Calendar.HOUR_OF_DAY as fragment will return 15 * (equivalent to deprecated date.getMinutes())
    • *
    • January 1, 2008 7:15:10.538 with Calendar.MONTH as fragment will return 15
    • *
    • January 6, 2008 7:15:10.538 with Calendar.MONTH as fragment will return 435 (7*60 + 15)
    • *
    • January 16, 2008 7:15:10.538 with Calendar.MILLISECOND as fragment will return 0 * (a millisecond cannot be split in minutes)
    • *
    *

    * * @param date the date to work with, not null * @param fragment the Calendar field part of date to calculate * @return number of minutes within the fragment of date * @throws IllegalArgumentException if the date is null or * fragment is not supported * @since 2.4 */ public static long getFragmentInMinutes(Date date, int fragment) { return getFragment(date, fragment, Calendar.MINUTE); } /** *

    Returns the number of hours within the * fragment. All datefields greater than the fragment will be ignored.

    * *

    Asking the hours of any date will only return the number of hours * of the current day (resulting in a number between 0 and 23). This * method will retrieve the number of hours for any fragment. * For example, if you want to calculate the number of hours past this month, * your fragment is Calendar.MONTH. The result will be all hours of the * past day(s).

    * *

    Valid fragments are: Calendar.YEAR, Calendar.MONTH, both * Calendar.DAY_OF_YEAR and Calendar.DATE, Calendar.HOUR_OF_DAY, * Calendar.MINUTE, Calendar.SECOND and Calendar.MILLISECOND * A fragment less than or equal to a HOUR field will return 0.

    * *

    *

      *
    • January 1, 2008 7:15:10.538 with Calendar.DAY_OF_YEAR as fragment will return 7 * (equivalent to deprecated date.getHours())
    • *
    • January 6, 2008 7:15:10.538 with Calendar.DAY_OF_YEAR as fragment will return 7 * (equivalent to deprecated date.getHours())
    • *
    • January 1, 2008 7:15:10.538 with Calendar.MONTH as fragment will return 7
    • *
    • January 6, 2008 7:15:10.538 with Calendar.MONTH as fragment will return 127 (5*24 + 7)
    • *
    • January 16, 2008 7:15:10.538 with Calendar.MILLISECOND as fragment will return 0 * (a millisecond cannot be split in hours)
    • *
    *

    * * @param date the date to work with, not null * @param fragment the Calendar field part of date to calculate * @return number of hours within the fragment of date * @throws IllegalArgumentException if the date is null or * fragment is not supported * @since 2.4 */ public static long getFragmentInHours(Date date, int fragment) { return getFragment(date, fragment, Calendar.HOUR_OF_DAY); } /** *

    Returns the number of days within the * fragment. All datefields greater than the fragment will be ignored.

    * *

    Asking the days of any date will only return the number of days * of the current month (resulting in a number between 1 and 31). This * method will retrieve the number of days for any fragment. * For example, if you want to calculate the number of days past this year, * your fragment is Calendar.YEAR. The result will be all days of the * past month(s).

    * *

    Valid fragments are: Calendar.YEAR, Calendar.MONTH, both * Calendar.DAY_OF_YEAR and Calendar.DATE, Calendar.HOUR_OF_DAY, * Calendar.MINUTE, Calendar.SECOND and Calendar.MILLISECOND * A fragment less than or equal to a DAY field will return 0.

    * *

    *

      *
    • January 28, 2008 with Calendar.MONTH as fragment will return 28 * (equivalent to deprecated date.getDay())
    • *
    • February 28, 2008 with Calendar.MONTH as fragment will return 28 * (equivalent to deprecated date.getDay())
    • *
    • January 28, 2008 with Calendar.YEAR as fragment will return 28
    • *
    • February 28, 2008 with Calendar.YEAR as fragment will return 59
    • *
    • January 28, 2008 with Calendar.MILLISECOND as fragment will return 0 * (a millisecond cannot be split in days)
    • *
    *

    * * @param date the date to work with, not null * @param fragment the Calendar field part of date to calculate * @return number of days within the fragment of date * @throws IllegalArgumentException if the date is null or * fragment is not supported * @since 2.4 */ public static long getFragmentInDays(Date date, int fragment) { return getFragment(date, fragment, Calendar.DAY_OF_YEAR); } /** *

    Returns the number of milliseconds within the * fragment. All datefields greater than the fragment will be ignored.

    * *

    Asking the milliseconds of any date will only return the number of milliseconds * of the current second (resulting in a number between 0 and 999). This * method will retrieve the number of milliseconds for any fragment. * For example, if you want to calculate the number of seconds past today, * your fragment is Calendar.DATE or Calendar.DAY_OF_YEAR. The result will * be all seconds of the past hour(s), minutes(s) and second(s).

    * *

    Valid fragments are: Calendar.YEAR, Calendar.MONTH, both * Calendar.DAY_OF_YEAR and Calendar.DATE, Calendar.HOUR_OF_DAY, * Calendar.MINUTE, Calendar.SECOND and Calendar.MILLISECOND * A fragment less than or equal to a MILLISECOND field will return 0.

    * *

    *

      *
    • January 1, 2008 7:15:10.538 with Calendar.SECOND as fragment will return 538 * (equivalent to calendar.get(Calendar.MILLISECOND))
    • *
    • January 6, 2008 7:15:10.538 with Calendar.SECOND as fragment will return 538 * (equivalent to calendar.get(Calendar.MILLISECOND))
    • *
    • January 6, 2008 7:15:10.538 with Calendar.MINUTE as fragment will return 10538 * (10*1000 + 538)
    • *
    • January 16, 2008 7:15:10.538 with Calendar.MILLISECOND as fragment will return 0 * (a millisecond cannot be split in milliseconds)
    • *
    *

    * * @param calendar the calendar to work with, not null * @param fragment the Calendar field part of calendar to calculate * @return number of milliseconds within the fragment of date * @throws IllegalArgumentException if the date is null or * fragment is not supported * @since 2.4 */ public static long getFragmentInMilliseconds(Calendar calendar, int fragment) { return getFragment(calendar, fragment, Calendar.MILLISECOND); } /** *

    Returns the number of seconds within the * fragment. All datefields greater than the fragment will be ignored.

    * *

    Asking the seconds of any date will only return the number of seconds * of the current minute (resulting in a number between 0 and 59). This * method will retrieve the number of seconds for any fragment. * For example, if you want to calculate the number of seconds past today, * your fragment is Calendar.DATE or Calendar.DAY_OF_YEAR. The result will * be all seconds of the past hour(s) and minutes(s).

    * *

    Valid fragments are: Calendar.YEAR, Calendar.MONTH, both * Calendar.DAY_OF_YEAR and Calendar.DATE, Calendar.HOUR_OF_DAY, * Calendar.MINUTE, Calendar.SECOND and Calendar.MILLISECOND * A fragment less than or equal to a SECOND field will return 0.

    * *

    *

      *
    • January 1, 2008 7:15:10.538 with Calendar.MINUTE as fragment will return 10 * (equivalent to calendar.get(Calendar.SECOND))
    • *
    • January 6, 2008 7:15:10.538 with Calendar.MINUTE as fragment will return 10 * (equivalent to calendar.get(Calendar.SECOND))
    • *
    • January 6, 2008 7:15:10.538 with Calendar.DAY_OF_YEAR as fragment will return 26110 * (7*3600 + 15*60 + 10)
    • *
    • January 16, 2008 7:15:10.538 with Calendar.MILLISECOND as fragment will return 0 * (a millisecond cannot be split in seconds)
    • *
    *

    * * @param calendar the calendar to work with, not null * @param fragment the Calendar field part of calendar to calculate * @return number of seconds within the fragment of date * @throws IllegalArgumentException if the date is null or * fragment is not supported * @since 2.4 */ public static long getFragmentInSeconds(Calendar calendar, int fragment) { return getFragment(calendar, fragment, Calendar.SECOND); } /** *

    Returns the number of minutes within the * fragment. All datefields greater than the fragment will be ignored.

    * *

    Asking the minutes of any date will only return the number of minutes * of the current hour (resulting in a number between 0 and 59). This * method will retrieve the number of minutes for any fragment. * For example, if you want to calculate the number of minutes past this month, * your fragment is Calendar.MONTH. The result will be all minutes of the * past day(s) and hour(s).

    * *

    Valid fragments are: Calendar.YEAR, Calendar.MONTH, both * Calendar.DAY_OF_YEAR and Calendar.DATE, Calendar.HOUR_OF_DAY, * Calendar.MINUTE, Calendar.SECOND and Calendar.MILLISECOND * A fragment less than or equal to a MINUTE field will return 0.

    * *

    *

      *
    • January 1, 2008 7:15:10.538 with Calendar.HOUR_OF_DAY as fragment will return 15 * (equivalent to calendar.get(Calendar.MINUTES))
    • *
    • January 6, 2008 7:15:10.538 with Calendar.HOUR_OF_DAY as fragment will return 15 * (equivalent to calendar.get(Calendar.MINUTES))
    • *
    • January 1, 2008 7:15:10.538 with Calendar.MONTH as fragment will return 15
    • *
    • January 6, 2008 7:15:10.538 with Calendar.MONTH as fragment will return 435 (7*60 + 15)
    • *
    • January 16, 2008 7:15:10.538 with Calendar.MILLISECOND as fragment will return 0 * (a millisecond cannot be split in minutes)
    • *
    *

    * * @param calendar the calendar to work with, not null * @param fragment the Calendar field part of calendar to calculate * @return number of minutes within the fragment of date * @throws IllegalArgumentException if the date is null or * fragment is not supported * @since 2.4 */ public static long getFragmentInMinutes(Calendar calendar, int fragment) { return getFragment(calendar, fragment, Calendar.MINUTE); } /** *

    Returns the number of hours within the * fragment. All datefields greater than the fragment will be ignored.

    * *

    Asking the hours of any date will only return the number of hours * of the current day (resulting in a number between 0 and 23). This * method will retrieve the number of hours for any fragment. * For example, if you want to calculate the number of hours past this month, * your fragment is Calendar.MONTH. The result will be all hours of the * past day(s).

    * *

    Valid fragments are: Calendar.YEAR, Calendar.MONTH, both * Calendar.DAY_OF_YEAR and Calendar.DATE, Calendar.HOUR_OF_DAY, * Calendar.MINUTE, Calendar.SECOND and Calendar.MILLISECOND * A fragment less than or equal to a HOUR field will return 0.

    * *

    *

      *
    • January 1, 2008 7:15:10.538 with Calendar.DAY_OF_YEAR as fragment will return 7 * (equivalent to calendar.get(Calendar.HOUR_OF_DAY))
    • *
    • January 6, 2008 7:15:10.538 with Calendar.DAY_OF_YEAR as fragment will return 7 * (equivalent to calendar.get(Calendar.HOUR_OF_DAY))
    • *
    • January 1, 2008 7:15:10.538 with Calendar.MONTH as fragment will return 7
    • *
    • January 6, 2008 7:15:10.538 with Calendar.MONTH as fragment will return 127 (5*24 + 7)
    • *
    • January 16, 2008 7:15:10.538 with Calendar.MILLISECOND as fragment will return 0 * (a millisecond cannot be split in hours)
    • *
    *

    * * @param calendar the calendar to work with, not null * @param fragment the Calendar field part of calendar to calculate * @return number of hours within the fragment of date * @throws IllegalArgumentException if the date is null or * fragment is not supported * @since 2.4 */ public static long getFragmentInHours(Calendar calendar, int fragment) { return getFragment(calendar, fragment, Calendar.HOUR_OF_DAY); } /** *

    Returns the number of days within the * fragment. All datefields greater than the fragment will be ignored.

    * *

    Asking the days of any date will only return the number of days * of the current month (resulting in a number between 1 and 31). This * method will retrieve the number of days for any fragment. * For example, if you want to calculate the number of days past this year, * your fragment is Calendar.YEAR. The result will be all days of the * past month(s).

    * *

    Valid fragments are: Calendar.YEAR, Calendar.MONTH, both * Calendar.DAY_OF_YEAR and Calendar.DATE, Calendar.HOUR_OF_DAY, * Calendar.MINUTE, Calendar.SECOND and Calendar.MILLISECOND * A fragment less than or equal to a DAY field will return 0.

    * *

    *

      *
    • January 28, 2008 with Calendar.MONTH as fragment will return 28 * (equivalent to calendar.get(Calendar.DAY_OF_MONTH))
    • *
    • February 28, 2008 with Calendar.MONTH as fragment will return 28 * (equivalent to calendar.get(Calendar.DAY_OF_MONTH))
    • *
    • January 28, 2008 with Calendar.YEAR as fragment will return 28 * (equivalent to calendar.get(Calendar.DAY_OF_YEAR))
    • *
    • February 28, 2008 with Calendar.YEAR as fragment will return 59 * (equivalent to calendar.get(Calendar.DAY_OF_YEAR))
    • *
    • January 28, 2008 with Calendar.MILLISECOND as fragment will return 0 * (a millisecond cannot be split in days)
    • *
    *

    * * @param calendar the calendar to work with, not null * @param fragment the Calendar field part of calendar to calculate * @return number of days within the fragment of date * @throws IllegalArgumentException if the date is null or * fragment is not supported * @since 2.4 */ public static long getFragmentInDays(Calendar calendar, int fragment) { return getFragment(calendar, fragment, Calendar.DAY_OF_YEAR); } /** * Date-version for fragment-calculation in any unit * * @param date the date to work with, not null * @param fragment the Calendar field part of date to calculate * @param unit Calendar field defining the unit * @return number of units within the fragment of the date * @throws IllegalArgumentException if the date is null or * fragment is not supported * @since 2.4 */ private static long getFragment(Date date, int fragment, int unit) { if(date == null) { throw new IllegalArgumentException("The date must not be null"); } Calendar calendar = Calendar.getInstance(); calendar.setTime(date); return getFragment(calendar, fragment, unit); } /** * Calendar-version for fragment-calculation in any unit * * @param calendar the calendar to work with, not null * @param fragment the Calendar field part of calendar to calculate * @param unit Calendar field defining the unit * @return number of units within the fragment of the calendar * @throws IllegalArgumentException if the date is null or * fragment is not supported * @since 2.4 */ private static long getFragment(Calendar calendar, int fragment, int unit) { if(calendar == null) { throw new IllegalArgumentException("The date must not be null"); } long millisPerUnit = getMillisPerUnit(unit); long result = 0; // Fragments bigger than a day require a breakdown to days switch (fragment) { case Calendar.YEAR: result += (calendar.get(Calendar.DAY_OF_YEAR) * MILLIS_PER_DAY) / millisPerUnit; break; case Calendar.MONTH: result += (calendar.get(Calendar.DAY_OF_MONTH) * MILLIS_PER_DAY) / millisPerUnit; break; } switch (fragment) { // Number of days already calculated for these cases case Calendar.YEAR: case Calendar.MONTH: // The rest of the valid cases case Calendar.DAY_OF_YEAR: case Calendar.DATE: result += (calendar.get(Calendar.HOUR_OF_DAY) * MILLIS_PER_HOUR) / millisPerUnit; //$FALL-THROUGH$ case Calendar.HOUR_OF_DAY: result += (calendar.get(Calendar.MINUTE) * MILLIS_PER_MINUTE) / millisPerUnit; //$FALL-THROUGH$ case Calendar.MINUTE: result += (calendar.get(Calendar.SECOND) * MILLIS_PER_SECOND) / millisPerUnit; //$FALL-THROUGH$ case Calendar.SECOND: result += (calendar.get(Calendar.MILLISECOND) * 1) / millisPerUnit; break; case Calendar.MILLISECOND: break;//never useful default: throw new IllegalArgumentException("The fragment " + fragment + " is not supported"); } return result; } /** * Determines if two calendars are equal up to no more than the specified * most significant field. * * @param cal1 the first calendar, not null * @param cal2 the second calendar, not null * @param field the field from Calendar * @return true if equal; otherwise false * @throws IllegalArgumentException if any argument is null * @see #truncate(Calendar, int) * @see #truncatedEquals(Date, Date, int) * @since 2.6 */ public static boolean truncatedEquals(Calendar cal1, Calendar cal2, int field) { return truncatedCompareTo(cal1, cal2, field) == 0; } /** * Determines if two dates are equal up to no more than the specified * most significant field. * * @param date1 the first date, not null * @param date2 the second date, not null * @param field the field from Calendar * @return true if equal; otherwise false * @throws IllegalArgumentException if any argument is null * @see #truncate(Date, int) * @see #truncatedEquals(Calendar, Calendar, int) * @since 2.6 */ public static boolean truncatedEquals(Date date1, Date date2, int field) { return truncatedCompareTo(date1, date2, field) == 0; } /** * Determines how two calendars compare up to no more than the specified * most significant field. * * @param cal1 the first calendar, not null * @param cal2 the second calendar, not null * @param field the field from Calendar * @return a negative integer, zero, or a positive integer as the first * calendar is less than, equal to, or greater than the second. * @throws IllegalArgumentException if any argument is null * @see #truncate(Calendar, int) * @see #truncatedCompareTo(Date, Date, int) * @since 2.6 */ public static int truncatedCompareTo(Calendar cal1, Calendar cal2, int field) { Calendar truncatedCal1 = truncate(cal1, field); Calendar truncatedCal2 = truncate(cal2, field); return truncatedCal1.getTime().compareTo(truncatedCal2.getTime()); } /** * Determines how two dates compare up to no more than the specified * most significant field. * * @param date1 the first date, not null * @param date2 the second date, not null * @param field the field from Calendar * @return a negative integer, zero, or a positive integer as the first * date is less than, equal to, or greater than the second. * @throws IllegalArgumentException if any argument is null * @see #truncate(Calendar, int) * @see #truncatedCompareTo(Date, Date, int) * @since 2.6 */ public static int truncatedCompareTo(Date date1, Date date2, int field) { Date truncatedDate1 = truncate(date1, field); Date truncatedDate2 = truncate(date2, field); return truncatedDate1.compareTo(truncatedDate2); } /** * Returns the number of millis of a datefield, if this is a constant value * * @param unit A Calendar field which is a valid unit for a fragment * @return number of millis * @throws IllegalArgumentException if date can't be represented in millisenconds * @since 2.4 */ private static long getMillisPerUnit(int unit) { long result = Long.MAX_VALUE; switch (unit) { case Calendar.DAY_OF_YEAR: case Calendar.DATE: result = MILLIS_PER_DAY; break; case Calendar.HOUR_OF_DAY: result = MILLIS_PER_HOUR; break; case Calendar.MINUTE: result = MILLIS_PER_MINUTE; break; case Calendar.SECOND: result = MILLIS_PER_SECOND; break; case Calendar.MILLISECOND: result = 1; break; default: throw new IllegalArgumentException("The unit " + unit + " cannot be represented is milleseconds"); } return result; } /** *

    Date iterator.

    */ static class DateIterator implements Iterator { private final Calendar endFinal; private final Calendar spot; /** * Constructs a DateIterator that ranges from one date to another. * * @param startFinal start date (inclusive) * @param endFinal end date (not inclusive) */ DateIterator(Calendar startFinal, Calendar endFinal) { super(); this.endFinal = endFinal; spot = startFinal; spot.add(Calendar.DATE, -1); } /** * Has the iterator not reached the end date yet? * * @return true if the iterator has yet to reach the end date */ public boolean hasNext() { return spot.before(endFinal); } /** * Return the next calendar in the iteration * * @return Object calendar for the next date */ public Object next() { if (spot.equals(endFinal)) { throw new NoSuchElementException(); } spot.add(Calendar.DATE, 1); return spot.clone(); } /** * Always throws UnsupportedOperationException. * * @throws UnsupportedOperationException * @see java.util.Iterator#remove() */ public void remove() { throw new UnsupportedOperationException(); } } //------------------------------------------------------------------------- // Deprecated int constants // TODO: Remove in 3.0 /** * Number of milliseconds in a standard second. * * @deprecated Use MILLIS_PER_SECOND. This will be removed in Commons Lang 3.0. */ public static final int MILLIS_IN_SECOND = 1000; /** * Number of milliseconds in a standard minute. * * @deprecated Use MILLIS_PER_MINUTE. This will be removed in Commons Lang 3.0. */ public static final int MILLIS_IN_MINUTE = 60 * 1000; /** * Number of milliseconds in a standard hour. * * @deprecated Use MILLIS_PER_HOUR. This will be removed in Commons Lang 3.0. */ public static final int MILLIS_IN_HOUR = 60 * 60 * 1000; /** * Number of milliseconds in a standard day. * * @deprecated Use MILLIS_PER_DAY. This will be removed in Commons Lang 3.0. */ public static final int MILLIS_IN_DAY = 24 * 60 * 60 * 1000; } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/time/DurationFormatUtils.java100644 0 0 63243 11513702443 26537 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.time; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.TimeZone; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.text.StrBuilder; /** *

    Duration formatting utilities and constants. The following table describes the tokens * used in the pattern language for formatting.

    * * * * * * * * * *
    characterduration element
    yyears
    Mmonths
    ddays
    Hhours
    mminutes
    sseconds
    Smilliseconds
    * * @author Apache Software Foundation * @author Apache Ant - DateUtils * @author Stephane Bailliez * @author Stefan Bodewig * @author Gary Gregory * @since 2.1 * @version $Id: DurationFormatUtils.java 1057072 2011-01-10 01:55:57Z niallp $ */ public class DurationFormatUtils { /** *

    DurationFormatUtils instances should NOT be constructed in standard programming.

    * *

    This constructor is public to permit tools that require a JavaBean instance * to operate.

    */ public DurationFormatUtils() { super(); } /** *

    Pattern used with FastDateFormat and SimpleDateFormat * for the ISO8601 period format used in durations.

    * * @see org.apache.commons.lang.time.FastDateFormat * @see java.text.SimpleDateFormat */ public static final String ISO_EXTENDED_FORMAT_PATTERN = "'P'yyyy'Y'M'M'd'DT'H'H'm'M's.S'S'"; //----------------------------------------------------------------------- /** *

    Formats the time gap as a string.

    * *

    The format used is ISO8601-like: * H:m:s.S.

    * * @param durationMillis the duration to format * @return the time as a String */ public static String formatDurationHMS(long durationMillis) { return formatDuration(durationMillis, "H:mm:ss.SSS"); } /** *

    Formats the time gap as a string.

    * *

    The format used is the ISO8601 period format.

    * *

    This method formats durations using the days and lower fields of the * ISO format pattern, such as P7D6TH5M4.321S.

    * * @param durationMillis the duration to format * @return the time as a String */ public static String formatDurationISO(long durationMillis) { return formatDuration(durationMillis, ISO_EXTENDED_FORMAT_PATTERN, false); } /** *

    Formats the time gap as a string, using the specified format, and padding with zeros and * using the default timezone.

    * *

    This method formats durations using the days and lower fields of the * format pattern. Months and larger are not used.

    * * @param durationMillis the duration to format * @param format the way in which to format the duration * @return the time as a String */ public static String formatDuration(long durationMillis, String format) { return formatDuration(durationMillis, format, true); } /** *

    Formats the time gap as a string, using the specified format. * Padding the left hand side of numbers with zeroes is optional and * the timezone may be specified.

    * *

    This method formats durations using the days and lower fields of the * format pattern. Months and larger are not used.

    * * @param durationMillis the duration to format * @param format the way in which to format the duration * @param padWithZeros whether to pad the left hand side of numbers with 0's * @return the time as a String */ public static String formatDuration(long durationMillis, String format, boolean padWithZeros) { Token[] tokens = lexx(format); int days = 0; int hours = 0; int minutes = 0; int seconds = 0; int milliseconds = 0; if (Token.containsTokenWithValue(tokens, d) ) { days = (int) (durationMillis / DateUtils.MILLIS_PER_DAY); durationMillis = durationMillis - (days * DateUtils.MILLIS_PER_DAY); } if (Token.containsTokenWithValue(tokens, H) ) { hours = (int) (durationMillis / DateUtils.MILLIS_PER_HOUR); durationMillis = durationMillis - (hours * DateUtils.MILLIS_PER_HOUR); } if (Token.containsTokenWithValue(tokens, m) ) { minutes = (int) (durationMillis / DateUtils.MILLIS_PER_MINUTE); durationMillis = durationMillis - (minutes * DateUtils.MILLIS_PER_MINUTE); } if (Token.containsTokenWithValue(tokens, s) ) { seconds = (int) (durationMillis / DateUtils.MILLIS_PER_SECOND); durationMillis = durationMillis - (seconds * DateUtils.MILLIS_PER_SECOND); } if (Token.containsTokenWithValue(tokens, S) ) { milliseconds = (int) durationMillis; } return format(tokens, 0, 0, days, hours, minutes, seconds, milliseconds, padWithZeros); } /** *

    Formats an elapsed time into a plurialization correct string.

    * *

    This method formats durations using the days and lower fields of the * format pattern. Months and larger are not used.

    * * @param durationMillis the elapsed time to report in milliseconds * @param suppressLeadingZeroElements suppresses leading 0 elements * @param suppressTrailingZeroElements suppresses trailing 0 elements * @return the formatted text in days/hours/minutes/seconds */ public static String formatDurationWords( long durationMillis, boolean suppressLeadingZeroElements, boolean suppressTrailingZeroElements) { // This method is generally replacable by the format method, but // there are a series of tweaks and special cases that require // trickery to replicate. String duration = formatDuration(durationMillis, "d' days 'H' hours 'm' minutes 's' seconds'"); if (suppressLeadingZeroElements) { // this is a temporary marker on the front. Like ^ in regexp. duration = " " + duration; String tmp = StringUtils.replaceOnce(duration, " 0 days", ""); if (tmp.length() != duration.length()) { duration = tmp; tmp = StringUtils.replaceOnce(duration, " 0 hours", ""); if (tmp.length() != duration.length()) { duration = tmp; tmp = StringUtils.replaceOnce(duration, " 0 minutes", ""); duration = tmp; if (tmp.length() != duration.length()) { duration = StringUtils.replaceOnce(tmp, " 0 seconds", ""); } } } if (duration.length() != 0) { // strip the space off again duration = duration.substring(1); } } if (suppressTrailingZeroElements) { String tmp = StringUtils.replaceOnce(duration, " 0 seconds", ""); if (tmp.length() != duration.length()) { duration = tmp; tmp = StringUtils.replaceOnce(duration, " 0 minutes", ""); if (tmp.length() != duration.length()) { duration = tmp; tmp = StringUtils.replaceOnce(duration, " 0 hours", ""); if (tmp.length() != duration.length()) { duration = StringUtils.replaceOnce(tmp, " 0 days", ""); } } } } // handle plurals duration = " " + duration; duration = StringUtils.replaceOnce(duration, " 1 seconds", " 1 second"); duration = StringUtils.replaceOnce(duration, " 1 minutes", " 1 minute"); duration = StringUtils.replaceOnce(duration, " 1 hours", " 1 hour"); duration = StringUtils.replaceOnce(duration, " 1 days", " 1 day"); return duration.trim(); } //----------------------------------------------------------------------- /** *

    Formats the time gap as a string.

    * *

    The format used is the ISO8601 period format.

    * * @param startMillis the start of the duration to format * @param endMillis the end of the duration to format * @return the time as a String */ public static String formatPeriodISO(long startMillis, long endMillis) { return formatPeriod(startMillis, endMillis, ISO_EXTENDED_FORMAT_PATTERN, false, TimeZone.getDefault()); } /** *

    Formats the time gap as a string, using the specified format. * Padding the left hand side of numbers with zeroes is optional. * * @param startMillis the start of the duration * @param endMillis the end of the duration * @param format the way in which to format the duration * @return the time as a String */ public static String formatPeriod(long startMillis, long endMillis, String format) { return formatPeriod(startMillis, endMillis, format, true, TimeZone.getDefault()); } /** *

    Formats the time gap as a string, using the specified format. * Padding the left hand side of numbers with zeroes is optional and * the timezone may be specified.

    * *

    When calculating the difference between months/days, it chooses to * calculate months first. So when working out the number of months and * days between January 15th and March 10th, it choose 1 month and * 23 days gained by choosing January->February = 1 month and then * calculating days forwards, and not the 1 month and 26 days gained by * choosing March -> February = 1 month and then calculating days * backwards.

    * *

    For more control, the Joda-Time * library is recommended.

    * * @param startMillis the start of the duration * @param endMillis the end of the duration * @param format the way in which to format the duration * @param padWithZeros whether to pad the left hand side of numbers with 0's * @param timezone the millis are defined in * @return the time as a String */ public static String formatPeriod(long startMillis, long endMillis, String format, boolean padWithZeros, TimeZone timezone) { // Used to optimise for differences under 28 days and // called formatDuration(millis, format); however this did not work // over leap years. // TODO: Compare performance to see if anything was lost by // losing this optimisation. Token[] tokens = lexx(format); // timezones get funky around 0, so normalizing everything to GMT // stops the hours being off Calendar start = Calendar.getInstance(timezone); start.setTime(new Date(startMillis)); Calendar end = Calendar.getInstance(timezone); end.setTime(new Date(endMillis)); // initial estimates int milliseconds = end.get(Calendar.MILLISECOND) - start.get(Calendar.MILLISECOND); int seconds = end.get(Calendar.SECOND) - start.get(Calendar.SECOND); int minutes = end.get(Calendar.MINUTE) - start.get(Calendar.MINUTE); int hours = end.get(Calendar.HOUR_OF_DAY) - start.get(Calendar.HOUR_OF_DAY); int days = end.get(Calendar.DAY_OF_MONTH) - start.get(Calendar.DAY_OF_MONTH); int months = end.get(Calendar.MONTH) - start.get(Calendar.MONTH); int years = end.get(Calendar.YEAR) - start.get(Calendar.YEAR); // each initial estimate is adjusted in case it is under 0 while (milliseconds < 0) { milliseconds += 1000; seconds -= 1; } while (seconds < 0) { seconds += 60; minutes -= 1; } while (minutes < 0) { minutes += 60; hours -= 1; } while (hours < 0) { hours += 24; days -= 1; } if (Token.containsTokenWithValue(tokens, M)) { while (days < 0) { days += start.getActualMaximum(Calendar.DAY_OF_MONTH); months -= 1; start.add(Calendar.MONTH, 1); } while (months < 0) { months += 12; years -= 1; } if (!Token.containsTokenWithValue(tokens, y) && years != 0) { while (years != 0) { months += 12 * years; years = 0; } } } else { // there are no M's in the format string if( !Token.containsTokenWithValue(tokens, y) ) { int target = end.get(Calendar.YEAR); if (months < 0) { // target is end-year -1 target -= 1; } while ( (start.get(Calendar.YEAR) != target)) { days += start.getActualMaximum(Calendar.DAY_OF_YEAR) - start.get(Calendar.DAY_OF_YEAR); // Not sure I grok why this is needed, but the brutal tests show it is if(start instanceof GregorianCalendar) { if( (start.get(Calendar.MONTH) == Calendar.FEBRUARY) && (start.get(Calendar.DAY_OF_MONTH) == 29 ) ) { days += 1; } } start.add(Calendar.YEAR, 1); days += start.get(Calendar.DAY_OF_YEAR); } years = 0; } while( start.get(Calendar.MONTH) != end.get(Calendar.MONTH) ) { days += start.getActualMaximum(Calendar.DAY_OF_MONTH); start.add(Calendar.MONTH, 1); } months = 0; while (days < 0) { days += start.getActualMaximum(Calendar.DAY_OF_MONTH); months -= 1; start.add(Calendar.MONTH, 1); } } // The rest of this code adds in values that // aren't requested. This allows the user to ask for the // number of months and get the real count and not just 0->11. if (!Token.containsTokenWithValue(tokens, d)) { hours += 24 * days; days = 0; } if (!Token.containsTokenWithValue(tokens, H)) { minutes += 60 * hours; hours = 0; } if (!Token.containsTokenWithValue(tokens, m)) { seconds += 60 * minutes; minutes = 0; } if (!Token.containsTokenWithValue(tokens, s)) { milliseconds += 1000 * seconds; seconds = 0; } return format(tokens, years, months, days, hours, minutes, seconds, milliseconds, padWithZeros); } //----------------------------------------------------------------------- /** *

    The internal method to do the formatting.

    * * @param tokens the tokens * @param years the number of years * @param months the number of months * @param days the number of days * @param hours the number of hours * @param minutes the number of minutes * @param seconds the number of seconds * @param milliseconds the number of millis * @param padWithZeros whether to pad * @return the formatted string */ static String format(Token[] tokens, int years, int months, int days, int hours, int minutes, int seconds, int milliseconds, boolean padWithZeros) { StrBuilder buffer = new StrBuilder(); boolean lastOutputSeconds = false; int sz = tokens.length; for (int i = 0; i < sz; i++) { Token token = tokens[i]; Object value = token.getValue(); int count = token.getCount(); if (value instanceof StringBuffer) { buffer.append(value.toString()); } else { if (value == y) { buffer.append(padWithZeros ? StringUtils.leftPad(Integer.toString(years), count, '0') : Integer .toString(years)); lastOutputSeconds = false; } else if (value == M) { buffer.append(padWithZeros ? StringUtils.leftPad(Integer.toString(months), count, '0') : Integer .toString(months)); lastOutputSeconds = false; } else if (value == d) { buffer.append(padWithZeros ? StringUtils.leftPad(Integer.toString(days), count, '0') : Integer .toString(days)); lastOutputSeconds = false; } else if (value == H) { buffer.append(padWithZeros ? StringUtils.leftPad(Integer.toString(hours), count, '0') : Integer .toString(hours)); lastOutputSeconds = false; } else if (value == m) { buffer.append(padWithZeros ? StringUtils.leftPad(Integer.toString(minutes), count, '0') : Integer .toString(minutes)); lastOutputSeconds = false; } else if (value == s) { buffer.append(padWithZeros ? StringUtils.leftPad(Integer.toString(seconds), count, '0') : Integer .toString(seconds)); lastOutputSeconds = true; } else if (value == S) { if (lastOutputSeconds) { milliseconds += 1000; String str = padWithZeros ? StringUtils.leftPad(Integer.toString(milliseconds), count, '0') : Integer.toString(milliseconds); buffer.append(str.substring(1)); } else { buffer.append(padWithZeros ? StringUtils.leftPad(Integer.toString(milliseconds), count, '0') : Integer.toString(milliseconds)); } lastOutputSeconds = false; } } } return buffer.toString(); } static final Object y = "y"; static final Object M = "M"; static final Object d = "d"; static final Object H = "H"; static final Object m = "m"; static final Object s = "s"; static final Object S = "S"; /** * Parses a classic date format string into Tokens * * @param format to parse * @return array of Token[] */ static Token[] lexx(String format) { char[] array = format.toCharArray(); ArrayList list = new ArrayList(array.length); boolean inLiteral = false; StringBuffer buffer = null; Token previous = null; int sz = array.length; for(int i=0; itrue
    if contained */ static boolean containsTokenWithValue(Token[] tokens, Object value) { int sz = tokens.length; for (int i = 0; i < sz; i++) { if (tokens[i].getValue() == value) { return true; } } return false; } private Object value; private int count; /** * Wraps a token around a value. A value would be something like a 'Y'. * * @param value to wrap */ Token(Object value) { this.value = value; this.count = 1; } /** * Wraps a token around a repeated number of a value, for example it would * store 'yyyy' as a value for y and a count of 4. * * @param value to wrap * @param count to wrap */ Token(Object value, int count) { this.value = value; this.count = count; } /** * Adds another one of the value */ void increment() { count++; } /** * Gets the current number of values represented * * @return int number of values represented */ int getCount() { return count; } /** * Gets the particular value this token represents. * * @return Object value */ Object getValue() { return value; } /** * Supports equality of this Token to another Token. * * @param obj2 Object to consider equality of * @return boolean true if equal */ public boolean equals(Object obj2) { if (obj2 instanceof Token) { Token tok2 = (Token) obj2; if (this.value.getClass() != tok2.value.getClass()) { return false; } if (this.count != tok2.count) { return false; } if (this.value instanceof StringBuffer) { return this.value.toString().equals(tok2.value.toString()); } else if (this.value instanceof Number) { return this.value.equals(tok2.value); } else { return this.value == tok2.value; } } return false; } /** * Returns a hashcode for the token equal to the * hashcode for the token's value. Thus 'TT' and 'TTTT' * will have the same hashcode. * * @return The hashcode for the token */ public int hashCode() { return this.value.hashCode(); } /** * Represents this token as a String. * * @return String representation of the token */ public String toString() { return StringUtils.repeat(this.value.toString(), this.count); } } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/time/FastDateFormat.java100644 0 0 162132 11513702443 25441 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.time; import java.io.IOException; import java.io.ObjectInputStream; import java.text.DateFormat; import java.text.DateFormatSymbols; import java.text.FieldPosition; import java.text.Format; import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.TimeZone; import org.apache.commons.lang.Validate; import org.apache.commons.lang.text.StrBuilder; /** *

    FastDateFormat is a fast and thread-safe version of * {@link java.text.SimpleDateFormat}.

    * *

    This class can be used as a direct replacement to * SimpleDateFormat in most formatting situations. * This class is especially useful in multi-threaded server environments. * SimpleDateFormat is not thread-safe in any JDK version, * nor will it be as Sun have closed the bug/RFE. *

    * *

    Only formatting is supported, but all patterns are compatible with * SimpleDateFormat (except time zones - see below).

    * *

    Java 1.4 introduced a new pattern letter, 'Z', to represent * time zones in RFC822 format (eg. +0800 or -1100). * This pattern letter can be used here (on all JDK versions).

    * *

    In addition, the pattern 'ZZ' has been made to represent * ISO8601 full format time zones (eg. +08:00 or -11:00). * This introduces a minor incompatibility with Java 1.4, but at a gain of * useful functionality.

    * * @author Apache Software Foundation * @author TeaTrove project * @author Brian S O'Neill * @author Sean Schofield * @author Gary Gregory * @author Nikolay Metchev * @since 2.0 * @version $Id: FastDateFormat.java 1057072 2011-01-10 01:55:57Z niallp $ */ public class FastDateFormat extends Format { // A lot of the speed in this class comes from caching, but some comes // from the special int to StringBuffer conversion. // // The following produces a padded 2 digit number: // buffer.append((char)(value / 10 + '0')); // buffer.append((char)(value % 10 + '0')); // // Note that the fastest append to StringBuffer is a single char (used here). // Note that Integer.toString() is not called, the conversion is simply // taking the value and adding (mathematically) the ASCII value for '0'. // So, don't change this code! It works and is very fast. /** * Required for serialization support. * * @see java.io.Serializable */ private static final long serialVersionUID = 1L; /** * FULL locale dependent date or time style. */ public static final int FULL = DateFormat.FULL; /** * LONG locale dependent date or time style. */ public static final int LONG = DateFormat.LONG; /** * MEDIUM locale dependent date or time style. */ public static final int MEDIUM = DateFormat.MEDIUM; /** * SHORT locale dependent date or time style. */ public static final int SHORT = DateFormat.SHORT; private static String cDefaultPattern; // lazily initialised by getInstance() private static final Map cInstanceCache = new HashMap(7); private static final Map cDateInstanceCache = new HashMap(7); private static final Map cTimeInstanceCache = new HashMap(7); private static final Map cDateTimeInstanceCache = new HashMap(7); private static final Map cTimeZoneDisplayCache = new HashMap(7); /** * The pattern. */ private final String mPattern; /** * The time zone. */ private final TimeZone mTimeZone; /** * Whether the time zone overrides any on Calendars. */ private final boolean mTimeZoneForced; /** * The locale. */ private final Locale mLocale; /** * Whether the locale overrides the default. */ private final boolean mLocaleForced; /** * The parsed rules. */ private transient Rule[] mRules; /** * The estimated maximum length. */ private transient int mMaxLengthEstimate; //----------------------------------------------------------------------- /** *

    Gets a formatter instance using the default pattern in the * default locale.

    * * @return a date/time formatter */ public static FastDateFormat getInstance() { return getInstance(getDefaultPattern(), null, null); } /** *

    Gets a formatter instance using the specified pattern in the * default locale.

    * * @param pattern {@link java.text.SimpleDateFormat} compatible * pattern * @return a pattern based date/time formatter * @throws IllegalArgumentException if pattern is invalid */ public static FastDateFormat getInstance(String pattern) { return getInstance(pattern, null, null); } /** *

    Gets a formatter instance using the specified pattern and * time zone.

    * * @param pattern {@link java.text.SimpleDateFormat} compatible * pattern * @param timeZone optional time zone, overrides time zone of * formatted date * @return a pattern based date/time formatter * @throws IllegalArgumentException if pattern is invalid */ public static FastDateFormat getInstance(String pattern, TimeZone timeZone) { return getInstance(pattern, timeZone, null); } /** *

    Gets a formatter instance using the specified pattern and * locale.

    * * @param pattern {@link java.text.SimpleDateFormat} compatible * pattern * @param locale optional locale, overrides system locale * @return a pattern based date/time formatter * @throws IllegalArgumentException if pattern is invalid */ public static FastDateFormat getInstance(String pattern, Locale locale) { return getInstance(pattern, null, locale); } /** *

    Gets a formatter instance using the specified pattern, time zone * and locale.

    * * @param pattern {@link java.text.SimpleDateFormat} compatible * pattern * @param timeZone optional time zone, overrides time zone of * formatted date * @param locale optional locale, overrides system locale * @return a pattern based date/time formatter * @throws IllegalArgumentException if pattern is invalid * or null */ public static synchronized FastDateFormat getInstance(String pattern, TimeZone timeZone, Locale locale) { FastDateFormat emptyFormat = new FastDateFormat(pattern, timeZone, locale); FastDateFormat format = (FastDateFormat) cInstanceCache.get(emptyFormat); if (format == null) { format = emptyFormat; format.init(); // convert shell format into usable one cInstanceCache.put(format, format); // this is OK! } return format; } //----------------------------------------------------------------------- /** *

    Gets a date formatter instance using the specified style in the * default time zone and locale.

    * * @param style date style: FULL, LONG, MEDIUM, or SHORT * @return a localized standard date formatter * @throws IllegalArgumentException if the Locale has no date * pattern defined * @since 2.1 */ public static FastDateFormat getDateInstance(int style) { return getDateInstance(style, null, null); } /** *

    Gets a date formatter instance using the specified style and * locale in the default time zone.

    * * @param style date style: FULL, LONG, MEDIUM, or SHORT * @param locale optional locale, overrides system locale * @return a localized standard date formatter * @throws IllegalArgumentException if the Locale has no date * pattern defined * @since 2.1 */ public static FastDateFormat getDateInstance(int style, Locale locale) { return getDateInstance(style, null, locale); } /** *

    Gets a date formatter instance using the specified style and * time zone in the default locale.

    * * @param style date style: FULL, LONG, MEDIUM, or SHORT * @param timeZone optional time zone, overrides time zone of * formatted date * @return a localized standard date formatter * @throws IllegalArgumentException if the Locale has no date * pattern defined * @since 2.1 */ public static FastDateFormat getDateInstance(int style, TimeZone timeZone) { return getDateInstance(style, timeZone, null); } /** *

    Gets a date formatter instance using the specified style, time * zone and locale.

    * * @param style date style: FULL, LONG, MEDIUM, or SHORT * @param timeZone optional time zone, overrides time zone of * formatted date * @param locale optional locale, overrides system locale * @return a localized standard date formatter * @throws IllegalArgumentException if the Locale has no date * pattern defined */ public static synchronized FastDateFormat getDateInstance(int style, TimeZone timeZone, Locale locale) { Object key = new Integer(style); if (timeZone != null) { key = new Pair(key, timeZone); } if (locale == null) { locale = Locale.getDefault(); } key = new Pair(key, locale); FastDateFormat format = (FastDateFormat) cDateInstanceCache.get(key); if (format == null) { try { SimpleDateFormat formatter = (SimpleDateFormat) DateFormat.getDateInstance(style, locale); String pattern = formatter.toPattern(); format = getInstance(pattern, timeZone, locale); cDateInstanceCache.put(key, format); } catch (ClassCastException ex) { throw new IllegalArgumentException("No date pattern for locale: " + locale); } } return format; } //----------------------------------------------------------------------- /** *

    Gets a time formatter instance using the specified style in the * default time zone and locale.

    * * @param style time style: FULL, LONG, MEDIUM, or SHORT * @return a localized standard time formatter * @throws IllegalArgumentException if the Locale has no time * pattern defined * @since 2.1 */ public static FastDateFormat getTimeInstance(int style) { return getTimeInstance(style, null, null); } /** *

    Gets a time formatter instance using the specified style and * locale in the default time zone.

    * * @param style time style: FULL, LONG, MEDIUM, or SHORT * @param locale optional locale, overrides system locale * @return a localized standard time formatter * @throws IllegalArgumentException if the Locale has no time * pattern defined * @since 2.1 */ public static FastDateFormat getTimeInstance(int style, Locale locale) { return getTimeInstance(style, null, locale); } /** *

    Gets a time formatter instance using the specified style and * time zone in the default locale.

    * * @param style time style: FULL, LONG, MEDIUM, or SHORT * @param timeZone optional time zone, overrides time zone of * formatted time * @return a localized standard time formatter * @throws IllegalArgumentException if the Locale has no time * pattern defined * @since 2.1 */ public static FastDateFormat getTimeInstance(int style, TimeZone timeZone) { return getTimeInstance(style, timeZone, null); } /** *

    Gets a time formatter instance using the specified style, time * zone and locale.

    * * @param style time style: FULL, LONG, MEDIUM, or SHORT * @param timeZone optional time zone, overrides time zone of * formatted time * @param locale optional locale, overrides system locale * @return a localized standard time formatter * @throws IllegalArgumentException if the Locale has no time * pattern defined */ public static synchronized FastDateFormat getTimeInstance(int style, TimeZone timeZone, Locale locale) { Object key = new Integer(style); if (timeZone != null) { key = new Pair(key, timeZone); } if (locale != null) { key = new Pair(key, locale); } FastDateFormat format = (FastDateFormat) cTimeInstanceCache.get(key); if (format == null) { if (locale == null) { locale = Locale.getDefault(); } try { SimpleDateFormat formatter = (SimpleDateFormat) DateFormat.getTimeInstance(style, locale); String pattern = formatter.toPattern(); format = getInstance(pattern, timeZone, locale); cTimeInstanceCache.put(key, format); } catch (ClassCastException ex) { throw new IllegalArgumentException("No date pattern for locale: " + locale); } } return format; } //----------------------------------------------------------------------- /** *

    Gets a date/time formatter instance using the specified style * in the default time zone and locale.

    * * @param dateStyle date style: FULL, LONG, MEDIUM, or SHORT * @param timeStyle time style: FULL, LONG, MEDIUM, or SHORT * @return a localized standard date/time formatter * @throws IllegalArgumentException if the Locale has no date/time * pattern defined * @since 2.1 */ public static FastDateFormat getDateTimeInstance( int dateStyle, int timeStyle) { return getDateTimeInstance(dateStyle, timeStyle, null, null); } /** *

    Gets a date/time formatter instance using the specified style and * locale in the default time zone.

    * * @param dateStyle date style: FULL, LONG, MEDIUM, or SHORT * @param timeStyle time style: FULL, LONG, MEDIUM, or SHORT * @param locale optional locale, overrides system locale * @return a localized standard date/time formatter * @throws IllegalArgumentException if the Locale has no date/time * pattern defined * @since 2.1 */ public static FastDateFormat getDateTimeInstance( int dateStyle, int timeStyle, Locale locale) { return getDateTimeInstance(dateStyle, timeStyle, null, locale); } /** *

    Gets a date/time formatter instance using the specified style and * time zone in the default locale.

    * * @param dateStyle date style: FULL, LONG, MEDIUM, or SHORT * @param timeStyle time style: FULL, LONG, MEDIUM, or SHORT * @param timeZone optional time zone, overrides time zone of * formatted date * @return a localized standard date/time formatter * @throws IllegalArgumentException if the Locale has no date/time * pattern defined * @since 2.1 */ public static FastDateFormat getDateTimeInstance( int dateStyle, int timeStyle, TimeZone timeZone) { return getDateTimeInstance(dateStyle, timeStyle, timeZone, null); } /** *

    Gets a date/time formatter instance using the specified style, * time zone and locale.

    * * @param dateStyle date style: FULL, LONG, MEDIUM, or SHORT * @param timeStyle time style: FULL, LONG, MEDIUM, or SHORT * @param timeZone optional time zone, overrides time zone of * formatted date * @param locale optional locale, overrides system locale * @return a localized standard date/time formatter * @throws IllegalArgumentException if the Locale has no date/time * pattern defined */ public static synchronized FastDateFormat getDateTimeInstance(int dateStyle, int timeStyle, TimeZone timeZone, Locale locale) { Object key = new Pair(new Integer(dateStyle), new Integer(timeStyle)); if (timeZone != null) { key = new Pair(key, timeZone); } if (locale == null) { locale = Locale.getDefault(); } key = new Pair(key, locale); FastDateFormat format = (FastDateFormat) cDateTimeInstanceCache.get(key); if (format == null) { try { SimpleDateFormat formatter = (SimpleDateFormat) DateFormat.getDateTimeInstance(dateStyle, timeStyle, locale); String pattern = formatter.toPattern(); format = getInstance(pattern, timeZone, locale); cDateTimeInstanceCache.put(key, format); } catch (ClassCastException ex) { throw new IllegalArgumentException("No date time pattern for locale: " + locale); } } return format; } //----------------------------------------------------------------------- /** *

    Gets the time zone display name, using a cache for performance.

    * * @param tz the zone to query * @param daylight true if daylight savings * @param style the style to use TimeZone.LONG * or TimeZone.SHORT * @param locale the locale to use * @return the textual name of the time zone */ static synchronized String getTimeZoneDisplay(TimeZone tz, boolean daylight, int style, Locale locale) { Object key = new TimeZoneDisplayKey(tz, daylight, style, locale); String value = (String) cTimeZoneDisplayCache.get(key); if (value == null) { // This is a very slow call, so cache the results. value = tz.getDisplayName(daylight, style, locale); cTimeZoneDisplayCache.put(key, value); } return value; } /** *

    Gets the default pattern.

    * * @return the default pattern */ private static synchronized String getDefaultPattern() { if (cDefaultPattern == null) { cDefaultPattern = new SimpleDateFormat().toPattern(); } return cDefaultPattern; } // Constructor //----------------------------------------------------------------------- /** *

    Constructs a new FastDateFormat.

    * * @param pattern {@link java.text.SimpleDateFormat} compatible * pattern * @param timeZone time zone to use, null means use * default for Date and value within for * Calendar * @param locale locale, null means use system * default * @throws IllegalArgumentException if pattern is invalid or * null */ protected FastDateFormat(String pattern, TimeZone timeZone, Locale locale) { super(); if (pattern == null) { throw new IllegalArgumentException("The pattern must not be null"); } mPattern = pattern; mTimeZoneForced = (timeZone != null); if (timeZone == null) { timeZone = TimeZone.getDefault(); } mTimeZone = timeZone; mLocaleForced = (locale != null); if (locale == null) { locale = Locale.getDefault(); } mLocale = locale; } /** *

    Initializes the instance for first use.

    */ protected void init() { List rulesList = parsePattern(); mRules = (Rule[]) rulesList.toArray(new Rule[rulesList.size()]); int len = 0; for (int i=mRules.length; --i >= 0; ) { len += mRules[i].estimateLength(); } mMaxLengthEstimate = len; } // Parse the pattern //----------------------------------------------------------------------- /** *

    Returns a list of Rules given a pattern.

    * * @return a List of Rule objects * @throws IllegalArgumentException if pattern is invalid */ protected List parsePattern() { DateFormatSymbols symbols = new DateFormatSymbols(mLocale); List rules = new ArrayList(); String[] ERAs = symbols.getEras(); String[] months = symbols.getMonths(); String[] shortMonths = symbols.getShortMonths(); String[] weekdays = symbols.getWeekdays(); String[] shortWeekdays = symbols.getShortWeekdays(); String[] AmPmStrings = symbols.getAmPmStrings(); int length = mPattern.length(); int[] indexRef = new int[1]; for (int i = 0; i < length; i++) { indexRef[0] = i; String token = parseToken(mPattern, indexRef); i = indexRef[0]; int tokenLen = token.length(); if (tokenLen == 0) { break; } Rule rule; char c = token.charAt(0); switch (c) { case 'G': // era designator (text) rule = new TextField(Calendar.ERA, ERAs); break; case 'y': // year (number) if (tokenLen >= 4) { rule = selectNumberRule(Calendar.YEAR, tokenLen); } else { rule = TwoDigitYearField.INSTANCE; } break; case 'M': // month in year (text and number) if (tokenLen >= 4) { rule = new TextField(Calendar.MONTH, months); } else if (tokenLen == 3) { rule = new TextField(Calendar.MONTH, shortMonths); } else if (tokenLen == 2) { rule = TwoDigitMonthField.INSTANCE; } else { rule = UnpaddedMonthField.INSTANCE; } break; case 'd': // day in month (number) rule = selectNumberRule(Calendar.DAY_OF_MONTH, tokenLen); break; case 'h': // hour in am/pm (number, 1..12) rule = new TwelveHourField(selectNumberRule(Calendar.HOUR, tokenLen)); break; case 'H': // hour in day (number, 0..23) rule = selectNumberRule(Calendar.HOUR_OF_DAY, tokenLen); break; case 'm': // minute in hour (number) rule = selectNumberRule(Calendar.MINUTE, tokenLen); break; case 's': // second in minute (number) rule = selectNumberRule(Calendar.SECOND, tokenLen); break; case 'S': // millisecond (number) rule = selectNumberRule(Calendar.MILLISECOND, tokenLen); break; case 'E': // day in week (text) rule = new TextField(Calendar.DAY_OF_WEEK, tokenLen < 4 ? shortWeekdays : weekdays); break; case 'D': // day in year (number) rule = selectNumberRule(Calendar.DAY_OF_YEAR, tokenLen); break; case 'F': // day of week in month (number) rule = selectNumberRule(Calendar.DAY_OF_WEEK_IN_MONTH, tokenLen); break; case 'w': // week in year (number) rule = selectNumberRule(Calendar.WEEK_OF_YEAR, tokenLen); break; case 'W': // week in month (number) rule = selectNumberRule(Calendar.WEEK_OF_MONTH, tokenLen); break; case 'a': // am/pm marker (text) rule = new TextField(Calendar.AM_PM, AmPmStrings); break; case 'k': // hour in day (1..24) rule = new TwentyFourHourField(selectNumberRule(Calendar.HOUR_OF_DAY, tokenLen)); break; case 'K': // hour in am/pm (0..11) rule = selectNumberRule(Calendar.HOUR, tokenLen); break; case 'z': // time zone (text) if (tokenLen >= 4) { rule = new TimeZoneNameRule(mTimeZone, mTimeZoneForced, mLocale, TimeZone.LONG); } else { rule = new TimeZoneNameRule(mTimeZone, mTimeZoneForced, mLocale, TimeZone.SHORT); } break; case 'Z': // time zone (value) if (tokenLen == 1) { rule = TimeZoneNumberRule.INSTANCE_NO_COLON; } else { rule = TimeZoneNumberRule.INSTANCE_COLON; } break; case '\'': // literal text String sub = token.substring(1); if (sub.length() == 1) { rule = new CharacterLiteral(sub.charAt(0)); } else { rule = new StringLiteral(sub); } break; default: throw new IllegalArgumentException("Illegal pattern component: " + token); } rules.add(rule); } return rules; } /** *

    Performs the parsing of tokens.

    * * @param pattern the pattern * @param indexRef index references * @return parsed token */ protected String parseToken(String pattern, int[] indexRef) { StrBuilder buf = new StrBuilder(); int i = indexRef[0]; int length = pattern.length(); char c = pattern.charAt(i); if (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z') { // Scan a run of the same character, which indicates a time // pattern. buf.append(c); while (i + 1 < length) { char peek = pattern.charAt(i + 1); if (peek == c) { buf.append(c); i++; } else { break; } } } else { // This will identify token as text. buf.append('\''); boolean inLiteral = false; for (; i < length; i++) { c = pattern.charAt(i); if (c == '\'') { if (i + 1 < length && pattern.charAt(i + 1) == '\'') { // '' is treated as escaped ' i++; buf.append(c); } else { inLiteral = !inLiteral; } } else if (!inLiteral && (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z')) { i--; break; } else { buf.append(c); } } } indexRef[0] = i; return buf.toString(); } /** *

    Gets an appropriate rule for the padding required.

    * * @param field the field to get a rule for * @param padding the padding required * @return a new rule with the correct padding */ protected NumberRule selectNumberRule(int field, int padding) { switch (padding) { case 1: return new UnpaddedNumberField(field); case 2: return new TwoDigitNumberField(field); default: return new PaddedNumberField(field, padding); } } // Format methods //----------------------------------------------------------------------- /** *

    Formats a Date, Calendar or * Long (milliseconds) object.

    * * @param obj the object to format * @param toAppendTo the buffer to append to * @param pos the position - ignored * @return the buffer passed in */ public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) { if (obj instanceof Date) { return format((Date) obj, toAppendTo); } else if (obj instanceof Calendar) { return format((Calendar) obj, toAppendTo); } else if (obj instanceof Long) { return format(((Long) obj).longValue(), toAppendTo); } else { throw new IllegalArgumentException("Unknown class: " + (obj == null ? "" : obj.getClass().getName())); } } /** *

    Formats a millisecond long value.

    * * @param millis the millisecond value to format * @return the formatted string * @since 2.1 */ public String format(long millis) { return format(new Date(millis)); } /** *

    Formats a Date object.

    * * @param date the date to format * @return the formatted string */ public String format(Date date) { Calendar c = new GregorianCalendar(mTimeZone, mLocale); c.setTime(date); return applyRules(c, new StringBuffer(mMaxLengthEstimate)).toString(); } /** *

    Formats a Calendar object.

    * * @param calendar the calendar to format * @return the formatted string */ public String format(Calendar calendar) { return format(calendar, new StringBuffer(mMaxLengthEstimate)).toString(); } /** *

    Formats a milliseond long value into the * supplied StringBuffer.

    * * @param millis the millisecond value to format * @param buf the buffer to format into * @return the specified string buffer * @since 2.1 */ public StringBuffer format(long millis, StringBuffer buf) { return format(new Date(millis), buf); } /** *

    Formats a Date object into the * supplied StringBuffer.

    * * @param date the date to format * @param buf the buffer to format into * @return the specified string buffer */ public StringBuffer format(Date date, StringBuffer buf) { Calendar c = new GregorianCalendar(mTimeZone); c.setTime(date); return applyRules(c, buf); } /** *

    Formats a Calendar object into the * supplied StringBuffer.

    * * @param calendar the calendar to format * @param buf the buffer to format into * @return the specified string buffer */ public StringBuffer format(Calendar calendar, StringBuffer buf) { if (mTimeZoneForced) { calendar.getTime(); /// LANG-538 calendar = (Calendar) calendar.clone(); calendar.setTimeZone(mTimeZone); } return applyRules(calendar, buf); } /** *

    Performs the formatting by applying the rules to the * specified calendar.

    * * @param calendar the calendar to format * @param buf the buffer to format into * @return the specified string buffer */ protected StringBuffer applyRules(Calendar calendar, StringBuffer buf) { Rule[] rules = mRules; int len = mRules.length; for (int i = 0; i < len; i++) { rules[i].appendTo(buf, calendar); } return buf; } // Parsing //----------------------------------------------------------------------- /** *

    Parsing is not supported.

    * * @param source the string to parse * @param pos the parsing position * @return null as not supported */ public Object parseObject(String source, ParsePosition pos) { pos.setIndex(0); pos.setErrorIndex(0); return null; } // Accessors //----------------------------------------------------------------------- /** *

    Gets the pattern used by this formatter.

    * * @return the pattern, {@link java.text.SimpleDateFormat} compatible */ public String getPattern() { return mPattern; } /** *

    Gets the time zone used by this formatter.

    * *

    This zone is always used for Date formatting. * If a Calendar is passed in to be formatted, the * time zone on that may be used depending on * {@link #getTimeZoneOverridesCalendar()}.

    * * @return the time zone */ public TimeZone getTimeZone() { return mTimeZone; } /** *

    Returns true if the time zone of the * calendar overrides the time zone of the formatter.

    * * @return true if time zone of formatter * overridden for calendars */ public boolean getTimeZoneOverridesCalendar() { return mTimeZoneForced; } /** *

    Gets the locale used by this formatter.

    * * @return the locale */ public Locale getLocale() { return mLocale; } /** *

    Gets an estimate for the maximum string length that the * formatter will produce.

    * *

    The actual formatted length will almost always be less than or * equal to this amount.

    * * @return the maximum formatted length */ public int getMaxLengthEstimate() { return mMaxLengthEstimate; } // Basics //----------------------------------------------------------------------- /** *

    Compares two objects for equality.

    * * @param obj the object to compare to * @return true if equal */ public boolean equals(Object obj) { if (obj instanceof FastDateFormat == false) { return false; } FastDateFormat other = (FastDateFormat) obj; if ( (mPattern == other.mPattern || mPattern.equals(other.mPattern)) && (mTimeZone == other.mTimeZone || mTimeZone.equals(other.mTimeZone)) && (mLocale == other.mLocale || mLocale.equals(other.mLocale)) && (mTimeZoneForced == other.mTimeZoneForced) && (mLocaleForced == other.mLocaleForced) ) { return true; } return false; } /** *

    Returns a hashcode compatible with equals.

    * * @return a hashcode compatible with equals */ public int hashCode() { int total = 0; total += mPattern.hashCode(); total += mTimeZone.hashCode(); total += (mTimeZoneForced ? 1 : 0); total += mLocale.hashCode(); total += (mLocaleForced ? 1 : 0); return total; } /** *

    Gets a debugging string version of this formatter.

    * * @return a debugging string */ public String toString() { return "FastDateFormat[" + mPattern + "]"; } // Serializing //----------------------------------------------------------------------- /** * Create the object after serialization. This implementation reinitializes the * transient properties. * * @param in ObjectInputStream from which the object is being deserialized. * @throws IOException if there is an IO issue. * @throws ClassNotFoundException if a class cannot be found. */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); init(); } // Rules //----------------------------------------------------------------------- /** *

    Inner class defining a rule.

    */ private interface Rule { /** * Returns the estimated lentgh of the result. * * @return the estimated length */ int estimateLength(); /** * Appends the value of the specified calendar to the output buffer based on the rule implementation. * * @param buffer the output buffer * @param calendar calendar to be appended */ void appendTo(StringBuffer buffer, Calendar calendar); } /** *

    Inner class defining a numeric rule.

    */ private interface NumberRule extends Rule { /** * Appends the specified value to the output buffer based on the rule implementation. * * @param buffer the output buffer * @param value the value to be appended */ void appendTo(StringBuffer buffer, int value); } /** *

    Inner class to output a constant single character.

    */ private static class CharacterLiteral implements Rule { private final char mValue; /** * Constructs a new instance of CharacterLiteral * to hold the specified value. * * @param value the character literal */ CharacterLiteral(char value) { mValue = value; } /** * {@inheritDoc} */ public int estimateLength() { return 1; } /** * {@inheritDoc} */ public void appendTo(StringBuffer buffer, Calendar calendar) { buffer.append(mValue); } } /** *

    Inner class to output a constant string.

    */ private static class StringLiteral implements Rule { private final String mValue; /** * Constructs a new instance of StringLiteral * to hold the specified value. * * @param value the string literal */ StringLiteral(String value) { mValue = value; } /** * {@inheritDoc} */ public int estimateLength() { return mValue.length(); } /** * {@inheritDoc} */ public void appendTo(StringBuffer buffer, Calendar calendar) { buffer.append(mValue); } } /** *

    Inner class to output one of a set of values.

    */ private static class TextField implements Rule { private final int mField; private final String[] mValues; /** * Constructs an instance of TextField * with the specified field and values. * * @param field the field * @param values the field values */ TextField(int field, String[] values) { mField = field; mValues = values; } /** * {@inheritDoc} */ public int estimateLength() { int max = 0; for (int i=mValues.length; --i >= 0; ) { int len = mValues[i].length(); if (len > max) { max = len; } } return max; } /** * {@inheritDoc} */ public void appendTo(StringBuffer buffer, Calendar calendar) { buffer.append(mValues[calendar.get(mField)]); } } /** *

    Inner class to output an unpadded number.

    */ private static class UnpaddedNumberField implements NumberRule { private final int mField; /** * Constructs an instance of UnpadedNumberField with the specified field. * * @param field the field */ UnpaddedNumberField(int field) { mField = field; } /** * {@inheritDoc} */ public int estimateLength() { return 4; } /** * {@inheritDoc} */ public void appendTo(StringBuffer buffer, Calendar calendar) { appendTo(buffer, calendar.get(mField)); } /** * {@inheritDoc} */ public final void appendTo(StringBuffer buffer, int value) { if (value < 10) { buffer.append((char)(value + '0')); } else if (value < 100) { buffer.append((char)(value / 10 + '0')); buffer.append((char)(value % 10 + '0')); } else { buffer.append(Integer.toString(value)); } } } /** *

    Inner class to output an unpadded month.

    */ private static class UnpaddedMonthField implements NumberRule { static final UnpaddedMonthField INSTANCE = new UnpaddedMonthField(); /** * Constructs an instance of UnpaddedMonthField. * */ UnpaddedMonthField() { super(); } /** * {@inheritDoc} */ public int estimateLength() { return 2; } /** * {@inheritDoc} */ public void appendTo(StringBuffer buffer, Calendar calendar) { appendTo(buffer, calendar.get(Calendar.MONTH) + 1); } /** * {@inheritDoc} */ public final void appendTo(StringBuffer buffer, int value) { if (value < 10) { buffer.append((char)(value + '0')); } else { buffer.append((char)(value / 10 + '0')); buffer.append((char)(value % 10 + '0')); } } } /** *

    Inner class to output a padded number.

    */ private static class PaddedNumberField implements NumberRule { private final int mField; private final int mSize; /** * Constructs an instance of PaddedNumberField. * * @param field the field * @param size size of the output field */ PaddedNumberField(int field, int size) { if (size < 3) { // Should use UnpaddedNumberField or TwoDigitNumberField. throw new IllegalArgumentException(); } mField = field; mSize = size; } /** * {@inheritDoc} */ public int estimateLength() { return 4; } /** * {@inheritDoc} */ public void appendTo(StringBuffer buffer, Calendar calendar) { appendTo(buffer, calendar.get(mField)); } /** * {@inheritDoc} */ public final void appendTo(StringBuffer buffer, int value) { if (value < 100) { for (int i = mSize; --i >= 2; ) { buffer.append('0'); } buffer.append((char)(value / 10 + '0')); buffer.append((char)(value % 10 + '0')); } else { int digits; if (value < 1000) { digits = 3; } else { Validate.isTrue(value > -1, "Negative values should not be possible", value); digits = Integer.toString(value).length(); } for (int i = mSize; --i >= digits; ) { buffer.append('0'); } buffer.append(Integer.toString(value)); } } } /** *

    Inner class to output a two digit number.

    */ private static class TwoDigitNumberField implements NumberRule { private final int mField; /** * Constructs an instance of TwoDigitNumberField with the specified field. * * @param field the field */ TwoDigitNumberField(int field) { mField = field; } /** * {@inheritDoc} */ public int estimateLength() { return 2; } /** * {@inheritDoc} */ public void appendTo(StringBuffer buffer, Calendar calendar) { appendTo(buffer, calendar.get(mField)); } /** * {@inheritDoc} */ public final void appendTo(StringBuffer buffer, int value) { if (value < 100) { buffer.append((char)(value / 10 + '0')); buffer.append((char)(value % 10 + '0')); } else { buffer.append(Integer.toString(value)); } } } /** *

    Inner class to output a two digit year.

    */ private static class TwoDigitYearField implements NumberRule { static final TwoDigitYearField INSTANCE = new TwoDigitYearField(); /** * Constructs an instance of TwoDigitYearField. */ TwoDigitYearField() { super(); } /** * {@inheritDoc} */ public int estimateLength() { return 2; } /** * {@inheritDoc} */ public void appendTo(StringBuffer buffer, Calendar calendar) { appendTo(buffer, calendar.get(Calendar.YEAR) % 100); } /** * {@inheritDoc} */ public final void appendTo(StringBuffer buffer, int value) { buffer.append((char)(value / 10 + '0')); buffer.append((char)(value % 10 + '0')); } } /** *

    Inner class to output a two digit month.

    */ private static class TwoDigitMonthField implements NumberRule { static final TwoDigitMonthField INSTANCE = new TwoDigitMonthField(); /** * Constructs an instance of TwoDigitMonthField. */ TwoDigitMonthField() { super(); } /** * {@inheritDoc} */ public int estimateLength() { return 2; } /** * {@inheritDoc} */ public void appendTo(StringBuffer buffer, Calendar calendar) { appendTo(buffer, calendar.get(Calendar.MONTH) + 1); } /** * {@inheritDoc} */ public final void appendTo(StringBuffer buffer, int value) { buffer.append((char)(value / 10 + '0')); buffer.append((char)(value % 10 + '0')); } } /** *

    Inner class to output the twelve hour field.

    */ private static class TwelveHourField implements NumberRule { private final NumberRule mRule; /** * Constructs an instance of TwelveHourField with the specified * NumberRule. * * @param rule the rule */ TwelveHourField(NumberRule rule) { mRule = rule; } /** * {@inheritDoc} */ public int estimateLength() { return mRule.estimateLength(); } /** * {@inheritDoc} */ public void appendTo(StringBuffer buffer, Calendar calendar) { int value = calendar.get(Calendar.HOUR); if (value == 0) { value = calendar.getLeastMaximum(Calendar.HOUR) + 1; } mRule.appendTo(buffer, value); } /** * {@inheritDoc} */ public void appendTo(StringBuffer buffer, int value) { mRule.appendTo(buffer, value); } } /** *

    Inner class to output the twenty four hour field.

    */ private static class TwentyFourHourField implements NumberRule { private final NumberRule mRule; /** * Constructs an instance of TwentyFourHourField with the specified * NumberRule. * * @param rule the rule */ TwentyFourHourField(NumberRule rule) { mRule = rule; } /** * {@inheritDoc} */ public int estimateLength() { return mRule.estimateLength(); } /** * {@inheritDoc} */ public void appendTo(StringBuffer buffer, Calendar calendar) { int value = calendar.get(Calendar.HOUR_OF_DAY); if (value == 0) { value = calendar.getMaximum(Calendar.HOUR_OF_DAY) + 1; } mRule.appendTo(buffer, value); } /** * {@inheritDoc} */ public void appendTo(StringBuffer buffer, int value) { mRule.appendTo(buffer, value); } } /** *

    Inner class to output a time zone name.

    */ private static class TimeZoneNameRule implements Rule { private final TimeZone mTimeZone; private final boolean mTimeZoneForced; private final Locale mLocale; private final int mStyle; private final String mStandard; private final String mDaylight; /** * Constructs an instance of TimeZoneNameRule with the specified properties. * * @param timeZone the time zone * @param timeZoneForced if true the time zone is forced into standard and daylight * @param locale the locale * @param style the style */ TimeZoneNameRule(TimeZone timeZone, boolean timeZoneForced, Locale locale, int style) { mTimeZone = timeZone; mTimeZoneForced = timeZoneForced; mLocale = locale; mStyle = style; if (timeZoneForced) { mStandard = getTimeZoneDisplay(timeZone, false, style, locale); mDaylight = getTimeZoneDisplay(timeZone, true, style, locale); } else { mStandard = null; mDaylight = null; } } /** * {@inheritDoc} */ public int estimateLength() { if (mTimeZoneForced) { return Math.max(mStandard.length(), mDaylight.length()); } else if (mStyle == TimeZone.SHORT) { return 4; } else { return 40; } } /** * {@inheritDoc} */ public void appendTo(StringBuffer buffer, Calendar calendar) { if (mTimeZoneForced) { if (mTimeZone.useDaylightTime() && calendar.get(Calendar.DST_OFFSET) != 0) { buffer.append(mDaylight); } else { buffer.append(mStandard); } } else { TimeZone timeZone = calendar.getTimeZone(); if (timeZone.useDaylightTime() && calendar.get(Calendar.DST_OFFSET) != 0) { buffer.append(getTimeZoneDisplay(timeZone, true, mStyle, mLocale)); } else { buffer.append(getTimeZoneDisplay(timeZone, false, mStyle, mLocale)); } } } } /** *

    Inner class to output a time zone as a number +/-HHMM * or +/-HH:MM.

    */ private static class TimeZoneNumberRule implements Rule { static final TimeZoneNumberRule INSTANCE_COLON = new TimeZoneNumberRule(true); static final TimeZoneNumberRule INSTANCE_NO_COLON = new TimeZoneNumberRule(false); final boolean mColon; /** * Constructs an instance of TimeZoneNumberRule with the specified properties. * * @param colon add colon between HH and MM in the output if true */ TimeZoneNumberRule(boolean colon) { mColon = colon; } /** * {@inheritDoc} */ public int estimateLength() { return 5; } /** * {@inheritDoc} */ public void appendTo(StringBuffer buffer, Calendar calendar) { int offset = calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET); if (offset < 0) { buffer.append('-'); offset = -offset; } else { buffer.append('+'); } int hours = offset / (60 * 60 * 1000); buffer.append((char)(hours / 10 + '0')); buffer.append((char)(hours % 10 + '0')); if (mColon) { buffer.append(':'); } int minutes = offset / (60 * 1000) - 60 * hours; buffer.append((char)(minutes / 10 + '0')); buffer.append((char)(minutes % 10 + '0')); } } // ---------------------------------------------------------------------- /** *

    Inner class that acts as a compound key for time zone names.

    */ private static class TimeZoneDisplayKey { private final TimeZone mTimeZone; private final int mStyle; private final Locale mLocale; /** * Constructs an instance of TimeZoneDisplayKey with the specified properties. * * @param timeZone the time zone * @param daylight adjust the style for daylight saving time if true * @param style the timezone style * @param locale the timezone locale */ TimeZoneDisplayKey(TimeZone timeZone, boolean daylight, int style, Locale locale) { mTimeZone = timeZone; if (daylight) { style |= 0x80000000; } mStyle = style; mLocale = locale; } /** * {@inheritDoc} */ public int hashCode() { return mStyle * 31 + mLocale.hashCode(); } /** * {@inheritDoc} */ public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof TimeZoneDisplayKey) { TimeZoneDisplayKey other = (TimeZoneDisplayKey)obj; return mTimeZone.equals(other.mTimeZone) && mStyle == other.mStyle && mLocale.equals(other.mLocale); } return false; } } // ---------------------------------------------------------------------- /** *

    Helper class for creating compound objects.

    * *

    One use for this class is to create a hashtable key * out of multiple objects.

    */ private static class Pair { private final Object mObj1; private final Object mObj2; /** * Constructs an instance of Pair to hold the specified objects. * @param obj1 one object in the pair * @param obj2 second object in the pair */ public Pair(Object obj1, Object obj2) { mObj1 = obj1; mObj2 = obj2; } /** * {@inheritDoc} */ public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof Pair)) { return false; } Pair key = (Pair)obj; return (mObj1 == null ? key.mObj1 == null : mObj1.equals(key.mObj1)) && (mObj2 == null ? key.mObj2 == null : mObj2.equals(key.mObj2)); } /** * {@inheritDoc} */ public int hashCode() { return (mObj1 == null ? 0 : mObj1.hashCode()) + (mObj2 == null ? 0 : mObj2.hashCode()); } /** * {@inheritDoc} */ public String toString() { return "[" + mObj1 + ':' + mObj2 + ']'; } } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/time/package.html100644 0 0 2465 11513702443 24155 0ustar 0 0

    Provides classes and methods to work with dates and durations.

    This includes:

    • DateUtils - a set of static utility methods for working with dates
    • FastDateFormat - a replacement for SimpleDateFormat that is fast and thread-safe
    • DateFormatUtils - a formatting class for dates
    • StopWatch - a duration timer
    @since 2.0

    These classes are immutable (and therefore thread-safe) apart from {@link StopWatch}.

    commons-lang-2.6-src/src/main/java/org/apache/commons/lang/time/StopWatch.java100644 0 0 24521 11513702443 24470 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.time; /** *

    * StopWatch provides a convenient API for timings. *

    * *

    * To start the watch, call {@link #start()}. At this point you can: *

    *
      *
    • {@link #split()} the watch to get the time whilst the watch continues in the background. {@link #unsplit()} will * remove the effect of the split. At this point, these three options are available again.
    • *
    • {@link #suspend()} the watch to pause it. {@link #resume()} allows the watch to continue. Any time between the * suspend and resume will not be counted in the total. At this point, these three options are available again.
    • *
    • {@link #stop()} the watch to complete the timing session.
    • *
    * *

    * It is intended that the output methods {@link #toString()} and {@link #getTime()} should only be called after stop, * split or suspend, however a suitable result will be returned at other points. *

    * *

    * NOTE: As from v2.1, the methods protect against inappropriate calls. Thus you cannot now call stop before start, * resume before suspend or unsplit before split. *

    * *

    * 1. split(), suspend(), or stop() cannot be invoked twice
    * 2. unsplit() may only be called if the watch has been split()
    * 3. resume() may only be called if the watch has been suspend()
    * 4. start() cannot be called twice without calling reset() *

    * *

    This class is not thread-safe

    * * @author Apache Software Foundation * @since 2.0 * @version $Id: StopWatch.java 1056988 2011-01-09 17:58:53Z niallp $ */ public class StopWatch { // running states private static final int STATE_UNSTARTED = 0; private static final int STATE_RUNNING = 1; private static final int STATE_STOPPED = 2; private static final int STATE_SUSPENDED = 3; // split state private static final int STATE_UNSPLIT = 10; private static final int STATE_SPLIT = 11; /** * The current running state of the StopWatch. */ private int runningState = STATE_UNSTARTED; /** * Whether the stopwatch has a split time recorded. */ private int splitState = STATE_UNSPLIT; /** * The start time. */ private long startTime = -1; /** * The stop time. */ private long stopTime = -1; /** *

    * Constructor. *

    */ public StopWatch() { super(); } /** *

    * Start the stopwatch. *

    * *

    * This method starts a new timing session, clearing any previous values. *

    * * @throws IllegalStateException * if the StopWatch is already running. */ public void start() { if (this.runningState == STATE_STOPPED) { throw new IllegalStateException("Stopwatch must be reset before being restarted. "); } if (this.runningState != STATE_UNSTARTED) { throw new IllegalStateException("Stopwatch already started. "); } this.stopTime = -1; this.startTime = System.currentTimeMillis(); this.runningState = STATE_RUNNING; } /** *

    * Stop the stopwatch. *

    * *

    * This method ends a new timing session, allowing the time to be retrieved. *

    * * @throws IllegalStateException * if the StopWatch is not running. */ public void stop() { if (this.runningState != STATE_RUNNING && this.runningState != STATE_SUSPENDED) { throw new IllegalStateException("Stopwatch is not running. "); } if (this.runningState == STATE_RUNNING) { this.stopTime = System.currentTimeMillis(); } this.runningState = STATE_STOPPED; } /** *

    * Resets the stopwatch. Stops it if need be. *

    * *

    * This method clears the internal values to allow the object to be reused. *

    */ public void reset() { this.runningState = STATE_UNSTARTED; this.splitState = STATE_UNSPLIT; this.startTime = -1; this.stopTime = -1; } /** *

    * Split the time. *

    * *

    * This method sets the stop time of the watch to allow a time to be extracted. The start time is unaffected, * enabling {@link #unsplit()} to continue the timing from the original start point. *

    * * @throws IllegalStateException * if the StopWatch is not running. */ public void split() { if (this.runningState != STATE_RUNNING) { throw new IllegalStateException("Stopwatch is not running. "); } this.stopTime = System.currentTimeMillis(); this.splitState = STATE_SPLIT; } /** *

    * Remove a split. *

    * *

    * This method clears the stop time. The start time is unaffected, enabling timing from the original start point to * continue. *

    * * @throws IllegalStateException * if the StopWatch has not been split. */ public void unsplit() { if (this.splitState != STATE_SPLIT) { throw new IllegalStateException("Stopwatch has not been split. "); } this.stopTime = -1; this.splitState = STATE_UNSPLIT; } /** *

    * Suspend the stopwatch for later resumption. *

    * *

    * This method suspends the watch until it is resumed. The watch will not include time between the suspend and * resume calls in the total time. *

    * * @throws IllegalStateException * if the StopWatch is not currently running. */ public void suspend() { if (this.runningState != STATE_RUNNING) { throw new IllegalStateException("Stopwatch must be running to suspend. "); } this.stopTime = System.currentTimeMillis(); this.runningState = STATE_SUSPENDED; } /** *

    * Resume the stopwatch after a suspend. *

    * *

    * This method resumes the watch after it was suspended. The watch will not include time between the suspend and * resume calls in the total time. *

    * * @throws IllegalStateException * if the StopWatch has not been suspended. */ public void resume() { if (this.runningState != STATE_SUSPENDED) { throw new IllegalStateException("Stopwatch must be suspended to resume. "); } this.startTime += (System.currentTimeMillis() - this.stopTime); this.stopTime = -1; this.runningState = STATE_RUNNING; } /** *

    * Get the time on the stopwatch. *

    * *

    * This is either the time between the start and the moment this method is called, or the amount of time between * start and stop. *

    * * @return the time in milliseconds */ public long getTime() { if (this.runningState == STATE_STOPPED || this.runningState == STATE_SUSPENDED) { return this.stopTime - this.startTime; } else if (this.runningState == STATE_UNSTARTED) { return 0; } else if (this.runningState == STATE_RUNNING) { return System.currentTimeMillis() - this.startTime; } throw new RuntimeException("Illegal running state has occured. "); } /** *

    * Get the split time on the stopwatch. *

    * *

    * This is the time between start and latest split. *

    * * @return the split time in milliseconds * * @throws IllegalStateException * if the StopWatch has not yet been split. * @since 2.1 */ public long getSplitTime() { if (this.splitState != STATE_SPLIT) { throw new IllegalStateException("Stopwatch must be split to get the split time. "); } return this.stopTime - this.startTime; } /** * Returns the time this stopwatch was started. * * @return the time this stopwatch was started * @throws IllegalStateException * if this StopWatch has not been started * @since 2.4 */ public long getStartTime() { if (this.runningState == STATE_UNSTARTED) { throw new IllegalStateException("Stopwatch has not been started"); } return this.startTime; } /** *

    * Gets a summary of the time that the stopwatch recorded as a string. *

    * *

    * The format used is ISO8601-like, hours:minutes:seconds.milliseconds. *

    * * @return the time as a String */ public String toString() { return DurationFormatUtils.formatDurationHMS(getTime()); } /** *

    * Gets a summary of the split time that the stopwatch recorded as a string. *

    * *

    * The format used is ISO8601-like, hours:minutes:seconds.milliseconds. *

    * * @return the split time as a String * @since 2.1 */ public String toSplitString() { return DurationFormatUtils.formatDurationHMS(getSplitTime()); } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/UnhandledException.java100644 0 0 4715 11513702446 25365 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang; import org.apache.commons.lang.exception.NestableRuntimeException; /** *

    Thrown when it is impossible or undesirable to consume or throw a checked exception.

    * This exception supplements the standard exception classes by providing a more * semantically rich description of the problem.

    * *

    UnhandledException represents the case where a method has to deal * with a checked exception but does not wish to. * Instead, the checked exception is rethrown in this unchecked wrapper.

    * *
     * public void foo() {
     *   try {
     *     // do something that throws IOException
     *   } catch (IOException ex) {
     *     // don't want to or can't throw IOException from foo()
     *     throw new UnhandledException(ex);
     *   }
     * }
     * 
    * * @author Matthew Hawthorne * @since 2.0 * @version $Id: UnhandledException.java 437554 2006-08-28 06:21:41Z bayard $ */ public class UnhandledException extends NestableRuntimeException { /** * Required for serialization support. * * @see java.io.Serializable */ private static final long serialVersionUID = 1832101364842773720L; /** * Constructs the exception using a cause. * * @param cause the underlying cause */ public UnhandledException(Throwable cause) { super(cause); } /** * Constructs the exception using a message and cause. * * @param message the message to use * @param cause the underlying cause */ public UnhandledException(String message, Throwable cause) { super(message, cause); } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/Validate.java100644 0 0 50355 11513702446 23356 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang; import java.util.Collection; import java.util.Iterator; import java.util.Map; /** *

    This class assists in validating arguments.

    * *

    The class is based along the lines of JUnit. If an argument value is * deemed invalid, an IllegalArgumentException is thrown. For example:

    * *
     * Validate.isTrue( i > 0, "The value must be greater than zero: ", i);
     * Validate.notNull( surname, "The surname must not be null");
     * 
    * * @author Apache Software Foundation * @author Ola Berg * @author Gary Gregory * @author Norm Deane * @since 2.0 * @version $Id: Validate.java 1057051 2011-01-09 23:15:51Z sebb $ */ public class Validate { // Validate has no dependencies on other classes in Commons Lang at present /** * Constructor. This class should not normally be instantiated. */ public Validate() { super(); } // isTrue //--------------------------------------------------------------------------------- /** *

    Validate that the argument condition is true; otherwise * throwing an exception with the specified message. This method is useful when * validating according to an arbitrary boolean expression, such as validating an * object or using your own custom validation expression.

    * *
    Validate.isTrue( myObject.isOk(), "The object is not OK: ", myObject);
    * *

    For performance reasons, the object value is passed as a separate parameter and * appended to the exception message only in the case of an error.

    * * @param expression the boolean expression to check * @param message the exception message if invalid * @param value the value to append to the message when invalid * @throws IllegalArgumentException if expression is false */ public static void isTrue(boolean expression, String message, Object value) { if (expression == false) { throw new IllegalArgumentException(message + value); } } /** *

    Validate that the argument condition is true; otherwise * throwing an exception with the specified message. This method is useful when * validating according to an arbitrary boolean expression, such as validating a * primitive number or using your own custom validation expression.

    * *
    Validate.isTrue(i > 0.0, "The value must be greater than zero: ", i);
    * *

    For performance reasons, the long value is passed as a separate parameter and * appended to the exception message only in the case of an error.

    * * @param expression the boolean expression to check * @param message the exception message if invalid * @param value the value to append to the message when invalid * @throws IllegalArgumentException if expression is false */ public static void isTrue(boolean expression, String message, long value) { if (expression == false) { throw new IllegalArgumentException(message + value); } } /** *

    Validate that the argument condition is true; otherwise * throwing an exception with the specified message. This method is useful when * validating according to an arbitrary boolean expression, such as validating a * primitive number or using your own custom validation expression.

    * *
    Validate.isTrue(d > 0.0, "The value must be greater than zero: ", d);
    * *

    For performance reasons, the double value is passed as a separate parameter and * appended to the exception message only in the case of an error.

    * * @param expression the boolean expression to check * @param message the exception message if invalid * @param value the value to append to the message when invalid * @throws IllegalArgumentException if expression is false */ public static void isTrue(boolean expression, String message, double value) { if (expression == false) { throw new IllegalArgumentException(message + value); } } /** *

    Validate that the argument condition is true; otherwise * throwing an exception with the specified message. This method is useful when * validating according to an arbitrary boolean expression, such as validating a * primitive number or using your own custom validation expression.

    * *
         * Validate.isTrue( (i > 0), "The value must be greater than zero");
         * Validate.isTrue( myObject.isOk(), "The object is not OK");
         * 
    * * @param expression the boolean expression to check * @param message the exception message if invalid * @throws IllegalArgumentException if expression is false */ public static void isTrue(boolean expression, String message) { if (expression == false) { throw new IllegalArgumentException(message); } } /** *

    Validate that the argument condition is true; otherwise * throwing an exception. This method is useful when validating according * to an arbitrary boolean expression, such as validating a * primitive number or using your own custom validation expression.

    * *
         * Validate.isTrue(i > 0);
         * Validate.isTrue(myObject.isOk());
    * *

    The message of the exception is "The validated expression is * false".

    * * @param expression the boolean expression to check * @throws IllegalArgumentException if expression is false */ public static void isTrue(boolean expression) { if (expression == false) { throw new IllegalArgumentException("The validated expression is false"); } } // notNull //--------------------------------------------------------------------------------- /** *

    Validate that the specified argument is not null; * otherwise throwing an exception. * *

    Validate.notNull(myObject);
    * *

    The message of the exception is "The validated object is * null".

    * * @param object the object to check * @throws IllegalArgumentException if the object is null */ public static void notNull(Object object) { notNull(object, "The validated object is null"); } /** *

    Validate that the specified argument is not null; * otherwise throwing an exception with the specified message. * *

    Validate.notNull(myObject, "The object must not be null");
    * * @param object the object to check * @param message the exception message if invalid */ public static void notNull(Object object, String message) { if (object == null) { throw new IllegalArgumentException(message); } } // notEmpty array //--------------------------------------------------------------------------------- /** *

    Validate that the specified argument array is neither null * nor a length of zero (no elements); otherwise throwing an exception * with the specified message. * *

    Validate.notEmpty(myArray, "The array must not be empty");
    * * @param array the array to check * @param message the exception message if invalid * @throws IllegalArgumentException if the array is empty */ public static void notEmpty(Object[] array, String message) { if (array == null || array.length == 0) { throw new IllegalArgumentException(message); } } /** *

    Validate that the specified argument array is neither null * nor a length of zero (no elements); otherwise throwing an exception. * *

    Validate.notEmpty(myArray);
    * *

    The message in the exception is "The validated array is * empty". * * @param array the array to check * @throws IllegalArgumentException if the array is empty */ public static void notEmpty(Object[] array) { notEmpty(array, "The validated array is empty"); } // notEmpty collection //--------------------------------------------------------------------------------- /** *

    Validate that the specified argument collection is neither null * nor a size of zero (no elements); otherwise throwing an exception * with the specified message. * *

    Validate.notEmpty(myCollection, "The collection must not be empty");
    * * @param collection the collection to check * @param message the exception message if invalid * @throws IllegalArgumentException if the collection is empty */ public static void notEmpty(Collection collection, String message) { if (collection == null || collection.size() == 0) { throw new IllegalArgumentException(message); } } /** *

    Validate that the specified argument collection is neither null * nor a size of zero (no elements); otherwise throwing an exception. * *

    Validate.notEmpty(myCollection);
    * *

    The message in the exception is "The validated collection is * empty".

    * * @param collection the collection to check * @throws IllegalArgumentException if the collection is empty */ public static void notEmpty(Collection collection) { notEmpty(collection, "The validated collection is empty"); } // notEmpty map //--------------------------------------------------------------------------------- /** *

    Validate that the specified argument map is neither null * nor a size of zero (no elements); otherwise throwing an exception * with the specified message. * *

    Validate.notEmpty(myMap, "The map must not be empty");
    * * @param map the map to check * @param message the exception message if invalid * @throws IllegalArgumentException if the map is empty */ public static void notEmpty(Map map, String message) { if (map == null || map.size() == 0) { throw new IllegalArgumentException(message); } } /** *

    Validate that the specified argument map is neither null * nor a size of zero (no elements); otherwise throwing an exception. * *

    Validate.notEmpty(myMap);
    * *

    The message in the exception is "The validated map is * empty".

    * * @param map the map to check * @throws IllegalArgumentException if the map is empty * @see #notEmpty(Map, String) */ public static void notEmpty(Map map) { notEmpty(map, "The validated map is empty"); } // notEmpty string //--------------------------------------------------------------------------------- /** *

    Validate that the specified argument string is * neither null nor a length of zero (no characters); * otherwise throwing an exception with the specified message. * *

    Validate.notEmpty(myString, "The string must not be empty");
    * * @param string the string to check * @param message the exception message if invalid * @throws IllegalArgumentException if the string is empty */ public static void notEmpty(String string, String message) { if (string == null || string.length() == 0) { throw new IllegalArgumentException(message); } } /** *

    Validate that the specified argument string is * neither null nor a length of zero (no characters); * otherwise throwing an exception with the specified message. * *

    Validate.notEmpty(myString);
    * *

    The message in the exception is "The validated * string is empty".

    * * @param string the string to check * @throws IllegalArgumentException if the string is empty */ public static void notEmpty(String string) { notEmpty(string, "The validated string is empty"); } // notNullElements array //--------------------------------------------------------------------------------- /** *

    Validate that the specified argument array is neither * null nor contains any elements that are null; * otherwise throwing an exception with the specified message. * *

    Validate.noNullElements(myArray, "The array contain null at position %d");
    * *

    If the array is null, then the message in the exception * is "The validated object is null".

    * * @param array the array to check * @param message the exception message if the collection has null elements * @throws IllegalArgumentException if the array is null or * an element in the array is null */ public static void noNullElements(Object[] array, String message) { Validate.notNull(array); for (int i = 0; i < array.length; i++) { if (array[i] == null) { throw new IllegalArgumentException(message); } } } /** *

    Validate that the specified argument array is neither * null nor contains any elements that are null; * otherwise throwing an exception. * *

    Validate.noNullElements(myArray);
    * *

    If the array is null, then the message in the exception * is "The validated object is null".

    * *

    If the array has a null element, then the message in the * exception is "The validated array contains null element at index: * " followed by the index.

    * * @param array the array to check * @throws IllegalArgumentException if the array is null or * an element in the array is null */ public static void noNullElements(Object[] array) { Validate.notNull(array); for (int i = 0; i < array.length; i++) { if (array[i] == null) { throw new IllegalArgumentException("The validated array contains null element at index: " + i); } } } // notNullElements collection //--------------------------------------------------------------------------------- /** *

    Validate that the specified argument collection is neither * null nor contains any elements that are null; * otherwise throwing an exception with the specified message. * *

    Validate.noNullElements(myCollection, "The collection contains null elements");
    * *

    If the collection is null, then the message in the exception * is "The validated object is null".

    * * * @param collection the collection to check * @param message the exception message if the collection has * @throws IllegalArgumentException if the collection is null or * an element in the collection is null */ public static void noNullElements(Collection collection, String message) { Validate.notNull(collection); for (Iterator it = collection.iterator(); it.hasNext();) { if (it.next() == null) { throw new IllegalArgumentException(message); } } } /** *

    Validate that the specified argument collection is neither * null nor contains any elements that are null; * otherwise throwing an exception. * *

    Validate.noNullElements(myCollection);
    * *

    If the collection is null, then the message in the exception * is "The validated object is null".

    * *

    If the collection has a null element, then the message in the * exception is "The validated collection contains null element at index: * " followed by the index.

    * * @param collection the collection to check * @throws IllegalArgumentException if the collection is null or * an element in the collection is null */ public static void noNullElements(Collection collection) { Validate.notNull(collection); int i = 0; for (Iterator it = collection.iterator(); it.hasNext(); i++) { if (it.next() == null) { throw new IllegalArgumentException("The validated collection contains null element at index: " + i); } } } /** *

    Validate an argument, throwing IllegalArgumentException * if the argument collection is null or has elements that * are not of type clazz or a subclass.

    * *
         * Validate.allElementsOfType(collection, String.class, "Collection has invalid elements");
         * 
    * * @param collection the collection to check, not null * @param clazz the Class which the collection's elements are expected to be, not null * @param message the exception message if the Collection has elements not of type clazz * @since 2.1 */ public static void allElementsOfType(Collection collection, Class clazz, String message) { Validate.notNull(collection); Validate.notNull(clazz); for (Iterator it = collection.iterator(); it.hasNext(); ) { if (clazz.isInstance(it.next()) == false) { throw new IllegalArgumentException(message); } } } /** *

    * Validate an argument, throwing IllegalArgumentException if the argument collection is * null or has elements that are not of type clazz or a subclass. *

    * *
         * Validate.allElementsOfType(collection, String.class);
         * 
    * *

    * The message in the exception is 'The validated collection contains an element not of type clazz at index: '. *

    * * @param collection the collection to check, not null * @param clazz the Class which the collection's elements are expected to be, not null * @since 2.1 */ public static void allElementsOfType(Collection collection, Class clazz) { Validate.notNull(collection); Validate.notNull(clazz); int i = 0; for (Iterator it = collection.iterator(); it.hasNext(); i++) { if (clazz.isInstance(it.next()) == false) { throw new IllegalArgumentException("The validated collection contains an element not of type " + clazz.getName() + " at index: " + i); } } } } commons-lang-2.6-src/src/main/java/org/apache/commons/lang/WordUtils.java100644 0 0 63167 11513702446 23566 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang; /** *

    Operations on Strings that contain words.

    * *

    This class tries to handle null input gracefully. * An exception will not be thrown for a null input. * Each method documents its behaviour in more detail.

    * * @author Apache Jakarta Velocity * @author Apache Software Foundation * @author Henning P. Schmiedehausen * @author Gary Gregory * @since 2.0 * @version $Id: WordUtils.java 905636 2010-02-02 14:03:32Z niallp $ */ public class WordUtils { /** *

    WordUtils instances should NOT be constructed in * standard programming. Instead, the class should be used as * WordUtils.wrap("foo bar", 20);.

    * *

    This constructor is public to permit tools that require a JavaBean * instance to operate.

    */ public WordUtils() { super(); } // Wrapping //-------------------------------------------------------------------------- // /** // *

    Wraps a block of text to a specified line length using '\n' as // * a newline.

    // * // *

    This method takes a block of text, which might have long lines in it // * and wraps the long lines based on the supplied lineLength parameter.

    // * // *

    If a single word is longer than the line length (eg. a URL), it will // * not be broken, and will display beyond the expected width.

    // * // *

    If there are tabs in inString, you are going to get results that are // * a bit strange. Tabs are a single character but are displayed as 4 or 8 // * spaces. Remove the tabs.

    // * // * @param str text which is in need of word-wrapping, may be null // * @param lineLength the column to wrap the words at // * @return the text with all the long lines word-wrapped // * null if null string input // */ // public static String wrapText(String str, int lineLength) { // return wrap(str, null, lineLength); // } // /** // *

    Wraps a block of text to a specified line length.

    // * // *

    This method takes a block of text, which might have long lines in it // * and wraps the long lines based on the supplied lineLength parameter.

    // * // *

    If a single word is longer than the wrapColumn (eg. a URL), it will // * not be broken, and will display beyond the expected width.

    // * // *

    If there are tabs in inString, you are going to get results that are // * a bit strange. Tabs are a single character but are displayed as 4 or 8 // * spaces. Remove the tabs.

    // * // * @param str text which is in need of word-wrapping, may be null // * @param newLineChars the characters that define a newline, null treated as \n // * @param lineLength the column to wrap the words at // * @return the text with all the long lines word-wrapped // * null if null string input // */ // public static String wrapText(String str, String newLineChars, int lineLength) { // if (str == null) { // return null; // } // if (newLineChars == null) { // newLineChars = "\n"; // } // StringTokenizer lineTokenizer = new StringTokenizer(str, newLineChars, true); // StringBuffer stringBuffer = new StringBuffer(); // // while (lineTokenizer.hasMoreTokens()) { // try { // String nextLine = lineTokenizer.nextToken(); // // if (nextLine.length() > lineLength) { // // This line is long enough to be wrapped. // nextLine = wrapLine(nextLine, null, lineLength, false); // } // // stringBuffer.append(nextLine); // // } catch (NoSuchElementException nsee) { // // thrown by nextToken(), but I don't know why it would // break; // } // } // // return stringBuffer.toString(); // } // Wrapping //----------------------------------------------------------------------- /** *

    Wraps a single line of text, identifying words by ' '.

    * *

    New lines will be separated by the system property line separator. * Very long words, such as URLs will not be wrapped.

    * *

    Leading spaces on a new line are stripped. * Trailing spaces are not stripped.

    * *
         * WordUtils.wrap(null, *) = null
         * WordUtils.wrap("", *) = ""
         * 
    * * @param str the String to be word wrapped, may be null * @param wrapLength the column to wrap the words at, less than 1 is treated as 1 * @return a line with newlines inserted, null if null input */ public static String wrap(String str, int wrapLength) { return wrap(str, wrapLength, null, false); } /** *

    Wraps a single line of text, identifying words by ' '.

    * *

    Leading spaces on a new line are stripped. * Trailing spaces are not stripped.

    * *
         * WordUtils.wrap(null, *, *, *) = null
         * WordUtils.wrap("", *, *, *) = ""
         * 
    * * @param str the String to be word wrapped, may be null * @param wrapLength the column to wrap the words at, less than 1 is treated as 1 * @param newLineStr the string to insert for a new line, * null uses the system property line separator * @param wrapLongWords true if long words (such as URLs) should be wrapped * @return a line with newlines inserted, null if null input */ public static String wrap(String str, int wrapLength, String newLineStr, boolean wrapLongWords) { if (str == null) { return null; } if (newLineStr == null) { newLineStr = SystemUtils.LINE_SEPARATOR; } if (wrapLength < 1) { wrapLength = 1; } int inputLineLength = str.length(); int offset = 0; StringBuffer wrappedLine = new StringBuffer(inputLineLength + 32); while ((inputLineLength - offset) > wrapLength) { if (str.charAt(offset) == ' ') { offset++; continue; } int spaceToWrapAt = str.lastIndexOf(' ', wrapLength + offset); if (spaceToWrapAt >= offset) { // normal case wrappedLine.append(str.substring(offset, spaceToWrapAt)); wrappedLine.append(newLineStr); offset = spaceToWrapAt + 1; } else { // really long word or URL if (wrapLongWords) { // wrap really long word one line at a time wrappedLine.append(str.substring(offset, wrapLength + offset)); wrappedLine.append(newLineStr); offset += wrapLength; } else { // do not wrap really long word, just extend beyond limit spaceToWrapAt = str.indexOf(' ', wrapLength + offset); if (spaceToWrapAt >= 0) { wrappedLine.append(str.substring(offset, spaceToWrapAt)); wrappedLine.append(newLineStr); offset = spaceToWrapAt + 1; } else { wrappedLine.append(str.substring(offset)); offset = inputLineLength; } } } } // Whatever is left in line is short enough to just pass through wrappedLine.append(str.substring(offset)); return wrappedLine.toString(); } // Capitalizing //----------------------------------------------------------------------- /** *

    Capitalizes all the whitespace separated words in a String. * Only the first letter of each word is changed. To convert the * rest of each word to lowercase at the same time, * use {@link #capitalizeFully(String)}.

    * *

    Whitespace is defined by {@link Character#isWhitespace(char)}. * A null input String returns null. * Capitalization uses the unicode title case, normally equivalent to * upper case.

    * *
         * WordUtils.capitalize(null)        = null
         * WordUtils.capitalize("")          = ""
         * WordUtils.capitalize("i am FINE") = "I Am FINE"
         * 
    * * @param str the String to capitalize, may be null * @return capitalized String, null if null String input * @see #uncapitalize(String) * @see #capitalizeFully(String) */ public static String capitalize(String str) { return capitalize(str, null); } /** *

    Capitalizes all the delimiter separated words in a String. * Only the first letter of each word is changed. To convert the * rest of each word to lowercase at the same time, * use {@link #capitalizeFully(String, char[])}.

    * *

    The delimiters represent a set of characters understood to separate words. * The first string character and the first non-delimiter character after a * delimiter will be capitalized.

    * *

    A null input String returns null. * Capitalization uses the unicode title case, normally equivalent to * upper case.

    * *
         * WordUtils.capitalize(null, *)            = null
         * WordUtils.capitalize("", *)              = ""
         * WordUtils.capitalize(*, new char[0])     = *
         * WordUtils.capitalize("i am fine", null)  = "I Am Fine"
         * WordUtils.capitalize("i aM.fine", {'.'}) = "I aM.Fine"
         * 
    * * @param str the String to capitalize, may be null * @param delimiters set of characters to determine capitalization, null means whitespace * @return capitalized String, null if null String input * @see #uncapitalize(String) * @see #capitalizeFully(String) * @since 2.1 */ public static String capitalize(String str, char[] delimiters) { int delimLen = (delimiters == null ? -1 : delimiters.length); if (str == null || str.length() == 0 || delimLen == 0) { return str; } int strLen = str.length(); StringBuffer buffer = new StringBuffer(strLen); boolean capitalizeNext = true; for (int i = 0; i < strLen; i++) { char ch = str.charAt(i); if (isDelimiter(ch, delimiters)) { buffer.append(ch); capitalizeNext = true; } else if (capitalizeNext) { buffer.append(Character.toTitleCase(ch)); capitalizeNext = false; } else { buffer.append(ch); } } return buffer.toString(); } //----------------------------------------------------------------------- /** *

    Converts all the whitespace separated words in a String into capitalized words, * that is each word is made up of a titlecase character and then a series of * lowercase characters.

    * *

    Whitespace is defined by {@link Character#isWhitespace(char)}. * A null input String returns null. * Capitalization uses the unicode title case, normally equivalent to * upper case.

    * *
         * WordUtils.capitalizeFully(null)        = null
         * WordUtils.capitalizeFully("")          = ""
         * WordUtils.capitalizeFully("i am FINE") = "I Am Fine"
         * 
    * * @param str the String to capitalize, may be null * @return capitalized String, null if null String input */ public static String capitalizeFully(String str) { return capitalizeFully(str, null); } /** *

    Converts all the delimiter separated words in a String into capitalized words, * that is each word is made up of a titlecase character and then a series of * lowercase characters.

    * *

    The delimiters represent a set of characters understood to separate words. * The first string character and the first non-delimiter character after a * delimiter will be capitalized.

    * *

    A null input String returns null. * Capitalization uses the unicode title case, normally equivalent to * upper case.

    * *
         * WordUtils.capitalizeFully(null, *)            = null
         * WordUtils.capitalizeFully("", *)              = ""
         * WordUtils.capitalizeFully(*, null)            = *
         * WordUtils.capitalizeFully(*, new char[0])     = *
         * WordUtils.capitalizeFully("i aM.fine", {'.'}) = "I am.Fine"
         * 
    * * @param str the String to capitalize, may be null * @param delimiters set of characters to determine capitalization, null means whitespace * @return capitalized String, null if null String input * @since 2.1 */ public static String capitalizeFully(String str, char[] delimiters) { int delimLen = (delimiters == null ? -1 : delimiters.length); if (str == null || str.length() == 0 || delimLen == 0) { return str; } str = str.toLowerCase(); return capitalize(str, delimiters); } //----------------------------------------------------------------------- /** *

    Uncapitalizes all the whitespace separated words in a String. * Only the first letter of each word is changed.

    * *

    Whitespace is defined by {@link Character#isWhitespace(char)}. * A null input String returns null.

    * *
         * WordUtils.uncapitalize(null)        = null
         * WordUtils.uncapitalize("")          = ""
         * WordUtils.uncapitalize("I Am FINE") = "i am fINE"
         * 
    * * @param str the String to uncapitalize, may be null * @return uncapitalized String, null if null String input * @see #capitalize(String) */ public static String uncapitalize(String str) { return uncapitalize(str, null); } /** *

    Uncapitalizes all the whitespace separated words in a String. * Only the first letter of each word is changed.

    * *

    The delimiters represent a set of characters understood to separate words. * The first string character and the first non-delimiter character after a * delimiter will be uncapitalized.

    * *

    Whitespace is defined by {@link Character#isWhitespace(char)}. * A null input String returns null.

    * *
         * WordUtils.uncapitalize(null, *)            = null
         * WordUtils.uncapitalize("", *)              = ""
         * WordUtils.uncapitalize(*, null)            = *
         * WordUtils.uncapitalize(*, new char[0])     = *
         * WordUtils.uncapitalize("I AM.FINE", {'.'}) = "i AM.fINE"
         * 
    * * @param str the String to uncapitalize, may be null * @param delimiters set of characters to determine uncapitalization, null means whitespace * @return uncapitalized String, null if null String input * @see #capitalize(String) * @since 2.1 */ public static String uncapitalize(String str, char[] delimiters) { int delimLen = (delimiters == null ? -1 : delimiters.length); if (str == null || str.length() == 0 || delimLen == 0) { return str; } int strLen = str.length(); StringBuffer buffer = new StringBuffer(strLen); boolean uncapitalizeNext = true; for (int i = 0; i < strLen; i++) { char ch = str.charAt(i); if (isDelimiter(ch, delimiters)) { buffer.append(ch); uncapitalizeNext = true; } else if (uncapitalizeNext) { buffer.append(Character.toLowerCase(ch)); uncapitalizeNext = false; } else { buffer.append(ch); } } return buffer.toString(); } //----------------------------------------------------------------------- /** *

    Swaps the case of a String using a word based algorithm.

    * *
      *
    • Upper case character converts to Lower case
    • *
    • Title case character converts to Lower case
    • *
    • Lower case character after Whitespace or at start converts to Title case
    • *
    • Other Lower case character converts to Upper case
    • *
    * *

    Whitespace is defined by {@link Character#isWhitespace(char)}. * A null input String returns null.

    * *
         * StringUtils.swapCase(null)                 = null
         * StringUtils.swapCase("")                   = ""
         * StringUtils.swapCase("The dog has a BONE") = "tHE DOG HAS A bone"
         * 
    * * @param str the String to swap case, may be null * @return the changed String, null if null String input */ public static String swapCase(String str) { int strLen; if (str == null || (strLen = str.length()) == 0) { return str; } StringBuffer buffer = new StringBuffer(strLen); boolean whitespace = true; char ch = 0; char tmp = 0; for (int i = 0; i < strLen; i++) { ch = str.charAt(i); if (Character.isUpperCase(ch)) { tmp = Character.toLowerCase(ch); } else if (Character.isTitleCase(ch)) { tmp = Character.toLowerCase(ch); } else if (Character.isLowerCase(ch)) { if (whitespace) { tmp = Character.toTitleCase(ch); } else { tmp = Character.toUpperCase(ch); } } else { tmp = ch; } buffer.append(tmp); whitespace = Character.isWhitespace(ch); } return buffer.toString(); } //----------------------------------------------------------------------- /** *

    Extracts the initial letters from each word in the String.

    * *

    The first letter of the string and all first letters after * whitespace are returned as a new string. * Their case is not changed.

    * *

    Whitespace is defined by {@link Character#isWhitespace(char)}. * A null input String returns null.

    * *
         * WordUtils.initials(null)             = null
         * WordUtils.initials("")               = ""
         * WordUtils.initials("Ben John Lee")   = "BJL"
         * WordUtils.initials("Ben J.Lee")      = "BJ"
         * 
    * * @param str the String to get initials from, may be null * @return String of initial letters, null if null String input * @see #initials(String,char[]) * @since 2.2 */ public static String initials(String str) { return initials(str, null); } /** *

    Extracts the initial letters from each word in the String.

    * *

    The first letter of the string and all first letters after the * defined delimiters are returned as a new string. * Their case is not changed.

    * *

    If the delimiters array is null, then Whitespace is used. * Whitespace is defined by {@link Character#isWhitespace(char)}. * A null input String returns null. * An empty delimiter array returns an empty String.

    * *
         * WordUtils.initials(null, *)                = null
         * WordUtils.initials("", *)                  = ""
         * WordUtils.initials("Ben John Lee", null)   = "BJL"
         * WordUtils.initials("Ben J.Lee", null)      = "BJ"
         * WordUtils.initials("Ben J.Lee", [' ','.']) = "BJL"
         * WordUtils.initials(*, new char[0])         = ""
         * 
    * * @param str the String to get initials from, may be null * @param delimiters set of characters to determine words, null means whitespace * @return String of initial letters, null if null String input * @see #initials(String) * @since 2.2 */ public static String initials(String str, char[] delimiters) { if (str == null || str.length() == 0) { return str; } if (delimiters != null && delimiters.length == 0) { return ""; } int strLen = str.length(); char[] buf = new char[strLen / 2 + 1]; int count = 0; boolean lastWasGap = true; for (int i = 0; i < strLen; i++) { char ch = str.charAt(i); if (isDelimiter(ch, delimiters)) { lastWasGap = true; } else if (lastWasGap) { buf[count++] = ch; lastWasGap = false; } else { // ignore ch } } return new String(buf, 0, count); } //----------------------------------------------------------------------- /** * Is the character a delimiter. * * @param ch the character to check * @param delimiters the delimiters * @return true if it is a delimiter */ private static boolean isDelimiter(char ch, char[] delimiters) { if (delimiters == null) { return Character.isWhitespace(ch); } for (int i = 0, isize = delimiters.length; i < isize; i++) { if (ch == delimiters[i]) { return true; } } return false; } //----------------------------------------------------------------------- /** * Abbreviates a string nicely. * * This method searches for the first space after the lower limit and abbreviates * the String there. It will also append any String passed as a parameter * to the end of the String. The upper limit can be specified to forcibly * abbreviate a String. * * @param str the string to be abbreviated. If null is passed, null is returned. * If the empty String is passed, the empty string is returned. * @param lower the lower limit. * @param upper the upper limit; specify -1 if no limit is desired. * If the upper limit is lower than the lower limit, it will be * adjusted to be the same as the lower limit. * @param appendToEnd String to be appended to the end of the abbreviated string. * This is appended ONLY if the string was indeed abbreviated. * The append does not count towards the lower or upper limits. * @return the abbreviated String. * @since 2.4 */ public static String abbreviate(String str, int lower, int upper, String appendToEnd) { // initial parameter checks if (str == null) { return null; } if (str.length() == 0) { return StringUtils.EMPTY; } // if the lower value is greater than the length of the string, // set to the length of the string if (lower > str.length()) { lower = str.length(); } // if the upper value is -1 (i.e. no limit) or is greater // than the length of the string, set to the length of the string if (upper == -1 || upper > str.length()) { upper = str.length(); } // if upper is less than lower, raise it to lower if (upper < lower) { upper = lower; } StringBuffer result = new StringBuffer(); int index = StringUtils.indexOf(str, " ", lower); if (index == -1) { result.append(str.substring(0, upper)); // only if abbreviation has occured do we append the appendToEnd value if (upper != str.length()) { result.append(StringUtils.defaultString(appendToEnd)); } } else if (index > upper) { result.append(str.substring(0, upper)); result.append(StringUtils.defaultString(appendToEnd)); } else { result.append(str.substring(0, index)); result.append(StringUtils.defaultString(appendToEnd)); } return result.toString(); } } commons-lang-2.6-src/src/media/logo.xcf100644 0 0 45226 11513702433 15227 0ustar 0 0 gimp xcf file,dBB)/ gimp-commentCreated with The GIMP¦ .á+ Hÿ_3 Text Layer#2ÿ     ¬.&W_3o "_3ƒµ À À Àü887øUªâÿÿU4ü8ÆÿÿþU4ûqªªÆÿÿþU8þÆÿÿþU8þUÿÿþU8þUÿÿþU8þUÿÿþU8þUÿÿþU8þUÿÿþU8þUÿÿþU8þUÿÿþU8þUÿÿþU8þUÿÿþU ý8UªªýqU üqqþUªªýqþUÿÿþU ýqâÿÿýâqùqÆÿÿªýqâÿÿþþUÿÿþUùâÿÿÆUýUÆÿÿþªü8ÆÿÿûªªÿÿþªþUÿÿþUþÿÿþÆþÆÿÿþUûqªªâÿÿöªâÿªUUqÆÿÿþ8þUÿÿþUþÆÿÿþUþUÿÿþâþUÿÿûâÿâ8þqÿÿþªþUÿÿþUþ8ÿÿþqÿÿþªþâÿÿþUÿÿþUþUÿÿþªÿþUÿþÆþÿÿþ8þUÿÿþUþÿÿþqÿþUÿþªþUÿÿþUþUÿÿþUûUÆÆqÿþUÿþªþUÿÿþUþUÿÿþUþ8ÿÿþUÿþªþUÿÿþUþUÿÿþUüâÿÿþUÿþªþUÿÿþUþUÿÿþU ùqÆÿªUÿÿþUÿþªþUÿÿþUþUÿÿþU ù8ÿâqÿþUÿþªþUÿÿþUþUÿÿþUúªÿÿÿþUÿþªþUÿÿþUþUÿÿþUþqÿÿþUÿþUÿþªþUÿÿþUþUÿÿþUþªÿÿþUÿþUÿþªþUÿÿþUþUÿÿþUþqÿÿþÆÿþUÿþªþUÿÿþUþUÿÿþUþâÿÿþªÿþUÿþªþUÿÿþUþUÿÿþUþ8ÿÿþªÿþUÿþªþUÿÿþUþUÿÿþUþUÿÿþªÿþUÿþªþUÿÿþUþUÿÿþUþUÿÿþþªÿÿþUÿþªþUÿÿþUþUÿÿþUþÿÿýâüqââÿÿúªÿþªþUÿÿþUþÿÿþqþÆÿÿ÷ƪÆÿÿÆÆÿÿûƪÿUþÿÿþªþÿÿþqýâÿÿþâþÿÿûÿÿþªþÿÿþýâÿÿûÆ8qªÿÿûâªU8ý8âÿÿýÆýâÿÿùªUÆÿÿ÷ªUUâÿÿþqª ªþqþUªªýqúªª8þ8ª ªü8ªª---¡ýUªªýU8øÿÿƪâÿÿüâUú8âÿâýUâÿÿþUþÿÿþþÿÿþUûâÿÿªþÿÿþq þqÿÿþUþÿÿþâ þâÿÿþUþªÿÿþ þÿÿþUþqÿÿþU þUÿÿþUþ8ÿÿþU þUÿÿþÿþU þUÿÿþªÿþ8 ÿþÿ þÿÿþqþ8ÿÿþ ýâÿÿýâúÿÿâ ýâÿÿýâþUÿÿþUýªÿÿ÷UUªÿÿâþÿÿýÆqúUÿUUþüUÿUüUÿûUÿÿUùâÿÿâU ÿªüU þâÿÿýÆüâ8ýÆÿÿøâ8ªªqüqÿªÿ ÿþâ üUÿUUüªªÿÿþUüªÿª ûªÿªüªÿâüÿªûÿÿqýÿªþ8ÿÿþUü8ÿUþÿÿþýÆâþªÿÿþU ûªÿ8þqÿÿýú8ÿÿUýâÿÿýƪUUøªâÿÿâ8ýâÿÿþ þÿ ÿüâüUªÆÿÿûƪq8/mADrop-Shadow#2c     ©,) ØmA ðÕmA ÅÍ‹5üû0ð  -î -í "*042-#+ì *7CMQNE5% +ì +;M^kql^I2+ë #4I`u†Œ†tY=$*ë $7Oiƒ—Ÿ™„eE) *ë !4Mj‡Ÿ©¤mJ, *ë-Ed„Ÿ­¨’pL- +ì %=\~›«¨“rM. +ì6Uy˜©¨“rN. ,í 1Qu•¨§“rN. ó Ú /Os“§§“rN.  ûú î .Nr“§§“rN. ÷ ø î  Ä .Nr“§§“rN.  !#%&&$!  $)+Ä .Nr“§§“rN.  &,14689::71)  $,243/)&',3Xu¡¨¡’~l`[^fsƒÄ .Nr“§§“rN/-Gcy„q[F717F]uˆŽ…oQ6"(=Yy—¬´­š‚kYPNS`sÄ .Nr“§§“rN/2Mj‡€lR;+%+&#8Uw˜¯¸°š~bL>9=J_Ä .Nr“§§“rN/2LfyvaH1"$6QpŒœ™„eD)1Nq”­¶­•uV=-'*7MÄ .Nr“§§“rN/,CZjneS=+%7Rr Ÿ‹kH,+Hl©²§kJ0 (?Ä .Nr“§§“rN/ #5GTXRE5(!"+=Xw”¤£nK-(EhŒ¦®¢‡cA'6Ä .Nr“§§“rN/ '5?DA:1*(*4F_}˜§¥‘pL.&CfФ¬Ÿƒ^<" 1Ä .Nr“§§“rN.  '17974103^€›§¢ŒnO6&!'7Rr‘¥§—yW8")DgФª[9 /Ä 2Rv–©©•uR4")Bc†¢¯«–y[C4/4C\z—©¬€_A+ -GiŒ¥«ž]:  1Ã6Vz™««˜yV8%!+Bc†£²±¡ˆmWHBERg›­°£ŠkN7)(4Lm§­ ƒ`>$6à $<\}›¬¬š|Z=)#*>]œ¯³ª—m_WV^mƒ™ª°§’w[C41O^jppi\M<-"$2CTaikh_TH>76;FS]a]SE9119FUcmoj_O>/$ ",: $0;EMQPLD:.#*6AHJHB:1("!%-6>B@90(#$*4?HNPME;0%#-  ',0320,& &+-,(#$'&""(.120,&à       à  ýýû  û ýûþûõþ? @ @ @£ú ü ø ú  ÷÷ ö ò ö+'" ã !#$#" ÕGB:/"  $)-02589973.)$  ÕfbXI8&  '07;=>AEKPSSQLE>70(  €ß€vfP9%  -:EJJHGINWakpqmf\QF:.! ”€iN4/APYZUMGGMZjz‡‹„whXH7(’Ÿ”aC)  +AVekfYJ?Tl†}fJ/ ØNr“¦¦“rN. &>[xŽ˜”„nWE=>IZlxxlU<% ÙNr“¦¦“rN. 0Je}ˆxeUMLS^gkfWC-ÙNr“§§“rN.  %;Tl‡„zk^VTVZ]ZQB0 ÚNr“§§“rN.  2I_qzzsh]VRQPMG<.  ÚNs“§§“rN.  1FZhnmf]TNIFB<5+  ÚOs”§§”sO/ %8L]ghd[RKE@<71*! ØQu–©¨•uP1 /EZholdZPIC?;61*$ ×Uy˜«ª—xT4$:Sjy~ype[TOKHD?:4-%×Z|š««™zX8!*C`yŠ„zrlgc`\YTNF<1& Ö^~™¨¨—{[=&.Hg‚–Ÿž˜‘‹‡ƒ€}zwsmdYK<+ Õ_{‘žx[@)/Hgƒ˜£¥£Ÿœ™—•“‘Ž‹†teS?+ÕYo‹ŠlU>*.Fb|›žžœ›š™˜˜—–”’…xfP:% æK\hoogYH6' /E]r‰ŠŠ‰ˆ‰‰ŠŠ‹ôЇq]F/€Š8CKPOJA6* %5H[jqrokiijklmnpruxzyqbL5 %+022/*$!.?Q_ec\TMHGHIJLMOSX^eji_N8# (:N_hg\M?4.,+,-/037=FPY]XJ7#    Ù 1H_pum\H5' %,6ALRPE3!Ü "9Uo„ydL7' '1EFA5& Ü&Aa•–…o[J>61/./148=AEFB9, í$=\{“  •†uf[RMJHHñIKLKID;0# Ý4Pn‡˜Ÿ•Švnida_^\YUOH=2% Þ (?Yr†’˜—“އ|vrmhc\TJ>2&  Þ-BWkz„‰‹Š‡ƒ~ysle\SH<0$  à ,=:4," &Å +7BJOTX\_^WI7%   -:CJOSWZ]]ZQE5% #1@LÄ &8HTZ\\]bkw€€u_D*  )bŒeD( ;e‘±¹§Q*=eŠ ƒ]9 &Bh‘³Á¸šoD$*Ky©Ì0V}–”zT0 )Lt”¡”rI'.T€£¯wK'*Mz¦Ãȳ‹\3 >m¡È Bm“£”oD"  3QlxoV7 >j˜µµ˜i<  8d•½ÏÅ¢rC  6f›Ä+S¤ª‘d8 0BJE5"'M~ªÀ·‘_2Ü)Q„³ÏÏ´…R) 3c™Â5b‘¯­\0è  $" /[Ž¸È·ŒX,Ý Cu¨ËÔ¿“^1 2b™Â ?o·¯ŠX,é   6e™Á̸‹V*Ý8ižÇÖÆh8 2b™Á !Gx¦½²ŠW+ê ;l¡ÇѺŒW+Ý1_•ÁÕÊ£n<2b™Á $L­Â¶ŽZ-ï >p¤ÊÔ¾Z-Þ,Y½Óʤp>2b™Á%N‚°Ç¼•a3î >o¤Ë××a2Þ*U‹ºÑÈ¢n<2b™Á %M±Êßl< ì ;k ÉØÉ j:Ý)TЏÎÃh8 2b™Á "I|­Ëʬ}K&ë 6c˜ÄØÎªvD Ü+V‹·Ê¼“_1 2b™Á Bs¦ÉÑ»‘a7 é 0YŒ»ÔÒ´ƒP(Û.[·Ä±†S) 2b™Á8g›ÃÔɨ{O- é !,/*)K|­ÍÓ¾“`3€5c”·¼¢uE! 2b™Á-WŠ·ÑÓ¾špJ. )7@?2" =išÀÐÅ¢rC!  @nš³¯Ž`6 2b™Â !Et¤ÇÖÏ·”pQ;-%#%,7EPQF2-S¬ÆÈ°†X1 *NzªšuJ&3c™Â3[гÎÖÍ·›gVLHJQZabXC+ m ÆÂ*Kr˜·ÊÑÏÆ»°¦ž˜…s[@' -LoŽ¢¤•|aI:35>Ocu|t]@% )Jw¥ÆÃ .Mp‘«½ÅÇĽ´ªw^C*  -Ig€†veWPPV_hleT<% !8X~¤¾× -Gd~“¢ª¬©¡”„oX?)  )?Vjvyume`]]î[SF4!  )A\z•¦é &:Napz~|uiYG4" Þ  1AOY]][WSNH@5( (<82+# +7AIMî !##  í   ö !$&ñ  ð ÷  ÷þþþ?   @þ þð ó Ç      !! €)   ! )&(4>DE@6(  ,8AFFA6) !(*% ,8AFD=2# PI:+%*8HYgqtoaM6#,=N^ksuoaM5  (6EOOE4'%-m¡ÆÑ½“`4  #5Y‡±Ëʰ…W2 3Y‡²ÌÍ´‹]6Ķ–nI, 6V~¤¾ÆºœuO1 6U}£½Ä¶—pL2%$.DeŒ®ÂÁ¬‰b?&&Ad‹®ÃıhEª¡‹mO5!(>Zy”§¬¤sU:&)>Zx”¦ª¡‹nR<0/9Lg„›©¨šcF-.Geƒœ©ªž†iL€zm[F1!'9Nbs~|q_K7&'9Nbs}€zm[I90/7EWiw~vgT?,,@Viw€ykXDNLF<1$)5@HMOMG?4')5@HMNLF=3*%$)1;DJNNJC9-  -:DJNNKE;0&%# !$&&Ã$  !$&&%# #%&&%" "%&&%#  ó  õ  ô  ü þþþþþ>   Aøþüí  ù  ù á  " ì   Ý   "$0;CGE>2# Ä #+17;=><7/&  $+.+"%1$ .Hf…Ÿ¯¯ž„mceo|‹šªµ¶acgn{§ºÀ±Ža6 %A`y„}kTA516CXr¡§„a?$1Mp–¶Êʸ›€nfejt„›²ÁOHEHTl®ÃÁ¤wG"  <`“yZ='&9Uw™°¶¦†^9)Di”»ÓÖã‚fTJHN_z»6)$&1Jp›½Ç³ˆU+ 1Wœ¢ŽjD' 7Z„©¿¾¦~R.4Z‰¶ÒÖÂuR:,'+;Y‚¬ 3ZŠµÈ¼•a3 #Fr™®¦…Y1 !@k˜¼É½šk? (M~¯ÎÒºb<#"@l&L®Èžj:1ZŠ®¸¤yJ$,T…±Ì˰‚Q*"ExªÊͱƒR+  1^‘  FxªÇÅ£p??m¼¾ o? à Bs¥ÈÒ¿•b5 Cu¨ÈÉ«zH" +W‹  Cv¨ÇƦsA &K}­ÇÁi8Ã5c˜ÂÔÉ£p? Cu§ÇȨvD )T‰  Bu§ÇƦtB",U‰·ÎÜf6Ã,WŒºÓέzG$!Cu§ÇǧuB (R‡  Bu§ÇǧtC#0[‘¾ÓÆžg6Ä&Nƒ´Ñв€L'!Cu§ÇǧuB (R‡  Bu§ÇǧtC#2^•ÂÖÊ¢l:Ä "H|¯Îг‚N("Cu§ÇǧuB (R‡  Bu§ÇǧuC#1^”Â×ͨs@ Ä Ex«Ìα€L'!Cu§ÇǧuB (R‡  Bu§ÇǧuC#/Y¾×Ѱ}I" à DwªÉʬzH$!Cu§ÇǧuB (R‡  Bu§ÇǧuC"*R‡·ÔÔ¸ˆS)à FyªÇÄ¢p@ Cu§ÇǧuB (R‡  Bu§ÇǧuC!$Hz¬ÎÖÁ•a3à $K~¬Ã»–c6 Bu§ÇǧuB (R‡  Bu§ÇǧuB 43:H\p|yfJ-  1X‡²Ë˰†X3 "@kš*'@cŠ­ÁÁ­Šb@& &@]x‹‘Š{j[QOS\eki[E- "=b‹®Â­Šc@'/Nuœ3!/Gd‚›¨¨š‚dG. "7Odsywpha^]]\WK:(  (Cc‚œ©©›‚dG/#7Sr0!-@Uhw~~vhU@-+=94.& *7CJNNJC:.!%2>G "%&&%"    á"%&&%"  $ ø ð ù ó  þüþþ?¤¤¤ þ üú  øú í  ù- ë &-13321/,)! ùU>' ÷)8BGHHõJKNNI<) á‚eE( 1FUZWRNMRZeljX< €Ä©Œf?  0LdmgXI@?GVj{~kI'À«„W/&Fh}|hL6)'0B\upN*ɾœm> 4[€„d@%+EaqhK)ÇÈ­~K$ ?k‘žf=  /I[XB%ÁÌ·ŠU* !Etœª™sI( 3CE5 ¼Ì½’\. EtŸ´ªŠc@'".0& á¹ÍÀ–`0 >lš·º¦†eH1!á·ÌÁ—a12\НÀ½ªsXA.!â¶ÌÁ˜b2%Gr›¸Äµ ‡lS=+ á¶ÌÁ˜b2 0S{ž¸ÅÈÀ°šfL5" €̶ÌÁ˜b2 5Ux˜±ÂÊȽ«“x[?' ¶ÌÁ™b24PnŒ¦ºÆÊŸ¢†eD(¶ÌÁ™b2 .D^z•¬½ÈÉÀ¬Œf@"¶ÌÁ™b2 %7Mg›²ÃÊĬ‡[3¶ÌÁ™b2 )-$$,=Xuˆ‡pM+ºÆ¾¤}U4$@b|„yeQB;;BPbquiP3 ¤¬§”xX;$3Mcli_TLHINV^`YH2|}sbL5""3AHIGDCCEHJJD9*âMOMH@4&"&()+-/121.' &æ$!   è  þ)p8 ,d Backgroundÿ     I¦,dIÆJrJ~JŠ,dIúJJJJ*J6JBJNJZJfÿÿÿÿÿÿÿÿÿÿÿÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ0ÿ0ÿ0ÿ–2K% commons-lang-2.6-src/src/site/changes/changes.xml100644 0 0 114223 11513702446 17232 0ustar 0 0 Commons Lang Changes BooleanUtils: use same optimization in toBooleanObject(String) as in toBoolean(String) ClassUtils: allow Dots as Inner Class Separators in getClass() DateUtils: equal and compare functions up to most significant field DateUtils: provide a Date to Calendar convenience method ObjectUtils: add clone methods to ObjectUtils ObjectUtils: add a Null-safe compare() method ObjectUtils: add notEqual() method StrBuilder: implement clone() method StringUtils: add a normalizeSpace() method StringUtils: add endsWithAny() method StringUtils: add defaultIfBlank() method StrSubstitutor: add a replace(String, Properties) variant StrSubstitutor: support substitution in variable names Use StrBuilder instead of StringBuffer to improve performance where sync. is not an issue CharSet: make the underlying set synchronized CompareToBuilder: fix passing along compareTransients to the reflectionCompare method ExtendedMessageFormat doesn't override equals(Object) FastDateFormat: fix to properly include the locale when formatting a Date NumberUtils: createNumber() throws a StringIndexOutOfBoundsException when argument containing "e" and "E" is passed in StringUtils methods do not handle Unicode 2.0+ supplementary characters correctly SystemUtils: getJavaVersionAsFloat throws StringIndexOutOfBoundsException on Android runtime/Dalvik VM MemberUtils: getMatchingAccessibleMethod does not correctly handle inheritance and method overloading Javadoc is incorrect for lastIndexOf() method Javadoc for HashCodeBuilder.append(boolean) does not match implementation Javadoc StringUtils.left() claims to throw an exception on negative lenth, but doesn't Javadoc - document thread safety Test for StringUtils replaceChars() icelandic characters ArrayUtils - add isNotEmpty() methods ArrayUtils - add nullToEmpty() methods CharRange - provide an iterator that lets you walk the chars in the range CharRange - add more readable static builder methods ClassUtils - new isAssignable() methods with autoboxing ClassUtils - add support to getShortClassName and getPackageName for arrays DateUtils - add ceiling() method DateUtils - add parseDateStrictly() method EqualsBuilder - add reset() method NumberUtils - add toByte() and toShort() methods Mutable numbers - add string constructors MutableBoolean - add toBoolean(), isTrue() and isFalse() methods StrBuilder - add appendSeparator() methods with an alternative default separator if the StrBuilder is currently empty SystemUtils - add IS_OS_WINDOWS_7 constant SystemUtils - add IS_JAVA_1_7 constant for JDK 1.7 StringUtils - add abbreviateMiddle() method StringUtils - add indexOfIgnoreCase() and lastIndexOfIgnoreCase() methods StringUtils - add isAllUpperCase() and isAllLowerCase() methods StringUtils - add lastOrdinalIndexOf() method to complement the existing ordinalIndexOf() method StringUtils - add repeat() method StringUtils - add startsWithAny() method StringUtils - add upperCase(String, Locale) and lowerCase(String, Locale) methods New Reflection package containing ConstructorUtils, FieldUtils, MemberUtils and MethodUtils ArrayUtils - addAll() does not handle mixed types very well CharSet - Synchronizing the COMMON Map so that getInstance doesn't miss a put from a subclass in another thread ClassUtils - improving performance of getAllInterfaces ClassUtils - toClass() throws NullPointerException on null array element DateUtils - Fix parseDate() cannot parse ISO8601 dates produced by FastDateFormat DateUtils - round() doesn't work correct for Calendar.AM_PM DateUtils - improve tests Entities - multithreaded initialization Entities - missing final modifiers; thread-safety issues EnumUtils - getEnum() doesn't work well in 1.5+ ExceptionUtils - use immutable lock target ExtendedMessageFormat - OutOfMemory with a pattern containing single quotes FastDateFormat - call getTime() on a calendar to ensure timezone is in the right state FastDateFormat - Remove unused field LocaleUtils - Initialization of available locales in LocaleUtils can be deferred NumberUtils - createNumber() thows a StringIndexOutOfBoundsException when only an "l" is passed in NumberUtils - isNumber(String) and createNumber(String) both modified to support '2.' StringUtils - improve handling of case-insensitive Strings StringUtils - replaceEach() no longer NPEs when null appears in the last String[] StringUtils - correct JavaDocs for startsWith() and startsWithIgnoreCase() StringEscapeUtils - escapeJava() escapes '/' characters StringEscapeUtils - change escapeJavaStyleString() to throw UnhandledException instead swallowing IOException and returning null WordUtils - fix StringIndexOutOfBoundsException when lower is greater than the String length StrBuilder - Performance improvement by doubling the size of the String in ensureCapacity Compare, Equals and HashCode builders - use ArrayUtils to avoid creating a temporary List EqualsBuilder - removing the special handling of BigDecimal (LANG-393) to use compareTo instead of equals because it creates an inequality with HashCodeBuilder HashCodeBuilder - Performance improvement: check for isArray to short-circuit the 9 instanceof checks HashCodeBuilder - Changing the hashCode() method to return toHashCode() HashCodeBuilder - reflectionHashCode() can generate incorrect hashcodes HashCodeBuilder and ToStringStyle - use of ThreadLocal causes memory leaks in container environments ToStringBuilder - make default style thread-safe RandomUtils - nextLong() always produces even numbers RandomUtils - RandomUtils tests are failing frequently ClassUtils.getShortClassName(String) inefficient Shouldn't Commons Lang's StringUtils have a "common" string method? FastDateFormat getDateInstance() and getDateTimeInstance() assume Locale.getDefault() won't change OSGi-ify Lang StrBuilder appendFixedWidth does not handle nulls infinite loop in Fraction.reduce when numerator == 0 FastDateFormat thread safety ClassUtils.getShortClassName and ClassUtils.getPackageName and class of array LocaleUtils.toLocale() rejects strings with only language+variant Enum is not thread-safe BooleanUtils.toBoolean() - invalid drop-thru in case statement causes StringIndexOutOfBoundsException ArrayUtils.toClass Why does appendIdentityToString return null? NumberUtils.min(floatArray) returns wrong value if floatArray[0] happens to be Float.NaN Dates.round() behaves incorrectly for minutes and seconds StringUtils.length(String) returns null-safe length adding a StringUtils.replace method that takes an array or List of replacement strings Adding functionality to DateUtils to allow direct setting of various fields. Add escaping for CSV columns to StringEscapeUtils StringUtils: startsWith / endsWith / startsWithIgnoreCase / endsWithIgnoreCase / removeStartIgnoreCase / removeEndIgnoreCase methods Extension to ClassUtils: Obtain the primitive class from a wrapper Javadoc bugs - cannot find object Optimize HashCodeBuilder.append(Object) http://commons.apache.org/lang/developerguide.html "Building" section is incorrect and incomplete Ambiguous / confusing names in StringUtils replace* methods Add new splitByWholeSeparatorPreserveAllTokens() methods to StringUtils Add getStartTime to StopWatch Perhaps add containsAny() methods? Javadoc Example for EqualsBuilder is questionable EqualsBuilder don't compare BigDecimals correctly Split camel case strings Add Calendar flavour format methods to DateFormatUtils Calculating A date fragment in any time-unit Memory usage improvement for StringUtils#getLevenshteinDistance() Add ExtendedMessageFormat to org.apache.commons.lang.text StringEscapeUtils.escapeJavaScript() method did not escape '/' into '\/', it will make IE render page uncorrectly Add toArray() method to IntRange and LongRange classes add SystemUtils.IS_OS_WINDOWS_VISTA field Pointless synchronized in ThreadLocal.initialValue should be removed ToStringStyle javadoc should show examples of styles Documentation bug for ignoreEmptyTokens accessors in StrTokenizer BooleanUtils toBooleanObject javadoc does not match implementation truncateNicely method which avoids truncating in the middle of a word Use of enum prevents a classloader from being garbage collected resuling in out of memory exceptions. NumberUtils.max(byte[]) and NumberUtils.min(byte[]) are missing Null-safe comparison methods for finding most recent / least recent dates. StopWatch: suspend() acts as split(), if followed by stop() StrBuilder.replaceAll and StrBuilder.deleteAll can throw ArrayIndexOutOfBoundsException. Bug in method appendFixedWidthPadRight of class StrBuilder causes an ArrayIndexOutOfBoundsException ToStringBuilder throws StackOverflowError when an Object cycle exists Create more tests to test out the +=31 replacement code in DurationFormatUtils. StrBuilder contains usages of thisBuf.length when they should use size Enum JavaDoc: 1) outline 5.0 native Enum migration 2) warn not to use the switch() , 3) point out approaches for persistence and gui Wrong behavior of Entities.unescape NumberUtils.createNumber throws NumberFormatException for one digit long NullPointerException in isAvailableLocale(Locale) FastDateFormat.mRules is not transient or serializable StringUtils.join should allow you to pass a range for it (so it only joins a part of the array) Refactor Entities methods Tests fail to pass when building with Maven 2 DurationFormatUtils returns wrong result unescapeXml("&12345678;") should be "&12345678;" Optimize StringEscapeUtils.unescapeXml(String) BooleanUtils isNotTrue/isNotFalse Extra StrBuilder methods Add a pair of StringUtils.substringsBetween;String[] methods HashCodeBuilder throws java.lang.StackOverflowError when an object contains a cycle. Wish for StringUtils.join(Collection, *) StrBuilderTest#testReplaceStringString fails. EqualsBuilder.append(Object[], Object[]) crashes with a NullPointerException if an element of the first array is null Serialization - not backwards compatible Replace Clover with Cobertura ValuedEnum.compareTo(Object other) not typesafe - it easily could be... LocaleUtils test fails under Mustang javadoc example for StringUtils.splitByWholeSeparator incorrect PADDING array in StringUtils overflows on '\uffff' ClassUtils.primitiveToWrapper and Void unit test for org.apache.commons.lang.text.StrBuilder DateUtils.truncate method is buggy when dealing with DST switching hours RandomStringUtils.random() family of methods create invalid unicode sequences StringUtils#getLevenshteinDistance() performance is sub-optimal Wrong length check in StrTokenizer.StringMatcher ExceptionUtils goes into infinite loop in getThrowables is throwable.getCause() == throwable FastDateFormat: wrong format for date "01.01.1000" Unclear javadoc for DateUtils.iterator() Memory "leak" in StringUtils StringEscapeUtils should expose escape*() methods taking Writer argument Fraction.toProperString() returns -1/1 for -1 DurationFormatUtils.formatDurationWords "11 <unit>s" gets converted to "11 <unit>" Performance modifications on StringUtils.replace StringEscapeUtils.unescapeHtml skips first entity after standalone ampersand DurationFormatUtils.formatPeriod() returns the wrong result Request for MutableBoolean implementation New method for EqualsBuilder New ExceptionUtils method setCause() Add Mutable<Type> to<Type>() methods. Provides a Class.getPublicMethod which returns public invocable Method Using ReflectionToStringBuilder and excluding secure fields add generic add method to DateUtils Tokenizer Enhancements: reset input string, static CSV/TSV factories Trivial cleanup of javadoc in various files CompositeFormat Performance boost for RandomStringUtils Enhanced Class.forName version Add StringUtils.containsIgnoreCase(...) Support char array converters on ArrayUtils DurationFormatUtils.formatDurationISO() javadoc is missing T in duration string between date and time part Minor build and checkstyle changes Javadoc errors on StringUtils.splitPreserveAllTokens(String, char) EscapeUtil.escapeHtml() should clarify that it does not escape ' chars to &apos; Add methods and tests to StrBuilder replace() length calculation improvement New interpolation features Implementation of escape/unescapeHtml methods with Writer CompareToBuilder excludeFields for reflection method Add WordUtils.getInitials(String) Error in an example in the javadoc of the StringUtils.splitPreserveAllTokens() method ToStringBuilder/HashCodeBuilder javadoc code examples Cannot build tests from latest SVN minor javadoc improvements for StringUtils.stripXxx() methods javadoc for StringUtils.removeEnd is incorrect Minor tweak to fix of bug # 26616 make optional parameters in FastDateFormat really optional Nestable.indexOfThrowable(Class) uses Class.equals() to match buffer under/overrun on Strings.strip, stripStart & stripEnd ToStringStyle.setArrayEnd(String) doesn't replace null with empty string. New class proposal: CharacterEncoding SystemUtils fails init on HP-UX javadoc - 'four basic XML entities' should be 5 (apos is missing) o.a.c.lang.enum.ValuedEnum: 'enum'is a keyword in JDK1.5.0 StringEscapeUtils.unescapeHtml() doesn't handle an empty entity EqualsBuilder.append(Object[], Object[]) incorrectly checks that rhs[i] is instance of lhs[i]'s class Method enums.Enum.equals(Object o) doesn't work correctly. ExceptionUtils.addCauseMethodName(String) does not check for duplicates. Make StopWatch validate state transitions enum package is not compatible with 1.5 jdk WordUtils capitalizeFully() throws a null pointer exception ValuedEnum parseDate class from HttpClient's DateParser class ArrayUtils.isEquals() throws ClassCastException when array1 and array2 are different dimension ClassCastException in Enum.equals(Object) FastDateFormat year bug unbalanced ReflectionToStringBuilder FastDateFormat.getDateInstance(int, Locale) always uses the pattern from the first invocation ReflectionToStringBuilder.toString(null) throws exception by design Make ClassUtils methods null-safe and not throw an IAE. StringUtils.split ignores empty items EqualsBuilder.append(Object[], Object[]) throws NPE ArrayUtils.addAll doesn't always return new array Enum.equals does not handle different class loaders. Add SystemUtils.AWT_TOOLKIT and others. Throwable cause for NotImplementedException ClassUtils.primitivesToWrappers method public static boolean DateUtils.equals(Date dt1, Date dt2) ? Documentation error in StringUtils.replace DateUtils constants should be long DateUtils.truncate() is off by one hour when using a date in DST switch 'zone' StringEscapeUtils.unescapeHtml() doesn't handle hex entities new StringUtils.replaceChars behaves differently from old CharSetUtils.translate last substring returned by StringUtils.split( String, String, int ) is too long Can't subclass EqualsBuilder because isEquals is private new StringUtils.split methods that split on the whole separator string New method for converting a primitive Class to its corresponding wrapper Class Add convenience format(long) methods to FastDateFormat Enum's outer class may not be loaded for EnumUtils WordUtils.capitalizeFully(String str) should take a delimiter Make javadoc crosslinking configurable Minor javadoc fixes for StringUtils.contains(String, String) Error in JavaDoc for StringUtils.chomp(String, String) StringUtils.defaultString: Documentation error Add hashCode-support to class ObjectUtils add another "known method" to ExceptionUtils Enhancement of ExceptionUtils.CAUSE_METHOD_NAMES DateUtils.truncate oddity at the far end of the Date spectrum add getLength() method to ArrayUtils Validate.java: fixes comment skew, removes unused loop counter StringUtils.isAsciiPrintable() ExceptionUtils: new getCause() methodname (for tomcat-exception) fixes 75 typos mutable numbers Javadoc fixes for ClassUtils Add StringUtils.nIndexOf? Javadoc fixes for CharSetUtils Remove redundant check for null separator in StringUtils#join Class and Package Comparators for ClassUtils add remove methods to ArrayUtils WordUtils capitalize improvement add isEmpty method to ArrayUtils lang.math.Fraction class deficiencies Add methods to ArrayUtils: add at end and insert-like ops Add SystemUtils methods for directory properties. Add method that validates Collection elements are a certain type elapsed time formatting utility method Infinite loop in ToStringBuilder.reflectionToString for inner classes NumberUtils.createBigDecimal("") NPE in Sun 1.3.1_08 Rationalize StringUtils slice functions SystemUtils.IS_OS_OS2 Javadoc is wrong A small, but important javadoc fix for Fraction proper whole and numerator Adding tolerance to double[] search methods in ArrayUtils lang.builder classes javadoc edits (mostly typo fixes) StringUtils javadoc and test enhancements SystemUtils.IS_OS_*, IS_JAVA_* are always false. Improve util.Validate tests maven-beta10 checkstyle problem StringUtils.chopNewLine - StringIndexOutOfBoundsException ToStringBuilder doesn't work well in subclasses static option for reversing the stacktrace NullPointerException in CompareToBuilder RandomStringUtils.randomAlpha methods omit 'z' test.time fails in Japanese (non-us) locale. NumberUtils.isNumber allows illegal trailing characters Improve javadoc and overflow behavior of Fraction RandomStringUtils infloops with length > 1 test.lang fails if compiled with non iso-8859-1 locales SystemUtils does not play nice in an Applet time unit tests fail on Sundays java.lang.ExceptionInInitializerError thrown by JVMRandom constructor StringUtils.chomp does not match Perl patch and test case fixing problem with RandomStringUtils.random() General case: infinite loop: ToStringBuilder.reflectionToString Should ToStringBuilder.reflectionToString handle arrays? EnumUtils nit: The import java.io.Serializable is never used Example in Javadoc for ToStringBuilder wrong for append. Added class hierachy support to HashCodeBuilder.reflectionHashCode() ExceptionUtils new methods. Infinite loop in StringUtils.replace(text, repl, with) + FIX StackOverflow due to ToStringBuilder No Javadoc for NestableDelegate Specify initial size for Enum's HashMap. Enum does not support inner sub-classes Removed compile warning in ObjectUtils SystemUtils.IS_JAVA_1_5 Javadoc is wrong NumberRange inaccurate for Long, etc. Hierarchy support in ToStringBuilder.reflectionToString() StringUtils.countMatches loops forever if substring empty javadoc fixes (remove @links to non-public identifiers) Add javadoc examples and tests for StringUtils Make NumberUtils null handling consistent Unused field 'startFinal' in DateIterator reduce object creation in ToStringBuilder Improved tests, javadoc for CharSetUtils, StringEscapeUtils NumberUtils min/max, BooleanUtils.xor, and ArrayUtils toPrimitive and toObject Javadoc, tests improvements for CharSet, CharSetUtils StringUtil enhancement Javadoc nit Additional Lang Method Suggestions Make NestableDelegate methods public instead of package private Missing @since tags Refactored reflection feature of ToStringBuilder into new ReflectionToStringBuilder Typo in documentation Patch for javadocs Add join(..., char c) to StringUtils (and some performance fixes). Even contains tests! Resurrect the WordWrapUtils from commons-sandbox/utils EnumTest fails on Linux Sun JDK 1.3.0 What to do with FastDateFormat unused private constructors Added class hierachy support to CompareToBuilder.reflectionCompare() Removed compile warning in FastDateFormat typo in the javadoc example code MethodUtils: Removed unused code/unused local vars. Hierarchy support in EqualsBuilder.reflectionEquals() JavaDoc Errata ArrayUtils.contains() More flexibility for getRootCause in ExceptionUtils NumberRange.getMaximum returns minimum Enum constructor validations NestableException/Delegate is not serializable split using null and max less than actual token count adds "null" ExceptionUtils cannot handle J2EE-Exception in a default way commons-lang-2.6-src/src/site/resources/images/logo.png100644 0 0 24773 11513702446 20407 0ustar 0 0 ‰PNG  IHDR,d³cš—bKGDÿÿÿ ½§“ pHYs  ÒÝ~ütIMEÔ!T®[¦ IDATxœí]{XTåÖ÷ÜAì</À •Ú©4Ó` £«Š‚J\ÌÌ[eçxI©NÏÉzN_íX*–÷,/ ^±Ò4/xÎIãªiyž²Lf€™R˜áÎÌþþXÎúïž!¿hÿþðÁ=k¯½ö»ßß{]k½‚(ŠL† ·Š[m€ ¿wÈ$”!ãC&¡ ·2 eȸÅI(CÆ-†LB2n1dÊq‹!“P†Œ[ ™„2dÜbÈ$”!ãC&¡ ·2 eȸÅI(CÆ-†êæUpq‚ t•ª›ÔÖî#ÚU~CÂÝaC÷•m×ìÍT7õoBçB™òóósssóóóáö   ƒÁ¦×ë¡é¿íª*++ËÊÊBKÂÂÂÂÃà h@%íj3™LáááaaaÜ#òòòÀÚ   „„N9Õœ‘‘QPPPVVïå]Øíëdff®\¹’^ª KHHðTV&“)77 …;nÕƒe®Ï”À=´]myyyYYY´(@ff&Ö„„Ns»jáv£Ñˆ° ½úê«+W®ìø§ÿmC¼A¬^½:((È“¶¸¸¸ü±©©©¥¥Åáp8N§ÓéIÕªU«¼¨Òëõ/¿üòO?ýÔÜÜÜÚÚê]ÛÞ½{§L™7îÞ½»¹¹¹¥¥¥µµõ믿—*7 /^ljjå Ù“=n…9ŒFãªU«ðY---hƒ'µ .lll¤eUVV–œœì¶4¤Â^¾Q^^žÛ·¦Ÿé«¯¾B =lnnnrr2ÛÜÜ|éҥŋ»ýdéééô“¹µ_3(((>>>>>èÍ‹‡6žåÝž a^^~E‹ýç?ÿ©««³Ùl.\xê©§èÇØ±cG]]]cc£§“‘‘ª^~ùeªjùòåT[jjj}}½´þÆÕ«W#÷iiiv»½®®náÂ…^*bHHHMMÝnolleÊ) ­VëÇ ­‰Á`øç?ÿ j¹RbŒ={¶ºº:66–¹:ÿ;wîØ±cëÖ­“'Ov+l³Ù¥õ’¶’ñññv»½¦¦æ—_~©ªªÂ‚ý裨ÂÀÀÀï¾ûŽk\¦L™â¶`·lÙ²e˸kþüù©©©;vìHJJâ * Àl6ÿòË/ð½8b£ùÕW_a-ª"À&ØjµVUU]½zÕn·Kõô$tˆ„È@½^_WWwíÚµªª*‹ÅRYYYáÂÛo¿M¿„¿¿EEEuu5W‚¨Š1–––võêU«ÕJõL&Stt4U8iÒ¤ªªªÚÚZZ]GKKË{ï½G%£¢¢c#GŽhÓ¹ÀÞyçúúz:Ù`îv5†¾lÙ2XÆ€ÙTD•J¥V«¹îðáÃW¬Xvb­Ecè…1f4iW סFRÉE‹=òÈ#0ÝÂ×µjµj<â•W^yì±Ç@j–í¨Q£PÒl6ƒ`*¨EqõêÕÈÀ˜˜˜Ûo¿>VbZ°Z­véÒ¥t yèС¯¿þniiiGZ¶ðRPªØ +•JµZJG ¥¥¥ø:´C# ñWQA ©Ñh`pNÛ8i ÷$´CBúu£££ñó³¶ „²KMMÅýŠ+úôéCW·òòòèhpìØ± ðÉ …Z­Ö¶…N§=z4­+f³yÓ¦Mðu±®H—ÂûöíÛê‚Óé„~@£Ñèt:__ßÑ£GsÂÍÍÍð^´ÊúøøH…;†Kv@¸M>§ûU°A¥RiµZPËí ôéÓ§©© ˆ¥áVøË/¿D-kÖ¬A¨¨(|A°rÓ‚ÕétÜ„séÒ¥\‹É\4à^ Ç–œtºk±XZZZèz2ÇêòòòM›6Á+À‚æ ¬…v_­V«TªžÚûQ´C¬¬,ü{ذa5 ”àwÜqþüù¢¢¢ÿþ÷¿‘‘‘8ªo@+ʨQ£¸:‡Ú`ìU‡[w=|ø0mbq¬Å™ 'í`}|| ºpÂ8e.B5yN-.b+€CSN˜1†5 :5 '‰tƒ‘*^„qR𙙉 %c,88–mðuhÁBÙjµÚøøxª¶´´ôòåË8ÌŽI_ €Ã °J•û 0JcM”eË–mݺŠZRx"™““-»Z­ö`*z#¡ÑhľëÁ„† š.µ 8Ó€¡?P*|~Í ‚°oß>ÔÜ¿`sg¨*øp[£ûæ›oš\@º­+pù Ÿþà$¥Œ¥à„a¦„CA|Ô¨7À@N§JÅ;*!Ÿ±4¼ ã¤QE:cŒÝ~ûí8ƃק*(X•J5zôhn+èÌ™3P°ÐA1w[äÒRÅ‚åJgŒtÈÀ}Í+VL:µ¨¨[4æj¶zè!Pû{轑Ž68 àæÊؒѱ\¯^½|||´Z­J¥ª¬¬¤š¡?Á©šT*|衇8«Š‹‹q” ˜ûBºýj=ÞÞ­  ÿEHº†‰X‡€„½zõòóóóóóƒUaa!Õ Í$ŒyðrUr[Õ••---8Õt;_§u{WÁ‹W5R{Ðr·<”ÀH'Éé”ÚÐqa© ùùùôWœ…Ò²u[8Üv¼Ùl†$íçÝ–•´`=‰Àëï½÷^LL '|æÌ™ààà×^{í§Ÿ~’N×=!ú2×0ŒN q⊆›¬cO(«`ƒçåC‚~®ÁÓY™—W$舤…Ì5Ùkw±ëk»:iÑBKÍÀY–—²…+Ü’ÜË ¶;òR‚‡ÖÍÓíiiisçΕþºaÆ'Ÿ|2%%'ün›Ñž$ä¾AII ]‡ðTî”Ò9!§üرcT¿ºý ·þ¼ô„RóèOÞ¯´ûSyØÝpk–mG©B,Øv¸ÎY¼Z¶lÙ§Ÿ~:`Àî×ŠŠŠ%K–ÜsÏ=—.]‚.õxïíŽÇšÍfŽ6nÅ6í¶aþÆýû÷çÆ9¿2n9÷Úµ¡ÓËÈ0²“–ym£ÃÃÃsss_ýu©Xyyùرc÷îÝ‹;ÝaÌÿÜÀ|÷èÑ£ÔoÈ‹¤t(uDÌÉÉñ4màTqW‚ƒƒY7וß8ç2,X:kõ2^@pÛ}<„`ض}饗þõ¯Íœ9“«¨¨xóÍ7üñGغ„ÑiOýÜÞHÈm%íÚµ ×:âÄ X ¸õ•o¿ý–®.0Ïí7­+Çg72û=ÀKÁzr*r‹_­lAÀUô^½z <ø­·Þ:~üø˜1c¨Xeeåºuë8‚ÉCo$8p ýï¹sçJKKa>Ö.s233Ÿ~úiÚ¦r”>wîªò^]¨Ãx$råwNEn”a±X,‹“ÀÓ´`ï¿ÿþ~ýúu7§Nš’’ú¹…ô»îºkíÚµï¿ÿ>•?tè:*öàq©7 ®•ýÛßþV^^N½œÝÞ˜ŸŸÿôÓOïÙ³‡VŽ„çÏŸGziä¸M°1cÆdñ½g¯\w¡¡¡Üg‚’÷¾vÅÚ–í¸qã¸‚í¦²ÍÏÏG“è¸ÔÏϯwïÞqqqÏ=÷ ›Ífp0¦N­=¯3lgNÈm­Z,–÷Þ{¯¬¬ ý'¥ßB¬BCC¹Í†œœ\÷´&NÝAžþybÀt™„Œ1AæÏŸO¯œ8q¼j¼lä˜L&Ü`ô÷÷Ÿ1c†@¼Ün¾ß¨ž*ÉoÞH(ÂË/¿Ì97?~ü™gžÉÏϧ<Ä&jõêÕáááF£1==v~©CpZZUµ{÷îÊÊJô0tÛΡÇi@@¬¤¡Ûl?Ê<„ÏDCX,ËÎ;¹ÝTO˃¨EZ°nÝzº )))èn!º¼¦ÐÃ~È!(9lØ0êƒÚ#»Aæ…„8Ýz÷Ýw¹ŸÌfs||üˆ#þú׿îÝ»wïÞ½ÉÉɃ ‚`¥ôôô~ýúÑ Ñ•jÛ¶mTÕë¯¿Ž½¥´ÃŽÀÀÀýû÷£#zwIƒý›þ®ðú …"55•Fœ¬Y³¦¼¼A®3„Ì ð÷æÍ›aI:¥®òPñB˜µk×^¾|™vnøY5Muu5J ™[Àëyh§'T( [·n•þZQQ±qãÆY³fMŸ>}Ú´ikÖ¬¤¦¦FGGcÔî·ÂP'!!R$Î;·xñbê ŠÍvFFPZ¯×ñÅ}ûöEã§À ZknÞȼòŠ€íÞ‚°X,™_µ Nmè, wÊvРAGŽ¡<œ5k–Ñh¤ƒ€ÑhÄ­mÛ¶M˜0ò¡lÁ™^„òòòŽFcV«ÿæi2™Þxã ðS¥m4tÅë€15{ölïU=í 9 ‰ŠçâkÝ"00ð“O>‰ŒŒÄ?±­›”rBBÂ矎1 ÇŽ‹ˆˆX¿~=ºðfddŒ=zêÔ©Œ1ƒÁpäÈ‘~ýú9IT=Né*cìøñãP¤»d¢(r‹%''å’’B…Ï;'Õ pjwíÚ…:9¤Â999@onÜ(Jb™kµÝ)…Ï4hР/¾øb„ øj?þøßÿþ÷¼¼èàKqáT`'kK?ÊÃÏ?ÿ|âĉ0©¡Ñɯ¾ú*<4&&fÆ è,Þ³çÿíä]t /^œ;w.æ†à0gΜ_|2J°¶!gÔ}µÕÕÕmܸqûö혻äGzà0àê °iµÚÏ>û¬¢¢"++‹ËÃëß¿ÿ°aÃ&MšôðÃ:T«Õž>}:??ß­0cl̘1'NìéÓ§KKK¿ùæè*•Jell¬Á`€¥P9N…B­5è|öÙgÑH§+ÌÃs¡HJJŠˆˆÐjµ6l@ç˜`Ðpx®Á`X´hÃà …qm5 †Ñ£GoÚ´ ߋڀîé*•jÛ¶m¾¾¾fÆŒh0ºJsÂIII<òˆF£A'ÐL×™Qxþüù8(€—jjj‚‚-+++..>zô(º ƒÁ‚_^ Æ¢¡«ÑhÖ®]KËÊí£·mÛæããSZZúá‡ÒzB—d¡2$&&FDD  ðÇ?þ’J[­ÖsçÎUVVBTGHHÈSO=ÕÚÚ -oKK c ƒãàM»oÅèV¡ý ÜX½€‡¸oC«;òcX9bëEµAAÓl?¢ @žÐð\t ‡¬®««ƒ4•0{„`___0t +a§Ó©T*u:csËH¿]__O…¡N€f°Äétb;›ËP³ÁŒ&e¨d „c Œj¡P †„ (L5£ÀCÌìtEëÓ /.Nbð|)(X° vâ;})x}hX±S(Z­J"ÚAp8ð:X˜t5ˆ¹¼óqíT©Tb]ê©1MíŸE!¸B×!Ì\áŠy§+Ÿ‚Ë1‡ ”-´à¨6¼‹nc@ÓK'âPônEáéèõ‰1†#!°I"†¬†&Ìð" šQ{h†ðFæjJÀ<Ê €B¡ Ž,ð\Æ6Ô*\iޏ-5Ô ¥ûCЂ hƘ ,Xú-®g˜ m…ní¤;¡(°&¥q±¿P?%c :a|k´?¥‚„ööàia‡„¡ÌA/x.¶÷y1ó…§}<¤6n‹‚:Oq}¬§/k6PËE’^vÂŒ¬ÓB+µ—È¥¡ôTX£ÑPÍ܉•F©T:]ÑÏ´c§ cíä^K‰Ó Ê9Í\ÁªÕjη‰.6J –j£z8;ñ¥8;‘]кÁí”?Q©ThWŒ JÑ6Ï@Ï…"nà@l©› ]_¦éç©éÂÅ=ÔC—Ñ)90×7£·ƒI´“ Ja"P˜ÚÏõ´RaÔŒ]"#Ãlìá0‡‚T-F°Š{V¶­¦8’w÷,XZ¶C¤šs»‘>šµåz)U¦8­ÿW/Iipß½çáÆNeƒèZOw÷Q$V ï¥&’¥vü$XWXÛ>“Öª?§SâB+­aT¾MY¸$mg°RaÁµEŽvŠmÁÙ€jáâ Lë«'aŽEŒ´q\Ù2É@ï¢e‹7JÙ"}4'ï¶T¹1*Ûn`à9óz*ý9–—´jv„~RmÌE» ¥–Híam£È;"Œÿº­(Raé‹x….4Ø{yº—{„Û²ÍËËËÌÌÄãÐ:òRÞ ÊS• š±™ðòR=9$”6ÿ´Œ:W^ô;I[ï:=YÒîSºPø†Lí´ü*§×=½…ô ×Ç2Æ`WƒªòbØÍIé×®ª†›:©·ËKªÓ oèÆîþk€w%p°)—" ’‡÷ní&íü]±ŽC]q’Ñqäåå#›ôŒ7؃å|ñ¥7ƒN—-£‡©õðÃÓD¦Ÿ|òÉäÉ“’WbÏ}W×Bî e\Œ<,X@/655ÕÕÕ¡wq«Lía¸©9¡ŒždÝâ466Úl6…BŽ ¸w×ã· ~MÈ$”q¸×G/‚ï¨B¡3ð‘ûÀ®…LB×áv„ áQÐõi4OkdÜ dʸÁÝ!sàöít:U*u“yØ…fdðŽlܯœï½þëšÙc!“PÆuÄ”^të@'£ !Ge0Ö1¯4Ý™„2®G¤Òë¹ÜMi²™°°0½^ŸÐqÿR“É/^L¯gff¢æ°°°)S¦Ð¤ão)¨[,c,!!!((ˆ;§ñ´;¢ .8ŽÝ»wÓêñüãĉ'NœÈÍÍ=wîÜåË—«««ëëëé®ýêÕ«¹C)‚‚‚V®\‰q‰Üêò ¢Ó\BB†P®ZµÊ­òE‹'†;JÕRýÉÉÉpcxx8pZ¸xñâ={ö …rDJ7· 2 eüœNç ‘Ðh4bmß³gOKK dJOO‡ð @||<¤Ì£ fóòò’““¥« ÍÍÍ—.]âÎ/áÉ51o¢[Îäåå‘AAA—/_†$CÍÍÍ»víâÎðbïÞ½”“ÝTìòpTF'a2™ ‡……}õÕW¸Ÿát:'Mš4qâıcÇ2ÆöíÛ7yòäøøx,Ÿ›› ŽãAAA4½¢Óéüù矟xâ “É0–——gggÓÃÙÙÙ§N2 èÎÊ…ƒ‘Hò“'Oúûû#£&OžtäÈ‘TaAA%?r»ûb¸ä…A``àîݻ׬Y#ŠbttôÌ™3ñ LŠù‚‡o ®l”°”ÂUk‡ÃÑÐÐàt:!zƒ1&dd•CšpPH“”ÒÐdÆXKK Ðc®wA¸³k[[[”J%.ÉЩݙ„2:Qãââ&Ož Q¿¸("¸2²BÐÓÙ³gé]N§3óc†hi‡)Š"t’@T‘œÁœNüÙgŸ1Æôzý¡C‡þð‡?Øívä=îª[ã›dÊè >øàd Á`ˆ…ã–a¨‰Ë*Þ×öĽ"ܨ×ë×­[÷?ÿó?iiip======þ MJJ‚óƒ™ë H9†Qáõ¿›‡LBácNrj%#“:·“½.7Æ-=à"teGMKK{öÙgNçÉ“'a­õ¡‡ºãŽ;”J%úÄ0ÉÆô¬Ènâ¡LB7Œ‚‚“É„ÿEΫ€µGØ‚ñÄF§Óùøø455Á>!:²Ùxê»§§»2 eÜ0(™ËË <˜ëP{Áå˜F%»µ?qû ýû÷?÷ÜsIII111õõõ@33Ãþ>ØÉ\»ó@?…B]%PÙö\ô.‡¼:*ãfqàÀK—.[6x¥áþá /¼@%»ifåi™gß¾}Ï>û,cÌ`0h4Ê+…äìtèŸU*•V«õññÑétà@w»Ür€LB7Q9gÆØ´iÓÊÊÊèˆtË–-ÁÁÁ§OŸ¦b999ð‡ÕjµX,Ý‘@ñÚk¯ÁK–,ùâ‹/ªªªèŽ?-c«DÕét@Â_¡dòpTš?‚1fµZñoäL@@€Á` ’f³yÒ¤IÁÁÁ ¨ªª*))aŒ…††îܹsÆŒá‚1–““c6›ûöíûïÿ{åÊ•C† ‘aeee—XÈC™L&¼Ë?~<Ýý 5jThhh`` 8è »µd2 ePÆ}ûöÑ+{÷î}ê©§¤’©©©úÓŸ¸‹çÏŸ?þ<ü˜˜øî»ï*Š$!cìÛo¿eŒ=þøãcÆŒA/³?üêÉÉÉ™;wnŸ>}ÜZˆ[#€'N …t’1Æ¥®á;‡R„„„¤¦¦8ðW @>$TËÏχ³²iÖPDß¾}ï»ï¾1cÆÜyç£GöóóÓjµ‚ äççÏž=»¢¢‚“>|ø† î¼óNz0™L&L b>úèÒ¥K{õêUWWwáÂ…?þ¸¨¨HúÜG}ô‰'ž :thïÞ½=zæÌ™ììl)¯úöíûØc;6,,ì¶ÛnóóóóññQ«ÕåååÓ¦Mã ;‚ÀÀÀ´´´°°0Îe´›)“PKII„1›~ÌÎS(£FJJJêÕ«—N§‚_³²²8b÷Ýwß“O>9hÐ Š¢h47oÞl2™G\\Ü=÷Ü£V«}||~üñÇôôt¨èÌ`ÏÅýÆÙ³g=ºwïÞ‰‰‰¸OàÖÂáÇϙ3ç¶ÛnëÝ»·ÌúGJJÊo¼uèÐ¡Ž—I``àwß}Ç9ÍteÊ`ŒÐ©ohh°Ùl6›­®®®©©‰1¦Õjýüüz÷î S(N§³±±Ó±455‰¢¨T*qu–A€ü.˜'bu:]¯^½zõêåãã£ÑhÕv»rÆ8NµZíëë ›¯¯¯F£@[H“†P]´{BA233gΜ¹yóæÇv:'Nœà¨¥P(JJJÌf3cìðáÃP&[¶l‰…ù!'ßµ…/Ï e\í¥qF‚+*} öƒ®‰¹R*§LBüqÙXÝWø9s1¿‚ë ì³á&!ªÂ°=ŒÄ…1†£PFBœÙ-€dZTm q/~š>}úþýûõzýÖ­[ëëë©å˜ Ýèè¬ï¶Ûn[¸pá‘#GG}}=¼Ê@º®å¡LB×A㌠vªÕjL?=uCªˆ® A…Bs9ˆ;ãø_ÌàÂí×ÑÍ:èHQ†ã?å6v˰Å›o¾¹ÿ~ÆØ¼yóP3f¬I0¡è û L»ýöÛc0ÞÆÎ–¦¥’I(£»€$¨ýŒ1Lv¤ ©™¤±vp &P¸‚qq·¹2Áh4XJÁ¡,̸˜‹p;¤¢At…\¡Ð Q‘ù ­¤¤dýúõðFÔ‹ôÆÌQ”HÜÊl´<ùä“èݦR©Z[[¡Ñù.ä¡LB×Á1P¨µXe1¶€®R`èZ­ÆÕ‚$; se À\£‚˹Çœð¨ÂÐD.²{Hè-ØL€ØÁƒñ¥ ÇOϬ턓"Á>üðÃL˜0®Óy24rO(£‹U 8@geHæ /@Úp$ÄCíQ']ü`®¹ Ò™!è¡é'P? eÀ‹Ò'* º'¹nݺáÇ7ȃ<§3RFfÅK—.---ÍÌÌÔét87Fû»£üeʸ\¥€ª C/:NÄÛ4ƒi ó(%IT!Í„+´G‚ѯ—‡ÂEœ›¹µ0<<&„€¿üå/Ï?ÿü¬Y³ !úpÓ­¨¨è³Ï>Û°acì£> ‡¥TS;»ò>¡ŒëÀÁ˜H<¿¸*ÎÚæ#”Þ‹ÿRnà'ÕéI‰'=Rk©°ÉdŠˆˆàâ­c#FŒð÷÷ŸäéÀ]D.áŽc1´¢«l–I(£GHØÒÒ‚G‚~úé§GޱX,À5jT@@@HHHhhhHHÞ+‡\•áR ])G&¡Œì „è‰ÚÒÒÂð]ÜŸ”.ºàºÝhAvy7ÈäÕQ=È$Lí`xÙÜÜŒ~êœû(.ÿÐ}êr€ž=]k°LB= °›=˜V«…mÆ,u‚Ïl‡(<€ßtôèŽ>ð¿üïQê OIEND®B`‚commons-lang-2.6-src/src/site/site.xml100644 0 0 3751 11513702447 15122 0ustar 0 0 Commons Lang /images/logo.png /index.html commons-lang-2.6-src/src/site/xdoc/article2_4.xml100644 0 0 42342 11513702447 17062 0ustar 0 0 What's new in Commons Lang 2.4? Commons Documentation Team

    Commons Lang 2.4 is out, and the obvious question is: "So what? What's changed?".

    This article aims to briefly cover the changes and save you from having to dig through each JIRA issue to see what went on in the year of development between Lang 2.3 and 2.4.

    First, let us start with a couple of deprecations. As you can see in the release notes, we chose to deprecate the ObjectUtils.appendIdentityToString(StringBuffer, Object) method as its null handling did not match its design (see LANG-360 for more details. Instead users should use ObjectUtils.identityToString(StringBuffer, Object).

    We also deprecated DateUtils.add(java.util.Date, int, int). It should have been private from the beginning; please let us know if you actually use it.

    Before we move on, a quick note on the build: we built 2.4 using Maven 2 and Java 1.4. We also tested that the Ant build passed the tests successfully under Java 1.3, and that the classes compiled under Java 1.2. As it's been so long, we stopped building a Java 1.1-compatible jar. Most importantly, it should be a drop in replacement for Lang 2.3, but we recommend testing first, of course. Also, for those of you who work within an OSGi framework, the jar should be ready for OSGi. Now... time to move on.

    Three new classes were added, so let's cover those next.

    Firstly, we added an IEEE754rUtils class to the org.apache.commons.lang.math package. This candidate for ugly name of the month was needed to add IEEE-754r semantics for some of the NumberUtils methods. The relevant part of that IEEE specification in this case is the NaN handling for min and max methods, and you can read more about it in LANG-381.

    Second and third on our newcomers list are the ExtendedMessageFormat class and its peer FormatFactory interface, both found in the org.apache.commons.lang.text package.

    Together they allow you to take the java.text.MessageFormat class further and insert your own formatting elements.

    By way of an example, imagine that we have a need for custom formatting of a employee identification number or EIN. Perhaps, simplistically, our EIN is composed of a two-character department code followed by a four-digit number, and that it is customary within our organization to render the EIN with a hyphen following the department identifier. Here we'll represent the EIN as a simple String (of course in real life we would likely create a class composed of department and number). We can create a custom Format class:

    
    public class EINFormat extends Format {
      private char[] idMask;
    
      public EINFormat() {
      }
      public EINFormat(char maskChar) {
        idMask = new char[4];
        Arrays.fill(idMask, maskChar);
      }
      public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {
        String ein = (String) obj; //assume or assert length >= 2
        if (idMask == null) {
          return new StringBuffer(ein).insert(2, '-').toString();
        }
        return new StringBuffer(ein.substring(0, 2)).append('-').append(idMask).toString();
      }
      public Object parseObject(String source, ParsePosition pos) {
        int idx = pos.getIndex();
        int endIdx = idx + 7;
        if (source == null || source.length() < endIdx) {
          pos.setErrorIndex(idx);
          return null;
        }
        if (source.charAt(idx + 2) != '-') {
          pos.setErrorIndex(idx);
          return null;
        }
        pos.setIndex(endIdx);
        return source.substring(idx, endIdx).deleteCharAt(2);
      }
    }
    
    Our custom EIN format is made available for MessageFormat-style processing by a FormatFactory implementation:
    
    public class EINFormatFactory implements FormatFactory {
      public static final String EIN_FORMAT = "ein";
      public Format getFormat(String name, String arguments, Locale locale) {
        if (EIN_FORMAT.equals(name)) {
          if (arguments == null || "".equals(arguments)) {
            return new EINFormat();
          }
          return new EINFormat(arguments.charAt(0));
        }
        return null;
      }
    }
    
    Now you simply provide a java.util.Map<String, FormatFactory> registry (keyed by format type) to ExtendedMessageFormat:
    
    new ExtendedMessageFormat("EIN: {0,ein}", Collections.singletonMap(EINFormatFactory.EIN_FORMAT, new EINFormatFactory()));
    
    As expected, this will render a String EIN "AA9999" as: "EIN: AA-9999".

    If we wanted to trigger the EIN masking code, we could trigger that in the format pattern:
    
    new ExtendedMessageFormat("EIN: {0,ein,#}", Collections.singletonMap(EINFormatFactory.EIN_FORMAT, new EINFormatFactory()));
    
    This should render "AA9999" as: "EIN: AA-####".

    You can also use ExtendedMessageFormat to override any or all of the built-in formats supported by java.text.MessageFormat. Finally, note that because ExtendedMessageFormat extends MessageFormat it should work in most cases as a true drop-in replacement.

    There were 58 new methods added to existing Commons Lang classes. Going through each one, one at a time would be dull, and fortunately there are some nice groupings that we can discuss instead:

    CharSet getInstance(String[]) adds an additional builder method by which you can build a CharSet from multiple sets of characters at the same time. If you weren't aware of the CharSet class, it holds a set of characters created by a simple pattern language allowing constructs such as "a-z" and "^a" (everything but 'a'). It's most used by the CharSetUtils class, and came out of CharSetUtils.translate, a simple variant of the UNIX tr command.

    ClassUtils canonical name methods are akin to the non 'Canonical' methods, except they work with the more human readable int[] type names rather than the JVM versions of [I. This makes them useful for parsing input from developer's configuration files.

    ClassUtils toClass(String[]) is very easy to explain - it calls toClass on each Object in the array and returns an array of Class objects.

    ClassUtils wrapper->primitive conversions are the reflection of the pre-existing primitiveToWrapper methods. Again easy to explain, they turn an array of Integer into an array of int[].

    ObjectUtils identityToString(StringBuffer, Object) is the StringBuffer variant of the pre-existing identityToString method. In case you've not met that before, it produces the toString that would have been produced by an Object if it hadn't been overridden.

    StringEscapeUtils CSV methods are a new addition to our range of simple parser/printers. These, quite as expected, parse and unparse CSV text as per RFC-4180.

    StringUtils has a host of new methods, as always, and we'll leave these for later.

    WordUtils abbreviate finds the first space after the lower limit and abbreviates the text.

    math.IntRange/LongRange.toArray turn the range into an array of primitive int/longs contained in the range.

    text.StrMatch.isMatch(char[], int) is a helper method for checking whether there was a match with the StrMatcher objects.

    time.DateFormatUtils format(Calendar, ...) provide Calendar variants for the pre-existing format methods. If these are new to you, they are helper methods to formatting a date.

    time.DateUtils getFragment* methods are used to splice the time element out of Date. If you have 2008/12/13 14:57, then these could, for example, pull out the 13.

    time.DateUtils setXxx methods round off our walk through the methods - the setXxx variant of the existing addXxx helper methods.

    The StringUtils class is a little large, isn't it? Sorry, but it's gotten bigger.

    Hopefully they are in many cases self-describing. Rather than spend a lot of time describing them, we'll let you read the Javadoc of the ones that interest you.

    In addition to new things, there are the bugfixes. As you can tell from the release notes, there are a good few - 24 in fact according to JIRA. Here are some of the interesting ones:

    • LANG-393 - We fixed EqualsBuilder so that it understands that BigDecimals are equal even when they think they're not. It seems very likely that usually you will want "29.0" and "29.00" to be equal, even if BigDecimal disagrees.
    • LANG-380 - Chances are you'll know if you met this one. Fraction.reduce has an infinite loop if the numerator is 0.
    • LANG-369, LANG-367, LANG-334 - Threading bugs - we improved how things work in concurrency situations for ExceptionUtils, FastDateFormat and Enum.
    • LANG-346 - DateUtils.round was getting things wrong for minutes and seconds.
    • LANG-328 - LocaleUtils.toLocale was broken if there was no country code defined.

    Hopefully that was all of interest. Don't forget to download Lang 2.4, or, for the Maven repository users, upgrade your <version> tag to 2.4. Please feel free to raise any questions you might have on the mailing lists, and report bugs or enhancements in the issue tracker.

    commons-lang-2.6-src/src/site/xdoc/article2_5.xml100644 0 0 21437 11513702447 17065 0ustar 0 0 What's new in Commons Lang 2.5? Commons Documentation Team

    Commons Lang 2.5 is out, and the obvious question is: "So what? What's changed?".

    This article aims to briefly cover the changes and save you from having to dig through each JIRA issue to see what went on in the two years of development between Lang 2.4 and 2.5.

    Two years?!? Yes, it's true. The reason is that 2.5 represents the backwards compatible changes in the nearly complete Java-5 focused Lang 3.0.

    There were no new deprecations in 2.5.

    2.5 was built using Sun's 1.6.0_17 JVM, but targets Java 1.3.

    A new org.apache.commons.lang.reflect package was added, accumulating common high-level uses of the java.lang.reflect APIs. The classes, hopefully self-evident in nature, were pulled together from the existing BeanUtils and the unreleased Reflect components. The classes are:

    • ConstructorUtils - primarily creating new instances of classes
    • FieldUtils - primarily reading and writing to Object/Class fields
    • MethodUtils - primarily methods to make invoking methods simpler

    You can read more about the classes in their javadoc.

    With both Java 7 and Windows 7 becoming a reality, SystemUtils was updated to provide boolean fields for both versions.

    There were 66 new methods added to existing Commons Lang classes.

    The ArrayUtils class received two new types of methods. Firstly, a boolean isNotEmpty(array) set of methods, identifying whether the particular array is null or an empty sized array. This makes it the inverse of the existing isEmpty(array) methods. Secondly, an array nullToEmpty(array) set of methods that converts null or empty arrays to a singleton empty array already available from the ArrayUtils class. Non null/empty arrays are left untouched.

    The constructor for the CharRange class is somewhat confusing. It takes a boolean parameter that when set to true means the CharRange is negated. To make code easier to read, the following static helper methods were added:

    • public org.apache.commons.lang.CharRange is(char)
    • public org.apache.commons.lang.CharRange isIn(char, char)
    • public org.apache.commons.lang.CharRange isNot(char)
    • public org.apache.commons.lang.CharRange isNotIn(char, char)

    An iterator() method was also added to provide another way of walking the range.

    The EqualsBuilder obtained a new reset() method to allow for reuse, while the HashCodeBuilder received a hashCode() method that returns the built hash code instead of the natural hash code of the builder object itself. It doesn't really matter what the builder chooses to use as a hash code and this stops accidental use of the hashCode() instead of toHashCode() method from causing lots of pain.

    Helper isFalse(), isTrue() and toBoolean() methods were added to MutableBoolean, while the other mutable classes received String argument constructors.

    Lastly, the DateUtils class received a new ceiling set of methods to truncate upwards, and a parseDateStrictly method to parse a Date with the supplied DateFormat classes leniency set to false.

    As with 2.4, the StringUtils class has grown and we cover its new methods in its own section.

    • abbreviateMiddle(String, String, int);String - This method turns aRatherLongNameSuchAsAFileName into 'aRatherLo...AFileName'. This is often desirable when you want to restrict the length of a name, but you can afford to have quite long names.
    • indexOfIgnoreCase(String, String);int - An indexOf method that ignores the case of what it's matching. Matching lastIndexOfIgnoreCase and 'start at index' variants were also added.
    • lastOrdinalIndexOf(String, String, int);int - A matching variant for the already exisitng ordinalIndexOf method - they support finding the Nth indexOf instead of the first time the search term is found.
    • isAllLowerCase(String);boolean - Is the String all lower case.
    • isAllUpperCase(String);boolean - Is the String all upper case.
    • lowerCase(String, Locale);String - Null protected toLowerCase methods for the platform independent inclined.
    • upperCase(String, Locale);String - Null protected toUpperCase methods for the platform independent inclined.
    • repeat(String, String, int);String - Repeat option that includes an optional separator.
    • startsWithAny(String, String[]);boolean - Does the specified String start with any of the supplied values.

    Per the release notes there are 32 bugs fixed in Lang 2.5. Some highlights are:

    • LANG-477 - fixing an OutOfMemoryError in ExtendedMessageFormat.
    • LANG-76 - EnumUtils.getEnum() doesn't work well in 1.5.
    • LANG-204 and LANG-506 - Multithread improvements to the package private Entities class, used behind the scenes by StringEscapeUtils.
    • LANG-511 - Improve performance by deferring LocaleUtils initialization.
    • LANG-523 - Two orders of magnitude performance improvement in StrBuilder.
    • LANG-467 - Reverted the change to EqualsBuilder in Lang 2.4 to specially handle BigDecimal. While useful, it put things out of sync with HashCodeBuilder.
    • LANG-586 - Use of a ThreadLocal in HashCodeBuilder and ToStringStyle meant that containers could end up with memory leaks. This was rewritten to avoid this.
    • LANG-472 - RandomUtils.nextLong() was returning only even numbers. Fans of Java-based roulette wheels can breathe a sigh of relief.

    Hopefully that was all of interest. Don't forget to download Lang 2.5, or, for the Maven repository users, upgrade your <version> tag to 2.5. Please feel free to raise any questions you might have on the mailing lists, and report bugs or enhancements in the issue tracker.

    commons-lang-2.6-src/src/site/xdoc/building.xml100644 0 0 5577 11513702447 16720 0ustar 0 0 Building Commons Documentation Team

    Commons Lang uses Maven or Ant as a build system.

    You may also be interested in the upgrade notes:

    To build a jar file, change into the root directory of Lang and run "mvn package". The result will be in the "target" subdirectory.

    To build the full website, run "mvn site". The result will be in "target/site". You must be online to successfully complete this target.

    Further details can be found in the commons build instructions.

    To build a jar file, change into the root directory of Lang and run "ant jar". The result will be in the "target" subdirectory.

    To build the Javadocs, run "ant javadoc". The result will be in "target/docs/api".

    commons-lang-2.6-src/src/site/xdoc/developerguide.xml100644 0 0 15517 11513702447 20141 0ustar 0 0 Developer guide for Commons "Lang"

    The Commons Lang Package

    Developers Guide


    [Introduction] [Package Structure] [Utility Classes] [Javadoc] [Building]

    1. INTRODUCTION

    The Lang package contains a set of Java classes that extend the basic JDK classes. This developer guide seeks to set out rules for the naming of classes and methods within the package. The purpose of this, as with all naming standards, is to improve the coherency and consistency of the whole API.

    The philosophy of the naming standards is to follow those of the JDK if possible.

    2. PACKAGE STRUCTURE

    The main package for Lang is org.apache.commons.lang. Subpackages should be created for each group of related items.

    Each package should have a package.html file for javadoc. This should describe the use of the package and its scope.

    3. UTILITY CLASSES

    Utility classes provide additional functionality around a class or interface. Examples include StringUtils and SerializationUtils.

    Each class shall follow the naming pattern XxxUtils where Xxx relates to the class or interface that the utility services. Variations on a theme (Integer as opposed to Number) should be dealt with in one Utils class where possible. Each Utils class shall:

    • be a single, static method based, class
    • have a name consisting of the interface name plus 'Utils'
    • deal with one class or interface and its variations (subclasses)
    • provide methods that perform useful utility functions
    • the class will not be final
    • for null parameters, rather than throwing an Exception, consider performing a Null patterned concept, such as returning 0 or ""

    A utility class can act as a factory for specific implementations of a class or interface. In such cases the implementations should be non-public, static, inner classes of the utility class. However, if warranted due to maintenance or other reasons, these decorator classes may be moved to top-level classes in a subpackage. The naming of such a subpackage should be discussed and agreed upon on the developers mailing list.

    If different overloaded variants of a method are desired, with the same method signature, it should not be indicated via a boolean argument, but via a more focused method name. Rather than replace(boolean repeat), replace and replaceAll, or replaceOnce and replace.

    4. JAVADOC

    The Sun javadoc guidelines are the starting point for Lang. These points are an extension to make it easier for users reading the generated docs and developers with javadoc-popup capabilities from within their IDE.

    General

    References to other objects, interfaces or methods use the @link-tag the first time it is referenced in a class or interface. On the following references always enclose it inside <code></code>.

    References to null, this, long, int, short, char, byte, double, float and boolean should be enclosed in <code></code>.

    Classes/Interfaces/Methods

    Use a short description of what the class/interface/method is used for, enclose with <p></p>.

    A longer description about what the class/interface/method is used for and if it is needed how it is done. If it is necessary include description of the parameters, what they are used for and how. Enclose with <p></p> where it is needed, try to divide into smaller parts (not to small!) to enhance readability of the generated Javadoc.

    If an example is needed enclose it with <pre></pre>. It should be supported with an explanation within a normal paragraph.

    Exception throwing

    When throwing an exception to indicate a bad argument, always try to throw IllegalArgumentException, even if the argument was null. Do not throw NullPointerException. (Obviously, you should document what the code actually does!)

    Deprecations

    When deprecating a method or class include a clear reference to when the method will be deleted. This should be of the form 'Method will be removed in Commons Lang 3.0.'.

    Language used in code/comments

    It has been decided to casually standardize on US-English. To avoid misplaced jeers of 'americanisation', the people making this decision largely write in non-US-English. However, it's not something to get worked up about. Lots of spelling differences will creep in all over.

    5.BUILDING

    Building a Release

    Commons Lang is intended to interoperate with older versions of Java. To achieve this, the distribution must be built with the minimum targetted JDK. Why? Over time the base JDK has changed. Building with a later JDK would make some things in Commons Lang not run with prior libraries. For example, new StringBuffer(StringBuffer) was added after JDK1.2, but compiling under 1.4 could link to it. Run the code under 1.2 and you get a NoSuchMethodError.

    The currently targetted version of Java is 1.3.

    To build Lang:
    Tested JARDistributionSite
    Maven 2.xmvn packagemvn assembly:assemblymvn site

    commons-lang-2.6-src/src/site/xdoc/download_lang.xml100644 0 0 21314 11513702447 17736 0ustar 0 0 Download Commons Lang Commons Documentation Team

    We recommend you use a mirror to download our release builds, but you must verify the integrity of the downloaded files using signatures downloaded from our main distribution directories. Recent releases (48 hours) may not yet be available from the mirrors.

    You are currently using [preferred]. If you encounter a problem with this mirror, please select another mirror. If all mirrors are failing, there are backup mirrors (at the end of the mirrors list) that should be available.

    [if-any logo][end]

    Other mirrors:

    The KEYS link links to the code signing keys used to sign the product. The PGP link downloads the OpenPGP compatible signature from our main site. The MD5 link downloads the checksum from the main site.

    commons-lang-2.6-bin.tar.gz md5 pgp
    commons-lang-2.6-bin.zip md5 pgp
    commons-lang-2.6-src.tar.gz md5 pgp
    commons-lang-2.6-src.zip md5 pgp
    commons-lang-3.0-beta-bin.tar.gz md5 pgp
    commons-lang-3.0-beta-bin.zip md5 pgp
    commons-lang-3.0-beta-src.tar.gz md5 pgp
    commons-lang-3.0-beta-src.zip md5 pgp

    Older releases can be obtained from the archives.

    commons-lang-2.6-src/src/site/xdoc/index.xml100644 0 0 7044 11513702447 16221 0ustar 0 0 Home Commons Documentation Team

    The standard Java libraries fail to provide enough methods for manipulation of its core classes. Apache Commons Lang provides these extra methods.

    Lang provides a host of helper utilities for the java.lang API, notably String manipulation methods, basic numerical methods, object reflection, concurrency, creation and serialization and System properties. Additionally it contains basic enhancements to java.util.Date and a series of utilities dedicated to help with building methods, such as hashCode, toString and equals.

    A getting started user guide is available together with various project reports.

    The JavaDoc API documents are available online:

    The subversion repository can be browsed.

    The latest version 2.6, is JDK 1.3 compatible - Download now! (Release Notes).

    For information on previous releases, see the Release History and to download previous releases, see the Apache Archive.

    The commons mailing lists act as the main support forum. The user list is suitable for most library usage queries. The dev list is intended for the development discussion. Please remember that the lists are shared between all commons components, so prefix your email by [lang].

    Issues may be reported via ASF JIRA. Please read the instructions carefully to submit a useful bug report or enhancement request.

    commons-lang-2.6-src/src/site/xdoc/issue-tracking.xml100644 0 0 13367 11513702447 20067 0ustar 0 0 Commons Lang Issue tracking Commons Documentation Team

    Commons Lang uses ASF JIRA for tracking issues. See the Commons Lang JIRA project page.

    To use JIRA you may need to create an account (if you have previously created/updated Commons issues using Bugzilla an account will have been automatically created and you can use the Forgot Password page to get a new password).

    If you would like to report a bug, or raise an enhancement request with Commons Lang please do the following:

    1. Search existing open bugs. If you find your issue listed then please add a comment with your details.
    2. Search the mailing list archive(s). You may find your issue or idea has already been discussed.
    3. Decide if your issue is a bug or an enhancement.
    4. Submit either a bug report or enhancement request.

    Please also remember these points:

    • the more information you provide, the better we can help you
    • test cases are vital, particularly for any proposed enhancements
    • the developers of Commons Lang are all unpaid volunteers

    For more information on subversion and creating patches see the Apache Contributors Guide.

    You may also find these links useful:

    commons-lang-2.6-src/src/site/xdoc/mail-lists.xml100644 0 0 22737 11513702447 17216 0ustar 0 0 Commons Lang Mailing Lists Commons Documentation Team

    Commons Lang shares mailing lists with all the other Commons Components. To make it easier for people to only read messages related to components they are interested in, the convention in Commons is to prefix the subject line of messages with the component's name, for example:

    • [lang] Problem with the ...

    Questions related to the usage of Commons Lang should be posted to the User List.
    The Developer List is for questions and discussion related to the development of Commons Lang.
    Please do not cross-post; developers are also subscribed to the user list.
    You must be subscribed to post to the mailing lists. Follow the Subscribe links below to subscribe.

    Note: please don't send patches or attachments to any of the mailing lists. Patches are best handled via the Issue Tracking system. Otherwise, please upload the file to a public server and include the URL in the mail.

    Please prefix the subject line of any messages for Commons Lang with [lang] - thanks!

    Name Subscribe Unsubscribe Post Archive Other Archives
    Commons User List

    Questions on using Commons Lang.

    Subscribe Unsubscribe Post mail-archives.apache.org markmail.org
    www.mail-archive.com
    news.gmane.org
    Commons Developer List

    Discussion of development of Commons Lang.

    Subscribe Unsubscribe Post mail-archives.apache.org markmail.org
    www.mail-archive.com
    news.gmane.org
    Commons Issues List

    Only for e-mails automatically generated by the issue tracking system.

    Subscribe Unsubscribe read only mail-archives.apache.org markmail.org
    www.mail-archive.com
    Commons Commits List

    Only for e-mails automatically generated by the source control sytem.

    Subscribe Unsubscribe read only mail-archives.apache.org markmail.org
    www.mail-archive.com

    Other mailing lists which you may find useful include:

    Name Subscribe Unsubscribe Post Archive Other Archives
    Apache Announce List

    General announcements of Apache project releases.

    Subscribe Unsubscribe read only mail-archives.apache.org markmail.org
    old.nabble.com
    www.mail-archive.com
    news.gmane.org
    commons-lang-2.6-src/src/site/xdoc/proposal.xml100644 0 0 6352 11513702447 16752 0ustar 0 0 Proposal for Lang Package

    The standard Java libraries fail to provide enough methods for manipulation of its main components. The Lang Package provides these extra methods. There are other classes which might justifiably be included in java.lang someday, this package also provides for them.

    This proposal is to create a package of Java utility classes for the classes that are in java.lang's hierarchy, or are considered to be so standard as to justify existence in java.lang. The Lang Package also applies to primitives and arrays.

    Lang relies only on standard JDK 1.2 (or later) APIs for production deployment. It utilizes the JUnit unit testing framework for developing and executing unit tests, but this is of interest only to developers of the component. Lang will be a dependency for several existing components in the open source world.

    No external configuration files are utilized.

    The initial classes came from the Commons.Util subproject.

    The proposed package name for the new component is org.apache.commons.lang.

    • CVS Repository - New directory lang in the jakarta-commons CVS repository.
    • Mailing List - Discussions will take place on the general dev@commons.apache.org mailing list. To help list subscribers identify messages of interest, it is suggested that the message subject of messages about this component be prefixed with [lang].
    • Bugzilla - New component "Lang" under the "Commons" product category, with appropriate version identifiers as needed.
    • Jyve FAQ - New category "commons-lang" (when available).

    The initial committers on the Lang component shall be as follows:

    • Henri Yandell (bayard)
    • Daniel Rall (dlr)
    • Stephen Colebourne (scolebourne)

    commons-lang-2.6-src/src/site/xdoc/release-history.xml100644 0 0 5236 11513702447 20232 0ustar 0 0 Home Commons Documentation Team
    VersionRelease dateJavadocRelease notes
    2.616/Jan/16api-2.6release notes for 2.6
    2.523/Feb/10api-2.5release notes for 2.5
    2.418/Mar/08api-2.4release notes for 2.4
    2.313/Feb/07api-2.3release notes for 2.3
    2.204/Oct/06api-2.2release notes for 2.2
    2.113/Jun/06api-2.1release notes for 2.1
    2.002/Sep/03api-2.0release notes for 2.0
    1.0.125/Nov/02api-1.0.1release notes for 1.0.1
    1.004/Oct/02api-1.0release notes for 1.0
    commons-lang-2.6-src/src/site/xdoc/upgradeto2_0.xml100644 0 0 110367 11513702447 17450 0ustar 0 0 2.0 Release Notes Commons Documentation Team

    These are the release notes and advice for upgrading Commons-Lang from version 1.0 to version 2.0. INTRODUCTION: This document contains the release notes for this version of the Commons Lang package. Commons Lang is a set of utility functions and reusable components that should be a help in any Java environment. This release has involved a major clean and tidy exercise. Javadoc and Tests are now much more thorough. All methods should now be much clearer in what they do in unusual cases. INCOMPATIBLE CHANGES: Some StringUtils methods have changed functionality from 1.0: isEmpty() chomp(String) chomp(String,String) swapCase(String) Numerous other methods have changed null handling to accept nulls gracefully. As with all major version releases, check your code for incompatibilities. NEW FEATURES: Since the release of the 1.0 package the following classes have been added: lang package: ArrayUtils BitField BooleanUtils CharRange (previously package scoped) ClassUtils StringEscapeUtils WordUtils IllegalClassException IncompleteArgumentException NotImplementedException NullArgumentException SerializationException UnhandledException Validate math sub-package: IntRange LongRange Range DoubleRange JVMRandom NumberRange FloatRange NumberUtils Fraction RandomUtils time sub-package: DateFormatUtils FastDateFormat DateUtils StopWatch Since the release of the 1.0 package the following classes have been changed: lang: CharSet: Added factory method, equals and hashCode(). Better defined and tested the set syntax. CharSetUtils: added keep method: keep any characters specified in the CharSet string RandomStringUtils: random method: overloaded to allow passing in of a Random class SerializationUtils: added empty constructor StringUtils: isEmpty() changed to not trim chomp() changed to be more like Perl. swapCase() no longer word based, but no difference if you pass in ASCII Various methods changed in the handling of null (less exceptions). Many new methods. Various methods deprecated. SystemUtils: isJavaVersionAtLeast(int) added. getJavaVersion() deprecated. host of new constants. enum: Enum: getEnumClass(Class) added EnumUtils: Removed irrelevant Comparable/Serializable interfaces. exception: NestableDelegate: Gained many new methods for dissecting an Exception. ExceptionUtils: Gained many new methods to improve handling of nested stack traces. builder: ReflectionToStringBuilder: Handy class added for creating default toStrings. All other builder classes received a set of new methods. BUG FIXES: ID Sev Pri Plt Owner State Result Summary 13367 [PATCH] StringUtil enhancement 13391 Javadoc nit 13771 Additional Lang Method Suggestions 14306 NullPointerException in CompareToBuilder 14357 static option for reversing the stacktrace 14447 ToStringBuilder doesn't work well in subclasses 14883 StringUtils.countMatches loops forever if substring empty 14884 NumberRange inaccurate for Long, etc. 14985 More flexibility for getRootCause in ExceptionUtils 15154 SystemUtils.IS_JAVA_1_5 Javadoc is wrong 15257 Hierarchy support in ToStringBuilder.reflectionToString() 15438 ArrayUtils.contains() 15439 Enum does not support inner sub-classes 15986 Infinite loop in ToStringBuilder.reflectionToString for inne 16076 Example in Javadoc for ToStringBuilder wrong for append. 16193 Hierarchy support in EqualsBuilder.reflectionEquals() 16202 typo in the javadoc example code 16204 Infinite loop in StringUtils.replace(text, repl, with) + FIX 16227 Added class hierachy support to CompareToBuilder.reflectionC 16228 Added class hierachy support to HashCodeBuilder.reflectionHa 16284 MethodUtils: Removed unused code/unused local vars. 16341 No Javadoc for NestableDelegate 16622 Removed compile warning in FastDateFormat 16669 JavaDoc Errata 16676 StackOverflow due to ToStringBuilder 16689 ExceptionUtils new methods. 16690 Specify initial size for Enum's HashMap. 16787 Removed compile warning in ObjectUtils 17250 [Lang] Should ToStringBuilder.reflectionToString handle arra 17654 EnumUtils nit: The import java.io.Serializable is never used 17882 Add join(..., char c) to StringUtils (and some performance f 18077 StringUtils.chomp does not match Perl 18723 RandomStringUtils infloops with length < 1 18836 test.lang fails if compiled with non iso-8859-1 locales 18948 Resurrect the WordWrapUtils from commons-sandbox/utils 19296 [Lang] What to do with FastDateFormat unused private constru 19364 [Lang] time unit tests fail on Sundays 19756 [lang] java.lang.ExceptionInInitializerError thrown by JVMRa 19880 [lang] patch and test case fixing problem with RandomStringU 20165 [LANG] SystemUtils does not play nice in an Applet 20538 [lang] NumberUtils.isNumber allows illegal trailing characte 20592 [lang] RandomStringUtils.randomAlpha methods omit 'z' 20603 [lang] Make NestableDelegate methods public instead of packa 20632 Refactored reflection feature of ToStringBuilder into new Re 20652 StringUtils.chopNewLine - StringIndexOutOfBoundsException 21021 [PATCH] reduce object creation in ToStringBuilder 21068 [lang] [PATCH] NumberUtils min/max, BooleanUtils.xor, and Ar 21099 [lang][PATCH] Unused field 'startFinal' in DateIterator 21715 The javadoc says "Mac" instead of "OS/2" 21734 [PATCH] all NumberUtils.createXXX(String) methods handle null 21750 [lang] StringUtils javadoc and test enhancements 21758 [lang] lang.builder classes javadoc edits (mostly typo fixes) 21797 [lang] Add javadoc examples and tests for StringUtils 21809 [lang] maven-beta10 checkstyle problem 21904 NumberUtils.createBigDecimal("") NPE in Sun 1.3.1_08 21952 [lang] Improved tests, javadoc for CharSetUtils, StringEscapeUtils 22091 Adding tolerance to double[] search methods in ArrayUtils 22094 A small, but important javadoc fix for Fraction proper whole/numerator 22095 [lang] Javadoc, tests improvements for CharSet, CharSetUtils 22098 [lang] Improve util.Validate tests 22245 [lang] test.time fails in Japanese (non-us) locale. 22286 [lang] Missing @since tags 22367 Typo in documentation 22386 [lang] Improve javadoc and overflow behavior of Fraction DEPRECATIONS: lang: NumberRange: now deprecated, see math subpackage NumberUtils: now deprecated, see math subpackage CHANGES: [In 'diff' format] Jar changes =========== > org.apache.commons.lang.math.Range > org.apache.commons.lang.math.FloatRange > org.apache.commons.lang.math.NumberUtils > org.apache.commons.lang.math.JVMRandom > org.apache.commons.lang.math.IntRange > org.apache.commons.lang.math.LongRange > org.apache.commons.lang.math.DoubleRange > org.apache.commons.lang.math.NumberRange > org.apache.commons.lang.math.Fraction > org.apache.commons.lang.math.RandomUtils > org.apache.commons.lang.time.FastDateFormat > org.apache.commons.lang.time.DateUtils$DateIterator > org.apache.commons.lang.time.DateUtils > org.apache.commons.lang.time.FastDateFormat$UnpaddedMonthField > org.apache.commons.lang.time.FastDateFormat$StringLiteral > org.apache.commons.lang.time.FastDateFormat$TwelveHourField > org.apache.commons.lang.time.FastDateFormat$NumberRule > org.apache.commons.lang.time.FastDateFormat$CharacterLiteral > org.apache.commons.lang.time.FastDateFormat$TimeZoneNumberRule > org.apache.commons.lang.time.FastDateFormat$TimeZoneNameRule > org.apache.commons.lang.time.DateFormatUtils > org.apache.commons.lang.time.FastDateFormat$TwoDigitMonthField > org.apache.commons.lang.time.DurationFormatUtils > org.apache.commons.lang.time.FastDateFormat$TimeZoneDisplayKey > org.apache.commons.lang.time.FastDateFormat$UnpaddedNumberField > org.apache.commons.lang.time.FastDateFormat$PaddedNumberField > org.apache.commons.lang.time.StopWatch > org.apache.commons.lang.time.FastDateFormat$TwentyFourHourField > org.apache.commons.lang.time.FastDateFormat$Rule > org.apache.commons.lang.time.FastDateFormat$TwoDigitNumberField > org.apache.commons.lang.time.FastDateFormat$TextField > org.apache.commons.lang.time.FastDateFormat$Pair > org.apache.commons.lang.time.FastDateFormat$TwoDigitYearField > org.apache.commons.lang.util.IdentifierUtils$StringNumericIdentifierFactory > org.apache.commons.lang.util.IdentifierUtils$StringSessionIdentifierFactory > org.apache.commons.lang.util.IdentifierUtils$LongNumericIdentifierFactory > org.apache.commons.lang.util.IdentifierUtils$StringAlphanumericIdentifierFactory > org.apache.commons.lang.util.Validate > org.apache.commons.lang.util.LongIdentifierFactory > org.apache.commons.lang.util.IdentifierUtils$1 > org.apache.commons.lang.util.StringIdentifierFactory > org.apache.commons.lang.util.IdentifierUtils > org.apache.commons.lang.util.IdentifierFactory > org.apache.commons.lang.util.BitField > org.apache.commons.lang.Entities > org.apache.commons.lang.Entities$LookupEntityMap > org.apache.commons.lang.NotImplementedException > org.apache.commons.lang.NullArgumentException < org.apache.commons.lang.ObjectUtils$1 --- > org.apache.commons.lang.StringPrintWriter > org.apache.commons.lang.UnhandledException > org.apache.commons.lang.Entities$HashEntityMap > org.apache.commons.lang.Entities$ArrayEntityMap > org.apache.commons.lang.Entities$EntityMap > org.apache.commons.lang.IntHashMap > org.apache.commons.lang.BooleanUtils > org.apache.commons.lang.IncompleteArgumentException > org.apache.commons.lang.Entities$PrimitiveEntityMap > org.apache.commons.lang.Entities$TreeEntityMap > org.apache.commons.lang.WordUtils > org.apache.commons.lang.StringEscapeUtils > org.apache.commons.lang.ArrayUtils > org.apache.commons.lang.Entities$BinaryEntityMap > org.apache.commons.lang.ClassUtils > org.apache.commons.lang.IntHashMap$Entry > org.apache.commons.lang.IllegalClassException > org.apache.commons.lang.builder.ReflectionToStringBuilder$1 > org.apache.commons.lang.builder.ReflectionToStringBuilder > org.apache.commons.lang.Entities$MapIntMap Class changes ============= org.apache.commons.lang.enum.EnumUtils -------------------- < public abstract class org.apache.commons.lang.enum.EnumUtils extends java.lang.Object implements java.lang.Comparable, java.io.Serializable { --- > public class org.apache.commons.lang.enum.EnumUtils extends java.lang.Object { > public org.apache.commons.lang.enum.EnumUtils(); org.apache.commons.lang.enum.Enum$Entry -------------------- > final java.util.Map unmodifiableMap; > final java.util.List unmodifiableList; org.apache.commons.lang.enum.Enum -------------------- > protected transient java.lang.String iToString; > static java.lang.Class class$org$apache$commons$lang$enum$ValuedEnum; > public java.lang.Class getEnumClass(); org.apache.commons.lang.enum.ValuedEnum -------------------- > static {}; org.apache.commons.lang.StringUtils -------------------- > public static final java.lang.String EMPTY; > public static boolean isEmpty(java.lang.String); > public static boolean isNotEmpty(java.lang.String); > public static boolean isBlank(java.lang.String); > public static boolean isNotBlank(java.lang.String); < public static java.lang.String deleteSpaces(java.lang.String); < public static java.lang.String deleteWhitespace(java.lang.String); < public static boolean isNotEmpty(java.lang.String); < public static boolean isEmpty(java.lang.String); --- > public static java.lang.String trimToNull(java.lang.String); > public static java.lang.String trimToEmpty(java.lang.String); > public static java.lang.String strip(java.lang.String); > public static java.lang.String stripToNull(java.lang.String); > public static java.lang.String stripToEmpty(java.lang.String); > public static java.lang.String strip(java.lang.String, java.lang.String); > public static java.lang.String stripStart(java.lang.String, java.lang.String); > public static java.lang.String stripEnd(java.lang.String, java.lang.String); > public static java.lang.String stripAll(java.lang.String[])[]; > public static java.lang.String stripAll(java.lang.String[], java.lang.String)[]; > public static int indexOf(java.lang.String, char); > public static int indexOf(java.lang.String, char, int); > public static int indexOf(java.lang.String, java.lang.String); > public static int indexOf(java.lang.String, java.lang.String, int); > public static int lastIndexOf(java.lang.String, char); > public static int lastIndexOf(java.lang.String, char, int); > public static int lastIndexOf(java.lang.String, java.lang.String); > public static int lastIndexOf(java.lang.String, java.lang.String, int); > public static boolean contains(java.lang.String, char); > public static boolean contains(java.lang.String, java.lang.String); > public static int indexOfAny(java.lang.String, char[]); > public static int indexOfAny(java.lang.String, java.lang.String); > public static int indexOfAnyBut(java.lang.String, char[]); > public static int indexOfAnyBut(java.lang.String, java.lang.String); > public static boolean containsOnly(java.lang.String, char[]); > public static boolean containsOnly(java.lang.String, java.lang.String); > public static boolean containsNone(java.lang.String, char[]); > public static boolean containsNone(java.lang.String, java.lang.String); > public static java.lang.String substringBefore(java.lang.String, java.lang.String); > public static java.lang.String substringAfter(java.lang.String, java.lang.String); > public static java.lang.String substringBeforeLast(java.lang.String, java.lang.String); > public static java.lang.String substringAfterLast(java.lang.String, java.lang.String); > public static java.lang.String substringBetween(java.lang.String, java.lang.String); > public static java.lang.String substringBetween(java.lang.String, java.lang.String, java.lang.String); > public static java.lang.String getNestedString(java.lang.String, java.lang.String); > public static java.lang.String getNestedString(java.lang.String, java.lang.String, java.lang.String); > public static java.lang.String split(java.lang.String, char)[]; > public static java.lang.String join(java.lang.Object[]); > public static java.lang.String join(java.lang.Object[], char); > public static java.lang.String join(java.util.Iterator, char); > public static java.lang.String deleteSpaces(java.lang.String); > public static java.lang.String deleteWhitespace(java.lang.String); > public static java.lang.String replaceChars(java.lang.String, char, char); > public static java.lang.String replaceChars(java.lang.String, java.lang.String, java.lang.String); < public static java.lang.String center(java.lang.String, int); < public static java.lang.String center(java.lang.String, int, java.lang.String); --- > public static java.lang.String overlay(java.lang.String, java.lang.String, int, int); > public static java.lang.String rightPad(java.lang.String, int, char); > public static java.lang.String leftPad(java.lang.String, int, char); < public static java.lang.String strip(java.lang.String); < public static java.lang.String strip(java.lang.String, java.lang.String); < public static java.lang.String stripAll(java.lang.String[])[]; < public static java.lang.String stripAll(java.lang.String[], java.lang.String)[]; < public static java.lang.String stripEnd(java.lang.String, java.lang.String); < public static java.lang.String stripStart(java.lang.String, java.lang.String); --- > public static java.lang.String center(java.lang.String, int); > public static java.lang.String center(java.lang.String, int, char); > public static java.lang.String center(java.lang.String, int, java.lang.String); < public static java.lang.String uncapitalise(java.lang.String); --- > public static java.lang.String capitalize(java.lang.String); > public static java.lang.String uncapitalize(java.lang.String); > public static java.lang.String uncapitalise(java.lang.String); < public static java.lang.String getNestedString(java.lang.String, java.lang.String); < public static java.lang.String getNestedString(java.lang.String, java.lang.String, java.lang.String); > public static boolean isWhitespace(java.lang.String); > public static java.lang.String reverseDelimited(java.lang.String, char); > public static java.lang.String abbreviate(java.lang.String, int); > public static java.lang.String abbreviate(java.lang.String, int, int); > public static java.lang.String difference(java.lang.String, java.lang.String); > public static int differenceAt(java.lang.String, java.lang.String); < public static boolean containsOnly(java.lang.String, char[]); --- > static {}; org.apache.commons.lang.ObjectUtils -------------------- > public static java.lang.StringBuffer appendIdentityToString(java.lang.StringBuffer, java.lang.Object); > public static java.lang.String toString(java.lang.Object); > public static java.lang.String toString(java.lang.Object, java.lang.String); < org.apache.commons.lang.ObjectUtils.Null(org.apache.commons.lang.ObjectUtils$1); --- > org.apache.commons.lang.ObjectUtils.Null(); > static {}; org.apache.commons.lang.exception.NestableDelegate -------------------- > public static boolean topDown; > public static boolean trimStackFrames; < org.apache.commons.lang.exception.NestableDelegate(org.apache.commons.lang.exception.Nestable); < java.lang.String getMessage(int); < java.lang.String getMessage(java.lang.String); < java.lang.String getMessages()[]; < java.lang.Throwable getThrowable(int); < int getThrowableCount(); < java.lang.Throwable getThrowables()[]; < int indexOfThrowable(java.lang.Class, int); --- > public org.apache.commons.lang.exception.NestableDelegate(org.apache.commons.lang.exception.Nestable); > public java.lang.String getMessage(int); > public java.lang.String getMessage(java.lang.String); > public java.lang.String getMessages()[]; > public java.lang.Throwable getThrowable(int); > public int getThrowableCount(); > public java.lang.Throwable getThrowables()[]; > public int indexOfThrowable(java.lang.Class, int); > protected java.lang.String getStackFrames(java.lang.Throwable)[]; > protected void trimStackFrames(java.util.List); org.apache.commons.lang.exception.ExceptionUtils -------------------- < protected static final java.lang.String CAUSE_METHOD_NAMES[]; < protected static final java.lang.Object CAUSE_METHOD_PARAMS[]; --- > static final java.lang.String WRAPPED_MARKER; < protected org.apache.commons.lang.exception.ExceptionUtils(); --- > public org.apache.commons.lang.exception.ExceptionUtils(); > public static void addCauseMethodName(java.lang.String); > public static boolean isThrowableNested(); > public static boolean isNestedThrowable(java.lang.Throwable); > public static void printRootCauseStackTrace(java.lang.Throwable); > public static void printRootCauseStackTrace(java.lang.Throwable, java.io.PrintStream); > public static void printRootCauseStackTrace(java.lang.Throwable, java.io.PrintWriter); > public static java.lang.String getRootCauseStackTrace(java.lang.Throwable)[]; > public static void removeCommonFrames(java.util.List, java.util.List); > public static java.lang.String getFullStackTrace(java.lang.Throwable); > static java.util.List getStackFrameList(java.lang.Throwable); org.apache.commons.lang.CharRange -------------------- < class org.apache.commons.lang.CharRange extends java.lang.Object { --- > public final class org.apache.commons.lang.CharRange extends java.lang.Object implements java.io.Serializable { > public org.apache.commons.lang.CharRange(char,boolean); < public org.apache.commons.lang.CharRange(java.lang.String,java.lang.String); --- > public org.apache.commons.lang.CharRange(char,char,boolean); < public void setStart(char); < public void setEnd(char); < public boolean isRange(); < public boolean inRange(char); < public void setNegated(boolean); --- > public boolean contains(char); > public boolean contains(org.apache.commons.lang.CharRange); > public boolean equals(java.lang.Object); > public int hashCode(); > static {}; org.apache.commons.lang.ObjectUtils$1 -------------------- < Compiled from ObjectUtils.java < class org.apache.commons.lang.ObjectUtils$1 extends java.lang.Object { < } --- > Class 'org.apache.commons.lang.ObjectUtils$1' has been removed org.apache.commons.lang.ObjectUtils$Null -------------------- < org.apache.commons.lang.ObjectUtils.Null(org.apache.commons.lang.ObjectUtils$1); --- > org.apache.commons.lang.ObjectUtils.Null(); > static {}; org.apache.commons.lang.SystemUtils -------------------- > public static final java.lang.String FILE_ENCODING; > public static final java.lang.String JAVA_RUNTIME_NAME; > public static final java.lang.String JAVA_RUNTIME_VERSION; > public static final java.lang.String JAVA_VM_INFO; > public static final java.lang.String USER_COUNTRY; > public static final java.lang.String USER_LANGUAGE; > public static final float JAVA_VERSION_FLOAT; > public static final int JAVA_VERSION_INT; > public static final boolean IS_OS_AIX; > public static final boolean IS_OS_HP_UX; > public static final boolean IS_OS_IRIX; > public static final boolean IS_OS_LINUX; > public static final boolean IS_OS_MAC; > public static final boolean IS_OS_MAC_OSX; > public static final boolean IS_OS_OS2; > public static final boolean IS_OS_SOLARIS; > public static final boolean IS_OS_SUN_OS; > public static final boolean IS_OS_WINDOWS; > public static final boolean IS_OS_WINDOWS_2000; > public static final boolean IS_OS_WINDOWS_95; > public static final boolean IS_OS_WINDOWS_98; > public static final boolean IS_OS_WINDOWS_ME; > public static final boolean IS_OS_WINDOWS_NT; > public static final boolean IS_OS_WINDOWS_XP; > public static boolean isJavaVersionAtLeast(int); org.apache.commons.lang.SerializationUtils -------------------- > public org.apache.commons.lang.SerializationUtils(); org.apache.commons.lang.RandomStringUtils -------------------- > public static java.lang.String random(int, int, int, boolean, boolean, char[], java.util.Random); org.apache.commons.lang.CharSet -------------------- < public class org.apache.commons.lang.CharSet extends java.lang.Object { --- > public class org.apache.commons.lang.CharSet extends java.lang.Object implements java.io.Serializable { > public static final org.apache.commons.lang.CharSet EMPTY; > public static final org.apache.commons.lang.CharSet ASCII_ALPHA; > public static final org.apache.commons.lang.CharSet ASCII_ALPHA_LOWER; > public static final org.apache.commons.lang.CharSet ASCII_ALPHA_UPPER; > public static final org.apache.commons.lang.CharSet ASCII_NUMERIC; > protected static final java.util.Map COMMON; > public static org.apache.commons.lang.CharSet getInstance(java.lang.String); > protected org.apache.commons.lang.CharSet(java.lang.String); < public boolean contains(char); > public org.apache.commons.lang.CharRange getCharRanges()[]; > public boolean contains(char); > public boolean equals(java.lang.Object); > public int hashCode(); > static {}; org.apache.commons.lang.CharSetUtils -------------------- > public static java.lang.String keep(java.lang.String, java.lang.String); > public static java.lang.String keep(java.lang.String, java.lang.String[]); org.apache.commons.lang.builder.ToStringBuilder -------------------- < public org.apache.commons.lang.builder.ToStringBuilder(java.lang.Object); < public org.apache.commons.lang.builder.ToStringBuilder(java.lang.Object,org.apache.commons.lang.builder.ToStringStyle); < public org.apache.commons.lang.builder.ToStringBuilder(java.lang.Object,org.apache.commons.lang.builder.ToStringStyle,java.lang.StringBuffer); < public static void setDefaultStyle(org.apache.commons.lang.builder.ToStringStyle); < public org.apache.commons.lang.builder.ToStringBuilder append(java.lang.Object); < public org.apache.commons.lang.builder.ToStringBuilder append(java.lang.String, java.lang.Object); < public org.apache.commons.lang.builder.ToStringBuilder append(java.lang.String, java.lang.Object, boolean); < public org.apache.commons.lang.builder.ToStringBuilder append(long); < public org.apache.commons.lang.builder.ToStringBuilder append(java.lang.String, long); < public org.apache.commons.lang.builder.ToStringBuilder append(int); < public org.apache.commons.lang.builder.ToStringBuilder append(java.lang.String, int); < public org.apache.commons.lang.builder.ToStringBuilder append(short); < public org.apache.commons.lang.builder.ToStringBuilder append(java.lang.String, short); < public org.apache.commons.lang.builder.ToStringBuilder append(char); < public org.apache.commons.lang.builder.ToStringBuilder append(java.lang.String, char); --- > public static java.lang.String reflectionToString(java.lang.Object, org.apache.commons.lang.builder.ToStringStyle, boolean, java.lang.Class); > public static void setDefaultStyle(org.apache.commons.lang.builder.ToStringStyle); > public org.apache.commons.lang.builder.ToStringBuilder(java.lang.Object); > public org.apache.commons.lang.builder.ToStringBuilder(java.lang.Object,org.apache.commons.lang.builder.ToStringStyle); > public org.apache.commons.lang.builder.ToStringBuilder(java.lang.Object,org.apache.commons.lang.builder.ToStringStyle,java.lang.StringBuffer); > public org.apache.commons.lang.builder.ToStringBuilder append(boolean); > public org.apache.commons.lang.builder.ToStringBuilder append(boolean[]); < public org.apache.commons.lang.builder.ToStringBuilder append(java.lang.String, byte); --- > public org.apache.commons.lang.builder.ToStringBuilder append(byte[]); > public org.apache.commons.lang.builder.ToStringBuilder append(char); > public org.apache.commons.lang.builder.ToStringBuilder append(char[]); < public org.apache.commons.lang.builder.ToStringBuilder append(java.lang.String, double); --- > public org.apache.commons.lang.builder.ToStringBuilder append(double[]); < public org.apache.commons.lang.builder.ToStringBuilder append(java.lang.String, float); < public org.apache.commons.lang.builder.ToStringBuilder append(boolean); < public org.apache.commons.lang.builder.ToStringBuilder append(java.lang.String, boolean); < public org.apache.commons.lang.builder.ToStringBuilder append(java.lang.Object[]); < public org.apache.commons.lang.builder.ToStringBuilder append(java.lang.String, java.lang.Object[]); < public org.apache.commons.lang.builder.ToStringBuilder append(java.lang.String, java.lang.Object[], boolean); < public org.apache.commons.lang.builder.ToStringBuilder append(long[]); < public org.apache.commons.lang.builder.ToStringBuilder append(java.lang.String, long[]); < public org.apache.commons.lang.builder.ToStringBuilder append(java.lang.String, long[], boolean); --- > public org.apache.commons.lang.builder.ToStringBuilder append(float[]); > public org.apache.commons.lang.builder.ToStringBuilder append(int); < public org.apache.commons.lang.builder.ToStringBuilder append(java.lang.String, int[]); < public org.apache.commons.lang.builder.ToStringBuilder append(java.lang.String, int[], boolean); --- > public org.apache.commons.lang.builder.ToStringBuilder append(long); > public org.apache.commons.lang.builder.ToStringBuilder append(long[]); > public org.apache.commons.lang.builder.ToStringBuilder append(java.lang.Object); > public org.apache.commons.lang.builder.ToStringBuilder append(java.lang.Object[]); > public org.apache.commons.lang.builder.ToStringBuilder append(short); < public org.apache.commons.lang.builder.ToStringBuilder append(java.lang.String, short[]); < public org.apache.commons.lang.builder.ToStringBuilder append(java.lang.String, short[], boolean); < public org.apache.commons.lang.builder.ToStringBuilder append(char[]); < public org.apache.commons.lang.builder.ToStringBuilder append(java.lang.String, char[]); < public org.apache.commons.lang.builder.ToStringBuilder append(java.lang.String, char[], boolean); < public org.apache.commons.lang.builder.ToStringBuilder append(byte[]); --- > public org.apache.commons.lang.builder.ToStringBuilder append(java.lang.String, boolean); > public org.apache.commons.lang.builder.ToStringBuilder append(java.lang.String, boolean[]); > public org.apache.commons.lang.builder.ToStringBuilder append(java.lang.String, boolean[], boolean); > public org.apache.commons.lang.builder.ToStringBuilder append(java.lang.String, byte); < public org.apache.commons.lang.builder.ToStringBuilder append(double[]); --- > public org.apache.commons.lang.builder.ToStringBuilder append(java.lang.String, char); > public org.apache.commons.lang.builder.ToStringBuilder append(java.lang.String, char[]); > public org.apache.commons.lang.builder.ToStringBuilder append(java.lang.String, char[], boolean); > public org.apache.commons.lang.builder.ToStringBuilder append(java.lang.String, double); < public org.apache.commons.lang.builder.ToStringBuilder append(float[]); --- > public org.apache.commons.lang.builder.ToStringBuilder append(java.lang.String, float); < public org.apache.commons.lang.builder.ToStringBuilder append(boolean[]); < public org.apache.commons.lang.builder.ToStringBuilder append(java.lang.String, boolean[]); < public org.apache.commons.lang.builder.ToStringBuilder append(java.lang.String, boolean[], boolean); --- > public org.apache.commons.lang.builder.ToStringBuilder append(java.lang.String, int); > public org.apache.commons.lang.builder.ToStringBuilder append(java.lang.String, int[]); > public org.apache.commons.lang.builder.ToStringBuilder append(java.lang.String, int[], boolean); > public org.apache.commons.lang.builder.ToStringBuilder append(java.lang.String, long); > public org.apache.commons.lang.builder.ToStringBuilder append(java.lang.String, long[]); > public org.apache.commons.lang.builder.ToStringBuilder append(java.lang.String, long[], boolean); > public org.apache.commons.lang.builder.ToStringBuilder append(java.lang.String, java.lang.Object); > public org.apache.commons.lang.builder.ToStringBuilder append(java.lang.String, java.lang.Object, boolean); > public org.apache.commons.lang.builder.ToStringBuilder append(java.lang.String, java.lang.Object[]); > public org.apache.commons.lang.builder.ToStringBuilder append(java.lang.String, java.lang.Object[], boolean); > public org.apache.commons.lang.builder.ToStringBuilder append(java.lang.String, short); > public org.apache.commons.lang.builder.ToStringBuilder append(java.lang.String, short[]); > public org.apache.commons.lang.builder.ToStringBuilder append(java.lang.String, short[], boolean); > public org.apache.commons.lang.builder.ToStringBuilder appendAsObjectToString(java.lang.Object); > public org.apache.commons.lang.builder.ToStringBuilder appendSuper(java.lang.String); > public org.apache.commons.lang.builder.ToStringBuilder appendToString(java.lang.String); > public org.apache.commons.lang.builder.ToStringStyle getStyle(); > public java.lang.Object getObject(); org.apache.commons.lang.builder.StandardToStringStyle -------------------- > public boolean isUseShortClassName(); > public void setUseShortClassName(boolean); > public boolean isFieldSeparatorAtStart(); > public void setFieldSeparatorAtStart(boolean); > public boolean isFieldSeparatorAtEnd(); > public void setFieldSeparatorAtEnd(boolean); org.apache.commons.lang.builder.ToStringStyle -------------------- > public void appendSuper(java.lang.StringBuffer, java.lang.String); > public void appendToString(java.lang.StringBuffer, java.lang.String); > protected void removeLastFieldSeparator(java.lang.StringBuffer); > protected void reflectionAppendArrayDetail(java.lang.StringBuffer, java.lang.String, java.lang.Object); > protected boolean isUseShortClassName(); > protected void setUseShortClassName(boolean); > protected boolean isFieldSeparatorAtStart(); > protected void setFieldSeparatorAtStart(boolean); > protected boolean isFieldSeparatorAtEnd(); > protected void setFieldSeparatorAtEnd(boolean); org.apache.commons.lang.builder.HashCodeBuilder -------------------- > public static int reflectionHashCode(int, int, java.lang.Object, boolean, java.lang.Class); > public org.apache.commons.lang.builder.HashCodeBuilder appendSuper(int); org.apache.commons.lang.builder.CompareToBuilder -------------------- > public static int reflectionCompare(java.lang.Object, java.lang.Object, boolean, java.lang.Class); > public org.apache.commons.lang.builder.CompareToBuilder appendSuper(int); > public org.apache.commons.lang.builder.CompareToBuilder append(java.lang.Object, java.lang.Object, java.util.Comparator); > public org.apache.commons.lang.builder.CompareToBuilder append(java.lang.Object[], java.lang.Object[], java.util.Comparator); org.apache.commons.lang.builder.EqualsBuilder -------------------- > public static boolean reflectionEquals(java.lang.Object, java.lang.Object, boolean, java.lang.Class); > public org.apache.commons.lang.builder.EqualsBuilder appendSuper(boolean);

    commons-lang-2.6-src/src/site/xdoc/upgradeto2_1.xml100644 0 0 17274 11513702447 17434 0ustar 0 0 2.1 Release Notes Commons Documentation Team

    These are the release notes and advice for upgrading Commons-Lang from version 2.0 to version 2.1. INTRODUCTION: This document contains the release notes for the 2.1 version of Apache Jakarta Commons Lang. Commons Lang is a set of utility functions and reusable components that should be of use in any Java environment. INCOMPATIBLE CHANGES: - The Nestable interface defines the method indexOfThrowable(Class). Previously the implementations checked only for a specific Class. Now they check for subclasses of that Class as well. For most situations this will be the expected behaviour (ie. its a bug fix). If it causes problems, please use the ExceptionUtils.indexOfThrowable(Class) method instead. Note that the ExceptionUtils method is available in v1.0 and v2.0 of commons-lang and has not been changed. (An alternative to this is to change the public static matchSubclasses flag on NestableDelegate. However, we don't recommend that as a long-term solution.) - The StopWatch class has had much extra validation added. If your code previously relied on unusual aspects, it may no longer work. - Starting with version 2.1, Ant version 1.6.x is required to build. Copy junit.jar to ANT_HOME/lib. You can get JUnit from http://www.junit.org. See the developer's guide for more details. DEPRECATIONS: - The enum package has been renamed to enums for JDK1.5 compilance. All functionality is identical, just the package has changed. This package will be removed in v3.0. - NumberUtils.stringToInt - renamed to toInt - DateUtils - four constants, MILLIS_IN_* have been deprecated as they were defined as int not long. The replacements are MILLIS_PER_*. NEW FEATURES: New: - Mutable package - contains basic classes that hold an Object or primitive and provide both get and set methods. - DurationFormatUtils - provides various methods for formatting durations - CharEncoding - definitions of constants for character encoding work - CharUtils - utilities for working with characters Updated: - ArrayUtils - many more methods, especially List-like methods - BooleanUtils - isTrue and isFalse methods that handle null - ClassUtils - primitive to wrapper class conversion methods - ClassUtils - class name comparator - IllegalClassException - extra constructor for common instanceof case - NotImplementedException - supports nested exceptions - ObjectUtils - hashcode method handling null - StringUtils - isAsciiPrintable to check the contents of a string -- ordinalIndexOf to find the nth index of a string -- various remove methods to remove parts of a string -- various split methods to provide more control over splitting a string -- defaultIfEmpty to default a string if null or empty - SystemUtils - methods to get system properties as File objects -- extra constants representing system properties - Validate - new methods to check whether all elements in a collection are of a specific type - WordUtils - new methods to capitalize based on a set of specified delimiters - EqualsBuilder - now provides setter to internal state - ToStringStyle - new style, short prefix style - ReflectionToStringBuilder - more flags to control the output with regards to statics - ExceptionUtils - added indexOfType methods that check subclasses, thus leaving the existing indexOfThrowable method untouched (see incompatible changes section) - NumberUtils - various string to number parsing methods added - DateUtils - methods added to compare dates in various ways -- method to parse a date string using multiple patterns - FastDateFormat - extra formatting methods that take in a millisecond long value -- additional static factory methods - StopWatch - new methods for split behaviour BUG FIXES: 19331 General case: infinite loop: ToStringBuilder.reflectionToString 23174 EqualsBuilder.append(Object[], Object[]) throws NPE 23356 Make DurationFormatUtils public! 23557 WordUtils.capitalizeFully(String str) should take a delimiters 23683 New method for converting a primitive Class to its corresponding wrapper 23430 Minor javadoc fixes for StringUtils.contains(String, String) 23590 make optional parameters in FastDateFormat really optional 24056 Documentation error in StringUtils.replace 25227 StringEscapeUtils.unescapeHtml() doesn't handle hex entities 25454 new StringUtils.replaceChars behaves differently from old Ch 25560 DateUtils.truncate() is off by one hour when using a date in DST switch 'zone' 25627 DateUtils constants should be long 25683 Add method that validates Collection elements are a correct 25849 Add SystemUtils methods for directory properties. 26616 ClassCastException in Enum.equals(Object) 26699 Tokenizer Enhancements: reset input string, static CSV 26734 NullPointerException in EqualsBuilder.append(Object[], Object[]) 26877 Add SystemUtils.AWT_TOOLKIT and others. 26922 public static boolean DateUtils.equals(Date dt1, Date dt2) 27592 WordUtils capitalize improvement 27876 ReflectionToStringBuilder.toString(null) throws exception by design 27877 Make ClassUtils methods null-safe and not throw an IAE. 28468 StringUtils.defaultString: Documentation error 28554 Add hashCode-support to class ObjectUtils 29082 Enhancement of ExceptionUtils.CAUSE_METHOD_NAMES 29149 StringEscapeUtils.unescapeHtml() doesn't handle an empty entity 29294 lang.math.Fraction class deficiencies 29673 ExceptionUtils: new getCause() methodname (for tomcat) 29794 Add convenience format(long) methods to FastDateForma 30328 HashCodeBuilder does not use the same values as Boolean (fixed as documentation) 30334 New class proposal: CharacterEncoding 30674 parseDate class from HttpClient's DateParser class 30815 ArrayUtils.isEquals() throws ClassCastException when array1 30929 Nestable.indexOfThrowable(Class) uses Class.equals() to match 31395 DateUtils.truncate oddity at the far end of the Date spectrum 31478 Compile error with JDK 5 "enum" is a keyword 31572 o.a.c.lang.enum.ValuedEnum: 'enum'is a keyword in JDK1.5.0 31933 ToStringStyle setArrayEnd handled null incorrectly 32133 SystemUtils fails init on HP-UX 32198 Error in JavaDoc for StringUtils.chomp(String, String) 32625 Can't subclass EqualsBuilder because isEquals is private 33067 EqualsBuilder.append(Object[], Object[]) crashes with a NullPointerException if an element of the first array is null 33069 EqualsBuilder.append(Object[], Object[]) incorrectly checks that rhs[i] is instance of lhs[i]'s class 33574 unbalanced ReflectionToStringBuilder 33737 ExceptionUtils.addCauseMethodName(String) does not check for duplicates.

    commons-lang-2.6-src/src/site/xdoc/upgradeto2_2.xml100644 0 0 20315 11513702447 17423 0ustar 0 0 2.2 Release Notes Commons Documentation Team

    These are the release notes and advice for upgrading Commons-Lang from version 2.1 to version 2.2. INTRODUCTION: This document contains the release notes for the 2.2 version of Apache Jakarta Commons Lang. Commons Lang is a set of utility functions and reusable components that should be of use in any Java environment. INCOMPATIBLE CHANGES WITH VERSION 2.1: - None DEPRECATIONS FROM 2.1 to 2.2: - None BUG FIXES IN 2.2: LANG-2 javadoc example for StringUtils.splitByWholeSeparator incorrect LANG-3 PADDING array in StringUtils overflows on '\uffff' LANG-10 [patch] ClassUtils.primitiveToWrapper and Void LANG-21 escapeXML() -> Not escaping low characters LANG-25 DurationFormatUtils.formatDurationISO() javadoc is missing T in duration string between date and time part LANG-37 unit test for org.apache.commons.lang.text.StrBuilder LANG-42 EqualsBuilder.append(Object[], Object[]) crashes with a NullPointerException if an element of the first array is null LANG-45 StrBuilderTest#testReplaceStringString fails. LANG-50 Replace Clover with Cobertura LANG-59 DateUtils.truncate method is buggy when dealing with DST switching hours LANG-100 RandomStringUtils.random() family of methods create invalid unicode sequences LANG-105 ExceptionUtils goes into infinite loop in getThrowables is throwable.getCause() == throwable LANG-106 StringUtils#getLevenshteinDistance() performance is sub-optimal LANG-112 Wrong length check in StrTokenizer.StringMatcher LANG-117 FastDateFormat: wrong format for date "01.01.1000" LANG-122 EscapeUtil.escapeHtml() should clarify that it does not escape ' chars to ' LANG-123 Unclear javadoc for DateUtils.iterator() LANG-127 Minor tweak to fix of bug # 26616 LANG-130 Memory "leak" in StringUtils LANG-140 DurationFormatUtils.formatPeriod() returns the wrong result LANG-141 Fraction.toProperString() returns -1/1 for -1 LANG-148 Performance modifications on StringUtils.replace LANG-150 StringEscapeUtils.unescapeHtml skips first entity after standalone ampersand LANG-152 DurationFormatUtils.formatDurationWords "11 <units>" gets converted to "11 <unit>" LANG-259 ValuedEnum.compareTo(Object other) not typesafe - it easily could be... LANG-261 Error in an example in the javadoc of the StringUtils.splitPreserveAllTokens() method LANG-264 ToStringBuilder/HashCodeBuilder javadoc code examples LANG-271 LocaleUtils test fails under Mustang LANG-272 Minor build and checkstyle changes LANG-277 Javadoc errors on StringUtils.splitPreserveAllTokens(String, char) LANG-278 javadoc for StringUtils.removeEnd is incorrect IMPROVEMENTS IN 2.2: LANG-159 Add WordUtils.getInitials(String) LANG-161 Add methods and tests to StrBuilder LANG-162 replace() length calculation improvement LANG-165 parseDate with TimeZone LANG-166 New interpolation features LANG-169 Implementation of escape/unescapeHtml methods with Writer LANG-176 CompareToBuilder excludeFields for reflection method LANG-186 Request for MutableBoolean implementation LANG-194 add generic add method to DateUtils LANG-198 New method for EqualsBuilder LANG-212 New ExceptionUtils method setCause() LANG-216 Provides a Class.getPublicMethod which returns public invocable Method LANG-217 Add Mutable<Type> to<Type>() methods. LANG-220 Tokenizer Enhancements: reset input string, static CSV/TSV factories LANG-226 Using ReflectionToStringBuilder and excluding secure fields LANG-242 Trivial cleanup of javadoc in various files LANG-246 CompositeFormat LANG-250 Performance boost for RandomStringUtils LANG-254 Enhanced Class.forName version LANG-260 StringEscapeUtils should expose escape*() methods taking Writer argument LANG-263 Add StringUtils.containsIgnoreCase(...) LANG-267 Support char array converters on ArrayUtils LANG-270 minor javadoc improvements for StringUtils.stripXxx() methods New ExceptionUtils methods getMessage/getRootCauseMessage

    commons-lang-2.6-src/src/site/xdoc/upgradeto2_3.xml100644 0 0 12202 11513702447 17420 0ustar 0 0 2.3 Release Notes Commons Documentation Team

    These are the release notes and advice for upgrading Commons-Lang from version 2.2 to version 2.3. INTRODUCTION: This document contains the release notes for the 2.3 version of Apache Jakarta Commons Lang. Commons Lang is a set of utility functions and reusable components that should be of use in any Java environment. INCOMPATIBLE CHANGES WITH VERSION 2.2: - Calling stop on a suspended StopWatch will no longer change the underlying time. It's very unlikely anyone was relying on that bug as a feature. ADDITIONAL INCOMPATIBLE CHANGES WITH VERSION 2.0: - The Nestable interface defines the method indexOfThrowable(Class). Previously the implementations checked only for a specific Class. Now they check for subclasses of that Class as well. For most situations this will be the expected behaviour (ie. its a bug fix). If it causes problems, please use the ExceptionUtils.indexOfThrowable(Class) method instead. Note that the ExceptionUtils method is available in v1.0 and v2.0 of commons-lang and has not been changed. (An alternative to this is to change the public static matchSubclasses flag on NestableDelegate. However, we don't recommend that as a long-term solution.) - The StopWatch class has had much extra validation added. If your code previously relied on unusual aspects, it may no longer work. - Starting with version 2.1, Ant version 1.6.x is required to build. Copy junit.jar to ANT_HOME/lib. You can get JUnit from http://www.junit.org. See the developer's guide for more details. DEPRECATIONS FROM 2.2 to 2.3: - None DEPRECATIONS FROM 2.1 to 2.2: - None DEPRECATIONS FROM 2.0 to 2.1: - The enum package has been renamed to enums for JDK1.5 compilance. All functionality is identical, just the package has changed. This package will be removed in v3.0. - NumberUtils.stringToInt - renamed to toInt - DateUtils - four constants, MILLIS_IN_* have been deprecated as they were defined as int not long. The replacements are MILLIS_PER_*. BUG FIXES IN 2.3: * [LANG-69 ] - ToStringBuilder throws StackOverflowError when an Object cycle exists * [LANG-102] - Refactor Entities methods * [LANG-153] - Can't XMLDecode an Enum * [LANG-262] - Use of enum prevents a classloader from being garbage collected resuling in out of memory exceptions. * [LANG-279] - HashCodeBuilder throws java.lang.StackOverflowError when an object contains a cycle. * [LANG-281] - DurationFormatUtils returns wrong result * [LANG-286] - Serialization - not backwards compatible * [LANG-292] - unescapeXml("&12345678;") should be "&12345678;" * [LANG-294] - StrBuilder.replaceAll and StrBuilder.deleteAll can throw ArrayIndexOutOfBoundsException. * [LANG-295] - StrBuilder contains usages of thisBuf.length when they should use size * [LANG-299] - Bug in method appendFixedWidthPadRight of class StrBuilder causes an ArrayIndexOutOfBoundsException * [LANG-300] - NumberUtils.createNumber throws NumberFormatException for one digit long * [LANG-303] - FastDateFormat.mRules is not transient or serializable * [LANG-304] - NullPointerException in isAvailableLocale(Locale) * [LANG-313] - Wrong behavior of Entities.unescape * [LANG-315] - StopWatch: suspend() acts as split(), if followed by stop() IMPROVEMENTS IN 2.3: * [LANG-258] - Enum JavaDoc * [LANG-266] - Wish for StringUtils.join(Collection, *) * [LANG-268] - StringUtils.join should allow you to pass a range for it (so it only joins a part of the array) * [LANG-275] - StringUtils substringsBetween * [LANG-282] - Create more tests to test out the +=31 replacement code in DurationFormatUtils. * [LANG-287] - Optimize StringEscapeUtils.unescapeXml(String) * [LANG-289] - NumberUtils.max(byte[]) and NumberUtils.min(byte[]) are missing * [LANG-291] - Null-safe comparison methods for finding most recent / least recent dates. * [LANG-306] - StrBuilder appendln/appendAll/appendSeparator * [LANG-310] - BooleanUtils isNotTrue/isNotFalse * [LANG-314] - Tests fail to pass when building with Maven 2

    commons-lang-2.6-src/src/site/xdoc/upgradeto2_4.xml100644 0 0 17047 11513702447 17435 0ustar 0 0 2.4 Release Notes Commons Documentation Team

    These are the release notes and advice for upgrading Commons-Lang from version 2.3 to version 2.4.

    See 'What's new in 2.4?' for more information. INTRODUCTION: This document contains the release notes for the 2.4 version of Apache Commons Lang. Commons Lang is a set of utility functions and reusable components that should be of use in any Java environment. Lang 2.4 no longer attempts to target the Java 1.1 environment and now targets Java 1.2. While previous versions were built for 1.1, some parts were using methods that were only available in 1.2, and the Enum class had become dependent on Java 1.3. INCOMPATIBLE CHANGES WITH VERSION 2.3: - None INCOMPATIBLE CHANGES WITH VERSION 2.2: - Calling stop on a suspended StopWatch will no longer change the underlying time. It's very unlikely anyone was relying on that bug as a feature. ADDITIONAL INCOMPATIBLE CHANGES WITH VERSION 2.0: - The Nestable interface defines the method indexOfThrowable(Class). Previously the implementations checked only for a specific Class. Now they check for subclasses of that Class as well. For most situations this will be the expected behaviour (ie. its a bug fix). If it causes problems, please use the ExceptionUtils.indexOfThrowable(Class) method instead. Note that the ExceptionUtils method is available in v1.0 and v2.0 of commons-lang and has not been changed. (An alternative to this is to change the public static matchSubclasses flag on NestableDelegate. However, we don't recommend that as a long-term solution.) - The StopWatch class has had much extra validation added. If your code previously relied on unusual aspects, it may no longer work. - Starting with version 2.1, Ant version 1.6.x is required to build. Copy junit.jar to ANT_HOME/lib. You can get JUnit from http://www.junit.org. See the developer's guide for more details. DEPRECATIONS FROM 2.3 to 2.4: - ObjectUtils.appendIdentityToString(StringBuffer, Object) - has very odd semantics, use ObjectUtils.identityToString(StringBuffer, Object) instead. - public static java.util.Date add(java.util.Date, int, int) - it is not intended for this method to be public. Please let us know if you use this. DEPRECATIONS FROM 2.2 to 2.3: - None DEPRECATIONS FROM 2.1 to 2.2: - None DEPRECATIONS FROM 2.0 to 2.1: - The enum package has been renamed to enums for JDK1.5 compilance. All functionality is identical, just the package has changed. This package will be removed in v3.0. - NumberUtils.stringToInt - renamed to toInt - DateUtils - four constants, MILLIS_IN_* have been deprecated as they were defined as int not long. The replacements are MILLIS_PER_*. BUG FIXES IN 2.4: * [LANG-76 ] - EnumUtils.getEnum() doesn't work well in 1.5 * [LANG-328] - LocaleUtils.toLocale() rejects strings with only language+variant * [LANG-334] - Enum is not thread-safe * [LANG-346] - Dates.round() behaves incorrectly for minutes and seconds * [LANG-349] - Deadlock using ReflectionToStringBuilder * [LANG-353] - Javadoc Example for EqualsBuilder is questionable * [LANG-360] - Why does appendIdentityToString return null? * [LANG-361] - BooleanUtils toBooleanObject javadoc does not match implementation * [LANG-363] - StringEscapeUtils..escapeJavaScript() method did not escape '/' into '\/', it will make IE render page uncorrectly * [LANG-364] - Documentation bug for ignoreEmptyTokens accessors in StrTokenizer * [LANG-365] - BooleanUtils.toBoolean() - invalid drop-thru in case statement causes StringIndexOutOfBoundsException * [LANG-367] - FastDateFormat thread safety * [LANG-368] - FastDateFormat getDateInstance() and getDateTimeInstance() assume Locale.getDefault() won't change * [LANG-369] - ExceptionUtils not thread-safe * [LANG-372] - ToStringBuilder: MULTI_LINE_STYLE does not print anything from appendToString methods. * [LANG-380] - infinite loop in Fraction.reduce when numerator == 0 * [LANG-381] - NumberUtils.min(floatArray) returns wrong value if floatArray[0] happens to be Float.NaN * [LANG-385] - http://commons.apache.org/lang/developerguide.html "Building" section is incorrect and incomplete * [LANG-393] - EqualsBuilder don't compare BigDecimals correctly * [LANG-399] - Javadoc bugs - cannot find object * [LANG-410] - Ambiguous / confusing names in StringUtils replace* methods * [LANG-412] - StrBuilder appendFixedWidth does not handle nulls * [LANG-414] - DateUtils.round() often fails IMPROVEMENTS IN 2.4: * [LANG-180] - adding a StringUtils.replace method that takes an array or List of replacement strings * [LANG-192] - Split camel case strings * [LANG-257] - Add new splitByWholeSeparatorPreserveAllTokens() methods to StringUtils * [LANG-269] - Shouldn't Commons Lang's StringUtils have a "common" string method? * [LANG-298] - ClassUtils.getShortClassName and ClassUtils.getPackageName and class of array * [LANG-321] - Add toArray() method to IntRange and LongRange classes * [LANG-322] - ClassUtils.getShortClassName(String) inefficient * [LANG-326] - StringUtils: startsWith / endsWith / startsWithIgnoreCase / endsWithIgnoreCase / removeStartIgnoreCase / removeEndIgnoreCase methods * [LANG-329] - Pointless synchronized in ThreadLocal.initialValue should be removed * [LANG-333] - ArrayUtils.toClass * [LANG-337] - Utility class constructor javadocs should acknowledge that they may sometimes be used, e.g. with Velocity. * [LANG-338] - truncateNicely method which avoids truncating in the middle of a word * [LANG-345] - Optimize HashCodeBuilder.append(Object) * [LANG-351] - Extension to ClassUtils: Obtain the primitive class from a wrapper * [LANG-356] - Add getStartTime to StopWatch * [LANG-362] - Add ExtendedMessageFormat to org.apache.commons.lang.text * [LANG-371] - ToStringStyle javadoc should show examples of styles * [LANG-374] - Add escaping for CSV columns to StringEscapeUtils * [LANG-375] - add SystemUtils.IS_OS_WINDOWS_VISTA field * [LANG-379] - Calculating A date fragment in any time-unit * [LANG-383] - Adding functionality to DateUtils to allow direct setting of various fields. * [LANG-402] - OSGi-ify Lang * [LANG-404] - Add Calendar flavour format methods to DateFormatUtils * [LANG-407] - StringUtils.length(String) returns null-safe length * [LANG-413] - Memory usage improvement for StringUtils#getLevenshteinDistance()

    commons-lang-2.6-src/src/site/xdoc/upgradeto2_5.xml100644 0 0 14357 11513702447 17437 0ustar 0 0 2.5 Release Notes Commons Documentation Team

    These are the release notes and advice for upgrading Commons-Lang from version 2.4 to version 2.5.

    See 'What's new in 2.5?' for more information. INTRODUCTION: This document contains the release notes for the 2.5 version of Apache Commons Lang. Commons Lang is a set of utility functions and reusable components that should be of use in any Java environment. Lang 2.5 no longer attempts to target the Java 1.2 environment and now targets Java 1.3. IMPROVEMENTS IN 2.5 =================== * [LANG-583] - ArrayUtils - add isNotEmpty() methods * [LANG-534] - ArrayUtils - add nullToEmpty() methods * [LANG-454] - CharRange - provide an iterator that lets you walk the chars in the range * [LANG-514] - CharRange - add more readable static builder methods * [ ] - ClassUtils - new isAssignable() methods with autoboxing * [LANG-535] - ClassUtils - add support to getShortClassName and getPackageName for arrays * [LANG-434] - DateUtils - add ceiling() method * [LANG-486] - DateUtils - add parseDateStrictly() method * [LANG-466] - EqualsBuilder - add reset() method * [LANG-461] - NumberUtils - add toByte() and toShort() methods * [LANG-522] - Mutable numbers - add string constructors * [ ] - MutableBoolean - add toBoolean(), isTrue() and isFalse() methods * [LANG-422] - StrBuilder - add appendSeparator() methods with an alternative default separator if the StrBuilder is currently empty * [LANG-555] - SystemUtils - add IS_OS_WINDOWS_7 constant * [LANG-554] - SystemUtils - add IS_JAVA_1_7 constant for JDK 1.7 * [LANG-405] - StringUtils - add abbreviateMiddle() method * [LANG-569] - StringUtils - add indexOfIgnoreCase() and lastIndexOfIgnoreCase() methods * [LANG-471] - StringUtils - add isAllUpperCase() and isAllLowerCase() methods * [LANG-469] - StringUtils - add lastOrdinalIndexOf() method to complement the existing ordinalIndexOf() method * [LANG-348] - StringUtils - add repeat() method * [LANG-445] - StringUtils - add startsWithAny() method * [LANG-430] - StringUtils - add upperCase(String, Locale) and lowerCase(String, Locale) methods * [LANG-416] - New Reflection package containing ConstructorUtils, FieldUtils, MemberUtils and MethodUtils BUG FIXES IN 2.5 ================ * [LANG-494] - CharSet - Synchronizing the COMMON Map so that getInstance doesn't miss a put from a subclass in another thread * [LANG-500] - ClassUtils - improving performance of getAllInterfaces * [LANG-587] - ClassUtils - toClass() throws NullPointerException on null array element * [LANG-530] - DateUtils - Fix parseDate() cannot parse ISO8601 dates produced by FastDateFormat * [LANG-440] - DateUtils - round() doesn't work correct for Calendar.AM_PM * [LANG-443] - DateUtils - improve tests * [LANG-204] - Entities - multithreaded initialization * [LANG-506] - Entities - missing final modifiers; thread-safety issues * [LANG-76] - EnumUtils - getEnum() doesn't work well in 1.5+ * [LANG-584] - ExceptionUtils - use immutable lock target * [LANG-477] - ExtendedMessageFormat - OutOfMemory with a pattern containing single quotes * [LANG-538] - FastDateFormat - call getTime() on a calendar to ensure timezone is in the right state * [LANG-547] - FastDateFormat - Remove unused field * [LANG-511] - LocaleUtils - initialization of available locales can be deferred * [LANG-457] - NumberUtils - createNumber() thows a StringIndexOutOfBoundsException for "l" * [LANG-521] - NumberUtils - isNumber(String) and createNumber(String) both modified to support '2.' * [LANG-432] - StringUtils - improve handling of case-insensitive Strings * [LANG-552] - StringUtils - replaceEach() no longer NPEs when null appears in the last String[] * [LANG-460] - StringUtils - correct JavaDocs for startsWith() and startsWithIgnoreCase() * [LANG-421] - StringEscapeUtils - escapeJava() escapes '/' characters * [LANG-450] - StringEscapeUtils - change escapeJavaStyleString() to throw UnhandledException instead swallowing IOException * [LANG-419] - WordUtils - fix StringIndexOutOfBoundsException when lower is greater than the String length * [LANG-523] - StrBuilder - Performance improvement by doubling the size of the String in ensureCapacity * [LANG-575] - Compare, Equals and HashCode builders - use ArrayUtils to avoid creating a temporary List * [LANG-467] - EqualsBuilder - removing the special handling of BigDecimal (LANG-393) to use compareTo * [LANG-574] - HashCodeBuilder - Performance improvement: check for isArray to short-circuit the 9 instanceof checks * [LANG-520] - HashCodeBuilder - Changing the hashCode() method to return toHashCode() * [LANG-459] - HashCodeBuilder - reflectionHashCode() can generate incorrect hashcodes * [LANG-586] - HashCodeBuilder and ToStringStyle - use of ThreadLocal causes memory leaks in container environments * [LANG-487] - ToStringBuilder - make default style thread-safe * [LANG-472] - RandomUtils - nextLong() always produces even numbers * [LANG-592] - RandomUtils - RandomUtils tests are failing frequently

    commons-lang-2.6-src/src/site/xdoc/upgradeto2_6.xml100644 0 0 7663 11513702447 17422 0ustar 0 0 2.6 Release Notes Commons Documentation Team

    These are the release notes and advice for upgrading Commons-Lang from version 2.5 to version 2.6.

    . INTRODUCTION: This document contains the release notes for the 2.6 version of Apache Commons Lang. Commons Lang is a set of utility functions and reusable components that should be of use in any Java environment. COMPATIBILITY WITH 2.5 ====================== Lang 2.6 is binary compatible release with Lang 2.5, containing bug fixes and small enhancements. Lang 2.6 requires a minimum of JDK 1.3. IMPROVEMENTS IN 2.6 =================== * [LANG-633] - BooleanUtils: use same optimization in toBooleanObject(String) as in toBoolean(String) * [LANG-599] - ClassUtils: allow Dots as Inner Class Separators in getClass() * [LANG-594] - DateUtils: equal and compare functions up to most significant field * [LANG-632] - DateUtils: provide a Date to Calendar convenience method * [LANG-576] - ObjectUtils: add clone methods to ObjectUtils * [LANG-667] - ObjectUtils: add a Null-safe compare() method * [LANG-670] - ObjectUtils: add notEqual() method * [LANG-302] - StrBuilder: implement clone() method * [LANG-640] - StringUtils: add a normalizeSpace() method * [LANG-614] - StringUtils: add endsWithAny() method * [LANG-655] - StringUtils: add defaultIfBlank() method * [LANG-596] - StrSubstitutor: add a replace(String, Properties) variant * [LANG-482] - StrSubstitutor: support substitution in variable names * [LANG-669] - Use StrBuilder instead of StringBuffer to improve performance where sync. is not an issue BUG FIXES IN 2.6 ================ * [LANG-629] - CharSet: make the underlying set synchronized * [LANG-635] - CompareToBuilder: fix passing along compareTransients to the reflectionCompare method * [LANG-636] - ExtendedMessageFormat doesn't override equals(Object) * [LANG-645] - FastDateFormat: fix to properly include the locale when formatting a Date * [LANG-638] - NumberUtils: createNumber() throws a StringIndexOutOfBoundsException when argument containing "e" and "E" is passed in * [LANG-607] - StringUtils methods do not handle Unicode 2.0+ supplementary characters correctly * [LANG-624] - SystemUtils: getJavaVersionAsFloat throws StringIndexOutOfBoundsException on Android runtime/Dalvik VM * [BEANUTILS-381] - MemberUtils: getMatchingAccessibleMethod does not correctly handle inheritance and method overloading OTHER CHANGES IN 2.6 ==================== * [LANG-600] - Javadoc is incorrect for lastIndexOf() method * [LANG-628] - Javadoc for HashCodeBuilder.append(boolean) does not match implementation * [LANG-643] - Javadoc StringUtils.left() claims to throw an exception on negative lenth, but doesn't * [LANG-370] - Javadoc - document thread safety * [LANG-623] - Test for StringUtils replaceChars() icelandic characters

    commons-lang-2.6-src/src/site/xdoc/userguide.xml100644 0 0 40177 11513702447 17132 0ustar 0 0 Commons Lang - User guide Commons Documentation Team

    The Commons Lang library provides much needed additions to the standard JDK's java.lang package. Very generic, very reusable components for everyday use.

    The top level package contains various Utils classes, whilst there are various subpackages including enums, exception and builder. Using the Utils classes is generally simplicity itself. They are the equivalent of global functions in another language, a collection of stand-alone, thread-safe, static methods. In contrast, subpackages may contain interfaces which may have to be implemented or classes which may need to be extended to get the full functionality from the code. They may, however, contain more global-like functions.

    Lang seeks to support Java 1.2 onwards, so although you may have seen features in later versions of Java, such as split methods and nested exceptions, Lang still maintains non-java.lang versions for users of earlier versions of Java.

    You will find deprecated methods as you stroll through the Lang documentation. These are removed in the next major release.

    Before we begin, it's a good time to mention the Utils classes. They all contain empty public constructors with warnings not to use. This may seem an odd thing to do, but it allows tools like Velocity to access the class as if it were a bean. In other words, yes we know about private constructors.

    Lang has a series of String utilities. The first is StringUtils, oodles and oodles of functions which tweak, transform, squeeze and cuddle java.lang.Strings. In addition to StringUtils, there are a series of other String manipulating classes; RandomStringUtils, StringEscapeUtils and Tokenizer. RandomStringUtils speaks for itself. It's provides ways in which to generate pieces of text, such as might be used for default passwords. StringEscapeUtils contains methods to escape and unescape Java, JavaScript, HTML, XML and SQL. Tokenizer is an improved alternative to java.util.StringTokenizer.

    These are ideal classes to start using if you're looking to get into Lang. StringUtils' capitalize, substringBetween/Before/After, split and join are good methods to begin with. If you use java.sql.Statements a lot, StringEscapeUtils.escapeSql might be of interest.

    In addition to these classes, WordUtils is another String manipulator. It works on Strings at the word level, for example WordUtils.capitalize will capitalize every word in a piece of text. WordUtils also contains methods to wrap text.

    In addition to dealing with Strings, it's also important to deal with chars and Characters. CharUtils exists for this purpose, while CharSetUtils exists for set-manipulation of Strings. Be careful, although CharSetUtils takes an argument of type String, it is only as a set of characters. For example, CharSetUtils.delete("testtest", "tr") will remove all t's and all r's from the String, not just the String "tr".

    CharRange and CharSet are both used internally by CharSetUtils, and will probaby rarely be used.

    SystemUtils is a simple little class which makes it easy to find out information about which platform you are on. For some, this is a necessary evil. It was never something I expected to use myself until I was trying to ensure that Commons Lang itself compiled under JDK 1.2. Having pushed out a few JDK 1.3 bits that had slipped in (Collections.EMPTY_MAP is a classic offender), I then found that one of the Unit Tests was dying mysteriously under JDK 1.2, but ran fine under JDK 1.3. There was no obvious solution and I needed to move onwards, so the simple solution was to wrap that particular test in a if(SystemUtils.isJavaVersionAtLeast(1.3f)) {, make a note and move on.

    The CharEncoding class is also used to interact with the Java environment and may be used to see which character encodings are supported in a particular environment.

    Serialization doesn't have to be that hard! A simple util class can take away the pain, plus it provides a method to clone an object by unserializing and reserializing, an old Java trick.

    Would you believe it, ObjectUtils contains handy functions for Objects, mainly null-safe implementations of the methods on java.lang.Object.

    ClassUtils is largely a set of helper methods for reflection. Of special note are the comparators hidden away in ClassUtils, useful for sorting Class and Package objects by name; however they merely sort alphabetically and don't understand the common habit of sorting java and javax first.

    Next up, ArrayUtils. This is a big one with many methods and many overloads of these methods so it is probably worth an in depth look here. Before we begin, assume that every method mentioned is overloaded for all the primitives and for Object. Also, the short-hand 'xxx' implies a generic primitive type, but usually also includes Object.

    • ArrayUtils provides singleton empty arrays for all the basic types. These will largely be of use in the Collections API with its toArray methods, but also will be of use with methods which want to return an empty array on error.
    • add(xxx[], xxx) will add a primitive type to an array, resizing the array as you'd expect. Object is also supported.
    • clone(xxx[]) clones a primitive or Object array.
    • contains(xxx[], xxx) searches for a primitive or Object in a primitive or Object array.
    • getLength(Object) returns the length of any array or an IllegalArgumentException if the parameter is not an array. hashCode(Object), equals(Object, Object), toString(Object)
    • indexOf(xxx[], xxx) and indexOf(xxx[], xxx, int) are copies of the classic String methods, but this time for primitive/Object arrays. In addition, a lastIndexOf set of methods exists.
    • isEmpty(xxx[]) lets you know if an array is zero-sized or null.
    • isSameLength(xxx[], xxx[]) returns true if the arrays are the same length.
    • Along side the add methods, there are also remove methods of two types. The first type remove the value at an index, remove(xxx[], int), while the second type remove the first value from the array, remove(xxx[], xxx).
    • Nearing the end now. The reverse(xxx[]) method turns an array around.
    • The subarray(xxx[], int, int) method splices an array out of a larger array.
    • Primitive to primitive wrapper conversion is handled by the toObject(xxx[]) and toPrimitive(Xxx[]) methods.

    Lastly, ArrayUtils.toMap(Object[]) is worthy of special note. It is not a heavily overloaded method for working with arrays, but a simple way to create Maps from literals.

    Using toMap
    Map colorMap = MapUtils.toMap(new String[][] {{ {"RED", "#FF0000"}, {"GREEN", "#00FF00"}, {"BLUE", "#0000FF"} });

    Our final util class is BooleanUtils. It contains various Boolean acting methods, probably of most interest is the BooleanUtils.toBoolean(String) method which turns various positive/negative Strings into a Boolean object, and not just true/false as with Boolean.valueOf.

    Lang also has a series of Exceptions that we felt are useful. All of these exceptions are descendents of RuntimeException, they're just a bit more meaningful than java.lang.IllegalArgumentException.

    On reaching the end of our package, we are left with a couple of classes that haven't fit any of the topics so far.

    The BitField class provides a wrapper class around the classic bitmask integer, whilst the Validate class may be used for assertions (remember, we support Java 1.2).

    When you write a hashcode, do you check Bloch's Effective Java? No? You just hack in a quick number? Well HashCodeBuilder will save your day. It, and its buddies (EqualsBuilder, CompareToBuilder, ToStringBuilder), take care of the nasty bits while you focus on the important bits, like which fields will go into making up the hashcode.

    (Formerly lang.enum.*)

    Enums are an old C thing. Very useful. One of the major uses is to give type to your constants, and even more, to give them order. For example:

    A simple Enum
    public final class ColorEnum extends Enum { public static final ColorEnum RED = new ColorEnum("Red"); public static final ColorEnum GREEN = new ColorEnum("Green"); public static final ColorEnum BLUE = new ColorEnum("Blue"); private ColorEnum(String color) { super(color); } public static ColorEnum getEnum(String color) { return (ColorEnum) getEnum(ColorEnum.class, color); } public static Iterator iterator() { return iterator(ColorEnum.class); } }

    The enums package used to be the enum package, but with Java 5 giving us an enum keyword, the move to the enums package name was necessary and the old enum package was deprecated.

    JDK 1.4 brought us NestedExceptions, that is an Exception which can link to another Exception. This subpackage provides it to those of us who have to code to something other than JDK 1.4 (most reusable code libaries are aimed at JDK 1.2).

    It isn't just a nested exception framework though, it uses reflection to allow it to handle many nested exception frameworks, including JDK 1.4's.

    The reflection ability is one of the more interesting tricks hidden in the reflection sub-package, and of much use to writers of applications such as Tomcat or IDEs, in fact any code which has to catch 'Exception' from an unknown source and then wanting to display in a novel way.

    Although Commons-Math also exists, some basic mathematical functions are contained within Lang. These include classes to represent ranges of numbers, a Fraction class, various utilities for random numbers, and the flagship class, NumberUtils which contains a handful of classic number functions.

    There are two aspects of this package I would like to highlight. The first is NumberUtils.createNumber(String), a method which does its best to convert a String into a Number object. You have no idea what type of Number it will return, so you should call the relevant xxxValue method when you reach the point of needing a number. NumberUtils also has a related isNumber method. The second is the JVMRandom class. This is an instance of Random which relies on the Math.random() method for its implementation and so gives the developer access to the JVM's random seed. If you try to create Random objects in the same millisecond, they will give the same answer; so quickly you will find yourself caching that Random object. Rather than caching your own object, simply use the one the JVM is caching already. The RandomUtils provides a static access to the JVMRandom class, which may be easier to use.

    New in 2.1, the mutable package provides mutable wrappers for primitive values (such as int, long, etc.) and Object. These wrappers are simiar to the wrappers provided by the Java API, but allow the wrapped value to be changed without needing to create a separate wrapper object.

    The text package was added in Lang 2.2. It provides, amongst other classes, a replacement for StringBuffer named StrBuilder, a class for substituting variables within a String named StrSubstitutor and a replacement for StringTokenizer named StrTokenizer. While somewhat ungainly, the Str prefix has been used to ensure we don't clash with any current or future standard Java classes.

    Lang 2.0 saw the arrival of a time package. It contains some basic utilities for manipulating time (a delorean, police box and grandfather clock?). These include a StopWatch for simple performance measurements and an optimised FastDateFormat class.

    New in Lang 2.1 is the DurationFormatUtils class, which provides various methods for formatting durations.

    commons-lang-2.6-src/src/test/java/org/apache/commons/lang/ArrayUtilsAddTest.java100644 0 0 71634 11513702440 25225 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang; import java.util.Arrays; import junit.framework.TestCase; /** * Tests ArrayUtils add methods. * * @author Gary D. Gregory * @version $Id: ArrayUtilsAddTest.java 905628 2010-02-02 13:29:55Z niallp $ */ public class ArrayUtilsAddTest extends TestCase { public void testJira567(){ Number[] n; // Valid array construction n = (Number[])ArrayUtils.addAll(new Number[]{new Integer(1)}, new Long[]{new Long(2)}); assertEquals(2,n.length); assertEquals(Number.class,n.getClass().getComponentType()); try { // Invalid - can't store Long in Integer array n = (Number[])ArrayUtils.addAll(new Integer[]{new Integer(1)}, new Long[]{new Long(2)}); fail("Should have generated IllegalArgumentException"); } catch (IllegalArgumentException expected) { } } public void testAddObjectArrayBoolean() { boolean[] newArray; newArray = ArrayUtils.add((boolean[])null, false); assertTrue(Arrays.equals(new boolean[]{false}, newArray)); assertEquals(Boolean.TYPE, newArray.getClass().getComponentType()); newArray = ArrayUtils.add((boolean[])null, true); assertTrue(Arrays.equals(new boolean[]{true}, newArray)); assertEquals(Boolean.TYPE, newArray.getClass().getComponentType()); boolean[] array1 = new boolean[]{true, false, true}; newArray = ArrayUtils.add(array1, false); assertTrue(Arrays.equals(new boolean[]{true, false, true, false}, newArray)); assertEquals(Boolean.TYPE, newArray.getClass().getComponentType()); } public void testAddObjectArrayByte() { byte[] newArray; newArray = ArrayUtils.add((byte[])null, (byte)0); assertTrue(Arrays.equals(new byte[]{0}, newArray)); assertEquals(Byte.TYPE, newArray.getClass().getComponentType()); newArray = ArrayUtils.add((byte[])null, (byte)1); assertTrue(Arrays.equals(new byte[]{1}, newArray)); assertEquals(Byte.TYPE, newArray.getClass().getComponentType()); byte[] array1 = new byte[]{1, 2, 3}; newArray = ArrayUtils.add(array1, (byte)0); assertTrue(Arrays.equals(new byte[]{1, 2, 3, 0}, newArray)); assertEquals(Byte.TYPE, newArray.getClass().getComponentType()); newArray = ArrayUtils.add(array1, (byte)4); assertTrue(Arrays.equals(new byte[]{1, 2, 3, 4}, newArray)); assertEquals(Byte.TYPE, newArray.getClass().getComponentType()); } public void testAddObjectArrayChar() { char[] newArray; newArray = ArrayUtils.add((char[])null, (char)0); assertTrue(Arrays.equals(new char[]{0}, newArray)); assertEquals(Character.TYPE, newArray.getClass().getComponentType()); newArray = ArrayUtils.add((char[])null, (char)1); assertTrue(Arrays.equals(new char[]{1}, newArray)); assertEquals(Character.TYPE, newArray.getClass().getComponentType()); char[] array1 = new char[]{1, 2, 3}; newArray = ArrayUtils.add(array1, (char)0); assertTrue(Arrays.equals(new char[]{1, 2, 3, 0}, newArray)); assertEquals(Character.TYPE, newArray.getClass().getComponentType()); newArray = ArrayUtils.add(array1, (char)4); assertTrue(Arrays.equals(new char[]{1, 2, 3, 4}, newArray)); assertEquals(Character.TYPE, newArray.getClass().getComponentType()); } public void testAddObjectArrayDouble() { double[] newArray; newArray = ArrayUtils.add((double[])null, 0); assertTrue(Arrays.equals(new double[]{0}, newArray)); assertEquals(Double.TYPE, newArray.getClass().getComponentType()); newArray = ArrayUtils.add((double[])null, 1); assertTrue(Arrays.equals(new double[]{1}, newArray)); assertEquals(Double.TYPE, newArray.getClass().getComponentType()); double[] array1 = new double[]{1, 2, 3}; newArray = ArrayUtils.add(array1, 0); assertTrue(Arrays.equals(new double[]{1, 2, 3, 0}, newArray)); assertEquals(Double.TYPE, newArray.getClass().getComponentType()); newArray = ArrayUtils.add(array1, 4); assertTrue(Arrays.equals(new double[]{1, 2, 3, 4}, newArray)); assertEquals(Double.TYPE, newArray.getClass().getComponentType()); } public void testAddObjectArrayFloat() { float[] newArray; newArray = ArrayUtils.add((float[])null, 0); assertTrue(Arrays.equals(new float[]{0}, newArray)); assertEquals(Float.TYPE, newArray.getClass().getComponentType()); newArray = ArrayUtils.add((float[])null, 1); assertTrue(Arrays.equals(new float[]{1}, newArray)); assertEquals(Float.TYPE, newArray.getClass().getComponentType()); float[] array1 = new float[]{1, 2, 3}; newArray = ArrayUtils.add(array1, 0); assertTrue(Arrays.equals(new float[]{1, 2, 3, 0}, newArray)); assertEquals(Float.TYPE, newArray.getClass().getComponentType()); newArray = ArrayUtils.add(array1, 4); assertTrue(Arrays.equals(new float[]{1, 2, 3, 4}, newArray)); assertEquals(Float.TYPE, newArray.getClass().getComponentType()); } public void testAddObjectArrayInt() { int[] newArray; newArray = ArrayUtils.add((int[])null, 0); assertTrue(Arrays.equals(new int[]{0}, newArray)); assertEquals(Integer.TYPE, newArray.getClass().getComponentType()); newArray = ArrayUtils.add((int[])null, 1); assertTrue(Arrays.equals(new int[]{1}, newArray)); assertEquals(Integer.TYPE, newArray.getClass().getComponentType()); int[] array1 = new int[]{1, 2, 3}; newArray = ArrayUtils.add(array1, 0); assertTrue(Arrays.equals(new int[]{1, 2, 3, 0}, newArray)); assertEquals(Integer.TYPE, newArray.getClass().getComponentType()); newArray = ArrayUtils.add(array1, 4); assertTrue(Arrays.equals(new int[]{1, 2, 3, 4}, newArray)); assertEquals(Integer.TYPE, newArray.getClass().getComponentType()); } public void testAddObjectArrayLong() { long[] newArray; newArray = ArrayUtils.add((long[])null, 0); assertTrue(Arrays.equals(new long[]{0}, newArray)); assertEquals(Long.TYPE, newArray.getClass().getComponentType()); newArray = ArrayUtils.add((long[])null, 1); assertTrue(Arrays.equals(new long[]{1}, newArray)); assertEquals(Long.TYPE, newArray.getClass().getComponentType()); long[] array1 = new long[]{1, 2, 3}; newArray = ArrayUtils.add(array1, 0); assertTrue(Arrays.equals(new long[]{1, 2, 3, 0}, newArray)); assertEquals(Long.TYPE, newArray.getClass().getComponentType()); newArray = ArrayUtils.add(array1, 4); assertTrue(Arrays.equals(new long[]{1, 2, 3, 4}, newArray)); assertEquals(Long.TYPE, newArray.getClass().getComponentType()); } public void testAddObjectArrayShort() { short[] newArray; newArray = ArrayUtils.add((short[])null, (short)0); assertTrue(Arrays.equals(new short[]{0}, newArray)); assertEquals(Short.TYPE, newArray.getClass().getComponentType()); newArray = ArrayUtils.add((short[])null, (short)1); assertTrue(Arrays.equals(new short[]{1}, newArray)); assertEquals(Short.TYPE, newArray.getClass().getComponentType()); short[] array1 = new short[]{1, 2, 3}; newArray = ArrayUtils.add(array1, (short)0); assertTrue(Arrays.equals(new short[]{1, 2, 3, 0}, newArray)); assertEquals(Short.TYPE, newArray.getClass().getComponentType()); newArray = ArrayUtils.add(array1, (short)4); assertTrue(Arrays.equals(new short[]{1, 2, 3, 4}, newArray)); assertEquals(Short.TYPE, newArray.getClass().getComponentType()); } public void testAddObjectArrayObject() { Object[] newArray; newArray = ArrayUtils.add((Object[])null, null); assertTrue(Arrays.equals((new Object[]{null}), newArray)); assertEquals(Object.class, newArray.getClass().getComponentType()); newArray = ArrayUtils.add((Object[])null, "a"); assertTrue(Arrays.equals((new String[]{"a"}), newArray)); assertTrue(Arrays.equals((new Object[]{"a"}), newArray)); assertEquals(String.class, newArray.getClass().getComponentType()); String[] stringArray1 = new String[]{"a", "b", "c"}; newArray = ArrayUtils.add(stringArray1, null); assertTrue(Arrays.equals((new String[]{"a", "b", "c", null}), newArray)); assertEquals(String.class, newArray.getClass().getComponentType()); newArray = ArrayUtils.add(stringArray1, "d"); assertTrue(Arrays.equals((new String[]{"a", "b", "c", "d"}), newArray)); assertEquals(String.class, newArray.getClass().getComponentType()); Number[] numberArray1 = new Number[]{new Integer(1), new Double(2)}; newArray = ArrayUtils.add(numberArray1, new Float(3)); assertTrue(Arrays.equals((new Number[]{new Integer(1), new Double(2), new Float(3)}), newArray)); assertEquals(Number.class, newArray.getClass().getComponentType()); numberArray1 = null; newArray = ArrayUtils.add(numberArray1, new Float(3)); assertTrue(Arrays.equals((new Float[]{new Float(3)}), newArray)); assertEquals(Float.class, newArray.getClass().getComponentType()); numberArray1 = null; newArray = ArrayUtils.add(numberArray1, null); assertTrue(Arrays.equals((new Object[]{null}), newArray)); assertEquals(Object.class, newArray.getClass().getComponentType()); } public void testAddObjectArrayToObjectArray() { assertNull(ArrayUtils.addAll((Object[]) null, (Object[]) null)); Object[] newArray; String[] stringArray1 = new String[]{"a", "b", "c"}; String[] stringArray2 = new String[]{"1", "2", "3"}; newArray = ArrayUtils.addAll(stringArray1, (String[]) null); assertNotSame(stringArray1, newArray); assertTrue(Arrays.equals(stringArray1, newArray)); assertTrue(Arrays.equals((new String[]{"a", "b", "c"}), newArray)); assertEquals(String.class, newArray.getClass().getComponentType()); newArray = ArrayUtils.addAll(null, stringArray2); assertNotSame(stringArray2, newArray); assertTrue(Arrays.equals(stringArray2, newArray)); assertTrue(Arrays.equals((new String[]{"1", "2", "3"}), newArray)); assertEquals(String.class, newArray.getClass().getComponentType()); newArray = ArrayUtils.addAll(stringArray1, stringArray2); assertTrue(Arrays.equals((new String[]{"a", "b", "c", "1", "2", "3"}), newArray)); assertEquals(String.class, newArray.getClass().getComponentType()); newArray = ArrayUtils.addAll(ArrayUtils.EMPTY_STRING_ARRAY, (String[]) null); assertTrue(Arrays.equals(ArrayUtils.EMPTY_STRING_ARRAY, newArray)); assertTrue(Arrays.equals((new String[]{}), newArray)); assertEquals(String.class, newArray.getClass().getComponentType()); newArray = ArrayUtils.addAll(null, ArrayUtils.EMPTY_STRING_ARRAY); assertTrue(Arrays.equals(ArrayUtils.EMPTY_STRING_ARRAY, newArray)); assertTrue(Arrays.equals((new String[]{}), newArray)); assertEquals(String.class, newArray.getClass().getComponentType()); newArray = ArrayUtils.addAll(ArrayUtils.EMPTY_STRING_ARRAY, ArrayUtils.EMPTY_STRING_ARRAY); assertTrue(Arrays.equals(ArrayUtils.EMPTY_STRING_ARRAY, newArray)); assertTrue(Arrays.equals((new String[]{}), newArray)); assertEquals(String.class, newArray.getClass().getComponentType()); String[] stringArrayNull = new String []{null}; newArray = ArrayUtils.addAll(stringArrayNull, stringArrayNull); assertTrue(Arrays.equals((new String[]{null, null}), newArray)); assertEquals(String.class, newArray.getClass().getComponentType()); // boolean assertTrue( Arrays.equals( new boolean[] { true, false, false, true }, ArrayUtils.addAll( new boolean[] { true, false }, new boolean[] { false, true } ) ) ); assertTrue( Arrays.equals( new boolean[] { false, true }, ArrayUtils.addAll( null, new boolean[] { false, true } ) ) ); assertTrue( Arrays.equals( new boolean[] { true, false }, ArrayUtils.addAll( new boolean[] { true, false }, null ) ) ); // char assertTrue( Arrays.equals( new char[] { 'a', 'b', 'c', 'd' }, ArrayUtils.addAll( new char[] { 'a', 'b' }, new char[] { 'c', 'd' } ) ) ); assertTrue( Arrays.equals( new char[] { 'c', 'd' }, ArrayUtils.addAll( null, new char[] { 'c', 'd' } ) ) ); assertTrue( Arrays.equals( new char[] { 'a', 'b' }, ArrayUtils.addAll( new char[] { 'a', 'b' }, null ) ) ); // byte assertTrue( Arrays.equals( new byte[] { (byte) 0, (byte) 1, (byte) 2, (byte) 3 }, ArrayUtils.addAll( new byte[] { (byte) 0, (byte) 1 }, new byte[] { (byte) 2, (byte) 3 } ) ) ); assertTrue( Arrays.equals( new byte[] { (byte) 2, (byte) 3 }, ArrayUtils.addAll( null, new byte[] { (byte) 2, (byte) 3 } ) ) ); assertTrue( Arrays.equals( new byte[] { (byte) 0, (byte) 1 }, ArrayUtils.addAll( new byte[] { (byte) 0, (byte) 1 }, null ) ) ); // short assertTrue( Arrays.equals( new short[] { (short) 10, (short) 20, (short) 30, (short) 40 }, ArrayUtils.addAll( new short[] { (short) 10, (short) 20 }, new short[] { (short) 30, (short) 40 } ) ) ); assertTrue( Arrays.equals( new short[] { (short) 30, (short) 40 }, ArrayUtils.addAll( null, new short[] { (short) 30, (short) 40 } ) ) ); assertTrue( Arrays.equals( new short[] { (short) 10, (short) 20 }, ArrayUtils.addAll( new short[] { (short) 10, (short) 20 }, null ) ) ); // int assertTrue( Arrays.equals( new int[] { 1, 1000, -1000, -1 }, ArrayUtils.addAll( new int[] { 1, 1000 }, new int[] { -1000, -1 } ) ) ); assertTrue( Arrays.equals( new int[] { -1000, -1 }, ArrayUtils.addAll( null, new int[] { -1000, -1 } ) ) ); assertTrue( Arrays.equals( new int[] { 1, 1000 }, ArrayUtils.addAll( new int[] { 1, 1000 }, null ) ) ); // long assertTrue( Arrays.equals( new long[] { 1L, -1L, 1000L, -1000L }, ArrayUtils.addAll( new long[] { 1L, -1L }, new long[] { 1000L, -1000L } ) ) ); assertTrue( Arrays.equals( new long[] { 1000L, -1000L }, ArrayUtils.addAll( null, new long[] { 1000L, -1000L } ) ) ); assertTrue( Arrays.equals( new long[] { 1L, -1L }, ArrayUtils.addAll( new long[] { 1L, -1L }, null ) ) ); // float assertTrue( Arrays.equals( new float[] { 10.5f, 10.1f, 1.6f, 0.01f }, ArrayUtils.addAll( new float[] { 10.5f, 10.1f }, new float[] { 1.6f, 0.01f } ) ) ); assertTrue( Arrays.equals( new float[] { 1.6f, 0.01f }, ArrayUtils.addAll( null, new float[] { 1.6f, 0.01f } ) ) ); assertTrue( Arrays.equals( new float[] { 10.5f, 10.1f }, ArrayUtils.addAll( new float[] { 10.5f, 10.1f }, null ) ) ); // double assertTrue( Arrays.equals( new double[] { Math.PI, -Math.PI, 0, 9.99 }, ArrayUtils.addAll( new double[] { Math.PI, -Math.PI }, new double[] { 0, 9.99 } ) ) ); assertTrue( Arrays.equals( new double[] { 0, 9.99 }, ArrayUtils.addAll( null, new double[] { 0, 9.99 } ) ) ); assertTrue( Arrays.equals( new double[] { Math.PI, -Math.PI }, ArrayUtils.addAll( new double[] { Math.PI, -Math.PI }, null ) ) ); } public void testAddObjectAtIndex() { Object[] newArray; newArray = ArrayUtils.add((Object[])null, 0, null); assertTrue(Arrays.equals((new Object[]{null}), newArray)); assertEquals(Object.class, newArray.getClass().getComponentType()); newArray = ArrayUtils.add((Object[])null, 0, "a"); assertTrue(Arrays.equals((new String[]{"a"}), newArray)); assertTrue(Arrays.equals((new Object[]{"a"}), newArray)); assertEquals(String.class, newArray.getClass().getComponentType()); String[] stringArray1 = new String[]{"a", "b", "c"}; newArray = ArrayUtils.add(stringArray1, 0, null); assertTrue(Arrays.equals((new String[]{null, "a", "b", "c"}), newArray)); assertEquals(String.class, newArray.getClass().getComponentType()); newArray = ArrayUtils.add(stringArray1, 1, null); assertTrue(Arrays.equals((new String[]{"a", null, "b", "c"}), newArray)); assertEquals(String.class, newArray.getClass().getComponentType()); newArray = ArrayUtils.add(stringArray1, 3, null); assertTrue(Arrays.equals((new String[]{"a", "b", "c", null}), newArray)); assertEquals(String.class, newArray.getClass().getComponentType()); newArray = ArrayUtils.add(stringArray1, 3, "d"); assertTrue(Arrays.equals((new String[]{"a", "b", "c", "d"}), newArray)); assertEquals(String.class, newArray.getClass().getComponentType()); assertEquals(String.class, newArray.getClass().getComponentType()); Object[] o = new Object[] {"1", "2", "4"}; Object[] result = ArrayUtils.add(o, 2, "3"); Object[] result2 = ArrayUtils.add(o, 3, "5"); assertNotNull(result); assertEquals(4, result.length); assertEquals("1", result[0]); assertEquals("2", result[1]); assertEquals("3", result[2]); assertEquals("4", result[3]); assertNotNull(result2); assertEquals(4, result2.length); assertEquals("1", result2[0]); assertEquals("2", result2[1]); assertEquals("4", result2[2]); assertEquals("5", result2[3]); // boolean tests boolean[] booleanArray = ArrayUtils.add( null, 0, true ); assertTrue( Arrays.equals( new boolean[] { true }, booleanArray ) ); try { booleanArray = ArrayUtils.add( null, -1, true ); } catch(IndexOutOfBoundsException e) { assertEquals("Index: -1, Length: 0", e.getMessage()); } booleanArray = ArrayUtils.add( new boolean[] { true }, 0, false); assertTrue( Arrays.equals( new boolean[] { false, true }, booleanArray ) ); booleanArray = ArrayUtils.add( new boolean[] { false }, 1, true); assertTrue( Arrays.equals( new boolean[] { false, true }, booleanArray ) ); booleanArray = ArrayUtils.add( new boolean[] { true, false }, 1, true); assertTrue( Arrays.equals( new boolean[] { true, true, false }, booleanArray ) ); try { booleanArray = ArrayUtils.add( new boolean[] { true, false }, 4, true); } catch(IndexOutOfBoundsException e) { assertEquals("Index: 4, Length: 2", e.getMessage()); } try { booleanArray = ArrayUtils.add( new boolean[] { true, false }, -1, true); } catch(IndexOutOfBoundsException e) { assertEquals("Index: -1, Length: 2", e.getMessage()); } // char tests char[] charArray = ArrayUtils.add( (char[]) null, 0, 'a' ); assertTrue( Arrays.equals( new char[] { 'a' }, charArray ) ); try { charArray = ArrayUtils.add( (char[]) null, -1, 'a' ); } catch(IndexOutOfBoundsException e) { assertEquals("Index: -1, Length: 0", e.getMessage()); } charArray = ArrayUtils.add( new char[] { 'a' }, 0, 'b'); assertTrue( Arrays.equals( new char[] { 'b', 'a' }, charArray ) ); charArray = ArrayUtils.add( new char[] { 'a', 'b' }, 0, 'c'); assertTrue( Arrays.equals( new char[] { 'c', 'a', 'b' }, charArray ) ); charArray = ArrayUtils.add( new char[] { 'a', 'b' }, 1, 'k'); assertTrue( Arrays.equals( new char[] { 'a', 'k', 'b' }, charArray ) ); charArray = ArrayUtils.add( new char[] { 'a', 'b', 'c' }, 1, 't'); assertTrue( Arrays.equals( new char[] { 'a', 't', 'b', 'c' }, charArray ) ); try { charArray = ArrayUtils.add( new char[] { 'a', 'b' }, 4, 'c'); } catch(IndexOutOfBoundsException e) { assertEquals("Index: 4, Length: 2", e.getMessage()); } try { charArray = ArrayUtils.add( new char[] { 'a', 'b' }, -1, 'c'); } catch(IndexOutOfBoundsException e) { assertEquals("Index: -1, Length: 2", e.getMessage()); } // short tests short[] shortArray = ArrayUtils.add( new short[] { 1 }, 0, (short) 2); assertTrue( Arrays.equals( new short[] { 2, 1 }, shortArray ) ); try { shortArray = ArrayUtils.add( (short[]) null, -1, (short) 2); } catch(IndexOutOfBoundsException e) { assertEquals("Index: -1, Length: 0", e.getMessage()); } shortArray = ArrayUtils.add( new short[] { 2, 6 }, 2, (short) 10); assertTrue( Arrays.equals( new short[] { 2, 6, 10 }, shortArray ) ); shortArray = ArrayUtils.add( new short[] { 2, 6 }, 0, (short) -4); assertTrue( Arrays.equals( new short[] { -4, 2, 6 }, shortArray ) ); shortArray = ArrayUtils.add( new short[] { 2, 6, 3 }, 2, (short) 1); assertTrue( Arrays.equals( new short[] { 2, 6, 1, 3 }, shortArray ) ); try { shortArray = ArrayUtils.add( new short[] { 2, 6 }, 4, (short) 10); } catch(IndexOutOfBoundsException e) { assertEquals("Index: 4, Length: 2", e.getMessage()); } try { shortArray = ArrayUtils.add( new short[] { 2, 6 }, -1, (short) 10); } catch(IndexOutOfBoundsException e) { assertEquals("Index: -1, Length: 2", e.getMessage()); } // byte tests byte[] byteArray = ArrayUtils.add( new byte[] { 1 }, 0, (byte) 2); assertTrue( Arrays.equals( new byte[] { 2, 1 }, byteArray ) ); try { byteArray = ArrayUtils.add( (byte[]) null, -1, (byte) 2); } catch(IndexOutOfBoundsException e) { assertEquals("Index: -1, Length: 0", e.getMessage()); } byteArray = ArrayUtils.add( new byte[] { 2, 6 }, 2, (byte) 3); assertTrue( Arrays.equals( new byte[] { 2, 6, 3 }, byteArray ) ); byteArray = ArrayUtils.add( new byte[] { 2, 6 }, 0, (byte) 1); assertTrue( Arrays.equals( new byte[] { 1, 2, 6 }, byteArray ) ); byteArray = ArrayUtils.add( new byte[] { 2, 6, 3 }, 2, (byte) 1); assertTrue( Arrays.equals( new byte[] { 2, 6, 1, 3 }, byteArray ) ); try { byteArray = ArrayUtils.add( new byte[] { 2, 6 }, 4, (byte) 3); } catch(IndexOutOfBoundsException e) { assertEquals("Index: 4, Length: 2", e.getMessage()); } try { byteArray = ArrayUtils.add( new byte[] { 2, 6 }, -1, (byte) 3); } catch(IndexOutOfBoundsException e) { assertEquals("Index: -1, Length: 2", e.getMessage()); } // int tests int[] intArray = ArrayUtils.add( new int[] { 1 }, 0, 2); assertTrue( Arrays.equals( new int[] { 2, 1 }, intArray ) ); try { intArray = ArrayUtils.add( (int[]) null, -1, 2); } catch(IndexOutOfBoundsException e) { assertEquals("Index: -1, Length: 0", e.getMessage()); } intArray = ArrayUtils.add( new int[] { 2, 6 }, 2, 10); assertTrue( Arrays.equals( new int[] { 2, 6, 10 }, intArray ) ); intArray = ArrayUtils.add( new int[] { 2, 6 }, 0, -4); assertTrue( Arrays.equals( new int[] { -4, 2, 6 }, intArray ) ); intArray = ArrayUtils.add( new int[] { 2, 6, 3 }, 2, 1); assertTrue( Arrays.equals( new int[] { 2, 6, 1, 3 }, intArray ) ); try { intArray = ArrayUtils.add( new int[] { 2, 6 }, 4, 10); } catch(IndexOutOfBoundsException e) { assertEquals("Index: 4, Length: 2", e.getMessage()); } try { intArray = ArrayUtils.add( new int[] { 2, 6 }, -1, 10); } catch(IndexOutOfBoundsException e) { assertEquals("Index: -1, Length: 2", e.getMessage()); } // long tests long[] longArray = ArrayUtils.add( new long[] { 1L }, 0, 2L); assertTrue( Arrays.equals( new long[] { 2L, 1L }, longArray ) ); try { longArray = ArrayUtils.add( (long[]) null, -1, 2L); } catch(IndexOutOfBoundsException e) { assertEquals("Index: -1, Length: 0", e.getMessage()); } longArray = ArrayUtils.add( new long[] { 2L, 6L }, 2, 10L); assertTrue( Arrays.equals( new long[] { 2L, 6L, 10L }, longArray ) ); longArray = ArrayUtils.add( new long[] { 2L, 6L }, 0, -4L); assertTrue( Arrays.equals( new long[] { -4L, 2L, 6L }, longArray ) ); longArray = ArrayUtils.add( new long[] { 2L, 6L, 3L }, 2, 1L); assertTrue( Arrays.equals( new long[] { 2L, 6L, 1L, 3L }, longArray ) ); try { longArray = ArrayUtils.add( new long[] { 2L, 6L }, 4, 10L); } catch(IndexOutOfBoundsException e) { assertEquals("Index: 4, Length: 2", e.getMessage()); } try { longArray = ArrayUtils.add( new long[] { 2L, 6L }, -1, 10L); } catch(IndexOutOfBoundsException e) { assertEquals("Index: -1, Length: 2", e.getMessage()); } // float tests float[] floatArray = ArrayUtils.add( new float[] { 1.1f }, 0, 2.2f); assertTrue( Arrays.equals( new float[] { 2.2f, 1.1f }, floatArray ) ); try { floatArray = ArrayUtils.add( (float[]) null, -1, 2.2f); } catch(IndexOutOfBoundsException e) { assertEquals("Index: -1, Length: 0", e.getMessage()); } floatArray = ArrayUtils.add( new float[] { 2.3f, 6.4f }, 2, 10.5f); assertTrue( Arrays.equals( new float[] { 2.3f, 6.4f, 10.5f }, floatArray ) ); floatArray = ArrayUtils.add( new float[] { 2.6f, 6.7f }, 0, -4.8f); assertTrue( Arrays.equals( new float[] { -4.8f, 2.6f, 6.7f }, floatArray ) ); floatArray = ArrayUtils.add( new float[] { 2.9f, 6.0f, 0.3f }, 2, 1.0f); assertTrue( Arrays.equals( new float[] { 2.9f, 6.0f, 1.0f, 0.3f }, floatArray ) ); try { floatArray = ArrayUtils.add( new float[] { 2.3f, 6.4f }, 4, 10.5f); } catch(IndexOutOfBoundsException e) { assertEquals("Index: 4, Length: 2", e.getMessage()); } try { floatArray = ArrayUtils.add( new float[] { 2.3f, 6.4f }, -1, 10.5f); } catch(IndexOutOfBoundsException e) { assertEquals("Index: -1, Length: 2", e.getMessage()); } // double tests double[] doubleArray = ArrayUtils.add( new double[] { 1.1 }, 0, 2.2); assertTrue( Arrays.equals( new double[] { 2.2, 1.1 }, doubleArray ) ); try { doubleArray = ArrayUtils.add( (double[]) null, -1, 2.2); } catch(IndexOutOfBoundsException e) { assertEquals("Index: -1, Length: 0", e.getMessage()); } doubleArray = ArrayUtils.add( new double[] { 2.3, 6.4 }, 2, 10.5); assertTrue( Arrays.equals( new double[] { 2.3, 6.4, 10.5 }, doubleArray ) ); doubleArray = ArrayUtils.add( new double[] { 2.6, 6.7 }, 0, -4.8); assertTrue( Arrays.equals( new double[] { -4.8, 2.6, 6.7 }, doubleArray ) ); doubleArray = ArrayUtils.add( new double[] { 2.9, 6.0, 0.3 }, 2, 1.0); assertTrue( Arrays.equals( new double[] { 2.9, 6.0, 1.0, 0.3 }, doubleArray ) ); try { doubleArray = ArrayUtils.add( new double[] { 2.3, 6.4 }, 4, 10.5); } catch(IndexOutOfBoundsException e) { assertEquals("Index: 4, Length: 2", e.getMessage()); } try { doubleArray = ArrayUtils.add( new double[] { 2.3, 6.4 }, -1, 10.5); } catch(IndexOutOfBoundsException e) { assertEquals("Index: -1, Length: 2", e.getMessage()); } } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/ArrayUtilsRemoveTest.java100644 0 0 56545 11513702441 25777 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang; import java.util.Arrays; import junit.framework.TestCase; /** * Tests ArrayUtils remove and removeElement methods. * * @author Maarten Coene * @version $Id: ArrayUtilsRemoveTest.java 905628 2010-02-02 13:29:55Z niallp $ */ public class ArrayUtilsRemoveTest extends TestCase { public void testRemoveObjectArray() { Object[] array; array = ArrayUtils.remove(new Object[] {"a"}, 0); assertTrue(Arrays.equals(ArrayUtils.EMPTY_OBJECT_ARRAY, array)); assertEquals(Object.class, array.getClass().getComponentType()); array = ArrayUtils.remove(new Object[] {"a", "b"}, 0); assertTrue(Arrays.equals(new Object[] {"b"}, array)); assertEquals(Object.class, array.getClass().getComponentType()); array = ArrayUtils.remove(new Object[] {"a", "b"}, 1); assertTrue(Arrays.equals(new Object[] {"a"}, array)); assertEquals(Object.class, array.getClass().getComponentType()); array = ArrayUtils.remove(new Object[] {"a", "b", "c"}, 1); assertTrue(Arrays.equals(new Object[] {"a", "c"}, array)); assertEquals(Object.class, array.getClass().getComponentType()); try { ArrayUtils.remove(new Object[] {"a", "b"}, -1); fail("IndexOutOfBoundsException expected"); } catch (IndexOutOfBoundsException e) {} try { ArrayUtils.remove(new Object[] {"a", "b"}, 2); fail("IndexOutOfBoundsException expected"); } catch (IndexOutOfBoundsException e) {} try { ArrayUtils.remove((Object[]) null, 0); fail("IndexOutOfBoundsException expected"); } catch (IndexOutOfBoundsException e) {} } public void testRemoveNumberArray(){ Number[] inarray = {new Integer(1), new Long(2), new Byte((byte) 3)}; assertEquals(3, inarray.length); Number[] outarray; outarray = (Number[])ArrayUtils.remove(inarray, 1); assertEquals(2, outarray.length); assertEquals(Number.class, outarray.getClass().getComponentType()); outarray = (Number[])ArrayUtils.remove(outarray, 1); assertEquals(1, outarray.length); assertEquals(Number.class, outarray.getClass().getComponentType()); outarray = (Number[])ArrayUtils.remove(outarray, 0); assertEquals(0, outarray.length); assertEquals(Number.class, outarray.getClass().getComponentType()); } public void testRemoveBooleanArray() { boolean[] array; array = ArrayUtils.remove(new boolean[] {true}, 0); assertTrue(Arrays.equals(ArrayUtils.EMPTY_BOOLEAN_ARRAY, array)); assertEquals(Boolean.TYPE, array.getClass().getComponentType()); array = ArrayUtils.remove(new boolean[] {true, false}, 0); assertTrue(Arrays.equals(new boolean[] {false}, array)); assertEquals(Boolean.TYPE, array.getClass().getComponentType()); array = ArrayUtils.remove(new boolean[] {true, false}, 1); assertTrue(Arrays.equals(new boolean[] {true}, array)); assertEquals(Boolean.TYPE, array.getClass().getComponentType()); array = ArrayUtils.remove(new boolean[] {true, false, true}, 1); assertTrue(Arrays.equals(new boolean[] {true, true}, array)); assertEquals(Boolean.TYPE, array.getClass().getComponentType()); try { ArrayUtils.remove(new boolean[] {true, false}, -1); fail("IndexOutOfBoundsException expected"); } catch (IndexOutOfBoundsException e) {} try { ArrayUtils.remove(new boolean[] {true, false}, 2); fail("IndexOutOfBoundsException expected"); } catch (IndexOutOfBoundsException e) {} try { ArrayUtils.remove((boolean[]) null, 0); fail("IndexOutOfBoundsException expected"); } catch (IndexOutOfBoundsException e) {} } public void testRemoveByteArray() { byte[] array; array = ArrayUtils.remove(new byte[] {1}, 0); assertTrue(Arrays.equals(ArrayUtils.EMPTY_BYTE_ARRAY, array)); assertEquals(Byte.TYPE, array.getClass().getComponentType()); array = ArrayUtils.remove(new byte[] {1, 2}, 0); assertTrue(Arrays.equals(new byte[] {2}, array)); assertEquals(Byte.TYPE, array.getClass().getComponentType()); array = ArrayUtils.remove(new byte[] {1, 2}, 1); assertTrue(Arrays.equals(new byte[] {1}, array)); assertEquals(Byte.TYPE, array.getClass().getComponentType()); array = ArrayUtils.remove(new byte[] {1, 2, 1}, 1); assertTrue(Arrays.equals(new byte[] {1, 1}, array)); assertEquals(Byte.TYPE, array.getClass().getComponentType()); try { ArrayUtils.remove(new byte[] {1, 2}, -1); fail("IndexOutOfBoundsException expected"); } catch (IndexOutOfBoundsException e) {} try { ArrayUtils.remove(new byte[] {1, 2}, 2); fail("IndexOutOfBoundsException expected"); } catch (IndexOutOfBoundsException e) {} try { ArrayUtils.remove((byte[]) null, 0); fail("IndexOutOfBoundsException expected"); } catch (IndexOutOfBoundsException e) {} } public void testRemoveCharArray() { char[] array; array = ArrayUtils.remove(new char[] {'a'}, 0); assertTrue(Arrays.equals(ArrayUtils.EMPTY_CHAR_ARRAY, array)); assertEquals(Character.TYPE, array.getClass().getComponentType()); array = ArrayUtils.remove(new char[] {'a', 'b'}, 0); assertTrue(Arrays.equals(new char[] {'b'}, array)); assertEquals(Character.TYPE, array.getClass().getComponentType()); array = ArrayUtils.remove(new char[] {'a', 'b'}, 1); assertTrue(Arrays.equals(new char[] {'a'}, array)); assertEquals(Character.TYPE, array.getClass().getComponentType()); array = ArrayUtils.remove(new char[] {'a', 'b', 'c'}, 1); assertTrue(Arrays.equals(new char[] {'a', 'c'}, array)); assertEquals(Character.TYPE, array.getClass().getComponentType()); try { ArrayUtils.remove(new char[] {'a', 'b'}, -1); fail("IndexOutOfBoundsException expected"); } catch (IndexOutOfBoundsException e) {} try { ArrayUtils.remove(new char[] {'a', 'b'}, 2); fail("IndexOutOfBoundsException expected"); } catch (IndexOutOfBoundsException e) {} try { ArrayUtils.remove((char[]) null, 0); fail("IndexOutOfBoundsException expected"); } catch (IndexOutOfBoundsException e) {} } public void testRemoveDoubleArray() { double[] array; array = ArrayUtils.remove(new double[] {1}, 0); assertTrue(Arrays.equals(ArrayUtils.EMPTY_DOUBLE_ARRAY, array)); assertEquals(Double.TYPE, array.getClass().getComponentType()); array = ArrayUtils.remove(new double[] {1, 2}, 0); assertTrue(Arrays.equals(new double[] {2}, array)); assertEquals(Double.TYPE, array.getClass().getComponentType()); array = ArrayUtils.remove(new double[] {1, 2}, 1); assertTrue(Arrays.equals(new double[] {1}, array)); assertEquals(Double.TYPE, array.getClass().getComponentType()); array = ArrayUtils.remove(new double[] {1, 2, 1}, 1); assertTrue(Arrays.equals(new double[] {1, 1}, array)); assertEquals(Double.TYPE, array.getClass().getComponentType()); try { ArrayUtils.remove(new double[] {1, 2}, -1); fail("IndexOutOfBoundsException expected"); } catch (IndexOutOfBoundsException e) {} try { ArrayUtils.remove(new double[] {1, 2}, 2); fail("IndexOutOfBoundsException expected"); } catch (IndexOutOfBoundsException e) {} try { ArrayUtils.remove((double[]) null, 0); fail("IndexOutOfBoundsException expected"); } catch (IndexOutOfBoundsException e) {} } public void testRemoveFloatArray() { float[] array; array = ArrayUtils.remove(new float[] {1}, 0); assertTrue(Arrays.equals(ArrayUtils.EMPTY_FLOAT_ARRAY, array)); assertEquals(Float.TYPE, array.getClass().getComponentType()); array = ArrayUtils.remove(new float[] {1, 2}, 0); assertTrue(Arrays.equals(new float[] {2}, array)); assertEquals(Float.TYPE, array.getClass().getComponentType()); array = ArrayUtils.remove(new float[] {1, 2}, 1); assertTrue(Arrays.equals(new float[] {1}, array)); assertEquals(Float.TYPE, array.getClass().getComponentType()); array = ArrayUtils.remove(new float[] {1, 2, 1}, 1); assertTrue(Arrays.equals(new float[] {1, 1}, array)); assertEquals(Float.TYPE, array.getClass().getComponentType()); try { ArrayUtils.remove(new float[] {1, 2}, -1); fail("IndexOutOfBoundsException expected"); } catch (IndexOutOfBoundsException e) {} try { ArrayUtils.remove(new float[] {1, 2}, 2); fail("IndexOutOfBoundsException expected"); } catch (IndexOutOfBoundsException e) {} try { ArrayUtils.remove((float[]) null, 0); fail("IndexOutOfBoundsException expected"); } catch (IndexOutOfBoundsException e) {} } public void testRemoveIntArray() { int[] array; array = ArrayUtils.remove(new int[] {1}, 0); assertTrue(Arrays.equals(ArrayUtils.EMPTY_INT_ARRAY, array)); assertEquals(Integer.TYPE, array.getClass().getComponentType()); array = ArrayUtils.remove(new int[] {1, 2}, 0); assertTrue(Arrays.equals(new int[] {2}, array)); assertEquals(Integer.TYPE, array.getClass().getComponentType()); array = ArrayUtils.remove(new int[] {1, 2}, 1); assertTrue(Arrays.equals(new int[] {1}, array)); assertEquals(Integer.TYPE, array.getClass().getComponentType()); array = ArrayUtils.remove(new int[] {1, 2, 1}, 1); assertTrue(Arrays.equals(new int[] {1, 1}, array)); assertEquals(Integer.TYPE, array.getClass().getComponentType()); try { ArrayUtils.remove(new int[] {1, 2}, -1); fail("IndexOutOfBoundsException expected"); } catch (IndexOutOfBoundsException e) {} try { ArrayUtils.remove(new int[] {1, 2}, 2); fail("IndexOutOfBoundsException expected"); } catch (IndexOutOfBoundsException e) {} try { ArrayUtils.remove((int[]) null, 0); fail("IndexOutOfBoundsException expected"); } catch (IndexOutOfBoundsException e) {} } public void testRemoveLongArray() { long[] array; array = ArrayUtils.remove(new long[] {1}, 0); assertTrue(Arrays.equals(ArrayUtils.EMPTY_LONG_ARRAY, array)); assertEquals(Long.TYPE, array.getClass().getComponentType()); array = ArrayUtils.remove(new long[] {1, 2}, 0); assertTrue(Arrays.equals(new long[] {2}, array)); assertEquals(Long.TYPE, array.getClass().getComponentType()); array = ArrayUtils.remove(new long[] {1, 2}, 1); assertTrue(Arrays.equals(new long[] {1}, array)); assertEquals(Long.TYPE, array.getClass().getComponentType()); array = ArrayUtils.remove(new long[] {1, 2, 1}, 1); assertTrue(Arrays.equals(new long[] {1, 1}, array)); assertEquals(Long.TYPE, array.getClass().getComponentType()); try { ArrayUtils.remove(new long[] {1, 2}, -1); fail("IndexOutOfBoundsException expected"); } catch (IndexOutOfBoundsException e) {} try { ArrayUtils.remove(new long[] {1, 2}, 2); fail("IndexOutOfBoundsException expected"); } catch (IndexOutOfBoundsException e) {} try { ArrayUtils.remove((long[]) null, 0); fail("IndexOutOfBoundsException expected"); } catch (IndexOutOfBoundsException e) {} } public void testRemoveShortArray() { short[] array; array = ArrayUtils.remove(new short[] {1}, 0); assertTrue(Arrays.equals(ArrayUtils.EMPTY_SHORT_ARRAY, array)); assertEquals(Short.TYPE, array.getClass().getComponentType()); array = ArrayUtils.remove(new short[] {1, 2}, 0); assertTrue(Arrays.equals(new short[] {2}, array)); assertEquals(Short.TYPE, array.getClass().getComponentType()); array = ArrayUtils.remove(new short[] {1, 2}, 1); assertTrue(Arrays.equals(new short[] {1}, array)); assertEquals(Short.TYPE, array.getClass().getComponentType()); array = ArrayUtils.remove(new short[] {1, 2, 1}, 1); assertTrue(Arrays.equals(new short[] {1, 1}, array)); assertEquals(Short.TYPE, array.getClass().getComponentType()); try { ArrayUtils.remove(new short[] {1, 2}, -1); fail("IndexOutOfBoundsException expected"); } catch (IndexOutOfBoundsException e) {} try { ArrayUtils.remove(new short[] {1, 2}, 2); fail("IndexOutOfBoundsException expected"); } catch (IndexOutOfBoundsException e) {} try { ArrayUtils.remove((short[]) null, 0); fail("IndexOutOfBoundsException expected"); } catch (IndexOutOfBoundsException e) {} } public void testRemoveElementObjectArray() { Object[] array; array = ArrayUtils.removeElement((Object[]) null, "a"); assertNull(array); array = ArrayUtils.removeElement(ArrayUtils.EMPTY_OBJECT_ARRAY, "a"); assertTrue(Arrays.equals(ArrayUtils.EMPTY_OBJECT_ARRAY, array)); assertEquals(Object.class, array.getClass().getComponentType()); array = ArrayUtils.removeElement(new Object[] {"a"}, "a"); assertTrue(Arrays.equals(ArrayUtils.EMPTY_OBJECT_ARRAY, array)); assertEquals(Object.class, array.getClass().getComponentType()); array = ArrayUtils.removeElement(new Object[] {"a", "b"}, "a"); assertTrue(Arrays.equals(new Object[] {"b"}, array)); assertEquals(Object.class, array.getClass().getComponentType()); array = ArrayUtils.removeElement(new Object[] {"a", "b", "a"}, "a"); assertTrue(Arrays.equals(new Object[] {"b", "a"}, array)); assertEquals(Object.class, array.getClass().getComponentType()); } public void testRemoveElementBooleanArray() { boolean[] array; array = ArrayUtils.removeElement((boolean[]) null, true); assertNull(array); array = ArrayUtils.removeElement(ArrayUtils.EMPTY_BOOLEAN_ARRAY, true); assertTrue(Arrays.equals(ArrayUtils.EMPTY_BOOLEAN_ARRAY, array)); assertEquals(Boolean.TYPE, array.getClass().getComponentType()); array = ArrayUtils.removeElement(new boolean[] {true}, true); assertTrue(Arrays.equals(ArrayUtils.EMPTY_BOOLEAN_ARRAY, array)); assertEquals(Boolean.TYPE, array.getClass().getComponentType()); array = ArrayUtils.removeElement(new boolean[] {true, false}, true); assertTrue(Arrays.equals(new boolean[] {false}, array)); assertEquals(Boolean.TYPE, array.getClass().getComponentType()); array = ArrayUtils.removeElement(new boolean[] {true, false, true}, true); assertTrue(Arrays.equals(new boolean[] {false, true}, array)); assertEquals(Boolean.TYPE, array.getClass().getComponentType()); } public void testRemoveElementByteArray() { byte[] array; array = ArrayUtils.removeElement((byte[]) null, (byte) 1); assertNull(array); array = ArrayUtils.removeElement(ArrayUtils.EMPTY_BYTE_ARRAY, (byte) 1); assertTrue(Arrays.equals(ArrayUtils.EMPTY_BYTE_ARRAY, array)); assertEquals(Byte.TYPE, array.getClass().getComponentType()); array = ArrayUtils.removeElement(new byte[] {1}, (byte) 1); assertTrue(Arrays.equals(ArrayUtils.EMPTY_BYTE_ARRAY, array)); assertEquals(Byte.TYPE, array.getClass().getComponentType()); array = ArrayUtils.removeElement(new byte[] {1, 2}, (byte) 1); assertTrue(Arrays.equals(new byte[] {2}, array)); assertEquals(Byte.TYPE, array.getClass().getComponentType()); array = ArrayUtils.removeElement(new byte[] {1, 2, 1}, (byte) 1); assertTrue(Arrays.equals(new byte[] {2, 1}, array)); assertEquals(Byte.TYPE, array.getClass().getComponentType()); } public void testRemoveElementCharArray() { char[] array; array = ArrayUtils.removeElement((char[]) null, 'a'); assertNull(array); array = ArrayUtils.removeElement(ArrayUtils.EMPTY_CHAR_ARRAY, 'a'); assertTrue(Arrays.equals(ArrayUtils.EMPTY_CHAR_ARRAY, array)); assertEquals(Character.TYPE, array.getClass().getComponentType()); array = ArrayUtils.removeElement(new char[] {'a'}, 'a'); assertTrue(Arrays.equals(ArrayUtils.EMPTY_CHAR_ARRAY, array)); assertEquals(Character.TYPE, array.getClass().getComponentType()); array = ArrayUtils.removeElement(new char[] {'a', 'b'}, 'a'); assertTrue(Arrays.equals(new char[] {'b'}, array)); assertEquals(Character.TYPE, array.getClass().getComponentType()); array = ArrayUtils.removeElement(new char[] {'a', 'b', 'a'}, 'a'); assertTrue(Arrays.equals(new char[] {'b', 'a'}, array)); assertEquals(Character.TYPE, array.getClass().getComponentType()); } public void testRemoveElementDoubleArray() { double[] array; array = ArrayUtils.removeElement((double[]) null, (double) 1); assertNull(array); array = ArrayUtils.removeElement(ArrayUtils.EMPTY_DOUBLE_ARRAY, (double) 1); assertTrue(Arrays.equals(ArrayUtils.EMPTY_DOUBLE_ARRAY, array)); assertEquals(Double.TYPE, array.getClass().getComponentType()); array = ArrayUtils.removeElement(new double[] {1}, (double) 1); assertTrue(Arrays.equals(ArrayUtils.EMPTY_DOUBLE_ARRAY, array)); assertEquals(Double.TYPE, array.getClass().getComponentType()); array = ArrayUtils.removeElement(new double[] {1, 2}, (double) 1); assertTrue(Arrays.equals(new double[] {2}, array)); assertEquals(Double.TYPE, array.getClass().getComponentType()); array = ArrayUtils.removeElement(new double[] {1, 2, 1}, (double) 1); assertTrue(Arrays.equals(new double[] {2, 1}, array)); assertEquals(Double.TYPE, array.getClass().getComponentType()); } public void testRemoveElementFloatArray() { float[] array; array = ArrayUtils.removeElement((float[]) null, (float) 1); assertNull(array); array = ArrayUtils.removeElement(ArrayUtils.EMPTY_FLOAT_ARRAY, (float) 1); assertTrue(Arrays.equals(ArrayUtils.EMPTY_FLOAT_ARRAY, array)); assertEquals(Float.TYPE, array.getClass().getComponentType()); array = ArrayUtils.removeElement(new float[] {1}, (float) 1); assertTrue(Arrays.equals(ArrayUtils.EMPTY_FLOAT_ARRAY, array)); assertEquals(Float.TYPE, array.getClass().getComponentType()); array = ArrayUtils.removeElement(new float[] {1, 2}, (float) 1); assertTrue(Arrays.equals(new float[] {2}, array)); assertEquals(Float.TYPE, array.getClass().getComponentType()); array = ArrayUtils.removeElement(new float[] {1, 2, 1}, (float) 1); assertTrue(Arrays.equals(new float[] {2, 1}, array)); assertEquals(Float.TYPE, array.getClass().getComponentType()); } public void testRemoveElementIntArray() { int[] array; array = ArrayUtils.removeElement((int[]) null, 1); assertNull(array); array = ArrayUtils.removeElement(ArrayUtils.EMPTY_INT_ARRAY, 1); assertTrue(Arrays.equals(ArrayUtils.EMPTY_INT_ARRAY, array)); assertEquals(Integer.TYPE, array.getClass().getComponentType()); array = ArrayUtils.removeElement(new int[] {1}, 1); assertTrue(Arrays.equals(ArrayUtils.EMPTY_INT_ARRAY, array)); assertEquals(Integer.TYPE, array.getClass().getComponentType()); array = ArrayUtils.removeElement(new int[] {1, 2}, 1); assertTrue(Arrays.equals(new int[] {2}, array)); assertEquals(Integer.TYPE, array.getClass().getComponentType()); array = ArrayUtils.removeElement(new int[] {1, 2, 1}, 1); assertTrue(Arrays.equals(new int[] {2, 1}, array)); assertEquals(Integer.TYPE, array.getClass().getComponentType()); } public void testRemoveElementLongArray() { long[] array; array = ArrayUtils.removeElement((long[]) null, (long) 1); assertNull(array); array = ArrayUtils.removeElement(ArrayUtils.EMPTY_LONG_ARRAY, (long) 1); assertTrue(Arrays.equals(ArrayUtils.EMPTY_LONG_ARRAY, array)); assertEquals(Long.TYPE, array.getClass().getComponentType()); array = ArrayUtils.removeElement(new long[] {1}, (long) 1); assertTrue(Arrays.equals(ArrayUtils.EMPTY_LONG_ARRAY, array)); assertEquals(Long.TYPE, array.getClass().getComponentType()); array = ArrayUtils.removeElement(new long[] {1, 2}, (long) 1); assertTrue(Arrays.equals(new long[] {2}, array)); assertEquals(Long.TYPE, array.getClass().getComponentType()); array = ArrayUtils.removeElement(new long[] {1, 2, 1}, (long) 1); assertTrue(Arrays.equals(new long[] {2, 1}, array)); assertEquals(Long.TYPE, array.getClass().getComponentType()); } public void testRemoveElementShortArray() { short[] array; array = ArrayUtils.removeElement((short[]) null, (short) 1); assertNull(array); array = ArrayUtils.removeElement(ArrayUtils.EMPTY_SHORT_ARRAY, (short) 1); assertTrue(Arrays.equals(ArrayUtils.EMPTY_SHORT_ARRAY, array)); assertEquals(Short.TYPE, array.getClass().getComponentType()); array = ArrayUtils.removeElement(new short[] {1}, (short) 1); assertTrue(Arrays.equals(ArrayUtils.EMPTY_SHORT_ARRAY, array)); assertEquals(Short.TYPE, array.getClass().getComponentType()); array = ArrayUtils.removeElement(new short[] {1, 2}, (short) 1); assertTrue(Arrays.equals(new short[] {2}, array)); assertEquals(Short.TYPE, array.getClass().getComponentType()); array = ArrayUtils.removeElement(new short[] {1, 2, 1}, (short) 1); assertTrue(Arrays.equals(new short[] {2, 1}, array)); assertEquals(Short.TYPE, array.getClass().getComponentType()); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/ArrayUtilsTest.java100644 0 0 365034 11513702440 24634 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.Date; import java.util.Map; import junit.framework.TestCase; /** * Unit tests {@link org.apache.commons.lang.ArrayUtils}. * * @author Apache Software Foundation * @author Moritz Petersen * @author Nikolay Metchev * @author Matthew Hawthorne * @author Tim O'Brien * @author Ashwin S * @author Fredrik Westermarck * @author Gary Gregory * @author Maarten Coene * @version $Id: ArrayUtilsTest.java 905988 2010-02-03 10:52:37Z niallp $ */ public class ArrayUtilsTest extends TestCase { public ArrayUtilsTest(String name) { super(name); } //----------------------------------------------------------------------- public void testConstructor() { assertNotNull(new ArrayUtils()); Constructor[] cons = ArrayUtils.class.getDeclaredConstructors(); assertEquals(1, cons.length); assertEquals(true, Modifier.isPublic(cons[0].getModifiers())); assertEquals(true, Modifier.isPublic(ArrayUtils.class.getModifiers())); assertEquals(false, Modifier.isFinal(ArrayUtils.class.getModifiers())); } //----------------------------------------------------------------------- public void testToString() { assertEquals("{}", ArrayUtils.toString(null)); assertEquals("{}", ArrayUtils.toString(new Object[0])); assertEquals("{}", ArrayUtils.toString(new String[0])); assertEquals("{}", ArrayUtils.toString(new String[] {null})); assertEquals("{pink,blue}", ArrayUtils.toString(new String[] {"pink","blue"})); assertEquals("", ArrayUtils.toString(null, "")); assertEquals("{}", ArrayUtils.toString(new Object[0], "")); assertEquals("{}", ArrayUtils.toString(new String[0], "")); assertEquals("{}", ArrayUtils.toString(new String[] {null}, "")); assertEquals("{pink,blue}", ArrayUtils.toString(new String[] {"pink","blue"}, "")); } //----------------------------------------------------------------------- public void testHashCode() { long[][] array1 = new long[][] {{2,5}, {4,5}}; long[][] array2 = new long[][] {{2,5}, {4,6}}; assertEquals(true, ArrayUtils.hashCode(array1) == ArrayUtils.hashCode(array1)); assertEquals(false, ArrayUtils.hashCode(array1) == ArrayUtils.hashCode(array2)); Object[] array3 = new Object[] {new String(new char[] {'A', 'B'})}; Object[] array4 = new Object[] {"AB"}; assertEquals(true, ArrayUtils.hashCode(array3) == ArrayUtils.hashCode(array3)); assertEquals(true, ArrayUtils.hashCode(array3) == ArrayUtils.hashCode(array4)); } //----------------------------------------------------------------------- private void assertIsEquals(Object array1, Object array2, Object array3) { assertEquals(true, ArrayUtils.isEquals(array1, array1)); assertEquals(true, ArrayUtils.isEquals(array2, array2)); assertEquals(true, ArrayUtils.isEquals(array3, array3)); assertEquals(false, ArrayUtils.isEquals(array1, array2)); assertEquals(false, ArrayUtils.isEquals(array2, array1)); assertEquals(false, ArrayUtils.isEquals(array1, array3)); assertEquals(false, ArrayUtils.isEquals(array3, array1)); assertEquals(false, ArrayUtils.isEquals(array1, array2)); assertEquals(false, ArrayUtils.isEquals(array2, array1)); } public void testIsEquals() { long[][] larray1 = new long[][]{{2, 5}, {4, 5}}; long[][] larray2 = new long[][]{{2, 5}, {4, 6}}; long[] larray3 = new long[]{2, 5}; this.assertIsEquals(larray1, larray2, larray3); int[][] iarray1 = new int[][]{{2, 5}, {4, 5}}; int[][] iarray2 = new int[][]{{2, 5}, {4, 6}}; int[] iarray3 = new int[]{2, 5}; this.assertIsEquals(iarray1, iarray2, iarray3); short[][] sarray1 = new short[][]{{2, 5}, {4, 5}}; short[][] sarray2 = new short[][]{{2, 5}, {4, 6}}; short[] sarray3 = new short[]{2, 5}; this.assertIsEquals(sarray1, sarray2, sarray3); float[][] farray1 = new float[][]{{2, 5}, {4, 5}}; float[][] farray2 = new float[][]{{2, 5}, {4, 6}}; float[] farray3 = new float[]{2, 5}; this.assertIsEquals(farray1, farray2, farray3); double[][] darray1 = new double[][]{{2, 5}, {4, 5}}; double[][] darray2 = new double[][]{{2, 5}, {4, 6}}; double[] darray3 = new double[]{2, 5}; this.assertIsEquals(darray1, darray2, darray3); byte[][] byteArray1 = new byte[][]{{2, 5}, {4, 5}}; byte[][] byteArray2 = new byte[][]{{2, 5}, {4, 6}}; byte[] byteArray3 = new byte[]{2, 5}; this.assertIsEquals(byteArray1, byteArray2, byteArray3); char[][] charArray1 = new char[][]{{2, 5}, {4, 5}}; char[][] charArray2 = new char[][]{{2, 5}, {4, 6}}; char[] charArray3 = new char[]{2, 5}; this.assertIsEquals(charArray1, charArray2, charArray3); boolean[][] barray1 = new boolean[][]{{true, false}, {true, true}}; boolean[][] barray2 = new boolean[][]{{true, false}, {true, false}}; boolean[] barray3 = new boolean[]{false, true}; this.assertIsEquals(barray1, barray2, barray3); Object[] array3 = new Object[]{new String(new char[]{'A', 'B'})}; Object[] array4 = new Object[]{"AB"}; assertEquals(true, ArrayUtils.isEquals(array3, array3)); assertEquals(true, ArrayUtils.isEquals(array3, array4)); assertEquals(true, ArrayUtils.isEquals(null, null)); assertEquals(false, ArrayUtils.isEquals(null, array4)); } //----------------------------------------------------------------------- public void testToMap() { Map map = ArrayUtils.toMap(new String[][] {{"foo", "bar"}, {"hello", "world"}}); assertEquals("bar", map.get("foo")); assertEquals("world", map.get("hello")); assertEquals(null, ArrayUtils.toMap(null)); try { ArrayUtils.toMap(new String[][] {{"foo", "bar"}, {"short"}}); fail("exception expected"); } catch (IllegalArgumentException ex) {} try { ArrayUtils.toMap(new Object[] {new Object[] {"foo", "bar"}, "illegal type"}); fail("exception expected"); } catch (IllegalArgumentException ex) {} try { ArrayUtils.toMap(new Object[] {new Object[] {"foo", "bar"}, null}); fail("exception expected"); } catch (IllegalArgumentException ex) {} map = ArrayUtils.toMap(new Object[] {new Map.Entry() { public Object getKey() { return "foo"; } public Object getValue() { return "bar"; } public Object setValue(Object value) { throw new UnsupportedOperationException(); } public boolean equals(Object o) { throw new UnsupportedOperationException(); } public int hashCode() { throw new UnsupportedOperationException(); } }}); assertEquals("bar", map.get("foo")); } //----------------------------------------------------------------------- public void testClone() { assertEquals(null, ArrayUtils.clone((Object[]) null)); Object[] original1 = new Object[0]; Object[] cloned1 = ArrayUtils.clone(original1); assertTrue(Arrays.equals(original1, cloned1)); assertTrue(original1 != cloned1); StringBuffer buf = new StringBuffer("pick"); original1 = new Object[] {buf, "a", new String[] {"stick"}}; cloned1 = ArrayUtils.clone(original1); assertTrue(Arrays.equals(original1, cloned1)); assertTrue(original1 != cloned1); assertSame(original1[0], cloned1[0]); assertSame(original1[1], cloned1[1]); assertSame(original1[2], cloned1[2]); } public void testCloneBoolean() { assertEquals(null, ArrayUtils.clone((boolean[]) null)); boolean[] original = new boolean[] {true, false}; boolean[] cloned = ArrayUtils.clone(original); assertTrue(Arrays.equals(original, cloned)); assertTrue(original != cloned); } public void testCloneLong() { assertEquals(null, ArrayUtils.clone((long[]) null)); long[] original = new long[] {0L, 1L}; long[] cloned = ArrayUtils.clone(original); assertTrue(Arrays.equals(original, cloned)); assertTrue(original != cloned); } public void testCloneInt() { assertEquals(null, ArrayUtils.clone((int[]) null)); int[] original = new int[] {5, 8}; int[] cloned = ArrayUtils.clone(original); assertTrue(Arrays.equals(original, cloned)); assertTrue(original != cloned); } public void testCloneShort() { assertEquals(null, ArrayUtils.clone((short[]) null)); short[] original = new short[] {1, 4}; short[] cloned = ArrayUtils.clone(original); assertTrue(Arrays.equals(original, cloned)); assertTrue(original != cloned); } public void testCloneChar() { assertEquals(null, ArrayUtils.clone((char[]) null)); char[] original = new char[] {'a', '4'}; char[] cloned = ArrayUtils.clone(original); assertTrue(Arrays.equals(original, cloned)); assertTrue(original != cloned); } public void testCloneByte() { assertEquals(null, ArrayUtils.clone((byte[]) null)); byte[] original = new byte[] {1, 6}; byte[] cloned = ArrayUtils.clone(original); assertTrue(Arrays.equals(original, cloned)); assertTrue(original != cloned); } public void testCloneDouble() { assertEquals(null, ArrayUtils.clone((double[]) null)); double[] original = new double[] {2.4d, 5.7d}; double[] cloned = ArrayUtils.clone(original); assertTrue(Arrays.equals(original, cloned)); assertTrue(original != cloned); } public void testCloneFloat() { assertEquals(null, ArrayUtils.clone((float[]) null)); float[] original = new float[] {2.6f, 6.4f}; float[] cloned = ArrayUtils.clone(original); assertTrue(Arrays.equals(original, cloned)); assertTrue(original != cloned); } //----------------------------------------------------------------------- public void testNullToEmptyBoolean() { // Test null handling assertEquals(ArrayUtils.EMPTY_BOOLEAN_ARRAY, ArrayUtils.nullToEmpty((boolean[]) null)); // Test valid array handling boolean[] original = new boolean[] {true, false}; assertEquals(original, ArrayUtils.nullToEmpty(original)); // Test empty array handling boolean[] empty = new boolean[]{}; boolean[] result = ArrayUtils.nullToEmpty(empty); assertEquals(ArrayUtils.EMPTY_BOOLEAN_ARRAY, result); assertTrue(empty != result); } public void testNullToEmptyLong() { // Test null handling assertEquals(ArrayUtils.EMPTY_LONG_ARRAY, ArrayUtils.nullToEmpty((long[]) null)); // Test valid array handling long[] original = new long[] {1L, 2L}; assertEquals(original, ArrayUtils.nullToEmpty(original)); // Test empty array handling long[] empty = new long[]{}; long[] result = ArrayUtils.nullToEmpty(empty); assertEquals(ArrayUtils.EMPTY_LONG_ARRAY, result); assertTrue(empty != result); } public void testNullToEmptyInt() { // Test null handling assertEquals(ArrayUtils.EMPTY_INT_ARRAY, ArrayUtils.nullToEmpty((int[]) null)); // Test valid array handling int[] original = new int[] {1, 2}; assertEquals(original, ArrayUtils.nullToEmpty(original)); // Test empty array handling int[] empty = new int[]{}; int[] result = ArrayUtils.nullToEmpty(empty); assertEquals(ArrayUtils.EMPTY_INT_ARRAY, result); assertTrue(empty != result); } public void testNullToEmptyShort() { // Test null handling assertEquals(ArrayUtils.EMPTY_SHORT_ARRAY, ArrayUtils.nullToEmpty((short[]) null)); // Test valid array handling short[] original = new short[] {1, 2}; assertEquals(original, ArrayUtils.nullToEmpty(original)); // Test empty array handling short[] empty = new short[]{}; short[] result = ArrayUtils.nullToEmpty(empty); assertEquals(ArrayUtils.EMPTY_SHORT_ARRAY, result); assertTrue(empty != result); } public void testNullToEmptyChar() { // Test null handling assertEquals(ArrayUtils.EMPTY_CHAR_ARRAY, ArrayUtils.nullToEmpty((char[]) null)); // Test valid array handling char[] original = new char[] {'a', 'b'}; assertEquals(original, ArrayUtils.nullToEmpty(original)); // Test empty array handling char[] empty = new char[]{}; char[] result = ArrayUtils.nullToEmpty(empty); assertEquals(ArrayUtils.EMPTY_CHAR_ARRAY, result); assertTrue(empty != result); } public void testNullToEmptyByte() { // Test null handling assertEquals(ArrayUtils.EMPTY_BYTE_ARRAY, ArrayUtils.nullToEmpty((byte[]) null)); // Test valid array handling byte[] original = new byte[] {0x0F, 0x0E}; assertEquals(original, ArrayUtils.nullToEmpty(original)); // Test empty array handling byte[] empty = new byte[]{}; byte[] result = ArrayUtils.nullToEmpty(empty); assertEquals(ArrayUtils.EMPTY_BYTE_ARRAY, result); assertTrue(empty != result); } public void testNullToEmptyDouble() { // Test null handling assertEquals(ArrayUtils.EMPTY_DOUBLE_ARRAY, ArrayUtils.nullToEmpty((double[]) null)); // Test valid array handling double[] original = new double[] {1L, 2L}; assertEquals(original, ArrayUtils.nullToEmpty(original)); // Test empty array handling double[] empty = new double[]{}; double[] result = ArrayUtils.nullToEmpty(empty); assertEquals(ArrayUtils.EMPTY_DOUBLE_ARRAY, result); assertTrue(empty != result); } public void testNullToEmptyFloat() { // Test null handling assertEquals(ArrayUtils.EMPTY_FLOAT_ARRAY, ArrayUtils.nullToEmpty((float[]) null)); // Test valid array handling float[] original = new float[] {2.6f, 3.8f}; assertEquals(original, ArrayUtils.nullToEmpty(original)); // Test empty array handling float[] empty = new float[]{}; float[] result = ArrayUtils.nullToEmpty(empty); assertEquals(ArrayUtils.EMPTY_FLOAT_ARRAY, result); assertTrue(empty != result); } public void testNullToEmptyObject() { // Test null handling assertEquals(ArrayUtils.EMPTY_OBJECT_ARRAY, ArrayUtils.nullToEmpty((Object[]) null)); // Test valid array handling Object[] original = new Object[] {Boolean.TRUE, Boolean.TRUE}; assertEquals(original, ArrayUtils.nullToEmpty(original)); // Test empty array handling Object[] empty = new Object[]{}; Object[] result = ArrayUtils.nullToEmpty(empty); assertEquals(ArrayUtils.EMPTY_OBJECT_ARRAY, result); assertTrue(empty != result); } public void testNullToEmptyString() { // Test null handling assertEquals(ArrayUtils.EMPTY_STRING_ARRAY, ArrayUtils.nullToEmpty((String[]) null)); // Test valid array handling String[] original = new String[] {"abc", "def"}; assertEquals(original, ArrayUtils.nullToEmpty(original)); // Test empty array handling String[] empty = new String[]{}; String[] result = ArrayUtils.nullToEmpty(empty); assertEquals(ArrayUtils.EMPTY_STRING_ARRAY, result); assertTrue(empty != result); } public void testNullToEmptyBooleanObject() { // Test null handling assertEquals(ArrayUtils.EMPTY_BOOLEAN_OBJECT_ARRAY, ArrayUtils.nullToEmpty((Boolean[]) null)); // Test valid array handling Boolean[] original = new Boolean[] {Boolean.TRUE, Boolean.FALSE}; assertEquals(original, ArrayUtils.nullToEmpty(original)); // Test empty array handling Boolean[] empty = new Boolean[]{}; Boolean[] result = ArrayUtils.nullToEmpty(empty); assertEquals(ArrayUtils.EMPTY_BOOLEAN_OBJECT_ARRAY, result); assertTrue(empty != result); } public void testNullToEmptyLongObject() { // Test null handling assertEquals(ArrayUtils.EMPTY_LONG_OBJECT_ARRAY, ArrayUtils.nullToEmpty((Long[]) null)); // Test valid array handling Long[] original = new Long[] {new Long(1L), new Long(2L)}; assertEquals(original, ArrayUtils.nullToEmpty(original)); // Test empty array handling Long[] empty = new Long[]{}; Long[] result = ArrayUtils.nullToEmpty(empty); assertEquals(ArrayUtils.EMPTY_LONG_OBJECT_ARRAY, result); assertTrue(empty != result); } public void testNullToEmptyIntObject() { // Test null handling assertEquals(ArrayUtils.EMPTY_INTEGER_OBJECT_ARRAY, ArrayUtils.nullToEmpty((Integer[]) null)); // Test valid array handling Integer[] original = new Integer[] {new Integer(1), new Integer(2)}; assertEquals(original, ArrayUtils.nullToEmpty(original)); // Test empty array handling Integer[] empty = new Integer[]{}; Integer[] result = ArrayUtils.nullToEmpty(empty); assertEquals(ArrayUtils.EMPTY_INTEGER_OBJECT_ARRAY, result); assertTrue(empty != result); } public void testNullToEmptyShortObject() { // Test null handling assertEquals(ArrayUtils.EMPTY_SHORT_OBJECT_ARRAY, ArrayUtils.nullToEmpty((Short[]) null)); // Test valid array handling Short[] original = new Short[] {new Short((short)1), new Short((short)2)}; assertEquals(original, ArrayUtils.nullToEmpty(original)); // Test empty array handling Short[] empty = new Short[]{}; Short[] result = ArrayUtils.nullToEmpty(empty); assertEquals(ArrayUtils.EMPTY_SHORT_OBJECT_ARRAY, result); assertTrue(empty != result); } public void testNullToEmptyCharObject() { // Test null handling assertEquals(ArrayUtils.EMPTY_CHARACTER_OBJECT_ARRAY, ArrayUtils.nullToEmpty((Character[]) null)); // Test valid array handling Character[] original = new Character[] {new Character('a'), new Character('b')}; assertEquals(original, ArrayUtils.nullToEmpty(original)); // Test empty array handling Character[] empty = new Character[]{}; Character[] result = ArrayUtils.nullToEmpty(empty); assertEquals(ArrayUtils.EMPTY_CHARACTER_OBJECT_ARRAY, result); assertTrue(empty != result); } public void testNullToEmptyByteObject() { // Test null handling assertEquals(ArrayUtils.EMPTY_BYTE_OBJECT_ARRAY, ArrayUtils.nullToEmpty((Byte[]) null)); // Test valid array handling Byte[] original = new Byte[] {new Byte((byte)0x0F), new Byte((byte)0x0E)}; assertEquals(original, ArrayUtils.nullToEmpty(original)); // Test empty array handling Byte[] empty = new Byte[]{}; Byte[] result = ArrayUtils.nullToEmpty(empty); assertEquals(ArrayUtils.EMPTY_BYTE_OBJECT_ARRAY, result); assertTrue(empty != result); } public void testNullToEmptyDoubleObject() { // Test null handling assertEquals(ArrayUtils.EMPTY_DOUBLE_OBJECT_ARRAY, ArrayUtils.nullToEmpty((Double[]) null)); // Test valid array handling Double[] original = new Double[] {new Double(1D), new Double(2D)}; assertEquals(original, ArrayUtils.nullToEmpty(original)); // Test empty array handling Double[] empty = new Double[]{}; Double[] result = ArrayUtils.nullToEmpty(empty); assertEquals(ArrayUtils.EMPTY_DOUBLE_OBJECT_ARRAY, result); assertTrue(empty != result); } public void testNullToEmptyFloatObject() { // Test null handling assertEquals(ArrayUtils.EMPTY_FLOAT_OBJECT_ARRAY, ArrayUtils.nullToEmpty((Float[]) null)); // Test valid array handling Float[] original = new Float[] {new Float(2.6f), new Float(3.8f)}; assertEquals(original, ArrayUtils.nullToEmpty(original)); // Test empty array handling Float[] empty = new Float[]{}; Float[] result = ArrayUtils.nullToEmpty(empty); assertEquals(ArrayUtils.EMPTY_FLOAT_OBJECT_ARRAY, result); assertTrue(empty != result); } //----------------------------------------------------------------------- public void testSubarrayObject() { Object[] nullArray = null; Object[] objectArray = { "a", "b", "c", "d", "e", "f"}; assertEquals("0 start, mid end", "abcd", StringUtils.join(ArrayUtils.subarray(objectArray, 0, 4))); assertEquals("0 start, length end", "abcdef", StringUtils.join(ArrayUtils.subarray(objectArray, 0, objectArray.length))); assertEquals("mid start, mid end", "bcd", StringUtils.join(ArrayUtils.subarray(objectArray, 1, 4))); assertEquals("mid start, length end", "bcdef", StringUtils.join(ArrayUtils.subarray(objectArray, 1, objectArray.length))); assertNull("null input", ArrayUtils.subarray(nullArray, 0, 3)); assertEquals("empty array", "", StringUtils.join(ArrayUtils.subarray(ArrayUtils.EMPTY_OBJECT_ARRAY, 1, 2))); assertEquals("start > end", "", StringUtils.join(ArrayUtils.subarray(objectArray, 4, 2))); assertEquals("start == end", "", StringUtils.join(ArrayUtils.subarray(objectArray, 3, 3))); assertEquals("start undershoot, normal end", "abcd", StringUtils.join(ArrayUtils.subarray(objectArray, -2, 4))); assertEquals("start overshoot, any end", "", StringUtils.join(ArrayUtils.subarray(objectArray, 33, 4))); assertEquals("normal start, end overshoot", "cdef", StringUtils.join(ArrayUtils.subarray(objectArray, 2, 33))); assertEquals("start undershoot, end overshoot", "abcdef", StringUtils.join(ArrayUtils.subarray(objectArray, -2, 12))); // array type tests Date[] dateArray = { new java.sql.Date(new Date().getTime()), new Date(), new Date(), new Date(), new Date() }; assertSame("Object type", Object.class, ArrayUtils.subarray(objectArray, 2, 4).getClass().getComponentType()); assertSame("java.util.Date type", java.util.Date.class, ArrayUtils.subarray(dateArray, 1, 4).getClass().getComponentType()); assertNotSame("java.sql.Date type", java.sql.Date.class, ArrayUtils.subarray(dateArray, 1, 4).getClass().getComponentType()); try { Object dummy = (java.sql.Date[])ArrayUtils.subarray(dateArray, 1,3); fail("Invalid downcast"); } catch (ClassCastException e) {} } public void testSubarrayLong() { long[] nullArray = null; long[] array = { 999910, 999911, 999912, 999913, 999914, 999915 }; long[] leftSubarray = { 999910, 999911, 999912, 999913 }; long[] midSubarray = { 999911, 999912, 999913, 999914 }; long[] rightSubarray = { 999912, 999913, 999914, 999915 }; assertTrue("0 start, mid end", ArrayUtils.isEquals(leftSubarray, ArrayUtils.subarray(array, 0, 4))); assertTrue("0 start, length end", ArrayUtils.isEquals(array, ArrayUtils.subarray(array, 0, array.length))); assertTrue("mid start, mid end", ArrayUtils.isEquals(midSubarray, ArrayUtils.subarray(array, 1, 5))); assertTrue("mid start, length end", ArrayUtils.isEquals(rightSubarray, ArrayUtils.subarray(array, 2, array.length))); assertNull("null input", ArrayUtils.subarray(nullArray, 0, 3)); assertEquals("empty array", ArrayUtils.EMPTY_LONG_ARRAY, ArrayUtils.subarray(ArrayUtils.EMPTY_LONG_ARRAY, 1, 2)); assertEquals("start > end", ArrayUtils.EMPTY_LONG_ARRAY, ArrayUtils.subarray(array, 4, 2)); assertEquals("start == end", ArrayUtils.EMPTY_LONG_ARRAY, ArrayUtils.subarray(array, 3, 3)); assertTrue("start undershoot, normal end", ArrayUtils.isEquals(leftSubarray, ArrayUtils.subarray(array, -2, 4))); assertEquals("start overshoot, any end", ArrayUtils.EMPTY_LONG_ARRAY, ArrayUtils.subarray(array, 33, 4)); assertTrue("normal start, end overshoot", ArrayUtils.isEquals(rightSubarray, ArrayUtils.subarray(array, 2, 33))); assertTrue("start undershoot, end overshoot", ArrayUtils.isEquals(array, ArrayUtils.subarray(array, -2, 12))); // empty-return tests assertSame("empty array, object test", ArrayUtils.EMPTY_LONG_ARRAY, ArrayUtils.subarray(ArrayUtils.EMPTY_LONG_ARRAY, 1, 2)); assertSame("start > end, object test", ArrayUtils.EMPTY_LONG_ARRAY, ArrayUtils.subarray(array, 4, 1)); assertSame("start == end, object test", ArrayUtils.EMPTY_LONG_ARRAY, ArrayUtils.subarray(array, 3, 3)); assertSame("start overshoot, any end, object test", ArrayUtils.EMPTY_LONG_ARRAY, ArrayUtils.subarray(array, 8733, 4)); // array type tests assertSame("long type", long.class, ArrayUtils.subarray(array, 2, 4).getClass().getComponentType()); } public void testSubarrayInt() { int[] nullArray = null; int[] array = { 10, 11, 12, 13, 14, 15 }; int[] leftSubarray = { 10, 11, 12, 13 }; int[] midSubarray = { 11, 12, 13, 14 }; int[] rightSubarray = { 12, 13, 14, 15 }; assertTrue("0 start, mid end", ArrayUtils.isEquals(leftSubarray, ArrayUtils.subarray(array, 0, 4))); assertTrue("0 start, length end", ArrayUtils.isEquals(array, ArrayUtils.subarray(array, 0, array.length))); assertTrue("mid start, mid end", ArrayUtils.isEquals(midSubarray, ArrayUtils.subarray(array, 1, 5))); assertTrue("mid start, length end", ArrayUtils.isEquals(rightSubarray, ArrayUtils.subarray(array, 2, array.length))); assertNull("null input", ArrayUtils.subarray(nullArray, 0, 3)); assertEquals("empty array", ArrayUtils.EMPTY_INT_ARRAY, ArrayUtils.subarray(ArrayUtils.EMPTY_INT_ARRAY, 1, 2)); assertEquals("start > end", ArrayUtils.EMPTY_INT_ARRAY, ArrayUtils.subarray(array, 4, 2)); assertEquals("start == end", ArrayUtils.EMPTY_INT_ARRAY, ArrayUtils.subarray(array, 3, 3)); assertTrue("start undershoot, normal end", ArrayUtils.isEquals(leftSubarray, ArrayUtils.subarray(array, -2, 4))); assertEquals("start overshoot, any end", ArrayUtils.EMPTY_INT_ARRAY, ArrayUtils.subarray(array, 33, 4)); assertTrue("normal start, end overshoot", ArrayUtils.isEquals(rightSubarray, ArrayUtils.subarray(array, 2, 33))); assertTrue("start undershoot, end overshoot", ArrayUtils.isEquals(array, ArrayUtils.subarray(array, -2, 12))); // empty-return tests assertSame("empty array, object test", ArrayUtils.EMPTY_INT_ARRAY, ArrayUtils.subarray(ArrayUtils.EMPTY_INT_ARRAY, 1, 2)); assertSame("start > end, object test", ArrayUtils.EMPTY_INT_ARRAY, ArrayUtils.subarray(array, 4, 1)); assertSame("start == end, object test", ArrayUtils.EMPTY_INT_ARRAY, ArrayUtils.subarray(array, 3, 3)); assertSame("start overshoot, any end, object test", ArrayUtils.EMPTY_INT_ARRAY, ArrayUtils.subarray(array, 8733, 4)); // array type tests assertSame("int type", int.class, ArrayUtils.subarray(array, 2, 4).getClass().getComponentType()); } public void testSubarrayShort() { short[] nullArray = null; short[] array = { 10, 11, 12, 13, 14, 15 }; short[] leftSubarray = { 10, 11, 12, 13 }; short[] midSubarray = { 11, 12, 13, 14 }; short[] rightSubarray = { 12, 13, 14, 15 }; assertTrue("0 start, mid end", ArrayUtils.isEquals(leftSubarray, ArrayUtils.subarray(array, 0, 4))); assertTrue("0 start, length end", ArrayUtils.isEquals(array, ArrayUtils.subarray(array, 0, array.length))); assertTrue("mid start, mid end", ArrayUtils.isEquals(midSubarray, ArrayUtils.subarray(array, 1, 5))); assertTrue("mid start, length end", ArrayUtils.isEquals(rightSubarray, ArrayUtils.subarray(array, 2, array.length))); assertNull("null input", ArrayUtils.subarray(nullArray, 0, 3)); assertEquals("empty array", ArrayUtils.EMPTY_SHORT_ARRAY, ArrayUtils.subarray(ArrayUtils.EMPTY_SHORT_ARRAY, 1, 2)); assertEquals("start > end", ArrayUtils.EMPTY_SHORT_ARRAY, ArrayUtils.subarray(array, 4, 2)); assertEquals("start == end", ArrayUtils.EMPTY_SHORT_ARRAY, ArrayUtils.subarray(array, 3, 3)); assertTrue("start undershoot, normal end", ArrayUtils.isEquals(leftSubarray, ArrayUtils.subarray(array, -2, 4))); assertEquals("start overshoot, any end", ArrayUtils.EMPTY_SHORT_ARRAY, ArrayUtils.subarray(array, 33, 4)); assertTrue("normal start, end overshoot", ArrayUtils.isEquals(rightSubarray, ArrayUtils.subarray(array, 2, 33))); assertTrue("start undershoot, end overshoot", ArrayUtils.isEquals(array, ArrayUtils.subarray(array, -2, 12))); // empty-return tests assertSame("empty array, object test", ArrayUtils.EMPTY_SHORT_ARRAY, ArrayUtils.subarray(ArrayUtils.EMPTY_SHORT_ARRAY, 1, 2)); assertSame("start > end, object test", ArrayUtils.EMPTY_SHORT_ARRAY, ArrayUtils.subarray(array, 4, 1)); assertSame("start == end, object test", ArrayUtils.EMPTY_SHORT_ARRAY, ArrayUtils.subarray(array, 3, 3)); assertSame("start overshoot, any end, object test", ArrayUtils.EMPTY_SHORT_ARRAY, ArrayUtils.subarray(array, 8733, 4)); // array type tests assertSame("short type", short.class, ArrayUtils.subarray(array, 2, 4).getClass().getComponentType()); } public void testSubarrChar() { char[] nullArray = null; char[] array = { 'a', 'b', 'c', 'd', 'e', 'f' }; char[] leftSubarray = { 'a', 'b', 'c', 'd', }; char[] midSubarray = { 'b', 'c', 'd', 'e', }; char[] rightSubarray = { 'c', 'd', 'e', 'f', }; assertTrue("0 start, mid end", ArrayUtils.isEquals(leftSubarray, ArrayUtils.subarray(array, 0, 4))); assertTrue("0 start, length end", ArrayUtils.isEquals(array, ArrayUtils.subarray(array, 0, array.length))); assertTrue("mid start, mid end", ArrayUtils.isEquals(midSubarray, ArrayUtils.subarray(array, 1, 5))); assertTrue("mid start, length end", ArrayUtils.isEquals(rightSubarray, ArrayUtils.subarray(array, 2, array.length))); assertNull("null input", ArrayUtils.subarray(nullArray, 0, 3)); assertEquals("empty array", ArrayUtils.EMPTY_CHAR_ARRAY, ArrayUtils.subarray(ArrayUtils.EMPTY_CHAR_ARRAY, 1, 2)); assertEquals("start > end", ArrayUtils.EMPTY_CHAR_ARRAY, ArrayUtils.subarray(array, 4, 2)); assertEquals("start == end", ArrayUtils.EMPTY_CHAR_ARRAY, ArrayUtils.subarray(array, 3, 3)); assertTrue("start undershoot, normal end", ArrayUtils.isEquals(leftSubarray, ArrayUtils.subarray(array, -2, 4))); assertEquals("start overshoot, any end", ArrayUtils.EMPTY_CHAR_ARRAY, ArrayUtils.subarray(array, 33, 4)); assertTrue("normal start, end overshoot", ArrayUtils.isEquals(rightSubarray, ArrayUtils.subarray(array, 2, 33))); assertTrue("start undershoot, end overshoot", ArrayUtils.isEquals(array, ArrayUtils.subarray(array, -2, 12))); // empty-return tests assertSame("empty array, object test", ArrayUtils.EMPTY_CHAR_ARRAY, ArrayUtils.subarray(ArrayUtils.EMPTY_CHAR_ARRAY, 1, 2)); assertSame("start > end, object test", ArrayUtils.EMPTY_CHAR_ARRAY, ArrayUtils.subarray(array, 4, 1)); assertSame("start == end, object test", ArrayUtils.EMPTY_CHAR_ARRAY, ArrayUtils.subarray(array, 3, 3)); assertSame("start overshoot, any end, object test", ArrayUtils.EMPTY_CHAR_ARRAY, ArrayUtils.subarray(array, 8733, 4)); // array type tests assertSame("char type", char.class, ArrayUtils.subarray(array, 2, 4).getClass().getComponentType()); } public void testSubarrayByte() { byte[] nullArray = null; byte[] array = { 10, 11, 12, 13, 14, 15 }; byte[] leftSubarray = { 10, 11, 12, 13 }; byte[] midSubarray = { 11, 12, 13, 14 }; byte[] rightSubarray = { 12, 13, 14, 15 }; assertTrue("0 start, mid end", ArrayUtils.isEquals(leftSubarray, ArrayUtils.subarray(array, 0, 4))); assertTrue("0 start, length end", ArrayUtils.isEquals(array, ArrayUtils.subarray(array, 0, array.length))); assertTrue("mid start, mid end", ArrayUtils.isEquals(midSubarray, ArrayUtils.subarray(array, 1, 5))); assertTrue("mid start, length end", ArrayUtils.isEquals(rightSubarray, ArrayUtils.subarray(array, 2, array.length))); assertNull("null input", ArrayUtils.subarray(nullArray, 0, 3)); assertEquals("empty array", ArrayUtils.EMPTY_BYTE_ARRAY, ArrayUtils.subarray(ArrayUtils.EMPTY_BYTE_ARRAY, 1, 2)); assertEquals("start > end", ArrayUtils.EMPTY_BYTE_ARRAY, ArrayUtils.subarray(array, 4, 2)); assertEquals("start == end", ArrayUtils.EMPTY_BYTE_ARRAY, ArrayUtils.subarray(array, 3, 3)); assertTrue("start undershoot, normal end", ArrayUtils.isEquals(leftSubarray, ArrayUtils.subarray(array, -2, 4))); assertEquals("start overshoot, any end", ArrayUtils.EMPTY_BYTE_ARRAY, ArrayUtils.subarray(array, 33, 4)); assertTrue("normal start, end overshoot", ArrayUtils.isEquals(rightSubarray, ArrayUtils.subarray(array, 2, 33))); assertTrue("start undershoot, end overshoot", ArrayUtils.isEquals(array, ArrayUtils.subarray(array, -2, 12))); // empty-return tests assertSame("empty array, object test", ArrayUtils.EMPTY_BYTE_ARRAY, ArrayUtils.subarray(ArrayUtils.EMPTY_BYTE_ARRAY, 1, 2)); assertSame("start > end, object test", ArrayUtils.EMPTY_BYTE_ARRAY, ArrayUtils.subarray(array, 4, 1)); assertSame("start == end, object test", ArrayUtils.EMPTY_BYTE_ARRAY, ArrayUtils.subarray(array, 3, 3)); assertSame("start overshoot, any end, object test", ArrayUtils.EMPTY_BYTE_ARRAY, ArrayUtils.subarray(array, 8733, 4)); // array type tests assertSame("byte type", byte.class, ArrayUtils.subarray(array, 2, 4).getClass().getComponentType()); } public void testSubarrayDouble() { double[] nullArray = null; double[] array = { 10.123, 11.234, 12.345, 13.456, 14.567, 15.678 }; double[] leftSubarray = { 10.123, 11.234, 12.345, 13.456, }; double[] midSubarray = { 11.234, 12.345, 13.456, 14.567, }; double[] rightSubarray = { 12.345, 13.456, 14.567, 15.678 }; assertTrue("0 start, mid end", ArrayUtils.isEquals(leftSubarray, ArrayUtils.subarray(array, 0, 4))); assertTrue("0 start, length end", ArrayUtils.isEquals(array, ArrayUtils.subarray(array, 0, array.length))); assertTrue("mid start, mid end", ArrayUtils.isEquals(midSubarray, ArrayUtils.subarray(array, 1, 5))); assertTrue("mid start, length end", ArrayUtils.isEquals(rightSubarray, ArrayUtils.subarray(array, 2, array.length))); assertNull("null input", ArrayUtils.subarray(nullArray, 0, 3)); assertEquals("empty array", ArrayUtils.EMPTY_DOUBLE_ARRAY, ArrayUtils.subarray(ArrayUtils.EMPTY_DOUBLE_ARRAY, 1, 2)); assertEquals("start > end", ArrayUtils.EMPTY_DOUBLE_ARRAY, ArrayUtils.subarray(array, 4, 2)); assertEquals("start == end", ArrayUtils.EMPTY_DOUBLE_ARRAY, ArrayUtils.subarray(array, 3, 3)); assertTrue("start undershoot, normal end", ArrayUtils.isEquals(leftSubarray, ArrayUtils.subarray(array, -2, 4))); assertEquals("start overshoot, any end", ArrayUtils.EMPTY_DOUBLE_ARRAY, ArrayUtils.subarray(array, 33, 4)); assertTrue("normal start, end overshoot", ArrayUtils.isEquals(rightSubarray, ArrayUtils.subarray(array, 2, 33))); assertTrue("start undershoot, end overshoot", ArrayUtils.isEquals(array, ArrayUtils.subarray(array, -2, 12))); // empty-return tests assertSame("empty array, object test", ArrayUtils.EMPTY_DOUBLE_ARRAY, ArrayUtils.subarray(ArrayUtils.EMPTY_DOUBLE_ARRAY, 1, 2)); assertSame("start > end, object test", ArrayUtils.EMPTY_DOUBLE_ARRAY, ArrayUtils.subarray(array, 4, 1)); assertSame("start == end, object test", ArrayUtils.EMPTY_DOUBLE_ARRAY, ArrayUtils.subarray(array, 3, 3)); assertSame("start overshoot, any end, object test", ArrayUtils.EMPTY_DOUBLE_ARRAY, ArrayUtils.subarray(array, 8733, 4)); // array type tests assertSame("double type", double.class, ArrayUtils.subarray(array, 2, 4).getClass().getComponentType()); } public void testSubarrayFloat() { float[] nullArray = null; float[] array = { 10, 11, 12, 13, 14, 15 }; float[] leftSubarray = { 10, 11, 12, 13 }; float[] midSubarray = { 11, 12, 13, 14 }; float[] rightSubarray = { 12, 13, 14, 15 }; assertTrue("0 start, mid end", ArrayUtils.isEquals(leftSubarray, ArrayUtils.subarray(array, 0, 4))); assertTrue("0 start, length end", ArrayUtils.isEquals(array, ArrayUtils.subarray(array, 0, array.length))); assertTrue("mid start, mid end", ArrayUtils.isEquals(midSubarray, ArrayUtils.subarray(array, 1, 5))); assertTrue("mid start, length end", ArrayUtils.isEquals(rightSubarray, ArrayUtils.subarray(array, 2, array.length))); assertNull("null input", ArrayUtils.subarray(nullArray, 0, 3)); assertEquals("empty array", ArrayUtils.EMPTY_FLOAT_ARRAY, ArrayUtils.subarray(ArrayUtils.EMPTY_FLOAT_ARRAY, 1, 2)); assertEquals("start > end", ArrayUtils.EMPTY_FLOAT_ARRAY, ArrayUtils.subarray(array, 4, 2)); assertEquals("start == end", ArrayUtils.EMPTY_FLOAT_ARRAY, ArrayUtils.subarray(array, 3, 3)); assertTrue("start undershoot, normal end", ArrayUtils.isEquals(leftSubarray, ArrayUtils.subarray(array, -2, 4))); assertEquals("start overshoot, any end", ArrayUtils.EMPTY_FLOAT_ARRAY, ArrayUtils.subarray(array, 33, 4)); assertTrue("normal start, end overshoot", ArrayUtils.isEquals(rightSubarray, ArrayUtils.subarray(array, 2, 33))); assertTrue("start undershoot, end overshoot", ArrayUtils.isEquals(array, ArrayUtils.subarray(array, -2, 12))); // empty-return tests assertSame("empty array, object test", ArrayUtils.EMPTY_FLOAT_ARRAY, ArrayUtils.subarray(ArrayUtils.EMPTY_FLOAT_ARRAY, 1, 2)); assertSame("start > end, object test", ArrayUtils.EMPTY_FLOAT_ARRAY, ArrayUtils.subarray(array, 4, 1)); assertSame("start == end, object test", ArrayUtils.EMPTY_FLOAT_ARRAY, ArrayUtils.subarray(array, 3, 3)); assertSame("start overshoot, any end, object test", ArrayUtils.EMPTY_FLOAT_ARRAY, ArrayUtils.subarray(array, 8733, 4)); // array type tests assertSame("float type", float.class, ArrayUtils.subarray(array, 2, 4).getClass().getComponentType()); } public void testSubarrayBoolean() { boolean[] nullArray = null; boolean[] array = { true, true, false, true, false, true }; boolean[] leftSubarray = { true, true, false, true }; boolean[] midSubarray = { true, false, true, false }; boolean[] rightSubarray = { false, true, false, true }; assertTrue("0 start, mid end", ArrayUtils.isEquals(leftSubarray, ArrayUtils.subarray(array, 0, 4))); assertTrue("0 start, length end", ArrayUtils.isEquals(array, ArrayUtils.subarray(array, 0, array.length))); assertTrue("mid start, mid end", ArrayUtils.isEquals(midSubarray, ArrayUtils.subarray(array, 1, 5))); assertTrue("mid start, length end", ArrayUtils.isEquals(rightSubarray, ArrayUtils.subarray(array, 2, array.length))); assertNull("null input", ArrayUtils.subarray(nullArray, 0, 3)); assertEquals("empty array", ArrayUtils.EMPTY_BOOLEAN_ARRAY, ArrayUtils.subarray(ArrayUtils.EMPTY_BOOLEAN_ARRAY, 1, 2)); assertEquals("start > end", ArrayUtils.EMPTY_BOOLEAN_ARRAY, ArrayUtils.subarray(array, 4, 2)); assertEquals("start == end", ArrayUtils.EMPTY_BOOLEAN_ARRAY, ArrayUtils.subarray(array, 3, 3)); assertTrue("start undershoot, normal end", ArrayUtils.isEquals(leftSubarray, ArrayUtils.subarray(array, -2, 4))); assertEquals("start overshoot, any end", ArrayUtils.EMPTY_BOOLEAN_ARRAY, ArrayUtils.subarray(array, 33, 4)); assertTrue("normal start, end overshoot", ArrayUtils.isEquals(rightSubarray, ArrayUtils.subarray(array, 2, 33))); assertTrue("start undershoot, end overshoot", ArrayUtils.isEquals(array, ArrayUtils.subarray(array, -2, 12))); // empty-return tests assertSame("empty array, object test", ArrayUtils.EMPTY_BOOLEAN_ARRAY, ArrayUtils.subarray(ArrayUtils.EMPTY_BOOLEAN_ARRAY, 1, 2)); assertSame("start > end, object test", ArrayUtils.EMPTY_BOOLEAN_ARRAY, ArrayUtils.subarray(array, 4, 1)); assertSame("start == end, object test", ArrayUtils.EMPTY_BOOLEAN_ARRAY, ArrayUtils.subarray(array, 3, 3)); assertSame("start overshoot, any end, object test", ArrayUtils.EMPTY_BOOLEAN_ARRAY, ArrayUtils.subarray(array, 8733, 4)); // array type tests assertSame("boolean type", boolean.class, ArrayUtils.subarray(array, 2, 4).getClass().getComponentType()); } //----------------------------------------------------------------------- public void testSameLength() { Object[] nullArray = null; Object[] emptyArray = new Object[0]; Object[] oneArray = new Object[] {"pick"}; Object[] twoArray = new Object[] {"pick", "stick"}; assertEquals(true, ArrayUtils.isSameLength(nullArray, nullArray)); assertEquals(true, ArrayUtils.isSameLength(nullArray, emptyArray)); assertEquals(false, ArrayUtils.isSameLength(nullArray, oneArray)); assertEquals(false, ArrayUtils.isSameLength(nullArray, twoArray)); assertEquals(true, ArrayUtils.isSameLength(emptyArray, nullArray)); assertEquals(true, ArrayUtils.isSameLength(emptyArray, emptyArray)); assertEquals(false, ArrayUtils.isSameLength(emptyArray, oneArray)); assertEquals(false, ArrayUtils.isSameLength(emptyArray, twoArray)); assertEquals(false, ArrayUtils.isSameLength(oneArray, nullArray)); assertEquals(false, ArrayUtils.isSameLength(oneArray, emptyArray)); assertEquals(true, ArrayUtils.isSameLength(oneArray, oneArray)); assertEquals(false, ArrayUtils.isSameLength(oneArray, twoArray)); assertEquals(false, ArrayUtils.isSameLength(twoArray, nullArray)); assertEquals(false, ArrayUtils.isSameLength(twoArray, emptyArray)); assertEquals(false, ArrayUtils.isSameLength(twoArray, oneArray)); assertEquals(true, ArrayUtils.isSameLength(twoArray, twoArray)); } public void testSameLengthBoolean() { boolean[] nullArray = null; boolean[] emptyArray = new boolean[0]; boolean[] oneArray = new boolean[] {true}; boolean[] twoArray = new boolean[] {true, false}; assertEquals(true, ArrayUtils.isSameLength(nullArray, nullArray)); assertEquals(true, ArrayUtils.isSameLength(nullArray, emptyArray)); assertEquals(false, ArrayUtils.isSameLength(nullArray, oneArray)); assertEquals(false, ArrayUtils.isSameLength(nullArray, twoArray)); assertEquals(true, ArrayUtils.isSameLength(emptyArray, nullArray)); assertEquals(true, ArrayUtils.isSameLength(emptyArray, emptyArray)); assertEquals(false, ArrayUtils.isSameLength(emptyArray, oneArray)); assertEquals(false, ArrayUtils.isSameLength(emptyArray, twoArray)); assertEquals(false, ArrayUtils.isSameLength(oneArray, nullArray)); assertEquals(false, ArrayUtils.isSameLength(oneArray, emptyArray)); assertEquals(true, ArrayUtils.isSameLength(oneArray, oneArray)); assertEquals(false, ArrayUtils.isSameLength(oneArray, twoArray)); assertEquals(false, ArrayUtils.isSameLength(twoArray, nullArray)); assertEquals(false, ArrayUtils.isSameLength(twoArray, emptyArray)); assertEquals(false, ArrayUtils.isSameLength(twoArray, oneArray)); assertEquals(true, ArrayUtils.isSameLength(twoArray, twoArray)); } public void testSameLengthLong() { long[] nullArray = null; long[] emptyArray = new long[0]; long[] oneArray = new long[] {0L}; long[] twoArray = new long[] {0L, 76L}; assertEquals(true, ArrayUtils.isSameLength(nullArray, nullArray)); assertEquals(true, ArrayUtils.isSameLength(nullArray, emptyArray)); assertEquals(false, ArrayUtils.isSameLength(nullArray, oneArray)); assertEquals(false, ArrayUtils.isSameLength(nullArray, twoArray)); assertEquals(true, ArrayUtils.isSameLength(emptyArray, nullArray)); assertEquals(true, ArrayUtils.isSameLength(emptyArray, emptyArray)); assertEquals(false, ArrayUtils.isSameLength(emptyArray, oneArray)); assertEquals(false, ArrayUtils.isSameLength(emptyArray, twoArray)); assertEquals(false, ArrayUtils.isSameLength(oneArray, nullArray)); assertEquals(false, ArrayUtils.isSameLength(oneArray, emptyArray)); assertEquals(true, ArrayUtils.isSameLength(oneArray, oneArray)); assertEquals(false, ArrayUtils.isSameLength(oneArray, twoArray)); assertEquals(false, ArrayUtils.isSameLength(twoArray, nullArray)); assertEquals(false, ArrayUtils.isSameLength(twoArray, emptyArray)); assertEquals(false, ArrayUtils.isSameLength(twoArray, oneArray)); assertEquals(true, ArrayUtils.isSameLength(twoArray, twoArray)); } public void testSameLengthInt() { int[] nullArray = null; int[] emptyArray = new int[0]; int[] oneArray = new int[] {4}; int[] twoArray = new int[] {5, 7}; assertEquals(true, ArrayUtils.isSameLength(nullArray, nullArray)); assertEquals(true, ArrayUtils.isSameLength(nullArray, emptyArray)); assertEquals(false, ArrayUtils.isSameLength(nullArray, oneArray)); assertEquals(false, ArrayUtils.isSameLength(nullArray, twoArray)); assertEquals(true, ArrayUtils.isSameLength(emptyArray, nullArray)); assertEquals(true, ArrayUtils.isSameLength(emptyArray, emptyArray)); assertEquals(false, ArrayUtils.isSameLength(emptyArray, oneArray)); assertEquals(false, ArrayUtils.isSameLength(emptyArray, twoArray)); assertEquals(false, ArrayUtils.isSameLength(oneArray, nullArray)); assertEquals(false, ArrayUtils.isSameLength(oneArray, emptyArray)); assertEquals(true, ArrayUtils.isSameLength(oneArray, oneArray)); assertEquals(false, ArrayUtils.isSameLength(oneArray, twoArray)); assertEquals(false, ArrayUtils.isSameLength(twoArray, nullArray)); assertEquals(false, ArrayUtils.isSameLength(twoArray, emptyArray)); assertEquals(false, ArrayUtils.isSameLength(twoArray, oneArray)); assertEquals(true, ArrayUtils.isSameLength(twoArray, twoArray)); } public void testSameLengthShort() { short[] nullArray = null; short[] emptyArray = new short[0]; short[] oneArray = new short[] {4}; short[] twoArray = new short[] {6, 8}; assertEquals(true, ArrayUtils.isSameLength(nullArray, nullArray)); assertEquals(true, ArrayUtils.isSameLength(nullArray, emptyArray)); assertEquals(false, ArrayUtils.isSameLength(nullArray, oneArray)); assertEquals(false, ArrayUtils.isSameLength(nullArray, twoArray)); assertEquals(true, ArrayUtils.isSameLength(emptyArray, nullArray)); assertEquals(true, ArrayUtils.isSameLength(emptyArray, emptyArray)); assertEquals(false, ArrayUtils.isSameLength(emptyArray, oneArray)); assertEquals(false, ArrayUtils.isSameLength(emptyArray, twoArray)); assertEquals(false, ArrayUtils.isSameLength(oneArray, nullArray)); assertEquals(false, ArrayUtils.isSameLength(oneArray, emptyArray)); assertEquals(true, ArrayUtils.isSameLength(oneArray, oneArray)); assertEquals(false, ArrayUtils.isSameLength(oneArray, twoArray)); assertEquals(false, ArrayUtils.isSameLength(twoArray, nullArray)); assertEquals(false, ArrayUtils.isSameLength(twoArray, emptyArray)); assertEquals(false, ArrayUtils.isSameLength(twoArray, oneArray)); assertEquals(true, ArrayUtils.isSameLength(twoArray, twoArray)); } public void testSameLengthChar() { char[] nullArray = null; char[] emptyArray = new char[0]; char[] oneArray = new char[] {'f'}; char[] twoArray = new char[] {'d', 't'}; assertEquals(true, ArrayUtils.isSameLength(nullArray, nullArray)); assertEquals(true, ArrayUtils.isSameLength(nullArray, emptyArray)); assertEquals(false, ArrayUtils.isSameLength(nullArray, oneArray)); assertEquals(false, ArrayUtils.isSameLength(nullArray, twoArray)); assertEquals(true, ArrayUtils.isSameLength(emptyArray, nullArray)); assertEquals(true, ArrayUtils.isSameLength(emptyArray, emptyArray)); assertEquals(false, ArrayUtils.isSameLength(emptyArray, oneArray)); assertEquals(false, ArrayUtils.isSameLength(emptyArray, twoArray)); assertEquals(false, ArrayUtils.isSameLength(oneArray, nullArray)); assertEquals(false, ArrayUtils.isSameLength(oneArray, emptyArray)); assertEquals(true, ArrayUtils.isSameLength(oneArray, oneArray)); assertEquals(false, ArrayUtils.isSameLength(oneArray, twoArray)); assertEquals(false, ArrayUtils.isSameLength(twoArray, nullArray)); assertEquals(false, ArrayUtils.isSameLength(twoArray, emptyArray)); assertEquals(false, ArrayUtils.isSameLength(twoArray, oneArray)); assertEquals(true, ArrayUtils.isSameLength(twoArray, twoArray)); } public void testSameLengthByte() { byte[] nullArray = null; byte[] emptyArray = new byte[0]; byte[] oneArray = new byte[] {3}; byte[] twoArray = new byte[] {4, 6}; assertEquals(true, ArrayUtils.isSameLength(nullArray, nullArray)); assertEquals(true, ArrayUtils.isSameLength(nullArray, emptyArray)); assertEquals(false, ArrayUtils.isSameLength(nullArray, oneArray)); assertEquals(false, ArrayUtils.isSameLength(nullArray, twoArray)); assertEquals(true, ArrayUtils.isSameLength(emptyArray, nullArray)); assertEquals(true, ArrayUtils.isSameLength(emptyArray, emptyArray)); assertEquals(false, ArrayUtils.isSameLength(emptyArray, oneArray)); assertEquals(false, ArrayUtils.isSameLength(emptyArray, twoArray)); assertEquals(false, ArrayUtils.isSameLength(oneArray, nullArray)); assertEquals(false, ArrayUtils.isSameLength(oneArray, emptyArray)); assertEquals(true, ArrayUtils.isSameLength(oneArray, oneArray)); assertEquals(false, ArrayUtils.isSameLength(oneArray, twoArray)); assertEquals(false, ArrayUtils.isSameLength(twoArray, nullArray)); assertEquals(false, ArrayUtils.isSameLength(twoArray, emptyArray)); assertEquals(false, ArrayUtils.isSameLength(twoArray, oneArray)); assertEquals(true, ArrayUtils.isSameLength(twoArray, twoArray)); } public void testSameLengthDouble() { double[] nullArray = null; double[] emptyArray = new double[0]; double[] oneArray = new double[] {1.3d}; double[] twoArray = new double[] {4.5d, 6.3d}; assertEquals(true, ArrayUtils.isSameLength(nullArray, nullArray)); assertEquals(true, ArrayUtils.isSameLength(nullArray, emptyArray)); assertEquals(false, ArrayUtils.isSameLength(nullArray, oneArray)); assertEquals(false, ArrayUtils.isSameLength(nullArray, twoArray)); assertEquals(true, ArrayUtils.isSameLength(emptyArray, nullArray)); assertEquals(true, ArrayUtils.isSameLength(emptyArray, emptyArray)); assertEquals(false, ArrayUtils.isSameLength(emptyArray, oneArray)); assertEquals(false, ArrayUtils.isSameLength(emptyArray, twoArray)); assertEquals(false, ArrayUtils.isSameLength(oneArray, nullArray)); assertEquals(false, ArrayUtils.isSameLength(oneArray, emptyArray)); assertEquals(true, ArrayUtils.isSameLength(oneArray, oneArray)); assertEquals(false, ArrayUtils.isSameLength(oneArray, twoArray)); assertEquals(false, ArrayUtils.isSameLength(twoArray, nullArray)); assertEquals(false, ArrayUtils.isSameLength(twoArray, emptyArray)); assertEquals(false, ArrayUtils.isSameLength(twoArray, oneArray)); assertEquals(true, ArrayUtils.isSameLength(twoArray, twoArray)); } public void testSameLengthFloat() { float[] nullArray = null; float[] emptyArray = new float[0]; float[] oneArray = new float[] {2.5f}; float[] twoArray = new float[] {6.4f, 5.8f}; assertEquals(true, ArrayUtils.isSameLength(nullArray, nullArray)); assertEquals(true, ArrayUtils.isSameLength(nullArray, emptyArray)); assertEquals(false, ArrayUtils.isSameLength(nullArray, oneArray)); assertEquals(false, ArrayUtils.isSameLength(nullArray, twoArray)); assertEquals(true, ArrayUtils.isSameLength(emptyArray, nullArray)); assertEquals(true, ArrayUtils.isSameLength(emptyArray, emptyArray)); assertEquals(false, ArrayUtils.isSameLength(emptyArray, oneArray)); assertEquals(false, ArrayUtils.isSameLength(emptyArray, twoArray)); assertEquals(false, ArrayUtils.isSameLength(oneArray, nullArray)); assertEquals(false, ArrayUtils.isSameLength(oneArray, emptyArray)); assertEquals(true, ArrayUtils.isSameLength(oneArray, oneArray)); assertEquals(false, ArrayUtils.isSameLength(oneArray, twoArray)); assertEquals(false, ArrayUtils.isSameLength(twoArray, nullArray)); assertEquals(false, ArrayUtils.isSameLength(twoArray, emptyArray)); assertEquals(false, ArrayUtils.isSameLength(twoArray, oneArray)); assertEquals(true, ArrayUtils.isSameLength(twoArray, twoArray)); } //----------------------------------------------------------------------- public void testSameType() { try { ArrayUtils.isSameType(null, null); fail(); } catch (IllegalArgumentException ex) {} try { ArrayUtils.isSameType(null, new Object[0]); fail(); } catch (IllegalArgumentException ex) {} try { ArrayUtils.isSameType(new Object[0], null); fail(); } catch (IllegalArgumentException ex) {} assertEquals(true, ArrayUtils.isSameType(new Object[0], new Object[0])); assertEquals(false, ArrayUtils.isSameType(new String[0], new Object[0])); assertEquals(true, ArrayUtils.isSameType(new String[0][0], new String[0][0])); assertEquals(false, ArrayUtils.isSameType(new String[0], new String[0][0])); assertEquals(false, ArrayUtils.isSameType(new String[0][0], new String[0])); } //----------------------------------------------------------------------- public void testReverse() { StringBuffer str1 = new StringBuffer("pick"); String str2 = "a"; String[] str3 = new String[] {"stick"}; String str4 = "up"; Object[] array = new Object[] {str1, str2, str3}; ArrayUtils.reverse(array); assertEquals(array[0], str3); assertEquals(array[1], str2); assertEquals(array[2], str1); array = new Object[] {str1, str2, str3, str4}; ArrayUtils.reverse(array); assertEquals(array[0], str4); assertEquals(array[1], str3); assertEquals(array[2], str2); assertEquals(array[3], str1); array = null; ArrayUtils.reverse(array); assertEquals(null, array); } public void testReverseLong() { long[] array = new long[] {1L, 2L, 3L}; ArrayUtils.reverse(array); assertEquals(array[0], 3L); assertEquals(array[1], 2L); assertEquals(array[2], 1L); array = null; ArrayUtils.reverse(array); assertEquals(null, array); } public void testReverseInt() { int[] array = new int[] {1, 2, 3}; ArrayUtils.reverse(array); assertEquals(array[0], 3); assertEquals(array[1], 2); assertEquals(array[2], 1); array = null; ArrayUtils.reverse(array); assertEquals(null, array); } public void testReverseShort() { short[] array = new short[] {1, 2, 3}; ArrayUtils.reverse(array); assertEquals(array[0], 3); assertEquals(array[1], 2); assertEquals(array[2], 1); array = null; ArrayUtils.reverse(array); assertEquals(null, array); } public void testReverseChar() { char[] array = new char[] {'a', 'f', 'C'}; ArrayUtils.reverse(array); assertEquals(array[0], 'C'); assertEquals(array[1], 'f'); assertEquals(array[2], 'a'); array = null; ArrayUtils.reverse(array); assertEquals(null, array); } public void testReverseByte() { byte[] array = new byte[] {2, 3, 4}; ArrayUtils.reverse(array); assertEquals(array[0], 4); assertEquals(array[1], 3); assertEquals(array[2], 2); array = null; ArrayUtils.reverse(array); assertEquals(null, array); } public void testReverseDouble() { double[] array = new double[] {0.3d, 0.4d, 0.5d}; ArrayUtils.reverse(array); assertEquals(array[0], 0.5d, 0.0d); assertEquals(array[1], 0.4d, 0.0d); assertEquals(array[2], 0.3d, 0.0d); array = null; ArrayUtils.reverse(array); assertEquals(null, array); } public void testReverseFloat() { float[] array = new float[] {0.3f, 0.4f, 0.5f}; ArrayUtils.reverse(array); assertEquals(array[0], 0.5f, 0.0f); assertEquals(array[1], 0.4f, 0.0f); assertEquals(array[2], 0.3f, 0.0f); array = null; ArrayUtils.reverse(array); assertEquals(null, array); } public void testReverseBoolean() { boolean[] array = new boolean[] {false, false, true}; ArrayUtils.reverse(array); assertEquals(array[0], true); assertEquals(array[1], false); assertEquals(array[2], false); array = null; ArrayUtils.reverse(array); assertEquals(null, array); } //----------------------------------------------------------------------- public void testIndexOf() { Object[] array = new Object[] { "0", "1", "2", "3", null, "0" }; assertEquals(-1, ArrayUtils.indexOf(null, null)); assertEquals(-1, ArrayUtils.indexOf(null, "0")); assertEquals(-1, ArrayUtils.indexOf(new Object[0], "0")); assertEquals(0, ArrayUtils.indexOf(array, "0")); assertEquals(1, ArrayUtils.indexOf(array, "1")); assertEquals(2, ArrayUtils.indexOf(array, "2")); assertEquals(3, ArrayUtils.indexOf(array, "3")); assertEquals(4, ArrayUtils.indexOf(array, null)); assertEquals(-1, ArrayUtils.indexOf(array, "notInArray")); } public void testIndexOfWithStartIndex() { Object[] array = new Object[] { "0", "1", "2", "3", null, "0" }; assertEquals(-1, ArrayUtils.indexOf(null, null, 2)); assertEquals(-1, ArrayUtils.indexOf(new Object[0], "0", 0)); assertEquals(-1, ArrayUtils.indexOf(null, "0", 2)); assertEquals(5, ArrayUtils.indexOf(array, "0", 2)); assertEquals(-1, ArrayUtils.indexOf(array, "1", 2)); assertEquals(2, ArrayUtils.indexOf(array, "2", 2)); assertEquals(3, ArrayUtils.indexOf(array, "3", 2)); assertEquals(4, ArrayUtils.indexOf(array, null, 2)); assertEquals(-1, ArrayUtils.indexOf(array, "notInArray", 2)); assertEquals(4, ArrayUtils.indexOf(array, null, -1)); assertEquals(-1, ArrayUtils.indexOf(array, null, 8)); assertEquals(-1, ArrayUtils.indexOf(array, "0", 8)); } public void testLastIndexOf() { Object[] array = new Object[] { "0", "1", "2", "3", null, "0" }; assertEquals(-1, ArrayUtils.lastIndexOf(null, null)); assertEquals(-1, ArrayUtils.lastIndexOf(null, "0")); assertEquals(5, ArrayUtils.lastIndexOf(array, "0")); assertEquals(1, ArrayUtils.lastIndexOf(array, "1")); assertEquals(2, ArrayUtils.lastIndexOf(array, "2")); assertEquals(3, ArrayUtils.lastIndexOf(array, "3")); assertEquals(4, ArrayUtils.lastIndexOf(array, null)); assertEquals(-1, ArrayUtils.lastIndexOf(array, "notInArray")); } public void testLastIndexOfWithStartIndex() { Object[] array = new Object[] { "0", "1", "2", "3", null, "0" }; assertEquals(-1, ArrayUtils.lastIndexOf(null, null, 2)); assertEquals(-1, ArrayUtils.lastIndexOf(null, "0", 2)); assertEquals(0, ArrayUtils.lastIndexOf(array, "0", 2)); assertEquals(1, ArrayUtils.lastIndexOf(array, "1", 2)); assertEquals(2, ArrayUtils.lastIndexOf(array, "2", 2)); assertEquals(-1, ArrayUtils.lastIndexOf(array, "3", 2)); assertEquals(-1, ArrayUtils.lastIndexOf(array, "3", -1)); assertEquals(4, ArrayUtils.lastIndexOf(array, null, 5)); assertEquals(-1, ArrayUtils.lastIndexOf(array, null, 2)); assertEquals(-1, ArrayUtils.lastIndexOf(array, "notInArray", 5)); assertEquals(-1, ArrayUtils.lastIndexOf(array, null, -1)); assertEquals(5, ArrayUtils.lastIndexOf(array, "0", 88)); } public void testContains() { Object[] array = new Object[] { "0", "1", "2", "3", null, "0" }; assertEquals(false, ArrayUtils.contains(null, null)); assertEquals(false, ArrayUtils.contains(null, "1")); assertEquals(true, ArrayUtils.contains(array, "0")); assertEquals(true, ArrayUtils.contains(array, "1")); assertEquals(true, ArrayUtils.contains(array, "2")); assertEquals(true, ArrayUtils.contains(array, "3")); assertEquals(true, ArrayUtils.contains(array, null)); assertEquals(false, ArrayUtils.contains(array, "notInArray")); } //----------------------------------------------------------------------- public void testIndexOfLong() { long[] array = null; assertEquals(-1, ArrayUtils.indexOf(array, 0)); array = new long[] { 0, 1, 2, 3, 0 }; assertEquals(0, ArrayUtils.indexOf(array, 0)); assertEquals(1, ArrayUtils.indexOf(array, 1)); assertEquals(2, ArrayUtils.indexOf(array, 2)); assertEquals(3, ArrayUtils.indexOf(array, 3)); assertEquals(-1, ArrayUtils.indexOf(array, 99)); } public void testIndexOfLongWithStartIndex() { long[] array = null; assertEquals(-1, ArrayUtils.indexOf(array, 0, 2)); array = new long[] { 0, 1, 2, 3, 0 }; assertEquals(4, ArrayUtils.indexOf(array, 0, 2)); assertEquals(-1, ArrayUtils.indexOf(array, 1, 2)); assertEquals(2, ArrayUtils.indexOf(array, 2, 2)); assertEquals(3, ArrayUtils.indexOf(array, 3, 2)); assertEquals(3, ArrayUtils.indexOf(array, 3, -1)); assertEquals(-1, ArrayUtils.indexOf(array, 99, 0)); assertEquals(-1, ArrayUtils.indexOf(array, 0, 6)); } public void testLastIndexOfLong() { long[] array = null; assertEquals(-1, ArrayUtils.lastIndexOf(array, 0)); array = new long[] { 0, 1, 2, 3, 0 }; assertEquals(4, ArrayUtils.lastIndexOf(array, 0)); assertEquals(1, ArrayUtils.lastIndexOf(array, 1)); assertEquals(2, ArrayUtils.lastIndexOf(array, 2)); assertEquals(3, ArrayUtils.lastIndexOf(array, 3)); assertEquals(-1, ArrayUtils.lastIndexOf(array, 99)); } public void testLastIndexOfLongWithStartIndex() { long[] array = null; assertEquals(-1, ArrayUtils.lastIndexOf(array, 0, 2)); array = new long[] { 0, 1, 2, 3, 0 }; assertEquals(0, ArrayUtils.lastIndexOf(array, 0, 2)); assertEquals(1, ArrayUtils.lastIndexOf(array, 1, 2)); assertEquals(2, ArrayUtils.lastIndexOf(array, 2, 2)); assertEquals(-1, ArrayUtils.lastIndexOf(array, 3, 2)); assertEquals(-1, ArrayUtils.lastIndexOf(array, 3, -1)); assertEquals(-1, ArrayUtils.lastIndexOf(array, 99, 4)); assertEquals(4, ArrayUtils.lastIndexOf(array, 0, 88)); } public void testContainsLong() { long[] array = null; assertEquals(false, ArrayUtils.contains(array, 1)); array = new long[] { 0, 1, 2, 3, 0 }; assertEquals(true, ArrayUtils.contains(array, 0)); assertEquals(true, ArrayUtils.contains(array, 1)); assertEquals(true, ArrayUtils.contains(array, 2)); assertEquals(true, ArrayUtils.contains(array, 3)); assertEquals(false, ArrayUtils.contains(array, 99)); } //----------------------------------------------------------------------- public void testIndexOfInt() { int[] array = null; assertEquals(-1, ArrayUtils.indexOf(array, 0)); array = new int[] { 0, 1, 2, 3, 0 }; assertEquals(0, ArrayUtils.indexOf(array, 0)); assertEquals(1, ArrayUtils.indexOf(array, 1)); assertEquals(2, ArrayUtils.indexOf(array, 2)); assertEquals(3, ArrayUtils.indexOf(array, 3)); assertEquals(-1, ArrayUtils.indexOf(array, 99)); } public void testIndexOfIntWithStartIndex() { int[] array = null; assertEquals(-1, ArrayUtils.indexOf(array, 0, 2)); array = new int[] { 0, 1, 2, 3, 0 }; assertEquals(4, ArrayUtils.indexOf(array, 0, 2)); assertEquals(-1, ArrayUtils.indexOf(array, 1, 2)); assertEquals(2, ArrayUtils.indexOf(array, 2, 2)); assertEquals(3, ArrayUtils.indexOf(array, 3, 2)); assertEquals(3, ArrayUtils.indexOf(array, 3, -1)); assertEquals(-1, ArrayUtils.indexOf(array, 99, 0)); assertEquals(-1, ArrayUtils.indexOf(array, 0, 6)); } public void testLastIndexOfInt() { int[] array = null; assertEquals(-1, ArrayUtils.lastIndexOf(array, 0)); array = new int[] { 0, 1, 2, 3, 0 }; assertEquals(4, ArrayUtils.lastIndexOf(array, 0)); assertEquals(1, ArrayUtils.lastIndexOf(array, 1)); assertEquals(2, ArrayUtils.lastIndexOf(array, 2)); assertEquals(3, ArrayUtils.lastIndexOf(array, 3)); assertEquals(-1, ArrayUtils.lastIndexOf(array, 99)); } public void testLastIndexOfIntWithStartIndex() { int[] array = null; assertEquals(-1, ArrayUtils.lastIndexOf(array, 0, 2)); array = new int[] { 0, 1, 2, 3, 0 }; assertEquals(0, ArrayUtils.lastIndexOf(array, 0, 2)); assertEquals(1, ArrayUtils.lastIndexOf(array, 1, 2)); assertEquals(2, ArrayUtils.lastIndexOf(array, 2, 2)); assertEquals(-1, ArrayUtils.lastIndexOf(array, 3, 2)); assertEquals(-1, ArrayUtils.lastIndexOf(array, 3, -1)); assertEquals(-1, ArrayUtils.lastIndexOf(array, 99)); assertEquals(4, ArrayUtils.lastIndexOf(array, 0, 88)); } public void testContainsInt() { int[] array = null; assertEquals(false, ArrayUtils.contains(array, 1)); array = new int[] { 0, 1, 2, 3, 0 }; assertEquals(true, ArrayUtils.contains(array, 0)); assertEquals(true, ArrayUtils.contains(array, 1)); assertEquals(true, ArrayUtils.contains(array, 2)); assertEquals(true, ArrayUtils.contains(array, 3)); assertEquals(false, ArrayUtils.contains(array, 99)); } //----------------------------------------------------------------------- public void testIndexOfShort() { short[] array = null; assertEquals(-1, ArrayUtils.indexOf(array, (short) 0)); array = new short[] { 0, 1, 2, 3, 0 }; assertEquals(0, ArrayUtils.indexOf(array, (short) 0)); assertEquals(1, ArrayUtils.indexOf(array, (short) 1)); assertEquals(2, ArrayUtils.indexOf(array, (short) 2)); assertEquals(3, ArrayUtils.indexOf(array, (short) 3)); assertEquals(-1, ArrayUtils.indexOf(array, (short) 99)); } public void testIndexOfShortWithStartIndex() { short[] array = null; assertEquals(-1, ArrayUtils.indexOf(array, (short) 0, 2)); array = new short[] { 0, 1, 2, 3, 0 }; assertEquals(4, ArrayUtils.indexOf(array, (short) 0, 2)); assertEquals(-1, ArrayUtils.indexOf(array, (short) 1, 2)); assertEquals(2, ArrayUtils.indexOf(array, (short) 2, 2)); assertEquals(3, ArrayUtils.indexOf(array, (short) 3, 2)); assertEquals(3, ArrayUtils.indexOf(array, (short) 3, -1)); assertEquals(-1, ArrayUtils.indexOf(array, (short) 99, 0)); assertEquals(-1, ArrayUtils.indexOf(array, (short) 0, 6)); } public void testLastIndexOfShort() { short[] array = null; assertEquals(-1, ArrayUtils.lastIndexOf(array, (short) 0)); array = new short[] { 0, 1, 2, 3, 0 }; assertEquals(4, ArrayUtils.lastIndexOf(array, (short) 0)); assertEquals(1, ArrayUtils.lastIndexOf(array, (short) 1)); assertEquals(2, ArrayUtils.lastIndexOf(array, (short) 2)); assertEquals(3, ArrayUtils.lastIndexOf(array, (short) 3)); assertEquals(-1, ArrayUtils.lastIndexOf(array, (short) 99)); } public void testLastIndexOfShortWithStartIndex() { short[] array = null; assertEquals(-1, ArrayUtils.lastIndexOf(array, (short) 0, 2)); array = new short[] { 0, 1, 2, 3, 0 }; assertEquals(0, ArrayUtils.lastIndexOf(array, (short) 0, 2)); assertEquals(1, ArrayUtils.lastIndexOf(array, (short) 1, 2)); assertEquals(2, ArrayUtils.lastIndexOf(array, (short) 2, 2)); assertEquals(-1, ArrayUtils.lastIndexOf(array, (short) 3, 2)); assertEquals(-1, ArrayUtils.lastIndexOf(array, (short) 3, -1)); assertEquals(-1, ArrayUtils.lastIndexOf(array, (short) 99)); assertEquals(4, ArrayUtils.lastIndexOf(array, (short) 0, 88)); } public void testContainsShort() { short[] array = null; assertEquals(false, ArrayUtils.contains(array, (short) 1)); array = new short[] { 0, 1, 2, 3, 0 }; assertEquals(true, ArrayUtils.contains(array, (short) 0)); assertEquals(true, ArrayUtils.contains(array, (short) 1)); assertEquals(true, ArrayUtils.contains(array, (short) 2)); assertEquals(true, ArrayUtils.contains(array, (short) 3)); assertEquals(false, ArrayUtils.contains(array, (short) 99)); } //----------------------------------------------------------------------- public void testIndexOfChar() { char[] array = null; assertEquals(-1, ArrayUtils.indexOf(array, 'a')); array = new char[] { 'a', 'b', 'c', 'd', 'a' }; assertEquals(0, ArrayUtils.indexOf(array, 'a')); assertEquals(1, ArrayUtils.indexOf(array, 'b')); assertEquals(2, ArrayUtils.indexOf(array, 'c')); assertEquals(3, ArrayUtils.indexOf(array, 'd')); assertEquals(-1, ArrayUtils.indexOf(array, 'e')); } public void testIndexOfCharWithStartIndex() { char[] array = null; assertEquals(-1, ArrayUtils.indexOf(array, 'a', 2)); array = new char[] { 'a', 'b', 'c', 'd', 'a' }; assertEquals(4, ArrayUtils.indexOf(array, 'a', 2)); assertEquals(-1, ArrayUtils.indexOf(array, 'b', 2)); assertEquals(2, ArrayUtils.indexOf(array, 'c', 2)); assertEquals(3, ArrayUtils.indexOf(array, 'd', 2)); assertEquals(3, ArrayUtils.indexOf(array, 'd', -1)); assertEquals(-1, ArrayUtils.indexOf(array, 'e', 0)); assertEquals(-1, ArrayUtils.indexOf(array, 'a', 6)); } public void testLastIndexOfChar() { char[] array = null; assertEquals(-1, ArrayUtils.lastIndexOf(array, 'a')); array = new char[] { 'a', 'b', 'c', 'd', 'a' }; assertEquals(4, ArrayUtils.lastIndexOf(array, 'a')); assertEquals(1, ArrayUtils.lastIndexOf(array, 'b')); assertEquals(2, ArrayUtils.lastIndexOf(array, 'c')); assertEquals(3, ArrayUtils.lastIndexOf(array, 'd')); assertEquals(-1, ArrayUtils.lastIndexOf(array, 'e')); } public void testLastIndexOfCharWithStartIndex() { char[] array = null; assertEquals(-1, ArrayUtils.lastIndexOf(array, 'a', 2)); array = new char[] { 'a', 'b', 'c', 'd', 'a' }; assertEquals(0, ArrayUtils.lastIndexOf(array, 'a', 2)); assertEquals(1, ArrayUtils.lastIndexOf(array, 'b', 2)); assertEquals(2, ArrayUtils.lastIndexOf(array, 'c', 2)); assertEquals(-1, ArrayUtils.lastIndexOf(array, 'd', 2)); assertEquals(-1, ArrayUtils.lastIndexOf(array, 'd', -1)); assertEquals(-1, ArrayUtils.lastIndexOf(array, 'e')); assertEquals(4, ArrayUtils.lastIndexOf(array, 'a', 88)); } public void testContainsChar() { char[] array = null; assertEquals(false, ArrayUtils.contains(array, 'b')); array = new char[] { 'a', 'b', 'c', 'd', 'a' }; assertEquals(true, ArrayUtils.contains(array, 'a')); assertEquals(true, ArrayUtils.contains(array, 'b')); assertEquals(true, ArrayUtils.contains(array, 'c')); assertEquals(true, ArrayUtils.contains(array, 'd')); assertEquals(false, ArrayUtils.contains(array, 'e')); } //----------------------------------------------------------------------- public void testIndexOfByte() { byte[] array = null; assertEquals(-1, ArrayUtils.indexOf(array, (byte) 0)); array = new byte[] { 0, 1, 2, 3, 0 }; assertEquals(0, ArrayUtils.indexOf(array, (byte) 0)); assertEquals(1, ArrayUtils.indexOf(array, (byte) 1)); assertEquals(2, ArrayUtils.indexOf(array, (byte) 2)); assertEquals(3, ArrayUtils.indexOf(array, (byte) 3)); assertEquals(-1, ArrayUtils.indexOf(array, (byte) 99)); } public void testIndexOfByteWithStartIndex() { byte[] array = null; assertEquals(-1, ArrayUtils.indexOf(array, (byte) 0, 2)); array = new byte[] { 0, 1, 2, 3, 0 }; assertEquals(4, ArrayUtils.indexOf(array, (byte) 0, 2)); assertEquals(-1, ArrayUtils.indexOf(array, (byte) 1, 2)); assertEquals(2, ArrayUtils.indexOf(array, (byte) 2, 2)); assertEquals(3, ArrayUtils.indexOf(array, (byte) 3, 2)); assertEquals(3, ArrayUtils.indexOf(array, (byte) 3, -1)); assertEquals(-1, ArrayUtils.indexOf(array, (byte) 99, 0)); assertEquals(-1, ArrayUtils.indexOf(array, (byte) 0, 6)); } public void testLastIndexOfByte() { byte[] array = null; assertEquals(-1, ArrayUtils.lastIndexOf(array, (byte) 0)); array = new byte[] { 0, 1, 2, 3, 0 }; assertEquals(4, ArrayUtils.lastIndexOf(array, (byte) 0)); assertEquals(1, ArrayUtils.lastIndexOf(array, (byte) 1)); assertEquals(2, ArrayUtils.lastIndexOf(array, (byte) 2)); assertEquals(3, ArrayUtils.lastIndexOf(array, (byte) 3)); assertEquals(-1, ArrayUtils.lastIndexOf(array, (byte) 99)); } public void testLastIndexOfByteWithStartIndex() { byte[] array = null; assertEquals(-1, ArrayUtils.lastIndexOf(array, (byte) 0, 2)); array = new byte[] { 0, 1, 2, 3, 0 }; assertEquals(0, ArrayUtils.lastIndexOf(array, (byte) 0, 2)); assertEquals(1, ArrayUtils.lastIndexOf(array, (byte) 1, 2)); assertEquals(2, ArrayUtils.lastIndexOf(array, (byte) 2, 2)); assertEquals(-1, ArrayUtils.lastIndexOf(array, (byte) 3, 2)); assertEquals(-1, ArrayUtils.lastIndexOf(array, (byte) 3, -1)); assertEquals(-1, ArrayUtils.lastIndexOf(array, (byte) 99)); assertEquals(4, ArrayUtils.lastIndexOf(array, (byte) 0, 88)); } public void testContainsByte() { byte[] array = null; assertEquals(false, ArrayUtils.contains(array, (byte) 1)); array = new byte[] { 0, 1, 2, 3, 0 }; assertEquals(true, ArrayUtils.contains(array, (byte) 0)); assertEquals(true, ArrayUtils.contains(array, (byte) 1)); assertEquals(true, ArrayUtils.contains(array, (byte) 2)); assertEquals(true, ArrayUtils.contains(array, (byte) 3)); assertEquals(false, ArrayUtils.contains(array, (byte) 99)); } //----------------------------------------------------------------------- public void testIndexOfDouble() { double[] array = null; assertEquals(-1, ArrayUtils.indexOf(array, (double) 0)); array = new double[0]; assertEquals(-1, ArrayUtils.indexOf(array, (double) 0)); array = new double[] { 0, 1, 2, 3, 0 }; assertEquals(0, ArrayUtils.indexOf(array, (double) 0)); assertEquals(1, ArrayUtils.indexOf(array, (double) 1)); assertEquals(2, ArrayUtils.indexOf(array, (double) 2)); assertEquals(3, ArrayUtils.indexOf(array, (double) 3)); assertEquals(3, ArrayUtils.indexOf(array, (double) 3, -1)); assertEquals(-1, ArrayUtils.indexOf(array, (double) 99)); } public void testIndexOfDoubleTolerance() { double[] array = null; assertEquals(-1, ArrayUtils.indexOf(array, (double) 0, (double) 0)); array = new double[0]; assertEquals(-1, ArrayUtils.indexOf(array, (double) 0, (double) 0)); array = new double[] { 0, 1, 2, 3, 0 }; assertEquals(0, ArrayUtils.indexOf(array, (double) 0, (double) 0.3)); assertEquals(2, ArrayUtils.indexOf(array, (double) 2.2, (double) 0.35)); assertEquals(3, ArrayUtils.indexOf(array, (double) 4.15, (double) 2.0)); assertEquals(1, ArrayUtils.indexOf(array, (double) 1.00001324, (double) 0.0001)); } public void testIndexOfDoubleWithStartIndex() { double[] array = null; assertEquals(-1, ArrayUtils.indexOf(array, (double) 0, 2)); array = new double[0]; assertEquals(-1, ArrayUtils.indexOf(array, (double) 0, 2)); array = new double[] { 0, 1, 2, 3, 0 }; assertEquals(4, ArrayUtils.indexOf(array, (double) 0, 2)); assertEquals(-1, ArrayUtils.indexOf(array, (double) 1, 2)); assertEquals(2, ArrayUtils.indexOf(array, (double) 2, 2)); assertEquals(3, ArrayUtils.indexOf(array, (double) 3, 2)); assertEquals(-1, ArrayUtils.indexOf(array, (double) 99, 0)); assertEquals(-1, ArrayUtils.indexOf(array, (double) 0, 6)); } public void testIndexOfDoubleWithStartIndexTolerance() { double[] array = null; assertEquals(-1, ArrayUtils.indexOf(array, (double) 0, 2, (double) 0)); array = new double[0]; assertEquals(-1, ArrayUtils.indexOf(array, (double) 0, 2, (double) 0)); array = new double[] { 0, 1, 2, 3, 0 }; assertEquals(-1, ArrayUtils.indexOf(array, (double) 0, 99, (double) 0.3)); assertEquals(0, ArrayUtils.indexOf(array, (double) 0, 0, (double) 0.3)); assertEquals(4, ArrayUtils.indexOf(array, (double) 0, 3, (double) 0.3)); assertEquals(2, ArrayUtils.indexOf(array, (double) 2.2, 0, (double) 0.35)); assertEquals(3, ArrayUtils.indexOf(array, (double) 4.15, 0, (double) 2.0)); assertEquals(1, ArrayUtils.indexOf(array, (double) 1.00001324, 0, (double) 0.0001)); assertEquals(3, ArrayUtils.indexOf(array, (double) 4.15, -1, (double) 2.0)); assertEquals(1, ArrayUtils.indexOf(array, (double) 1.00001324, -300, (double) 0.0001)); } public void testLastIndexOfDouble() { double[] array = null; assertEquals(-1, ArrayUtils.lastIndexOf(array, (double) 0)); array = new double[0]; assertEquals(-1, ArrayUtils.lastIndexOf(array, (double) 0)); array = new double[] { 0, 1, 2, 3, 0 }; assertEquals(4, ArrayUtils.lastIndexOf(array, (double) 0)); assertEquals(1, ArrayUtils.lastIndexOf(array, (double) 1)); assertEquals(2, ArrayUtils.lastIndexOf(array, (double) 2)); assertEquals(3, ArrayUtils.lastIndexOf(array, (double) 3)); assertEquals(-1, ArrayUtils.lastIndexOf(array, (double) 99)); } public void testLastIndexOfDoubleTolerance() { double[] array = null; assertEquals(-1, ArrayUtils.lastIndexOf(array, (double) 0, (double) 0)); array = new double[0]; assertEquals(-1, ArrayUtils.lastIndexOf(array, (double) 0, (double) 0)); array = new double[] { 0, 1, 2, 3, 0 }; assertEquals(4, ArrayUtils.lastIndexOf(array, (double) 0, (double) 0.3)); assertEquals(2, ArrayUtils.lastIndexOf(array, (double) 2.2, (double) 0.35)); assertEquals(3, ArrayUtils.lastIndexOf(array, (double) 4.15, (double) 2.0)); assertEquals(1, ArrayUtils.lastIndexOf(array, (double) 1.00001324, (double) 0.0001)); } public void testLastIndexOfDoubleWithStartIndex() { double[] array = null; assertEquals(-1, ArrayUtils.lastIndexOf(array, (double) 0, 2)); array = new double[0]; assertEquals(-1, ArrayUtils.lastIndexOf(array, (double) 0, 2)); array = new double[] { 0, 1, 2, 3, 0 }; assertEquals(0, ArrayUtils.lastIndexOf(array, (double) 0, 2)); assertEquals(1, ArrayUtils.lastIndexOf(array, (double) 1, 2)); assertEquals(2, ArrayUtils.lastIndexOf(array, (double) 2, 2)); assertEquals(-1, ArrayUtils.lastIndexOf(array, (double) 3, 2)); assertEquals(-1, ArrayUtils.lastIndexOf(array, (double) 3, -1)); assertEquals(-1, ArrayUtils.lastIndexOf(array, (double) 99)); assertEquals(4, ArrayUtils.lastIndexOf(array, (double) 0, 88)); } public void testLastIndexOfDoubleWithStartIndexTolerance() { double[] array = null; assertEquals(-1, ArrayUtils.lastIndexOf(array, (double) 0, 2, (double) 0)); array = new double[0]; assertEquals(-1, ArrayUtils.lastIndexOf(array, (double) 0, 2, (double) 0)); array = new double[] { (double) 3 }; assertEquals(-1, ArrayUtils.lastIndexOf(array, (double) 1, 0, (double) 0)); array = new double[] { 0, 1, 2, 3, 0 }; assertEquals(4, ArrayUtils.lastIndexOf(array, (double) 0, 99, (double) 0.3)); assertEquals(0, ArrayUtils.lastIndexOf(array, (double) 0, 3, (double) 0.3)); assertEquals(2, ArrayUtils.lastIndexOf(array, (double) 2.2, 3, (double) 0.35)); assertEquals(3, ArrayUtils.lastIndexOf(array, (double) 4.15, array.length, (double) 2.0)); assertEquals(1, ArrayUtils.lastIndexOf(array, (double) 1.00001324, array.length, (double) 0.0001)); assertEquals(-1, ArrayUtils.lastIndexOf(array, (double) 4.15, -200, (double) 2.0)); } public void testContainsDouble() { double[] array = null; assertEquals(false, ArrayUtils.contains(array, (double) 1)); array = new double[] { 0, 1, 2, 3, 0 }; assertEquals(true, ArrayUtils.contains(array, (double) 0)); assertEquals(true, ArrayUtils.contains(array, (double) 1)); assertEquals(true, ArrayUtils.contains(array, (double) 2)); assertEquals(true, ArrayUtils.contains(array, (double) 3)); assertEquals(false, ArrayUtils.contains(array, (double) 99)); } public void testContainsDoubleTolerance() { double[] array = null; assertEquals(false, ArrayUtils.contains(array, (double) 1, (double) 0)); array = new double[] { 0, 1, 2, 3, 0 }; assertEquals(false, ArrayUtils.contains(array, (double) 4.0, (double) 0.33)); assertEquals(false, ArrayUtils.contains(array, (double) 2.5, (double) 0.49)); assertEquals(true, ArrayUtils.contains(array, (double) 2.5, (double) 0.50)); assertEquals(true, ArrayUtils.contains(array, (double) 2.5, (double) 0.51)); } //----------------------------------------------------------------------- public void testIndexOfFloat() { float[] array = null; assertEquals(-1, ArrayUtils.indexOf(array, (float) 0)); array = new float[0]; assertEquals(-1, ArrayUtils.indexOf(array, (float) 0)); array = new float[] { 0, 1, 2, 3, 0 }; assertEquals(0, ArrayUtils.indexOf(array, (float) 0)); assertEquals(1, ArrayUtils.indexOf(array, (float) 1)); assertEquals(2, ArrayUtils.indexOf(array, (float) 2)); assertEquals(3, ArrayUtils.indexOf(array, (float) 3)); assertEquals(-1, ArrayUtils.indexOf(array, (float) 99)); } public void testIndexOfFloatWithStartIndex() { float[] array = null; assertEquals(-1, ArrayUtils.indexOf(array, (float) 0, 2)); array = new float[0]; assertEquals(-1, ArrayUtils.indexOf(array, (float) 0, 2)); array = new float[] { 0, 1, 2, 3, 0 }; assertEquals(4, ArrayUtils.indexOf(array, (float) 0, 2)); assertEquals(-1, ArrayUtils.indexOf(array, (float) 1, 2)); assertEquals(2, ArrayUtils.indexOf(array, (float) 2, 2)); assertEquals(3, ArrayUtils.indexOf(array, (float) 3, 2)); assertEquals(3, ArrayUtils.indexOf(array, (float) 3, -1)); assertEquals(-1, ArrayUtils.indexOf(array, (float) 99, 0)); assertEquals(-1, ArrayUtils.indexOf(array, (float) 0, 6)); } public void testLastIndexOfFloat() { float[] array = null; assertEquals(-1, ArrayUtils.lastIndexOf(array, (float) 0)); array = new float[0]; assertEquals(-1, ArrayUtils.lastIndexOf(array, (float) 0)); array = new float[] { 0, 1, 2, 3, 0 }; assertEquals(4, ArrayUtils.lastIndexOf(array, (float) 0)); assertEquals(1, ArrayUtils.lastIndexOf(array, (float) 1)); assertEquals(2, ArrayUtils.lastIndexOf(array, (float) 2)); assertEquals(3, ArrayUtils.lastIndexOf(array, (float) 3)); assertEquals(-1, ArrayUtils.lastIndexOf(array, (float) 99)); } public void testLastIndexOfFloatWithStartIndex() { float[] array = null; assertEquals(-1, ArrayUtils.lastIndexOf(array, (float) 0, 2)); array = new float[0]; assertEquals(-1, ArrayUtils.lastIndexOf(array, (float) 0, 2)); array = new float[] { 0, 1, 2, 3, 0 }; assertEquals(0, ArrayUtils.lastIndexOf(array, (float) 0, 2)); assertEquals(1, ArrayUtils.lastIndexOf(array, (float) 1, 2)); assertEquals(2, ArrayUtils.lastIndexOf(array, (float) 2, 2)); assertEquals(-1, ArrayUtils.lastIndexOf(array, (float) 3, 2)); assertEquals(-1, ArrayUtils.lastIndexOf(array, (float) 3, -1)); assertEquals(-1, ArrayUtils.lastIndexOf(array, (float) 99)); assertEquals(4, ArrayUtils.lastIndexOf(array, (float) 0, 88)); } public void testContainsFloat() { float[] array = null; assertEquals(false, ArrayUtils.contains(array, (float) 1)); array = new float[] { 0, 1, 2, 3, 0 }; assertEquals(true, ArrayUtils.contains(array, (float) 0)); assertEquals(true, ArrayUtils.contains(array, (float) 1)); assertEquals(true, ArrayUtils.contains(array, (float) 2)); assertEquals(true, ArrayUtils.contains(array, (float) 3)); assertEquals(false, ArrayUtils.contains(array, (float) 99)); } //----------------------------------------------------------------------- public void testIndexOfBoolean() { boolean[] array = null; assertEquals(-1, ArrayUtils.indexOf(array, true)); array = new boolean[0]; assertEquals(-1, ArrayUtils.indexOf(array, true)); array = new boolean[] { true, false, true }; assertEquals(0, ArrayUtils.indexOf(array, true)); assertEquals(1, ArrayUtils.indexOf(array, false)); array = new boolean[] { true, true }; assertEquals(-1, ArrayUtils.indexOf(array, false)); } public void testIndexOfBooleanWithStartIndex() { boolean[] array = null; assertEquals(-1, ArrayUtils.indexOf(array, true, 2)); array = new boolean[0]; assertEquals(-1, ArrayUtils.indexOf(array, true, 2)); array = new boolean[] { true, false, true }; assertEquals(2, ArrayUtils.indexOf(array, true, 1)); assertEquals(-1, ArrayUtils.indexOf(array, false, 2)); assertEquals(1, ArrayUtils.indexOf(array, false, 0)); assertEquals(1, ArrayUtils.indexOf(array, false, -1)); array = new boolean[] { true, true }; assertEquals(-1, ArrayUtils.indexOf(array, false, 0)); assertEquals(-1, ArrayUtils.indexOf(array, false, -1)); } public void testLastIndexOfBoolean() { boolean[] array = null; assertEquals(-1, ArrayUtils.lastIndexOf(array, true)); array = new boolean[0]; assertEquals(-1, ArrayUtils.lastIndexOf(array, true)); array = new boolean[] { true, false, true }; assertEquals(2, ArrayUtils.lastIndexOf(array, true)); assertEquals(1, ArrayUtils.lastIndexOf(array, false)); array = new boolean[] { true, true }; assertEquals(-1, ArrayUtils.lastIndexOf(array, false)); } public void testLastIndexOfBooleanWithStartIndex() { boolean[] array = null; assertEquals(-1, ArrayUtils.lastIndexOf(array, true, 2)); array = new boolean[0]; assertEquals(-1, ArrayUtils.lastIndexOf(array, true, 2)); array = new boolean[] { true, false, true }; assertEquals(2, ArrayUtils.lastIndexOf(array, true, 2)); assertEquals(0, ArrayUtils.lastIndexOf(array, true, 1)); assertEquals(1, ArrayUtils.lastIndexOf(array, false, 2)); assertEquals(-1, ArrayUtils.lastIndexOf(array, true, -1)); array = new boolean[] { true, true }; assertEquals(-1, ArrayUtils.lastIndexOf(array, false, 2)); assertEquals(-1, ArrayUtils.lastIndexOf(array, true, -1)); } public void testContainsBoolean() { boolean[] array = null; assertEquals(false, ArrayUtils.contains(array, true)); array = new boolean[] { true, false, true }; assertEquals(true, ArrayUtils.contains(array, true)); assertEquals(true, ArrayUtils.contains(array, false)); array = new boolean[] { true, true }; assertEquals(true, ArrayUtils.contains(array, true)); assertEquals(false, ArrayUtils.contains(array, false)); } // testToPrimitive/Object for boolean // ----------------------------------------------------------------------- public void testToPrimitive_boolean() { final Boolean[] b = null; assertEquals(null, ArrayUtils.toPrimitive(b)); assertSame(ArrayUtils.EMPTY_BOOLEAN_ARRAY, ArrayUtils.toPrimitive(new Boolean[0])); assertTrue(Arrays.equals( new boolean[] {true, false, true}, ArrayUtils.toPrimitive(new Boolean[] {Boolean.TRUE, Boolean.FALSE, Boolean.TRUE})) ); try { ArrayUtils.toPrimitive(new Boolean[] {Boolean.TRUE, null}); fail(); } catch (NullPointerException ex) {} } public void testToPrimitive_boolean_boolean() { assertEquals(null, ArrayUtils.toPrimitive(null, false)); assertSame(ArrayUtils.EMPTY_BOOLEAN_ARRAY, ArrayUtils.toPrimitive(new Boolean[0], false)); assertTrue(Arrays.equals( new boolean[] {true, false, true}, ArrayUtils.toPrimitive(new Boolean[] {Boolean.TRUE, Boolean.FALSE, Boolean.TRUE}, false)) ); assertTrue(Arrays.equals( new boolean[] {true, false, false}, ArrayUtils.toPrimitive(new Boolean[] {Boolean.TRUE, null, Boolean.FALSE}, false)) ); assertTrue(Arrays.equals( new boolean[] {true, true, false}, ArrayUtils.toPrimitive(new Boolean[] {Boolean.TRUE, null, Boolean.FALSE}, true)) ); } public void testToObject_boolean() { final boolean[] b = null; assertEquals(null, ArrayUtils.toObject(b)); assertSame(ArrayUtils.EMPTY_BOOLEAN_OBJECT_ARRAY, ArrayUtils.toObject(new boolean[0])); assertTrue(Arrays.equals( new Boolean[] {Boolean.TRUE, Boolean.FALSE, Boolean.TRUE}, ArrayUtils.toObject(new boolean[] {true, false, true})) ); } // testToPrimitive/Object for byte // ----------------------------------------------------------------------- public void testToPrimitive_char() { final Character[] b = null; assertEquals(null, ArrayUtils.toPrimitive(b)); assertSame(ArrayUtils.EMPTY_CHAR_ARRAY, ArrayUtils.toPrimitive(new Character[0])); assertTrue(Arrays.equals( new char[] {Character.MIN_VALUE, Character.MAX_VALUE, '0'}, ArrayUtils.toPrimitive(new Character[] {new Character(Character.MIN_VALUE), new Character(Character.MAX_VALUE), new Character('0')})) ); try { ArrayUtils.toPrimitive(new Character[] {new Character(Character.MIN_VALUE), null}); fail(); } catch (NullPointerException ex) {} } public void testToPrimitive_char_char() { final Character[] b = null; assertEquals(null, ArrayUtils.toPrimitive(b, Character.MIN_VALUE)); assertSame(ArrayUtils.EMPTY_CHAR_ARRAY, ArrayUtils.toPrimitive(new Character[0], (char)0)); assertTrue(Arrays.equals( new char[] {Character.MIN_VALUE, Character.MAX_VALUE, '0'}, ArrayUtils.toPrimitive(new Character[] {new Character(Character.MIN_VALUE), new Character(Character.MAX_VALUE), new Character('0')}, Character.MIN_VALUE)) ); assertTrue(Arrays.equals( new char[] {Character.MIN_VALUE, Character.MAX_VALUE, '0'}, ArrayUtils.toPrimitive(new Character[] {new Character(Character.MIN_VALUE), null, new Character('0')}, Character.MAX_VALUE)) ); } public void testToObject_char() { final char[] b = null; assertEquals(null, ArrayUtils.toObject(b)); assertSame(ArrayUtils.EMPTY_CHARACTER_OBJECT_ARRAY, ArrayUtils.toObject(new char[0])); assertTrue(Arrays.equals( new Character[] {new Character(Character.MIN_VALUE), new Character(Character.MAX_VALUE), new Character('0')}, ArrayUtils.toObject(new char[] {Character.MIN_VALUE, Character.MAX_VALUE, '0'} )) ); } // testToPrimitive/Object for byte // ----------------------------------------------------------------------- public void testToPrimitive_byte() { final Byte[] b = null; assertEquals(null, ArrayUtils.toPrimitive(b)); assertSame(ArrayUtils.EMPTY_BYTE_ARRAY, ArrayUtils.toPrimitive(new Byte[0])); assertTrue(Arrays.equals( new byte[] {Byte.MIN_VALUE, Byte.MAX_VALUE, (byte)9999999}, ArrayUtils.toPrimitive(new Byte[] {new Byte(Byte.MIN_VALUE), new Byte(Byte.MAX_VALUE), new Byte((byte)9999999)})) ); try { ArrayUtils.toPrimitive(new Byte[] {new Byte(Byte.MIN_VALUE), null}); fail(); } catch (NullPointerException ex) {} } public void testToPrimitive_byte_byte() { final Byte[] b = null; assertEquals(null, ArrayUtils.toPrimitive(b, Byte.MIN_VALUE)); assertSame(ArrayUtils.EMPTY_BYTE_ARRAY, ArrayUtils.toPrimitive(new Byte[0], (byte)1)); assertTrue(Arrays.equals( new byte[] {Byte.MIN_VALUE, Byte.MAX_VALUE, (byte)9999999}, ArrayUtils.toPrimitive(new Byte[] {new Byte(Byte.MIN_VALUE), new Byte(Byte.MAX_VALUE), new Byte((byte)9999999)}, Byte.MIN_VALUE)) ); assertTrue(Arrays.equals( new byte[] {Byte.MIN_VALUE, Byte.MAX_VALUE, (byte)9999999}, ArrayUtils.toPrimitive(new Byte[] {new Byte(Byte.MIN_VALUE), null, new Byte((byte)9999999)}, Byte.MAX_VALUE)) ); } public void testToObject_byte() { final byte[] b = null; assertEquals(null, ArrayUtils.toObject(b)); assertSame(ArrayUtils.EMPTY_BYTE_OBJECT_ARRAY, ArrayUtils.toObject(new byte[0])); assertTrue(Arrays.equals( new Byte[] {new Byte(Byte.MIN_VALUE), new Byte(Byte.MAX_VALUE), new Byte((byte)9999999)}, ArrayUtils.toObject(new byte[] {Byte.MIN_VALUE, Byte.MAX_VALUE, (byte)9999999})) ); } // testToPrimitive/Object for short // ----------------------------------------------------------------------- public void testToPrimitive_short() { final Short[] b = null; assertEquals(null, ArrayUtils.toPrimitive(b)); assertSame(ArrayUtils.EMPTY_SHORT_ARRAY, ArrayUtils.toPrimitive(new Short[0])); assertTrue(Arrays.equals( new short[] {Short.MIN_VALUE, Short.MAX_VALUE, (short)9999999}, ArrayUtils.toPrimitive(new Short[] {new Short(Short.MIN_VALUE), new Short(Short.MAX_VALUE), new Short((short)9999999)})) ); try { ArrayUtils.toPrimitive(new Short[] {new Short(Short.MIN_VALUE), null}); fail(); } catch (NullPointerException ex) {} } public void testToPrimitive_short_short() { final Short[] s = null; assertEquals(null, ArrayUtils.toPrimitive(s, Short.MIN_VALUE)); assertSame(ArrayUtils.EMPTY_SHORT_ARRAY, ArrayUtils.toPrimitive(new Short[0], Short.MIN_VALUE)); assertTrue(Arrays.equals( new short[] {Short.MIN_VALUE, Short.MAX_VALUE, (short)9999999}, ArrayUtils.toPrimitive(new Short[] {new Short(Short.MIN_VALUE), new Short(Short.MAX_VALUE), new Short((short)9999999)}, Short.MIN_VALUE)) ); assertTrue(Arrays.equals( new short[] {Short.MIN_VALUE, Short.MAX_VALUE, (short)9999999}, ArrayUtils.toPrimitive(new Short[] {new Short(Short.MIN_VALUE), null, new Short((short)9999999)}, Short.MAX_VALUE)) ); } public void testToObject_short() { final short[] b = null; assertEquals(null, ArrayUtils.toObject(b)); assertSame(ArrayUtils.EMPTY_SHORT_OBJECT_ARRAY, ArrayUtils.toObject(new short[0])); assertTrue(Arrays.equals( new Short[] {new Short(Short.MIN_VALUE), new Short(Short.MAX_VALUE), new Short((short)9999999)}, ArrayUtils.toObject(new short[] {Short.MIN_VALUE, Short.MAX_VALUE, (short)9999999})) ); } // testToPrimitive/Object for int // ----------------------------------------------------------------------- public void testToPrimitive_int() { final Integer[] b = null; assertEquals(null, ArrayUtils.toPrimitive(b)); assertSame(ArrayUtils.EMPTY_INT_ARRAY, ArrayUtils.toPrimitive(new Integer[0])); assertTrue(Arrays.equals( new int[] {Integer.MIN_VALUE, Integer.MAX_VALUE, 9999999}, ArrayUtils.toPrimitive(new Integer[] {new Integer(Integer.MIN_VALUE), new Integer(Integer.MAX_VALUE), new Integer(9999999)})) ); try { ArrayUtils.toPrimitive(new Integer[] {new Integer(Integer.MIN_VALUE), null}); fail(); } catch (NullPointerException ex) {} } public void testToPrimitive_int_int() { final Long[] l = null; assertEquals(null, ArrayUtils.toPrimitive(l, Integer.MIN_VALUE)); assertSame(ArrayUtils.EMPTY_INT_ARRAY, ArrayUtils.toPrimitive(new Integer[0], 1)); assertTrue(Arrays.equals( new int[] {Integer.MIN_VALUE, Integer.MAX_VALUE, 9999999}, ArrayUtils.toPrimitive(new Integer[] {new Integer(Integer.MIN_VALUE), new Integer(Integer.MAX_VALUE), new Integer(9999999)},1))); assertTrue(Arrays.equals( new int[] {Integer.MIN_VALUE, Integer.MAX_VALUE, 9999999}, ArrayUtils.toPrimitive(new Integer[] {new Integer(Integer.MIN_VALUE), null, new Integer(9999999)}, Integer.MAX_VALUE)) ); } public void testToPrimitive_intNull() { Integer[] iArray = null; assertEquals(null, ArrayUtils.toPrimitive(iArray, Integer.MIN_VALUE)); } public void testToObject_int() { final int[] b = null; assertEquals(null, ArrayUtils.toObject(b)); assertSame( ArrayUtils.EMPTY_INTEGER_OBJECT_ARRAY, ArrayUtils.toObject(new int[0])); assertTrue( Arrays.equals( new Integer[] { new Integer(Integer.MIN_VALUE), new Integer(Integer.MAX_VALUE), new Integer(9999999)}, ArrayUtils.toObject( new int[] { Integer.MIN_VALUE, Integer.MAX_VALUE, 9999999 }))); } // testToPrimitive/Object for long // ----------------------------------------------------------------------- public void testToPrimitive_long() { final Long[] b = null; assertEquals(null, ArrayUtils.toPrimitive(b)); assertSame(ArrayUtils.EMPTY_LONG_ARRAY, ArrayUtils.toPrimitive(new Long[0])); assertTrue(Arrays.equals( new long[] {Long.MIN_VALUE, Long.MAX_VALUE, 9999999}, ArrayUtils.toPrimitive(new Long[] {new Long(Long.MIN_VALUE), new Long(Long.MAX_VALUE), new Long(9999999)})) ); try { ArrayUtils.toPrimitive(new Long[] {new Long(Long.MIN_VALUE), null}); fail(); } catch (NullPointerException ex) {} } public void testToPrimitive_long_long() { final Long[] l = null; assertEquals(null, ArrayUtils.toPrimitive(l, Long.MIN_VALUE)); assertSame(ArrayUtils.EMPTY_LONG_ARRAY, ArrayUtils.toPrimitive(new Long[0], 1)); assertTrue(Arrays.equals( new long[] {Long.MIN_VALUE, Long.MAX_VALUE, 9999999}, ArrayUtils.toPrimitive(new Long[] {new Long(Long.MIN_VALUE), new Long(Long.MAX_VALUE), new Long(9999999)},1))); assertTrue(Arrays.equals( new long[] {Long.MIN_VALUE, Long.MAX_VALUE, 9999999}, ArrayUtils.toPrimitive(new Long[] {new Long(Long.MIN_VALUE), null, new Long(9999999)}, Long.MAX_VALUE)) ); } public void testToObject_long() { final long[] b = null; assertEquals(null, ArrayUtils.toObject(b)); assertSame( ArrayUtils.EMPTY_LONG_OBJECT_ARRAY, ArrayUtils.toObject(new long[0])); assertTrue( Arrays.equals( new Long[] { new Long(Long.MIN_VALUE), new Long(Long.MAX_VALUE), new Long(9999999)}, ArrayUtils.toObject( new long[] { Long.MIN_VALUE, Long.MAX_VALUE, 9999999 }))); } // testToPrimitive/Object for float // ----------------------------------------------------------------------- public void testToPrimitive_float() { final Float[] b = null; assertEquals(null, ArrayUtils.toPrimitive(b)); assertSame(ArrayUtils.EMPTY_FLOAT_ARRAY, ArrayUtils.toPrimitive(new Float[0])); assertTrue(Arrays.equals( new float[] {Float.MIN_VALUE, Float.MAX_VALUE, 9999999}, ArrayUtils.toPrimitive(new Float[] {new Float(Float.MIN_VALUE), new Float(Float.MAX_VALUE), new Float(9999999)})) ); try { ArrayUtils.toPrimitive(new Float[] {new Float(Float.MIN_VALUE), null}); fail(); } catch (NullPointerException ex) {} } public void testToPrimitive_float_float() { final Float[] l = null; assertEquals(null, ArrayUtils.toPrimitive(l, Float.MIN_VALUE)); assertSame(ArrayUtils.EMPTY_FLOAT_ARRAY, ArrayUtils.toPrimitive(new Float[0], 1)); assertTrue(Arrays.equals( new float[] {Float.MIN_VALUE, Float.MAX_VALUE, 9999999}, ArrayUtils.toPrimitive(new Float[] {new Float(Float.MIN_VALUE), new Float(Float.MAX_VALUE), new Float(9999999)},1))); assertTrue(Arrays.equals( new float[] {Float.MIN_VALUE, Float.MAX_VALUE, 9999999}, ArrayUtils.toPrimitive(new Float[] {new Float(Float.MIN_VALUE), null, new Float(9999999)}, Float.MAX_VALUE)) ); } public void testToObject_float() { final float[] b = null; assertEquals(null, ArrayUtils.toObject(b)); assertSame( ArrayUtils.EMPTY_FLOAT_OBJECT_ARRAY, ArrayUtils.toObject(new float[0])); assertTrue( Arrays.equals( new Float[] { new Float(Float.MIN_VALUE), new Float(Float.MAX_VALUE), new Float(9999999)}, ArrayUtils.toObject( new float[] { Float.MIN_VALUE, Float.MAX_VALUE, 9999999 }))); } // testToPrimitive/Object for double // ----------------------------------------------------------------------- public void testToPrimitive_double() { final Double[] b = null; assertEquals(null, ArrayUtils.toPrimitive(b)); assertSame(ArrayUtils.EMPTY_DOUBLE_ARRAY, ArrayUtils.toPrimitive(new Double[0])); assertTrue(Arrays.equals( new double[] {Double.MIN_VALUE, Double.MAX_VALUE, 9999999}, ArrayUtils.toPrimitive(new Double[] {new Double(Double.MIN_VALUE), new Double(Double.MAX_VALUE), new Double(9999999)})) ); try { ArrayUtils.toPrimitive(new Float[] {new Float(Float.MIN_VALUE), null}); fail(); } catch (NullPointerException ex) {} } public void testToPrimitive_double_double() { final Double[] l = null; assertEquals(null, ArrayUtils.toPrimitive(l, Double.MIN_VALUE)); assertSame(ArrayUtils.EMPTY_DOUBLE_ARRAY, ArrayUtils.toPrimitive(new Double[0], 1)); assertTrue(Arrays.equals( new double[] {Double.MIN_VALUE, Double.MAX_VALUE, 9999999}, ArrayUtils.toPrimitive(new Double[] {new Double(Double.MIN_VALUE), new Double(Double.MAX_VALUE), new Double(9999999)},1))); assertTrue(Arrays.equals( new double[] {Double.MIN_VALUE, Double.MAX_VALUE, 9999999}, ArrayUtils.toPrimitive(new Double[] {new Double(Double.MIN_VALUE), null, new Double(9999999)}, Double.MAX_VALUE)) ); } public void testToObject_double() { final double[] b = null; assertEquals(null, ArrayUtils.toObject(b)); assertSame( ArrayUtils.EMPTY_DOUBLE_OBJECT_ARRAY, ArrayUtils.toObject(new double[0])); assertTrue( Arrays.equals( new Double[] { new Double(Double.MIN_VALUE), new Double(Double.MAX_VALUE), new Double(9999999)}, ArrayUtils.toObject( new double[] { Double.MIN_VALUE, Double.MAX_VALUE, 9999999 }))); } //----------------------------------------------------------------------- /** * Test for {@link ArrayUtils#isEmpty(java.lang.Object[])}. */ public void testIsEmptyObject() { Object[] emptyArray = new Object[] {}; Object[] notEmptyArray = new Object[] { new String("Value") }; assertEquals(true, ArrayUtils.isEmpty((Object[])null)); assertEquals(true, ArrayUtils.isEmpty(emptyArray)); assertEquals(false, ArrayUtils.isEmpty(notEmptyArray)); } /** * Tests for {@link ArrayUtils#isEmpty(long[])}, * {@link ArrayUtils#isEmpty(int[])}, * {@link ArrayUtils#isEmpty(short[])}, * {@link ArrayUtils#isEmpty(char[])}, * {@link ArrayUtils#isEmpty(byte[])}, * {@link ArrayUtils#isEmpty(double[])}, * {@link ArrayUtils#isEmpty(float[])} and * {@link ArrayUtils#isEmpty(boolean[])}. */ public void testIsEmptyPrimitives() { long[] emptyLongArray = new long[] {}; long[] notEmptyLongArray = new long[] { 1L }; assertEquals(true, ArrayUtils.isEmpty((long[])null)); assertEquals(true, ArrayUtils.isEmpty(emptyLongArray)); assertEquals(false, ArrayUtils.isEmpty(notEmptyLongArray)); int[] emptyIntArray = new int[] {}; int[] notEmptyIntArray = new int[] { 1 }; assertEquals(true, ArrayUtils.isEmpty((int[])null)); assertEquals(true, ArrayUtils.isEmpty(emptyIntArray)); assertEquals(false, ArrayUtils.isEmpty(notEmptyIntArray)); short[] emptyShortArray = new short[] {}; short[] notEmptyShortArray = new short[] { 1 }; assertEquals(true, ArrayUtils.isEmpty((short[])null)); assertEquals(true, ArrayUtils.isEmpty(emptyShortArray)); assertEquals(false, ArrayUtils.isEmpty(notEmptyShortArray)); char[] emptyCharArray = new char[] {}; char[] notEmptyCharArray = new char[] { 1 }; assertEquals(true, ArrayUtils.isEmpty((char[])null)); assertEquals(true, ArrayUtils.isEmpty(emptyCharArray)); assertEquals(false, ArrayUtils.isEmpty(notEmptyCharArray)); byte[] emptyByteArray = new byte[] {}; byte[] notEmptyByteArray = new byte[] { 1 }; assertEquals(true, ArrayUtils.isEmpty((byte[])null)); assertEquals(true, ArrayUtils.isEmpty(emptyByteArray)); assertEquals(false, ArrayUtils.isEmpty(notEmptyByteArray)); double[] emptyDoubleArray = new double[] {}; double[] notEmptyDoubleArray = new double[] { 1.0 }; assertEquals(true, ArrayUtils.isEmpty((double[])null)); assertEquals(true, ArrayUtils.isEmpty(emptyDoubleArray)); assertEquals(false, ArrayUtils.isEmpty(notEmptyDoubleArray)); float[] emptyFloatArray = new float[] {}; float[] notEmptyFloatArray = new float[] { 1.0F }; assertEquals(true, ArrayUtils.isEmpty((float[])null)); assertEquals(true, ArrayUtils.isEmpty(emptyFloatArray)); assertEquals(false, ArrayUtils.isEmpty(notEmptyFloatArray)); boolean[] emptyBooleanArray = new boolean[] {}; boolean[] notEmptyBooleanArray = new boolean[] { true }; assertEquals(true, ArrayUtils.isEmpty((boolean[])null)); assertEquals(true, ArrayUtils.isEmpty(emptyBooleanArray)); assertEquals(false, ArrayUtils.isEmpty(notEmptyBooleanArray)); } /** * Test for {@link ArrayUtils#isNotEmpty(java.lang.Object[])}. */ public void testIsNotEmptyObject() { Object[] emptyArray = new Object[] {}; Object[] notEmptyArray = new Object[] { new String("Value") }; assertFalse(ArrayUtils.isNotEmpty((Object[])null)); assertFalse(ArrayUtils.isNotEmpty(emptyArray)); assertTrue(ArrayUtils.isNotEmpty(notEmptyArray)); } /** * Tests for {@link ArrayUtils#isNotEmpty(long[])}, * {@link ArrayUtils#isNotEmpty(int[])}, * {@link ArrayUtils#isNotEmpty(short[])}, * {@link ArrayUtils#isNotEmpty(char[])}, * {@link ArrayUtils#isNotEmpty(byte[])}, * {@link ArrayUtils#isNotEmpty(double[])}, * {@link ArrayUtils#isNotEmpty(float[])} and * {@link ArrayUtils#isNotEmpty(boolean[])}. */ public void testIsNotEmptyPrimitives() { long[] emptyLongArray = new long[] {}; long[] notEmptyLongArray = new long[] { 1L }; assertFalse(ArrayUtils.isNotEmpty((long[])null)); assertFalse(ArrayUtils.isNotEmpty(emptyLongArray)); assertTrue(ArrayUtils.isNotEmpty(notEmptyLongArray)); int[] emptyIntArray = new int[] {}; int[] notEmptyIntArray = new int[] { 1 }; assertFalse(ArrayUtils.isNotEmpty((int[])null)); assertFalse(ArrayUtils.isNotEmpty(emptyIntArray)); assertTrue(ArrayUtils.isNotEmpty(notEmptyIntArray)); short[] emptyShortArray = new short[] {}; short[] notEmptyShortArray = new short[] { 1 }; assertFalse(ArrayUtils.isNotEmpty((short[])null)); assertFalse(ArrayUtils.isNotEmpty(emptyShortArray)); assertTrue(ArrayUtils.isNotEmpty(notEmptyShortArray)); char[] emptyCharArray = new char[] {}; char[] notEmptyCharArray = new char[] { 1 }; assertFalse(ArrayUtils.isNotEmpty((char[])null)); assertFalse(ArrayUtils.isNotEmpty(emptyCharArray)); assertTrue(ArrayUtils.isNotEmpty(notEmptyCharArray)); byte[] emptyByteArray = new byte[] {}; byte[] notEmptyByteArray = new byte[] { 1 }; assertFalse(ArrayUtils.isNotEmpty((byte[])null)); assertFalse(ArrayUtils.isNotEmpty(emptyByteArray)); assertTrue(ArrayUtils.isNotEmpty(notEmptyByteArray)); double[] emptyDoubleArray = new double[] {}; double[] notEmptyDoubleArray = new double[] { 1.0 }; assertFalse(ArrayUtils.isNotEmpty((double[])null)); assertFalse(ArrayUtils.isNotEmpty(emptyDoubleArray)); assertTrue(ArrayUtils.isNotEmpty(notEmptyDoubleArray)); float[] emptyFloatArray = new float[] {}; float[] notEmptyFloatArray = new float[] { 1.0F }; assertFalse(ArrayUtils.isNotEmpty((float[])null)); assertFalse(ArrayUtils.isNotEmpty(emptyFloatArray)); assertTrue(ArrayUtils.isNotEmpty(notEmptyFloatArray)); boolean[] emptyBooleanArray = new boolean[] {}; boolean[] notEmptyBooleanArray = new boolean[] { true }; assertFalse(ArrayUtils.isNotEmpty((boolean[])null)); assertFalse(ArrayUtils.isNotEmpty(emptyBooleanArray)); assertTrue(ArrayUtils.isNotEmpty(notEmptyBooleanArray)); } // ------------------------------------------------------------------------ public void testGetLength() { assertEquals(0, ArrayUtils.getLength(null)); Object[] emptyObjectArray = new Object[0]; Object[] notEmptyObjectArray = new Object[] {"aValue"}; assertEquals(0, ArrayUtils.getLength((Object[]) null)); assertEquals(0, ArrayUtils.getLength(emptyObjectArray)); assertEquals(1, ArrayUtils.getLength(notEmptyObjectArray)); int[] emptyIntArray = new int[] {}; int[] notEmptyIntArray = new int[] { 1 }; assertEquals(0, ArrayUtils.getLength((int[]) null)); assertEquals(0, ArrayUtils.getLength(emptyIntArray)); assertEquals(1, ArrayUtils.getLength(notEmptyIntArray)); short[] emptyShortArray = new short[] {}; short[] notEmptyShortArray = new short[] { 1 }; assertEquals(0, ArrayUtils.getLength((short[]) null)); assertEquals(0, ArrayUtils.getLength(emptyShortArray)); assertEquals(1, ArrayUtils.getLength(notEmptyShortArray)); char[] emptyCharArray = new char[] {}; char[] notEmptyCharArray = new char[] { 1 }; assertEquals(0, ArrayUtils.getLength((char[]) null)); assertEquals(0, ArrayUtils.getLength(emptyCharArray)); assertEquals(1, ArrayUtils.getLength(notEmptyCharArray)); byte[] emptyByteArray = new byte[] {}; byte[] notEmptyByteArray = new byte[] { 1 }; assertEquals(0, ArrayUtils.getLength((byte[]) null)); assertEquals(0, ArrayUtils.getLength(emptyByteArray)); assertEquals(1, ArrayUtils.getLength(notEmptyByteArray)); double[] emptyDoubleArray = new double[] {}; double[] notEmptyDoubleArray = new double[] { 1.0 }; assertEquals(0, ArrayUtils.getLength((double[]) null)); assertEquals(0, ArrayUtils.getLength(emptyDoubleArray)); assertEquals(1, ArrayUtils.getLength(notEmptyDoubleArray)); float[] emptyFloatArray = new float[] {}; float[] notEmptyFloatArray = new float[] { 1.0F }; assertEquals(0, ArrayUtils.getLength((float[]) null)); assertEquals(0, ArrayUtils.getLength(emptyFloatArray)); assertEquals(1, ArrayUtils.getLength(notEmptyFloatArray)); boolean[] emptyBooleanArray = new boolean[] {}; boolean[] notEmptyBooleanArray = new boolean[] { true }; assertEquals(0, ArrayUtils.getLength((boolean[]) null)); assertEquals(0, ArrayUtils.getLength(emptyBooleanArray)); assertEquals(1, ArrayUtils.getLength(notEmptyBooleanArray)); try { ArrayUtils.getLength("notAnArray"); fail("IllegalArgumentException should have been thrown"); } catch (IllegalArgumentException e) {} } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/BitFieldTest.java100644 0 0 24001 11513702440 24161 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang; import junit.framework.TestCase; /** * Class to test BitField functionality * * @author Scott Sanders * @author Marc Johnson * @author Glen Stampoultzis * @version $Id: BitFieldTest.java 905628 2010-02-02 13:29:55Z niallp $ */ public class BitFieldTest extends TestCase { private static final BitField bf_multi = new BitField(0x3F80); private static final BitField bf_single = new BitField(0x4000); private static final BitField bf_zero = new BitField(0); /** * Constructor BitFieldTest * * @param name */ public BitFieldTest(String name) { super(name); } /** * test the getValue() method */ public void testGetValue() { assertEquals(bf_multi.getValue(-1), 127); assertEquals(bf_multi.getValue(0), 0); assertEquals(bf_single.getValue(-1), 1); assertEquals(bf_single.getValue(0), 0); assertEquals(bf_zero.getValue(-1), 0); assertEquals(bf_zero.getValue(0), 0); } /** * test the getShortValue() method */ public void testGetShortValue() { assertEquals(bf_multi.getShortValue((short) - 1), (short) 127); assertEquals(bf_multi.getShortValue((short) 0), (short) 0); assertEquals(bf_single.getShortValue((short) - 1), (short) 1); assertEquals(bf_single.getShortValue((short) 0), (short) 0); assertEquals(bf_zero.getShortValue((short) -1), (short) 0); assertEquals(bf_zero.getShortValue((short) 0), (short) 0); } /** * test the getRawValue() method */ public void testGetRawValue() { assertEquals(bf_multi.getRawValue(-1), 0x3F80); assertEquals(bf_multi.getRawValue(0), 0); assertEquals(bf_single.getRawValue(-1), 0x4000); assertEquals(bf_single.getRawValue(0), 0); assertEquals(bf_zero.getRawValue(-1), 0); assertEquals(bf_zero.getRawValue(0), 0); } /** * test the getShortRawValue() method */ public void testGetShortRawValue() { assertEquals(bf_multi.getShortRawValue((short) - 1), (short) 0x3F80); assertEquals(bf_multi.getShortRawValue((short) 0), (short) 0); assertEquals(bf_single.getShortRawValue((short) - 1), (short) 0x4000); assertEquals(bf_single.getShortRawValue((short) 0), (short) 0); assertEquals(bf_zero.getShortRawValue((short) -1), (short) 0); assertEquals(bf_zero.getShortRawValue((short) 0), (short) 0); } /** * test the isSet() method */ public void testIsSet() { assertTrue(!bf_multi.isSet(0)); assertTrue(!bf_zero.isSet(0)); for (int j = 0x80; j <= 0x3F80; j += 0x80) { assertTrue(bf_multi.isSet(j)); } for (int j = 0x80; j <= 0x3F80; j += 0x80) { assertTrue(!bf_zero.isSet(j)); } assertTrue(!bf_single.isSet(0)); assertTrue(bf_single.isSet(0x4000)); } /** * test the isAllSet() method */ public void testIsAllSet() { for (int j = 0; j < 0x3F80; j += 0x80) { assertTrue(!bf_multi.isAllSet(j)); assertTrue(bf_zero.isAllSet(j)); } assertTrue(bf_multi.isAllSet(0x3F80)); assertTrue(!bf_single.isAllSet(0)); assertTrue(bf_single.isAllSet(0x4000)); } /** * test the setValue() method */ public void testSetValue() { for (int j = 0; j < 128; j++) { assertEquals(bf_multi.getValue(bf_multi.setValue(0, j)), j); assertEquals(bf_multi.setValue(0, j), j << 7); } for (int j = 0; j < 128; j++) { assertEquals(bf_zero.getValue(bf_zero.setValue(0, j)), 0); assertEquals(bf_zero.setValue(0, j), 0); } // verify that excess bits are stripped off assertEquals(bf_multi.setValue(0x3f80, 128), 0); for (int j = 0; j < 2; j++) { assertEquals(bf_single.getValue(bf_single.setValue(0, j)), j); assertEquals(bf_single.setValue(0, j), j << 14); } // verify that excess bits are stripped off assertEquals(bf_single.setValue(0x4000, 2), 0); } /** * test the setShortValue() method */ public void testSetShortValue() { for (int j = 0; j < 128; j++) { assertEquals(bf_multi.getShortValue(bf_multi.setShortValue((short) 0, (short) j)), (short) j); assertEquals(bf_multi.setShortValue((short) 0, (short) j), (short) (j << 7)); } for (int j = 0; j < 128; j++) { assertEquals(bf_zero.getShortValue(bf_zero.setShortValue((short) 0, (short) j)), (short) 0); assertEquals(bf_zero.setShortValue((short) 0, (short) j), (short) (0)); } // verify that excess bits are stripped off assertEquals(bf_multi.setShortValue((short) 0x3f80, (short) 128), (short) 0); for (int j = 0; j < 2; j++) { assertEquals(bf_single.getShortValue(bf_single.setShortValue((short) 0, (short) j)), (short) j); assertEquals(bf_single.setShortValue((short) 0, (short) j), (short) (j << 14)); } // verify that excess bits are stripped off assertEquals(bf_single.setShortValue((short) 0x4000, (short) 2), (short) 0); } public void testByte() { assertEquals(0, new BitField(0).setByteBoolean((byte) 0, true)); assertEquals(1, new BitField(1).setByteBoolean((byte) 0, true)); assertEquals(2, new BitField(2).setByteBoolean((byte) 0, true)); assertEquals(4, new BitField(4).setByteBoolean((byte) 0, true)); assertEquals(8, new BitField(8).setByteBoolean((byte) 0, true)); assertEquals(16, new BitField(16).setByteBoolean((byte) 0, true)); assertEquals(32, new BitField(32).setByteBoolean((byte) 0, true)); assertEquals(64, new BitField(64).setByteBoolean((byte) 0, true)); assertEquals(-128, new BitField(128).setByteBoolean((byte) 0, true)); assertEquals(1, new BitField(0).setByteBoolean((byte) 1, false)); assertEquals(0, new BitField(1).setByteBoolean((byte) 1, false)); assertEquals(0, new BitField(2).setByteBoolean((byte) 2, false)); assertEquals(0, new BitField(4).setByteBoolean((byte) 4, false)); assertEquals(0, new BitField(8).setByteBoolean((byte) 8, false)); assertEquals(0, new BitField(16).setByteBoolean((byte) 16, false)); assertEquals(0, new BitField(32).setByteBoolean((byte) 32, false)); assertEquals(0, new BitField(64).setByteBoolean((byte) 64, false)); assertEquals(0, new BitField(128).setByteBoolean((byte) 128, false)); assertEquals(-2, new BitField(1).setByteBoolean((byte) 255, false)); byte clearedBit = new BitField(0x40).setByteBoolean((byte) - 63, false); assertEquals(false, new BitField(0x40).isSet(clearedBit)); } /** * test the clear() method */ public void testClear() { assertEquals(bf_multi.clear(-1), 0xFFFFC07F); assertEquals(bf_single.clear(-1), 0xFFFFBFFF); assertEquals(bf_zero.clear(-1), 0xFFFFFFFF); } /** * test the clearShort() method */ public void testClearShort() { assertEquals(bf_multi.clearShort((short) - 1), (short) 0xC07F); assertEquals(bf_single.clearShort((short) - 1), (short) 0xBFFF); assertEquals(bf_zero.clearShort((short) -1), (short) 0xFFFF); } /** * test the set() method */ public void testSet() { assertEquals(bf_multi.set(0), 0x3F80); assertEquals(bf_single.set(0), 0x4000); assertEquals(bf_zero.set(0), 0); } /** * test the setShort() method */ public void testSetShort() { assertEquals(bf_multi.setShort((short) 0), (short) 0x3F80); assertEquals(bf_single.setShort((short) 0), (short) 0x4000); assertEquals(bf_zero.setShort((short) 0), (short) 0); } /** * test the setBoolean() method */ public void testSetBoolean() { assertEquals(bf_multi.set(0), bf_multi.setBoolean(0, true)); assertEquals(bf_single.set(0), bf_single.setBoolean(0, true)); assertEquals(bf_zero.set(0), bf_zero.setBoolean(0, true)); assertEquals(bf_multi.clear(-1), bf_multi.setBoolean(-1, false)); assertEquals(bf_single.clear(-1), bf_single.setBoolean(-1, false)); assertEquals(bf_zero.clear(-1), bf_zero.setBoolean(-1, false)); } /** * test the setShortBoolean() method */ public void testSetShortBoolean() { assertEquals(bf_multi.setShort((short) 0), bf_multi.setShortBoolean((short) 0, true)); assertEquals(bf_single.setShort((short) 0), bf_single.setShortBoolean((short) 0, true)); assertEquals(bf_zero.setShort((short) 0), bf_zero.setShortBoolean((short) 0, true)); assertEquals(bf_multi.clearShort((short) - 1), bf_multi.setShortBoolean((short) - 1, false)); assertEquals(bf_single.clearShort((short) - 1), bf_single.setShortBoolean((short) - 1, false)); assertEquals(bf_zero.clearShort((short) -1), bf_zero.setShortBoolean((short) -1, false)); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/BooleanUtilsTest.java100644 0 0 62716 11513702440 25116 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import junit.framework.TestCase; /** * Unit tests {@link org.apache.commons.lang.BooleanUtils}. * * @author Apache Software Foundation * @author Matthew Hawthorne * @version $Id: BooleanUtilsTest.java 1056846 2011-01-09 00:40:03Z niallp $ */ public class BooleanUtilsTest extends TestCase { public BooleanUtilsTest(String name) { super(name); } //----------------------------------------------------------------------- public void testConstructor() { assertNotNull(new BooleanUtils()); Constructor[] cons = BooleanUtils.class.getDeclaredConstructors(); assertEquals(1, cons.length); assertEquals(true, Modifier.isPublic(cons[0].getModifiers())); assertEquals(true, Modifier.isPublic(BooleanUtils.class.getModifiers())); assertEquals(false, Modifier.isFinal(BooleanUtils.class.getModifiers())); } //----------------------------------------------------------------------- public void test_negate_Boolean() { assertSame(null, BooleanUtils.negate(null)); assertSame(Boolean.TRUE, BooleanUtils.negate(Boolean.FALSE)); assertSame(Boolean.FALSE, BooleanUtils.negate(Boolean.TRUE)); } //----------------------------------------------------------------------- public void test_isTrue_Boolean() { assertEquals(true, BooleanUtils.isTrue(Boolean.TRUE)); assertEquals(false, BooleanUtils.isTrue(Boolean.FALSE)); assertEquals(false, BooleanUtils.isTrue((Boolean) null)); } public void test_isNotTrue_Boolean() { assertEquals(false, BooleanUtils.isNotTrue(Boolean.TRUE)); assertEquals(true, BooleanUtils.isNotTrue(Boolean.FALSE)); assertEquals(true, BooleanUtils.isNotTrue((Boolean) null)); } //----------------------------------------------------------------------- public void test_isFalse_Boolean() { assertEquals(false, BooleanUtils.isFalse(Boolean.TRUE)); assertEquals(true, BooleanUtils.isFalse(Boolean.FALSE)); assertEquals(false, BooleanUtils.isFalse((Boolean) null)); } public void test_isNotFalse_Boolean() { assertEquals(true, BooleanUtils.isNotFalse(Boolean.TRUE)); assertEquals(false, BooleanUtils.isNotFalse(Boolean.FALSE)); assertEquals(true, BooleanUtils.isNotFalse((Boolean) null)); } //----------------------------------------------------------------------- public void test_toBooleanObject_boolean() { assertSame(Boolean.TRUE, BooleanUtils.toBooleanObject(true)); assertSame(Boolean.FALSE, BooleanUtils.toBooleanObject(false)); } public void test_toBoolean_Boolean() { assertEquals(true, BooleanUtils.toBoolean(Boolean.TRUE)); assertEquals(false, BooleanUtils.toBoolean(Boolean.FALSE)); assertEquals(false, BooleanUtils.toBoolean((Boolean) null)); } public void test_toBooleanDefaultIfNull_Boolean_boolean() { assertEquals(true, BooleanUtils.toBooleanDefaultIfNull(Boolean.TRUE, true)); assertEquals(true, BooleanUtils.toBooleanDefaultIfNull(Boolean.TRUE, false)); assertEquals(false, BooleanUtils.toBooleanDefaultIfNull(Boolean.FALSE, true)); assertEquals(false, BooleanUtils.toBooleanDefaultIfNull(Boolean.FALSE, false)); assertEquals(true, BooleanUtils.toBooleanDefaultIfNull((Boolean) null, true)); assertEquals(false, BooleanUtils.toBooleanDefaultIfNull((Boolean) null, false)); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- public void test_toBoolean_int() { assertEquals(true, BooleanUtils.toBoolean(1)); assertEquals(true, BooleanUtils.toBoolean(-1)); assertEquals(false, BooleanUtils.toBoolean(0)); } public void test_toBooleanObject_int() { assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject(1)); assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject(-1)); assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject(0)); } public void test_toBooleanObject_Integer() { assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject(new Integer(1))); assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject(new Integer(-1))); assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject(new Integer(0))); assertEquals(null, BooleanUtils.toBooleanObject((Integer) null)); } //----------------------------------------------------------------------- public void test_toBoolean_int_int_int() { assertEquals(true, BooleanUtils.toBoolean(6, 6, 7)); assertEquals(false, BooleanUtils.toBoolean(7, 6, 7)); try { BooleanUtils.toBoolean(8, 6, 7); fail(); } catch (IllegalArgumentException ex) {} } public void test_toBoolean_Integer_Integer_Integer() { Integer six = new Integer(6); Integer seven = new Integer(7); assertEquals(true, BooleanUtils.toBoolean((Integer) null, null, seven)); assertEquals(false, BooleanUtils.toBoolean((Integer) null, six, null)); try { BooleanUtils.toBoolean(null, six, seven); fail(); } catch (IllegalArgumentException ex) {} assertEquals(true, BooleanUtils.toBoolean(new Integer(6), six, seven)); assertEquals(false, BooleanUtils.toBoolean(new Integer(7), six, seven)); try { BooleanUtils.toBoolean(new Integer(8), six, seven); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void test_toBooleanObject_int_int_int() { assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject(6, 6, 7, 8)); assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject(7, 6, 7, 8)); assertEquals(null, BooleanUtils.toBooleanObject(8, 6, 7, 8)); try { BooleanUtils.toBooleanObject(9, 6, 7, 8); fail(); } catch (IllegalArgumentException ex) {} } public void test_toBooleanObject_Integer_Integer_Integer_Integer() { Integer six = new Integer(6); Integer seven = new Integer(7); Integer eight = new Integer(8); assertSame(Boolean.TRUE, BooleanUtils.toBooleanObject((Integer) null, null, seven, eight)); assertSame(Boolean.FALSE, BooleanUtils.toBooleanObject((Integer) null, six, null, eight)); assertSame(null, BooleanUtils.toBooleanObject((Integer) null, six, seven, null)); try { BooleanUtils.toBooleanObject(null, six, seven, eight); fail(); } catch (IllegalArgumentException ex) {} assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject(new Integer(6), six, seven, eight)); assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject(new Integer(7), six, seven, eight)); assertEquals(null, BooleanUtils.toBooleanObject(new Integer(8), six, seven, eight)); try { BooleanUtils.toBooleanObject(new Integer(9), six, seven, eight); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void test_toInteger_boolean() { assertEquals(1, BooleanUtils.toInteger(true)); assertEquals(0, BooleanUtils.toInteger(false)); } public void test_toIntegerObject_boolean() { assertEquals(new Integer(1), BooleanUtils.toIntegerObject(true)); assertEquals(new Integer(0), BooleanUtils.toIntegerObject(false)); } public void test_toIntegerObject_Boolean() { assertEquals(new Integer(1), BooleanUtils.toIntegerObject(Boolean.TRUE)); assertEquals(new Integer(0), BooleanUtils.toIntegerObject(Boolean.FALSE)); assertEquals(null, BooleanUtils.toIntegerObject((Boolean) null)); } //----------------------------------------------------------------------- public void test_toInteger_boolean_int_int() { assertEquals(6, BooleanUtils.toInteger(true, 6, 7)); assertEquals(7, BooleanUtils.toInteger(false, 6, 7)); } public void test_toInteger_Boolean_int_int_int() { assertEquals(6, BooleanUtils.toInteger(Boolean.TRUE, 6, 7, 8)); assertEquals(7, BooleanUtils.toInteger(Boolean.FALSE, 6, 7, 8)); assertEquals(8, BooleanUtils.toInteger(null, 6, 7, 8)); } public void test_toIntegerObject_boolean_Integer_Integer() { Integer six = new Integer(6); Integer seven = new Integer(7); assertEquals(six, BooleanUtils.toIntegerObject(true, six, seven)); assertEquals(seven, BooleanUtils.toIntegerObject(false, six, seven)); } public void test_toIntegerObject_Boolean_Integer_Integer_Integer() { Integer six = new Integer(6); Integer seven = new Integer(7); Integer eight = new Integer(8); assertEquals(six, BooleanUtils.toIntegerObject(Boolean.TRUE, six, seven, eight)); assertEquals(seven, BooleanUtils.toIntegerObject(Boolean.FALSE, six, seven, eight)); assertEquals(eight, BooleanUtils.toIntegerObject((Boolean) null, six, seven, eight)); assertEquals(null, BooleanUtils.toIntegerObject((Boolean) null, six, seven, null)); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- public void test_toBooleanObject_String() { assertEquals(null, BooleanUtils.toBooleanObject((String) null)); assertEquals(null, BooleanUtils.toBooleanObject("")); assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject("false")); assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject("no")); assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject("off")); assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject("FALSE")); assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject("NO")); assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject("OFF")); assertEquals(null, BooleanUtils.toBooleanObject("oof")); assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject("true")); assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject("yes")); assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject("on")); assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject("TRUE")); assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject("ON")); assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject("YES")); assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject("TruE")); assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject("TruE")); assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject("y")); assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject("Y")); assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject("t")); assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject("T")); assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject("f")); assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject("F")); assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject("n")); assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject("N")); assertEquals(null, BooleanUtils.toBooleanObject("z")); assertEquals(null, BooleanUtils.toBooleanObject("ab")); assertEquals(null, BooleanUtils.toBooleanObject("yoo")); } public void test_toBooleanObject_String_String_String_String() { assertSame(Boolean.TRUE, BooleanUtils.toBooleanObject((String) null, null, "N", "U")); assertSame(Boolean.FALSE, BooleanUtils.toBooleanObject((String) null, "Y", null, "U")); assertSame(null, BooleanUtils.toBooleanObject((String) null, "Y", "N", null)); try { BooleanUtils.toBooleanObject((String) null, "Y", "N", "U"); fail(); } catch (IllegalArgumentException ex) {} assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject("Y", "Y", "N", "U")); assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject("N", "Y", "N", "U")); assertEquals(null, BooleanUtils.toBooleanObject("U", "Y", "N", "U")); try { BooleanUtils.toBooleanObject(null, "Y", "N", "U"); fail(); } catch (IllegalArgumentException ex) {} try { BooleanUtils.toBooleanObject("X", "Y", "N", "U"); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void test_toBoolean_String() { assertEquals(false, BooleanUtils.toBoolean((String) null)); assertEquals(false, BooleanUtils.toBoolean("")); assertEquals(false, BooleanUtils.toBoolean("off")); assertEquals(false, BooleanUtils.toBoolean("oof")); assertEquals(false, BooleanUtils.toBoolean("yep")); assertEquals(false, BooleanUtils.toBoolean("trux")); assertEquals(false, BooleanUtils.toBoolean("false")); assertEquals(false, BooleanUtils.toBoolean("a")); assertEquals(true, BooleanUtils.toBoolean("true")); // interned handled differently assertEquals(true, BooleanUtils.toBoolean(new StringBuffer("tr").append("ue").toString())); assertEquals(true, BooleanUtils.toBoolean("truE")); assertEquals(true, BooleanUtils.toBoolean("trUe")); assertEquals(true, BooleanUtils.toBoolean("trUE")); assertEquals(true, BooleanUtils.toBoolean("tRue")); assertEquals(true, BooleanUtils.toBoolean("tRuE")); assertEquals(true, BooleanUtils.toBoolean("tRUe")); assertEquals(true, BooleanUtils.toBoolean("tRUE")); assertEquals(true, BooleanUtils.toBoolean("TRUE")); assertEquals(true, BooleanUtils.toBoolean("TRUe")); assertEquals(true, BooleanUtils.toBoolean("TRuE")); assertEquals(true, BooleanUtils.toBoolean("TRue")); assertEquals(true, BooleanUtils.toBoolean("TrUE")); assertEquals(true, BooleanUtils.toBoolean("TrUe")); assertEquals(true, BooleanUtils.toBoolean("TruE")); assertEquals(true, BooleanUtils.toBoolean("True")); assertEquals(true, BooleanUtils.toBoolean("on")); assertEquals(true, BooleanUtils.toBoolean("oN")); assertEquals(true, BooleanUtils.toBoolean("On")); assertEquals(true, BooleanUtils.toBoolean("ON")); assertEquals(true, BooleanUtils.toBoolean("yes")); assertEquals(true, BooleanUtils.toBoolean("yeS")); assertEquals(true, BooleanUtils.toBoolean("yEs")); assertEquals(true, BooleanUtils.toBoolean("yES")); assertEquals(true, BooleanUtils.toBoolean("Yes")); assertEquals(true, BooleanUtils.toBoolean("YeS")); assertEquals(true, BooleanUtils.toBoolean("YEs")); assertEquals(true, BooleanUtils.toBoolean("YES")); assertEquals(false, BooleanUtils.toBoolean("yes?")); assertEquals(false, BooleanUtils.toBoolean("tru")); assertEquals(false, BooleanUtils.toBoolean("no")); assertEquals(false, BooleanUtils.toBoolean("off")); assertEquals(false, BooleanUtils.toBoolean("yoo")); } public void test_toBoolean_String_String_String() { assertEquals(true, BooleanUtils.toBoolean((String) null, null, "N")); assertEquals(false, BooleanUtils.toBoolean((String) null, "Y", null)); try { BooleanUtils.toBooleanObject((String) null, "Y", "N", "U"); fail(); } catch (IllegalArgumentException ex) {} assertEquals(true, BooleanUtils.toBoolean("Y", "Y", "N")); assertEquals(false, BooleanUtils.toBoolean("N", "Y", "N")); try { BooleanUtils.toBoolean(null, "Y", "N"); fail(); } catch (IllegalArgumentException ex) {} try { BooleanUtils.toBoolean("X", "Y", "N"); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void test_toStringTrueFalse_Boolean() { assertEquals(null, BooleanUtils.toStringTrueFalse((Boolean) null)); assertEquals("true", BooleanUtils.toStringTrueFalse(Boolean.TRUE)); assertEquals("false", BooleanUtils.toStringTrueFalse(Boolean.FALSE)); } public void test_toStringOnOff_Boolean() { assertEquals(null, BooleanUtils.toStringOnOff((Boolean) null)); assertEquals("on", BooleanUtils.toStringOnOff(Boolean.TRUE)); assertEquals("off", BooleanUtils.toStringOnOff(Boolean.FALSE)); } public void test_toStringYesNo_Boolean() { assertEquals(null, BooleanUtils.toStringYesNo((Boolean) null)); assertEquals("yes", BooleanUtils.toStringYesNo(Boolean.TRUE)); assertEquals("no", BooleanUtils.toStringYesNo(Boolean.FALSE)); } public void test_toString_Boolean_String_String_String() { assertEquals("U", BooleanUtils.toString((Boolean) null, "Y", "N", "U")); assertEquals("Y", BooleanUtils.toString(Boolean.TRUE, "Y", "N", "U")); assertEquals("N", BooleanUtils.toString(Boolean.FALSE, "Y", "N", "U")); } //----------------------------------------------------------------------- public void test_toStringTrueFalse_boolean() { assertEquals("true", BooleanUtils.toStringTrueFalse(true)); assertEquals("false", BooleanUtils.toStringTrueFalse(false)); } public void test_toStringOnOff_boolean() { assertEquals("on", BooleanUtils.toStringOnOff(true)); assertEquals("off", BooleanUtils.toStringOnOff(false)); } public void test_toStringYesNo_boolean() { assertEquals("yes", BooleanUtils.toStringYesNo(true)); assertEquals("no", BooleanUtils.toStringYesNo(false)); } public void test_toString_boolean_String_String_String() { assertEquals("Y", BooleanUtils.toString(true, "Y", "N")); assertEquals("N", BooleanUtils.toString(false, "Y", "N")); } // testXor // ----------------------------------------------------------------------- public void testXor_primitive_nullInput() { final boolean[] b = null; try { BooleanUtils.xor(b); fail("Exception was not thrown for null input."); } catch (IllegalArgumentException ex) {} } public void testXor_primitive_emptyInput() { try { BooleanUtils.xor(new boolean[] {}); fail("Exception was not thrown for empty input."); } catch (IllegalArgumentException ex) {} } public void testXor_primitive_validInput_2items() { assertTrue( "True result for (true, true)", ! BooleanUtils.xor(new boolean[] { true, true })); assertTrue( "True result for (false, false)", ! BooleanUtils.xor(new boolean[] { false, false })); assertTrue( "False result for (true, false)", BooleanUtils.xor(new boolean[] { true, false })); assertTrue( "False result for (false, true)", BooleanUtils.xor(new boolean[] { false, true })); } public void testXor_primitive_validInput_3items() { assertTrue( "False result for (false, false, true)", BooleanUtils.xor(new boolean[] { false, false, true })); assertTrue( "False result for (false, true, false)", BooleanUtils.xor(new boolean[] { false, true, false })); assertTrue( "False result for (true, false, false)", BooleanUtils.xor(new boolean[] { true, false, false })); assertTrue( "True result for (true, true, true)", ! BooleanUtils.xor(new boolean[] { true, true, true })); assertTrue( "True result for (false, false)", ! BooleanUtils.xor(new boolean[] { false, false, false })); assertTrue( "True result for (true, true, false)", ! BooleanUtils.xor(new boolean[] { true, true, false })); assertTrue( "True result for (true, false, true)", ! BooleanUtils.xor(new boolean[] { true, false, true })); assertTrue( "False result for (false, true, true)", ! BooleanUtils.xor(new boolean[] { false, true, true })); } public void testXor_object_nullInput() { final Boolean[] b = null; try { BooleanUtils.xor(b); fail("Exception was not thrown for null input."); } catch (IllegalArgumentException ex) {} } public void testXor_object_emptyInput() { try { BooleanUtils.xor(new Boolean[] {}); fail("Exception was not thrown for empty input."); } catch (IllegalArgumentException ex) {} } public void testXor_object_nullElementInput() { try { BooleanUtils.xor(new Boolean[] {null}); fail("Exception was not thrown for null element input."); } catch (IllegalArgumentException ex) {} } public void testXor_object_validInput_2items() { assertTrue( "True result for (true, true)", ! BooleanUtils .xor(new Boolean[] { Boolean.TRUE, Boolean.TRUE }) .booleanValue()); assertTrue( "True result for (false, false)", ! BooleanUtils .xor(new Boolean[] { Boolean.FALSE, Boolean.FALSE }) .booleanValue()); assertTrue( "False result for (true, false)", BooleanUtils .xor(new Boolean[] { Boolean.TRUE, Boolean.FALSE }) .booleanValue()); assertTrue( "False result for (false, true)", BooleanUtils .xor(new Boolean[] { Boolean.FALSE, Boolean.TRUE }) .booleanValue()); } public void testXor_object_validInput_3items() { assertTrue( "False result for (false, false, true)", BooleanUtils .xor( new Boolean[] { Boolean.FALSE, Boolean.FALSE, Boolean.TRUE }) .booleanValue()); assertTrue( "False result for (false, true, false)", BooleanUtils .xor( new Boolean[] { Boolean.FALSE, Boolean.TRUE, Boolean.FALSE }) .booleanValue()); assertTrue( "False result for (true, false, false)", BooleanUtils .xor( new Boolean[] { Boolean.TRUE, Boolean.FALSE, Boolean.FALSE }) .booleanValue()); assertTrue( "True result for (true, true, true)", ! BooleanUtils .xor(new Boolean[] { Boolean.TRUE, Boolean.TRUE, Boolean.TRUE }) .booleanValue()); assertTrue( "True result for (false, false)", ! BooleanUtils.xor( new Boolean[] { Boolean.FALSE, Boolean.FALSE, Boolean.FALSE }) .booleanValue()); assertTrue( "True result for (true, true, false)", ! BooleanUtils.xor( new Boolean[] { Boolean.TRUE, Boolean.TRUE, Boolean.FALSE }) .booleanValue()); assertTrue( "True result for (true, false, true)", ! BooleanUtils.xor( new Boolean[] { Boolean.TRUE, Boolean.FALSE, Boolean.TRUE }) .booleanValue()); assertTrue( "False result for (false, true, true)", ! BooleanUtils.xor( new Boolean[] { Boolean.FALSE, Boolean.TRUE, Boolean.TRUE }) .booleanValue()); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/builder/CompareToBuilderTest.java100644 0 0 143163 11513702436 27365 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.builder; import java.math.BigInteger; import junit.framework.TestCase; /** * Unit tests {@link org.apache.commons.lang.builder.CompareToBuilder}. * * @author Apache Software Foundation * @author Steve Downey * @version $Id: CompareToBuilderTest.java 905636 2010-02-02 14:03:32Z niallp $ */ public class CompareToBuilderTest extends TestCase { public CompareToBuilderTest(String name) { super(name); } //----------------------------------------------------------------------- static class TestObject implements Comparable { private int a; public TestObject(int a) { this.a = a; } public boolean equals(Object o) { if (o == this) { return true; } if (!(o instanceof TestObject)) { return false; } TestObject rhs = (TestObject) o; return (a == rhs.a); } public void setA(int a) { this.a = a; } public int getA() { return a; } public int compareTo(Object o) { TestObject rhs = (TestObject) o; return (a < rhs.a) ? -1 : (a > rhs.a) ? +1 : 0; } } static class TestSubObject extends TestObject { private int b; public TestSubObject() { super(0); } public TestSubObject(int a, int b) { super(a); this.b = b; } public boolean equals(Object o) { if (o == this) { return true; } if (!(o instanceof TestSubObject)) { return false; } TestSubObject rhs = (TestSubObject) o; return super.equals(o) && (b == rhs.b); } } static class TestTransientSubObject extends TestObject { private transient int t; public TestTransientSubObject(int a, int t) { super(a); this.t = t; } } public void testReflectionCompare() { TestObject o1 = new TestObject(4); TestObject o2 = new TestObject(4); assertTrue(CompareToBuilder.reflectionCompare(o1, o1) == 0); assertTrue(CompareToBuilder.reflectionCompare(o1, o2) == 0); o2.setA(5); assertTrue(CompareToBuilder.reflectionCompare(o1, o2) < 0); assertTrue(CompareToBuilder.reflectionCompare(o2, o1) > 0); } public void testReflectionCompareEx1() { TestObject o1 = new TestObject(4); try { CompareToBuilder.reflectionCompare(o1, null); } catch (NullPointerException ex) { return; } fail(); } public void testReflectionCompareEx2() { TestObject o1 = new TestObject(4); Object o2 = new Object(); try { CompareToBuilder.reflectionCompare(o1, o2); fail(); } catch (ClassCastException ex) {} } public void testReflectionHierarchyCompare() { testReflectionHierarchyCompare(false, null); } public void testReflectionHierarchyCompareExcludeFields() { String[] excludeFields = new String[] { "b" }; testReflectionHierarchyCompare(true, excludeFields); TestSubObject x; TestSubObject y; TestSubObject z; x = new TestSubObject(1, 1); y = new TestSubObject(2, 1); z = new TestSubObject(3, 1); assertXYZCompareOrder(x, y, z, true, excludeFields); x = new TestSubObject(1, 3); y = new TestSubObject(2, 2); z = new TestSubObject(3, 1); assertXYZCompareOrder(x, y, z, true, excludeFields); } public void testReflectionHierarchyCompareTransients() { testReflectionHierarchyCompare(true, null); TestTransientSubObject x; TestTransientSubObject y; TestTransientSubObject z; x = new TestTransientSubObject(1, 1); y = new TestTransientSubObject(2, 2); z = new TestTransientSubObject(3, 3); assertXYZCompareOrder(x, y, z, true, null); x = new TestTransientSubObject(1, 1); y = new TestTransientSubObject(1, 2); z = new TestTransientSubObject(1, 3); assertXYZCompareOrder(x, y, z, true, null); } private void assertXYZCompareOrder(Object x, Object y, Object z, boolean testTransients, String[] excludeFields) { assertTrue(0 == CompareToBuilder.reflectionCompare(x, x, testTransients, null, excludeFields)); assertTrue(0 == CompareToBuilder.reflectionCompare(y, y, testTransients, null, excludeFields)); assertTrue(0 == CompareToBuilder.reflectionCompare(z, z, testTransients, null, excludeFields)); assertTrue(0 > CompareToBuilder.reflectionCompare(x, y, testTransients, null, excludeFields)); assertTrue(0 > CompareToBuilder.reflectionCompare(x, z, testTransients, null, excludeFields)); assertTrue(0 > CompareToBuilder.reflectionCompare(y, z, testTransients, null, excludeFields)); assertTrue(0 < CompareToBuilder.reflectionCompare(y, x, testTransients, null, excludeFields)); assertTrue(0 < CompareToBuilder.reflectionCompare(z, x, testTransients, null, excludeFields)); assertTrue(0 < CompareToBuilder.reflectionCompare(z, y, testTransients, null, excludeFields)); } public void testReflectionHierarchyCompare(boolean testTransients, String[] excludeFields) { TestObject to1 = new TestObject(1); TestObject to2 = new TestObject(2); TestObject to3 = new TestObject(3); TestSubObject tso1 = new TestSubObject(1, 1); TestSubObject tso2 = new TestSubObject(2, 2); TestSubObject tso3 = new TestSubObject(3, 3); assertReflectionCompareContract(to1, to1, to1, false, excludeFields); assertReflectionCompareContract(to1, to2, to3, false, excludeFields); assertReflectionCompareContract(tso1, tso1, tso1, false, excludeFields); assertReflectionCompareContract(tso1, tso2, tso3, false, excludeFields); assertReflectionCompareContract("1", "2", "3", false, excludeFields); assertTrue(0 != CompareToBuilder.reflectionCompare(tso1, new TestSubObject(1, 0), testTransients)); assertTrue(0 != CompareToBuilder.reflectionCompare(tso1, new TestSubObject(0, 1), testTransients)); // root class assertXYZCompareOrder(to1, to2, to3, true, null); // subclass assertXYZCompareOrder(tso1, tso2, tso3, true, null); } /** * See "Effective Java" under "Consider Implementing Comparable". * * @param x an object to compare * @param y an object to compare * @param z an object to compare * @param testTransients Whether to include transients in the comparison * @param excludeFields fields to exclude */ public void assertReflectionCompareContract(Object x, Object y, Object z, boolean testTransients, String[] excludeFields) { // signum assertTrue(reflectionCompareSignum(x, y, testTransients, excludeFields) == -reflectionCompareSignum(y, x, testTransients, excludeFields)); // transitive if (CompareToBuilder.reflectionCompare(x, y, testTransients, null, excludeFields) > 0 && CompareToBuilder.reflectionCompare(y, z, testTransients, null, excludeFields) > 0){ assertTrue(CompareToBuilder.reflectionCompare(x, z, testTransients, null, excludeFields) > 0); } // un-named if (CompareToBuilder.reflectionCompare(x, y, testTransients, null, excludeFields) == 0) { assertTrue(reflectionCompareSignum(x, z, testTransients, excludeFields) == -reflectionCompareSignum(y, z, testTransients, excludeFields)); } // strongly recommended but not strictly required assertTrue((CompareToBuilder.reflectionCompare(x, y, testTransients) ==0 ) == EqualsBuilder.reflectionEquals(x, y, testTransients)); } /** * Returns the signum of the result of comparing x and y with * CompareToBuilder.reflectionCompare * * @param lhs The "left-hand-side" of the comparison. * @param rhs The "right-hand-side" of the comparison. * @param testTransients Whether to include transients in the comparison * @param excludeFields fields to exclude * @return int The signum */ private int reflectionCompareSignum(Object lhs, Object rhs, boolean testTransients, String[] excludeFields) { return BigInteger.valueOf(CompareToBuilder.reflectionCompare(lhs, rhs, testTransients)).signum(); } public void testAppendSuper() { TestObject o1 = new TestObject(4); TestObject o2 = new TestObject(5); assertTrue(new CompareToBuilder().appendSuper(0).append(o1, o1).toComparison() == 0); assertTrue(new CompareToBuilder().appendSuper(0).append(o1, o2).toComparison() < 0); assertTrue(new CompareToBuilder().appendSuper(0).append(o2, o1).toComparison() > 0); assertTrue(new CompareToBuilder().appendSuper(-1).append(o1, o1).toComparison() < 0); assertTrue(new CompareToBuilder().appendSuper(-1).append(o1, o2).toComparison() < 0); assertTrue(new CompareToBuilder().appendSuper(1).append(o1, o1).toComparison() > 0); assertTrue(new CompareToBuilder().appendSuper(1).append(o1, o2).toComparison() > 0); } public void testObject() { TestObject o1 = new TestObject(4); TestObject o2 = new TestObject(4); assertTrue(new CompareToBuilder().append(o1, o1).toComparison() == 0); assertTrue(new CompareToBuilder().append(o1, o2).toComparison() == 0); o2.setA(5); assertTrue(new CompareToBuilder().append(o1, o2).toComparison() < 0); assertTrue(new CompareToBuilder().append(o2, o1).toComparison() > 0); assertTrue(new CompareToBuilder().append(o1, null).toComparison() > 0); assertTrue(new CompareToBuilder().append((Object) null, (Object) null).toComparison() == 0); assertTrue(new CompareToBuilder().append(null, o1).toComparison() < 0); } public void testObjectEx2() { TestObject o1 = new TestObject(4); Object o2 = new Object(); try { new CompareToBuilder().append(o1, o2); fail(); } catch (ClassCastException ex) {} } public void testObjectComparator() { String o1 = "Fred"; String o2 = "Fred"; assertTrue(new CompareToBuilder().append(o1, o1, String.CASE_INSENSITIVE_ORDER).toComparison() == 0); assertTrue(new CompareToBuilder().append(o1, o2, String.CASE_INSENSITIVE_ORDER).toComparison() == 0); o2 = "FRED"; assertTrue(new CompareToBuilder().append(o1, o2, String.CASE_INSENSITIVE_ORDER).toComparison() == 0); assertTrue(new CompareToBuilder().append(o2, o1, String.CASE_INSENSITIVE_ORDER).toComparison() == 0); o2 = "FREDA"; assertTrue(new CompareToBuilder().append(o1, o2, String.CASE_INSENSITIVE_ORDER).toComparison() < 0); assertTrue(new CompareToBuilder().append(o2, o1, String.CASE_INSENSITIVE_ORDER).toComparison() > 0); assertTrue(new CompareToBuilder().append(o1, null, String.CASE_INSENSITIVE_ORDER).toComparison() > 0); assertTrue(new CompareToBuilder().append((Object) null, (Object) null, String.CASE_INSENSITIVE_ORDER).toComparison() == 0); assertTrue(new CompareToBuilder().append(null, o1, String.CASE_INSENSITIVE_ORDER).toComparison() < 0); } public void testObjectComparatorNull() { String o1 = "Fred"; String o2 = "Fred"; assertTrue(new CompareToBuilder().append(o1, o1, null).toComparison() == 0); assertTrue(new CompareToBuilder().append(o1, o2, null).toComparison() == 0); o2 = "Zebra"; assertTrue(new CompareToBuilder().append(o1, o2, null).toComparison() < 0); assertTrue(new CompareToBuilder().append(o2, o1, null).toComparison() > 0); assertTrue(new CompareToBuilder().append(o1, null, null).toComparison() > 0); assertTrue(new CompareToBuilder().append((Object) null, (Object) null, null).toComparison() == 0); assertTrue(new CompareToBuilder().append(null, o1, null).toComparison() < 0); } public void testLong() { long o1 = 1L; long o2 = 2L; assertTrue(new CompareToBuilder().append(o1, o1).toComparison() == 0); assertTrue(new CompareToBuilder().append(o1, o2).toComparison() < 0); assertTrue(new CompareToBuilder().append(o2, o1).toComparison() > 0); assertTrue(new CompareToBuilder().append(o1, Long.MAX_VALUE).toComparison() < 0); assertTrue(new CompareToBuilder().append(Long.MAX_VALUE, o1).toComparison() > 0); assertTrue(new CompareToBuilder().append(o1, Long.MIN_VALUE).toComparison() > 0); assertTrue(new CompareToBuilder().append(Long.MIN_VALUE, o1).toComparison() < 0); } public void testInt() { int o1 = 1; int o2 = 2; assertTrue(new CompareToBuilder().append(o1, o1).toComparison() == 0); assertTrue(new CompareToBuilder().append(o1, o2).toComparison() < 0); assertTrue(new CompareToBuilder().append(o2, o1).toComparison() > 0); assertTrue(new CompareToBuilder().append(o1, Integer.MAX_VALUE).toComparison() < 0); assertTrue(new CompareToBuilder().append(Integer.MAX_VALUE, o1).toComparison() > 0); assertTrue(new CompareToBuilder().append(o1, Integer.MIN_VALUE).toComparison() > 0); assertTrue(new CompareToBuilder().append(Integer.MIN_VALUE, o1).toComparison() < 0); } public void testShort() { short o1 = 1; short o2 = 2; assertTrue(new CompareToBuilder().append(o1, o1).toComparison() == 0); assertTrue(new CompareToBuilder().append(o1, o2).toComparison() < 0); assertTrue(new CompareToBuilder().append(o2, o1).toComparison() > 0); assertTrue(new CompareToBuilder().append(o1, Short.MAX_VALUE).toComparison() < 0); assertTrue(new CompareToBuilder().append(Short.MAX_VALUE, o1).toComparison() > 0); assertTrue(new CompareToBuilder().append(o1, Short.MIN_VALUE).toComparison() > 0); assertTrue(new CompareToBuilder().append(Short.MIN_VALUE, o1).toComparison() < 0); } public void testChar() { char o1 = 1; char o2 = 2; assertTrue(new CompareToBuilder().append(o1, o1).toComparison() == 0); assertTrue(new CompareToBuilder().append(o1, o2).toComparison() < 0); assertTrue(new CompareToBuilder().append(o2, o1).toComparison() > 0); assertTrue(new CompareToBuilder().append(o1, Character.MAX_VALUE).toComparison() < 0); assertTrue(new CompareToBuilder().append(Character.MAX_VALUE, o1).toComparison() > 0); assertTrue(new CompareToBuilder().append(o1, Character.MIN_VALUE).toComparison() > 0); assertTrue(new CompareToBuilder().append(Character.MIN_VALUE, o1).toComparison() < 0); } public void testByte() { byte o1 = 1; byte o2 = 2; assertTrue(new CompareToBuilder().append(o1, o1).toComparison() == 0); assertTrue(new CompareToBuilder().append(o1, o2).toComparison() < 0); assertTrue(new CompareToBuilder().append(o2, o1).toComparison() > 0); assertTrue(new CompareToBuilder().append(o1, Byte.MAX_VALUE).toComparison() < 0); assertTrue(new CompareToBuilder().append(Byte.MAX_VALUE, o1).toComparison() > 0); assertTrue(new CompareToBuilder().append(o1, Byte.MIN_VALUE).toComparison() > 0); assertTrue(new CompareToBuilder().append(Byte.MIN_VALUE, o1).toComparison() < 0); } public void testDouble() { double o1 = 1; double o2 = 2; assertTrue(new CompareToBuilder().append(o1, o1).toComparison() == 0); assertTrue(new CompareToBuilder().append(o1, o2).toComparison() < 0); assertTrue(new CompareToBuilder().append(o2, o1).toComparison() > 0); assertTrue(new CompareToBuilder().append(o1, Double.MAX_VALUE).toComparison() < 0); assertTrue(new CompareToBuilder().append(Double.MAX_VALUE, o1).toComparison() > 0); assertTrue(new CompareToBuilder().append(o1, Double.MIN_VALUE).toComparison() > 0); assertTrue(new CompareToBuilder().append(Double.MIN_VALUE, o1).toComparison() < 0); assertTrue(new CompareToBuilder().append(Double.NaN, Double.NaN).toComparison() == 0); assertTrue(new CompareToBuilder().append(Double.NaN, Double.MAX_VALUE).toComparison() > 0); assertTrue(new CompareToBuilder().append(Double.POSITIVE_INFINITY, Double.MAX_VALUE).toComparison() > 0); assertTrue(new CompareToBuilder().append(Double.NEGATIVE_INFINITY, Double.MIN_VALUE).toComparison() < 0); assertTrue(new CompareToBuilder().append(o1, Double.NaN).toComparison() < 0); assertTrue(new CompareToBuilder().append(Double.NaN, o1).toComparison() > 0); assertTrue(new CompareToBuilder().append(-0.0, 0.0).toComparison() < 0); assertTrue(new CompareToBuilder().append(0.0, -0.0).toComparison() > 0); } public void testFloat() { float o1 = 1; float o2 = 2; assertTrue(new CompareToBuilder().append(o1, o1).toComparison() == 0); assertTrue(new CompareToBuilder().append(o1, o2).toComparison() < 0); assertTrue(new CompareToBuilder().append(o2, o1).toComparison() > 0); assertTrue(new CompareToBuilder().append(o1, Float.MAX_VALUE).toComparison() < 0); assertTrue(new CompareToBuilder().append(Float.MAX_VALUE, o1).toComparison() > 0); assertTrue(new CompareToBuilder().append(o1, Float.MIN_VALUE).toComparison() > 0); assertTrue(new CompareToBuilder().append(Float.MIN_VALUE, o1).toComparison() < 0); assertTrue(new CompareToBuilder().append(Float.NaN, Float.NaN).toComparison() == 0); assertTrue(new CompareToBuilder().append(Float.NaN, Float.MAX_VALUE).toComparison() > 0); assertTrue(new CompareToBuilder().append(Float.POSITIVE_INFINITY, Float.MAX_VALUE).toComparison() > 0); assertTrue(new CompareToBuilder().append(Float.NEGATIVE_INFINITY, Float.MIN_VALUE).toComparison() < 0); assertTrue(new CompareToBuilder().append(o1, Float.NaN).toComparison() < 0); assertTrue(new CompareToBuilder().append(Float.NaN, o1).toComparison() > 0); assertTrue(new CompareToBuilder().append(-0.0, 0.0).toComparison() < 0); assertTrue(new CompareToBuilder().append(0.0, -0.0).toComparison() > 0); } public void testBoolean() { boolean o1 = true; boolean o2 = false; assertTrue(new CompareToBuilder().append(o1, o1).toComparison() == 0); assertTrue(new CompareToBuilder().append(o2, o2).toComparison() == 0); assertTrue(new CompareToBuilder().append(o1, o2).toComparison() > 0); assertTrue(new CompareToBuilder().append(o2, o1).toComparison() < 0); } public void testObjectArray() { TestObject[] obj1 = new TestObject[2]; obj1[0] = new TestObject(4); obj1[1] = new TestObject(5); TestObject[] obj2 = new TestObject[2]; obj2[0] = new TestObject(4); obj2[1] = new TestObject(5); TestObject[] obj3 = new TestObject[3]; obj3[0] = new TestObject(4); obj3[1] = new TestObject(5); obj3[2] = new TestObject(6); assertTrue(new CompareToBuilder().append(obj1, obj1).toComparison() == 0); assertTrue(new CompareToBuilder().append(obj1, obj2).toComparison() == 0); assertTrue(new CompareToBuilder().append(obj1, obj3).toComparison() < 0); assertTrue(new CompareToBuilder().append(obj3, obj1).toComparison() > 0); obj1[1] = new TestObject(7); assertTrue(new CompareToBuilder().append(obj1, obj2).toComparison() > 0); assertTrue(new CompareToBuilder().append(obj2, obj1).toComparison() < 0); assertTrue(new CompareToBuilder().append(obj1, null).toComparison() > 0); assertTrue(new CompareToBuilder().append((Object[]) null, (Object[]) null).toComparison() == 0); assertTrue(new CompareToBuilder().append(null, obj1).toComparison() < 0); } public void testLongArray() { long[] obj1 = new long[2]; obj1[0] = 5L; obj1[1] = 6L; long[] obj2 = new long[2]; obj2[0] = 5L; obj2[1] = 6L; long[] obj3 = new long[3]; obj3[0] = 5L; obj3[1] = 6L; obj3[2] = 7L; assertTrue(new CompareToBuilder().append(obj1, obj1).toComparison() == 0); assertTrue(new CompareToBuilder().append(obj1, obj2).toComparison() == 0); assertTrue(new CompareToBuilder().append(obj1, obj3).toComparison() < 0); assertTrue(new CompareToBuilder().append(obj3, obj1).toComparison() > 0); obj1[1] = 7; assertTrue(new CompareToBuilder().append(obj1, obj2).toComparison() > 0); assertTrue(new CompareToBuilder().append(obj2, obj1).toComparison() < 0); assertTrue(new CompareToBuilder().append(obj1, null).toComparison() > 0); assertTrue(new CompareToBuilder().append((long[]) null, (long[]) null).toComparison() == 0); assertTrue(new CompareToBuilder().append(null, obj1).toComparison() < 0); } public void testIntArray() { int[] obj1 = new int[2]; obj1[0] = 5; obj1[1] = 6; int[] obj2 = new int[2]; obj2[0] = 5; obj2[1] = 6; int[] obj3 = new int[3]; obj3[0] = 5; obj3[1] = 6; obj3[2] = 7; assertTrue(new CompareToBuilder().append(obj1, obj1).toComparison() == 0); assertTrue(new CompareToBuilder().append(obj1, obj2).toComparison() == 0); assertTrue(new CompareToBuilder().append(obj1, obj3).toComparison() < 0); assertTrue(new CompareToBuilder().append(obj3, obj1).toComparison() > 0); obj1[1] = 7; assertTrue(new CompareToBuilder().append(obj1, obj2).toComparison() > 0); assertTrue(new CompareToBuilder().append(obj2, obj1).toComparison() < 0); assertTrue(new CompareToBuilder().append(obj1, null).toComparison() > 0); assertTrue(new CompareToBuilder().append((int[]) null, (int[]) null).toComparison() == 0); assertTrue(new CompareToBuilder().append(null, obj1).toComparison() < 0); } public void testShortArray() { short[] obj1 = new short[2]; obj1[0] = 5; obj1[1] = 6; short[] obj2 = new short[2]; obj2[0] = 5; obj2[1] = 6; short[] obj3 = new short[3]; obj3[0] = 5; obj3[1] = 6; obj3[2] = 7; assertTrue(new CompareToBuilder().append(obj1, obj1).toComparison() == 0); assertTrue(new CompareToBuilder().append(obj1, obj2).toComparison() == 0); assertTrue(new CompareToBuilder().append(obj1, obj3).toComparison() < 0); assertTrue(new CompareToBuilder().append(obj3, obj1).toComparison() > 0); obj1[1] = 7; assertTrue(new CompareToBuilder().append(obj1, obj2).toComparison() > 0); assertTrue(new CompareToBuilder().append(obj2, obj1).toComparison() < 0); assertTrue(new CompareToBuilder().append(obj1, null).toComparison() > 0); assertTrue(new CompareToBuilder().append((short[]) null, (short[]) null).toComparison() == 0); assertTrue(new CompareToBuilder().append(null, obj1).toComparison() < 0); } public void testCharArray() { char[] obj1 = new char[2]; obj1[0] = 5; obj1[1] = 6; char[] obj2 = new char[2]; obj2[0] = 5; obj2[1] = 6; char[] obj3 = new char[3]; obj3[0] = 5; obj3[1] = 6; obj3[2] = 7; assertTrue(new CompareToBuilder().append(obj1, obj1).toComparison() == 0); assertTrue(new CompareToBuilder().append(obj1, obj2).toComparison() == 0); assertTrue(new CompareToBuilder().append(obj1, obj3).toComparison() < 0); assertTrue(new CompareToBuilder().append(obj3, obj1).toComparison() > 0); obj1[1] = 7; assertTrue(new CompareToBuilder().append(obj1, obj2).toComparison() > 0); assertTrue(new CompareToBuilder().append(obj2, obj1).toComparison() < 0); assertTrue(new CompareToBuilder().append(obj1, null).toComparison() > 0); assertTrue(new CompareToBuilder().append((char[]) null, (char[]) null).toComparison() == 0); assertTrue(new CompareToBuilder().append(null, obj1).toComparison() < 0); } public void testByteArray() { byte[] obj1 = new byte[2]; obj1[0] = 5; obj1[1] = 6; byte[] obj2 = new byte[2]; obj2[0] = 5; obj2[1] = 6; byte[] obj3 = new byte[3]; obj3[0] = 5; obj3[1] = 6; obj3[2] = 7; assertTrue(new CompareToBuilder().append(obj1, obj1).toComparison() == 0); assertTrue(new CompareToBuilder().append(obj1, obj2).toComparison() == 0); assertTrue(new CompareToBuilder().append(obj1, obj3).toComparison() < 0); assertTrue(new CompareToBuilder().append(obj3, obj1).toComparison() > 0); obj1[1] = 7; assertTrue(new CompareToBuilder().append(obj1, obj2).toComparison() > 0); assertTrue(new CompareToBuilder().append(obj2, obj1).toComparison() < 0); assertTrue(new CompareToBuilder().append(obj1, null).toComparison() > 0); assertTrue(new CompareToBuilder().append((byte[]) null, (byte[]) null).toComparison() == 0); assertTrue(new CompareToBuilder().append(null, obj1).toComparison() < 0); } public void testDoubleArray() { double[] obj1 = new double[2]; obj1[0] = 5; obj1[1] = 6; double[] obj2 = new double[2]; obj2[0] = 5; obj2[1] = 6; double[] obj3 = new double[3]; obj3[0] = 5; obj3[1] = 6; obj3[2] = 7; assertTrue(new CompareToBuilder().append(obj1, obj1).toComparison() == 0); assertTrue(new CompareToBuilder().append(obj1, obj2).toComparison() == 0); assertTrue(new CompareToBuilder().append(obj1, obj3).toComparison() < 0); assertTrue(new CompareToBuilder().append(obj3, obj1).toComparison() > 0); obj1[1] = 7; assertTrue(new CompareToBuilder().append(obj1, obj2).toComparison() > 0); assertTrue(new CompareToBuilder().append(obj2, obj1).toComparison() < 0); assertTrue(new CompareToBuilder().append(obj1, null).toComparison() > 0); assertTrue(new CompareToBuilder().append((double[]) null, (double[]) null).toComparison() == 0); assertTrue(new CompareToBuilder().append(null, obj1).toComparison() < 0); } public void testFloatArray() { float[] obj1 = new float[2]; obj1[0] = 5; obj1[1] = 6; float[] obj2 = new float[2]; obj2[0] = 5; obj2[1] = 6; float[] obj3 = new float[3]; obj3[0] = 5; obj3[1] = 6; obj3[2] = 7; assertTrue(new CompareToBuilder().append(obj1, obj1).toComparison() == 0); assertTrue(new CompareToBuilder().append(obj1, obj2).toComparison() == 0); assertTrue(new CompareToBuilder().append(obj1, obj3).toComparison() < 0); assertTrue(new CompareToBuilder().append(obj3, obj1).toComparison() > 0); obj1[1] = 7; assertTrue(new CompareToBuilder().append(obj1, obj2).toComparison() > 0); assertTrue(new CompareToBuilder().append(obj2, obj1).toComparison() < 0); assertTrue(new CompareToBuilder().append(obj1, null).toComparison() > 0); assertTrue(new CompareToBuilder().append((float[]) null, (float[]) null).toComparison() == 0); assertTrue(new CompareToBuilder().append(null, obj1).toComparison() < 0); } public void testBooleanArray() { boolean[] obj1 = new boolean[2]; obj1[0] = true; obj1[1] = false; boolean[] obj2 = new boolean[2]; obj2[0] = true; obj2[1] = false; boolean[] obj3 = new boolean[3]; obj3[0] = true; obj3[1] = false; obj3[2] = true; assertTrue(new CompareToBuilder().append(obj1, obj1).toComparison() == 0); assertTrue(new CompareToBuilder().append(obj1, obj2).toComparison() == 0); assertTrue(new CompareToBuilder().append(obj1, obj3).toComparison() < 0); assertTrue(new CompareToBuilder().append(obj3, obj1).toComparison() > 0); obj1[1] = true; assertTrue(new CompareToBuilder().append(obj1, obj2).toComparison() > 0); assertTrue(new CompareToBuilder().append(obj2, obj1).toComparison() < 0); assertTrue(new CompareToBuilder().append(obj1, null).toComparison() > 0); assertTrue(new CompareToBuilder().append((boolean[]) null, (boolean[]) null).toComparison() == 0); assertTrue(new CompareToBuilder().append(null, obj1).toComparison() < 0); } public void testMultiLongArray() { long[][] array1 = new long[2][2]; long[][] array2 = new long[2][2]; long[][] array3 = new long[2][3]; for (int i = 0; i < array1.length; ++i) { for (int j = 0; j < array1[0].length; j++) { array1[i][j] = (i + 1) * (j + 1); array2[i][j] = (i + 1) * (j + 1); array3[i][j] = (i + 1) * (j + 1); } } array3[1][2] = 100; array3[1][2] = 100; assertTrue(new CompareToBuilder().append(array1, array1).toComparison() == 0); assertTrue(new CompareToBuilder().append(array1, array2).toComparison() == 0); assertTrue(new CompareToBuilder().append(array1, array3).toComparison() < 0); assertTrue(new CompareToBuilder().append(array3, array1).toComparison() > 0); array1[1][1] = 200; assertTrue(new CompareToBuilder().append(array1, array2).toComparison() > 0); assertTrue(new CompareToBuilder().append(array2, array1).toComparison() < 0); } public void testMultiIntArray() { int[][] array1 = new int[2][2]; int[][] array2 = new int[2][2]; int[][] array3 = new int[2][3]; for (int i = 0; i < array1.length; ++i) { for (int j = 0; j < array1[0].length; j++) { array1[i][j] = (i + 1) * (j + 1); array2[i][j] = (i + 1) * (j + 1); array3[i][j] = (i + 1) * (j + 1); } } array3[1][2] = 100; array3[1][2] = 100; assertTrue(new CompareToBuilder().append(array1, array1).toComparison() == 0); assertTrue(new CompareToBuilder().append(array1, array2).toComparison() == 0); assertTrue(new CompareToBuilder().append(array1, array3).toComparison() < 0); assertTrue(new CompareToBuilder().append(array3, array1).toComparison() > 0); array1[1][1] = 200; assertTrue(new CompareToBuilder().append(array1, array2).toComparison() > 0); assertTrue(new CompareToBuilder().append(array2, array1).toComparison() < 0); } public void testMultiShortArray() { short[][] array1 = new short[2][2]; short[][] array2 = new short[2][2]; short[][] array3 = new short[2][3]; for (short i = 0; i < array1.length; ++i) { for (short j = 0; j < array1[0].length; j++) { array1[i][j] = (short)((i + 1) * (j + 1)); array2[i][j] = (short)((i + 1) * (j + 1)); array3[i][j] = (short)((i + 1) * (j + 1)); } } array3[1][2] = 100; array3[1][2] = 100; assertTrue(new CompareToBuilder().append(array1, array1).toComparison() == 0); assertTrue(new CompareToBuilder().append(array1, array2).toComparison() == 0); assertTrue(new CompareToBuilder().append(array1, array3).toComparison() < 0); assertTrue(new CompareToBuilder().append(array3, array1).toComparison() > 0); array1[1][1] = 200; assertTrue(new CompareToBuilder().append(array1, array2).toComparison() > 0); assertTrue(new CompareToBuilder().append(array2, array1).toComparison() < 0); } public void testMultiCharArray() { char[][] array1 = new char[2][2]; char[][] array2 = new char[2][2]; char[][] array3 = new char[2][3]; for (short i = 0; i < array1.length; ++i) { for (short j = 0; j < array1[0].length; j++) { array1[i][j] = (char)((i + 1) * (j + 1)); array2[i][j] = (char)((i + 1) * (j + 1)); array3[i][j] = (char)((i + 1) * (j + 1)); } } array3[1][2] = 100; array3[1][2] = 100; assertTrue(new CompareToBuilder().append(array1, array1).toComparison() == 0); assertTrue(new CompareToBuilder().append(array1, array2).toComparison() == 0); assertTrue(new CompareToBuilder().append(array1, array3).toComparison() < 0); assertTrue(new CompareToBuilder().append(array3, array1).toComparison() > 0); array1[1][1] = 200; assertTrue(new CompareToBuilder().append(array1, array2).toComparison() > 0); assertTrue(new CompareToBuilder().append(array2, array1).toComparison() < 0); } public void testMultiByteArray() { byte[][] array1 = new byte[2][2]; byte[][] array2 = new byte[2][2]; byte[][] array3 = new byte[2][3]; for (byte i = 0; i < array1.length; ++i) { for (byte j = 0; j < array1[0].length; j++) { array1[i][j] = (byte)((i + 1) * (j + 1)); array2[i][j] = (byte)((i + 1) * (j + 1)); array3[i][j] = (byte)((i + 1) * (j + 1)); } } array3[1][2] = 100; array3[1][2] = 100; assertTrue(new CompareToBuilder().append(array1, array1).toComparison() == 0); assertTrue(new CompareToBuilder().append(array1, array2).toComparison() == 0); assertTrue(new CompareToBuilder().append(array1, array3).toComparison() < 0); assertTrue(new CompareToBuilder().append(array3, array1).toComparison() > 0); array1[1][1] = 127; assertTrue(new CompareToBuilder().append(array1, array2).toComparison() > 0); assertTrue(new CompareToBuilder().append(array2, array1).toComparison() < 0); } public void testMultiFloatArray() { float[][] array1 = new float[2][2]; float[][] array2 = new float[2][2]; float[][] array3 = new float[2][3]; for (int i = 0; i < array1.length; ++i) { for (int j = 0; j < array1[0].length; j++) { array1[i][j] = ((i + 1) * (j + 1)); array2[i][j] = ((i + 1) * (j + 1)); array3[i][j] = ((i + 1) * (j + 1)); } } array3[1][2] = 100; array3[1][2] = 100; assertTrue(new CompareToBuilder().append(array1, array1).toComparison() == 0); assertTrue(new CompareToBuilder().append(array1, array2).toComparison() == 0); assertTrue(new CompareToBuilder().append(array1, array3).toComparison() < 0); assertTrue(new CompareToBuilder().append(array3, array1).toComparison() > 0); array1[1][1] = 127; assertTrue(new CompareToBuilder().append(array1, array2).toComparison() > 0); assertTrue(new CompareToBuilder().append(array2, array1).toComparison() < 0); } public void testMultiDoubleArray() { double[][] array1 = new double[2][2]; double[][] array2 = new double[2][2]; double[][] array3 = new double[2][3]; for (int i = 0; i < array1.length; ++i) { for (int j = 0; j < array1[0].length; j++) { array1[i][j] = ((i + 1) * (j + 1)); array2[i][j] = ((i + 1) * (j + 1)); array3[i][j] = ((i + 1) * (j + 1)); } } array3[1][2] = 100; array3[1][2] = 100; assertTrue(new CompareToBuilder().append(array1, array1).toComparison() == 0); assertTrue(new CompareToBuilder().append(array1, array2).toComparison() == 0); assertTrue(new CompareToBuilder().append(array1, array3).toComparison() < 0); assertTrue(new CompareToBuilder().append(array3, array1).toComparison() > 0); array1[1][1] = 127; assertTrue(new CompareToBuilder().append(array1, array2).toComparison() > 0); assertTrue(new CompareToBuilder().append(array2, array1).toComparison() < 0); } public void testMultiBooleanArray() { boolean[][] array1 = new boolean[2][2]; boolean[][] array2 = new boolean[2][2]; boolean[][] array3 = new boolean[2][3]; for (int i = 0; i < array1.length; ++i) { for (int j = 0; j < array1[0].length; j++) { array1[i][j] = ((i == 1) ^ (j == 1)); array2[i][j] = ((i == 1) ^ (j == 1)); array3[i][j] = ((i == 1) ^ (j == 1)); } } array3[1][2] = false; array3[1][2] = false; assertTrue(new CompareToBuilder().append(array1, array1).toComparison() == 0); assertTrue(new CompareToBuilder().append(array1, array2).toComparison() == 0); assertTrue(new CompareToBuilder().append(array1, array3).toComparison() < 0); assertTrue(new CompareToBuilder().append(array3, array1).toComparison() > 0); array1[1][1] = true; assertTrue(new CompareToBuilder().append(array1, array2).toComparison() > 0); assertTrue(new CompareToBuilder().append(array2, array1).toComparison() < 0); } public void testRaggedArray() { long array1[][] = new long[2][]; long array2[][] = new long[2][]; long array3[][] = new long[3][]; for (int i = 0; i < array1.length; ++i) { array1[i] = new long[2]; array2[i] = new long[2]; array3[i] = new long[3]; for (int j = 0; j < array1[i].length; ++j) { array1[i][j] = (i + 1) * (j + 1); array2[i][j] = (i + 1) * (j + 1); array3[i][j] = (i + 1) * (j + 1); } } array3[1][2] = 100; array3[1][2] = 100; assertTrue(new CompareToBuilder().append(array1, array1).toComparison() == 0); assertTrue(new CompareToBuilder().append(array1, array2).toComparison() == 0); assertTrue(new CompareToBuilder().append(array1, array3).toComparison() < 0); assertTrue(new CompareToBuilder().append(array3, array1).toComparison() > 0); array1[1][1] = 200; assertTrue(new CompareToBuilder().append(array1, array2).toComparison() > 0); assertTrue(new CompareToBuilder().append(array2, array1).toComparison() < 0); } public void testMixedArray() { Object array1[] = new Object[2]; Object array2[] = new Object[2]; Object array3[] = new Object[2]; for (int i = 0; i < array1.length; ++i) { array1[i] = new long[2]; array2[i] = new long[2]; array3[i] = new long[3]; for (int j = 0; j < 2; ++j) { ((long[]) array1[i])[j] = (i + 1) * (j + 1); ((long[]) array2[i])[j] = (i + 1) * (j + 1); ((long[]) array3[i])[j] = (i + 1) * (j + 1); } } ((long[]) array3[0])[2] = 1; ((long[]) array3[1])[2] = 1; assertTrue(new CompareToBuilder().append(array1, array1).toComparison() == 0); assertTrue(new CompareToBuilder().append(array1, array2).toComparison() == 0); assertTrue(new CompareToBuilder().append(array1, array3).toComparison() < 0); assertTrue(new CompareToBuilder().append(array3, array1).toComparison() > 0); ((long[]) array1[1])[1] = 200; assertTrue(new CompareToBuilder().append(array1, array2).toComparison() > 0); assertTrue(new CompareToBuilder().append(array2, array1).toComparison() < 0); } public void testObjectArrayHiddenByObject() { TestObject[] array1 = new TestObject[2]; array1[0] = new TestObject(4); array1[1] = new TestObject(5); TestObject[] array2 = new TestObject[2]; array2[0] = new TestObject(4); array2[1] = new TestObject(5); TestObject[] array3 = new TestObject[3]; array3[0] = new TestObject(4); array3[1] = new TestObject(5); array3[2] = new TestObject(6); Object obj1 = array1; Object obj2 = array2; Object obj3 = array3; assertTrue(new CompareToBuilder().append(obj1, obj1).toComparison() == 0); assertTrue(new CompareToBuilder().append(obj1, obj2).toComparison() == 0); assertTrue(new CompareToBuilder().append(obj1, obj3).toComparison() < 0); assertTrue(new CompareToBuilder().append(obj3, obj1).toComparison() > 0); array1[1] = new TestObject(7); assertTrue(new CompareToBuilder().append(obj1, obj2).toComparison() > 0); assertTrue(new CompareToBuilder().append(obj2, obj1).toComparison() < 0); } public void testLongArrayHiddenByObject() { long[] array1 = new long[2]; array1[0] = 5L; array1[1] = 6L; long[] array2 = new long[2]; array2[0] = 5L; array2[1] = 6L; long[] array3 = new long[3]; array3[0] = 5L; array3[1] = 6L; array3[2] = 7L; Object obj1 = array1; Object obj2 = array2; Object obj3 = array3; assertTrue(new CompareToBuilder().append(obj1, obj1).toComparison() == 0); assertTrue(new CompareToBuilder().append(obj1, obj2).toComparison() == 0); assertTrue(new CompareToBuilder().append(obj1, obj3).toComparison() < 0); assertTrue(new CompareToBuilder().append(obj3, obj1).toComparison() > 0); array1[1] = 7; assertTrue(new CompareToBuilder().append(obj1, obj2).toComparison() > 0); assertTrue(new CompareToBuilder().append(obj2, obj1).toComparison() < 0); } public void testIntArrayHiddenByObject() { int[] array1 = new int[2]; array1[0] = 5; array1[1] = 6; int[] array2 = new int[2]; array2[0] = 5; array2[1] = 6; int[] array3 = new int[3]; array3[0] = 5; array3[1] = 6; array3[2] = 7; Object obj1 = array1; Object obj2 = array2; Object obj3 = array3; assertTrue(new CompareToBuilder().append(obj1, obj1).toComparison() == 0); assertTrue(new CompareToBuilder().append(obj1, obj2).toComparison() == 0); assertTrue(new CompareToBuilder().append(obj1, obj3).toComparison() < 0); assertTrue(new CompareToBuilder().append(obj3, obj1).toComparison() > 0); array1[1] = 7; assertTrue(new CompareToBuilder().append(obj1, obj2).toComparison() > 0); assertTrue(new CompareToBuilder().append(obj2, obj1).toComparison() < 0); } public void testShortArrayHiddenByObject() { short[] array1 = new short[2]; array1[0] = 5; array1[1] = 6; short[] array2 = new short[2]; array2[0] = 5; array2[1] = 6; short[] array3 = new short[3]; array3[0] = 5; array3[1] = 6; array3[2] = 7; Object obj1 = array1; Object obj2 = array2; Object obj3 = array3; assertTrue(new CompareToBuilder().append(obj1, obj1).toComparison() == 0); assertTrue(new CompareToBuilder().append(obj1, obj2).toComparison() == 0); assertTrue(new CompareToBuilder().append(obj1, obj3).toComparison() < 0); assertTrue(new CompareToBuilder().append(obj3, obj1).toComparison() > 0); array1[1] = 7; assertTrue(new CompareToBuilder().append(obj1, obj2).toComparison() > 0); assertTrue(new CompareToBuilder().append(obj2, obj1).toComparison() < 0); } public void testCharArrayHiddenByObject() { char[] array1 = new char[2]; array1[0] = 5; array1[1] = 6; char[] array2 = new char[2]; array2[0] = 5; array2[1] = 6; char[] array3 = new char[3]; array3[0] = 5; array3[1] = 6; array3[2] = 7; Object obj1 = array1; Object obj2 = array2; Object obj3 = array3; assertTrue(new CompareToBuilder().append(obj1, obj1).toComparison() == 0); assertTrue(new CompareToBuilder().append(obj1, obj2).toComparison() == 0); assertTrue(new CompareToBuilder().append(obj1, obj3).toComparison() < 0); assertTrue(new CompareToBuilder().append(obj3, obj1).toComparison() > 0); array1[1] = 7; assertTrue(new CompareToBuilder().append(obj1, obj2).toComparison() > 0); assertTrue(new CompareToBuilder().append(obj2, obj1).toComparison() < 0); } public void testByteArrayHiddenByObject() { byte[] array1 = new byte[2]; array1[0] = 5; array1[1] = 6; byte[] array2 = new byte[2]; array2[0] = 5; array2[1] = 6; byte[] array3 = new byte[3]; array3[0] = 5; array3[1] = 6; array3[2] = 7; Object obj1 = array1; Object obj2 = array2; Object obj3 = array3; assertTrue(new CompareToBuilder().append(obj1, obj1).toComparison() == 0); assertTrue(new CompareToBuilder().append(obj1, obj2).toComparison() == 0); assertTrue(new CompareToBuilder().append(obj1, obj3).toComparison() < 0); assertTrue(new CompareToBuilder().append(obj3, obj1).toComparison() > 0); array1[1] = 7; assertTrue(new CompareToBuilder().append(obj1, obj2).toComparison() > 0); assertTrue(new CompareToBuilder().append(obj2, obj1).toComparison() < 0); } public void testDoubleArrayHiddenByObject() { double[] array1 = new double[2]; array1[0] = 5; array1[1] = 6; double[] array2 = new double[2]; array2[0] = 5; array2[1] = 6; double[] array3 = new double[3]; array3[0] = 5; array3[1] = 6; array3[2] = 7; Object obj1 = array1; Object obj2 = array2; Object obj3 = array3; assertTrue(new CompareToBuilder().append(obj1, obj1).toComparison() == 0); assertTrue(new CompareToBuilder().append(obj1, obj2).toComparison() == 0); assertTrue(new CompareToBuilder().append(obj1, obj3).toComparison() < 0); assertTrue(new CompareToBuilder().append(obj3, obj1).toComparison() > 0); array1[1] = 7; assertTrue(new CompareToBuilder().append(obj1, obj2).toComparison() > 0); assertTrue(new CompareToBuilder().append(obj2, obj1).toComparison() < 0); } public void testFloatArrayHiddenByObject() { float[] array1 = new float[2]; array1[0] = 5; array1[1] = 6; float[] array2 = new float[2]; array2[0] = 5; array2[1] = 6; float[] array3 = new float[3]; array3[0] = 5; array3[1] = 6; array3[2] = 7; Object obj1 = array1; Object obj2 = array2; Object obj3 = array3; assertTrue(new CompareToBuilder().append(obj1, obj1).toComparison() == 0); assertTrue(new CompareToBuilder().append(obj1, obj2).toComparison() == 0); assertTrue(new CompareToBuilder().append(obj1, obj3).toComparison() < 0); assertTrue(new CompareToBuilder().append(obj3, obj1).toComparison() > 0); array1[1] = 7; assertTrue(new CompareToBuilder().append(obj1, obj2).toComparison() > 0); assertTrue(new CompareToBuilder().append(obj2, obj1).toComparison() < 0); } public void testBooleanArrayHiddenByObject() { boolean[] array1 = new boolean[2]; array1[0] = true; array1[1] = false; boolean[] array2 = new boolean[2]; array2[0] = true; array2[1] = false; boolean[] array3 = new boolean[3]; array3[0] = true; array3[1] = false; array3[2] = true; Object obj1 = array1; Object obj2 = array2; Object obj3 = array3; assertTrue(new CompareToBuilder().append(obj1, obj1).toComparison() == 0); assertTrue(new CompareToBuilder().append(obj1, obj2).toComparison() == 0); assertTrue(new CompareToBuilder().append(obj1, obj3).toComparison() < 0); assertTrue(new CompareToBuilder().append(obj3, obj1).toComparison() > 0); array1[1] = true; assertTrue(new CompareToBuilder().append(obj1, obj2).toComparison() > 0); assertTrue(new CompareToBuilder().append(obj2, obj1).toComparison() < 0); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/builder/DefaultToStringStyleTest.java100644 0 0 15026 11513702436 30240 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.builder; import java.util.ArrayList; import java.util.HashMap; import org.apache.commons.lang.builder.ToStringStyleTest.Person; import junit.framework.TestCase; /** * Unit tests {@link org.apache.commons.lang.builder.DefaultToStringStyleTest}. * * @author Apache Software Foundation * @version $Id: DefaultToStringStyleTest.java 905636 2010-02-02 14:03:32Z niallp $ */ public class DefaultToStringStyleTest extends TestCase { private final Integer base = new Integer(5); private final String baseStr = base.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(base)); public DefaultToStringStyleTest(String name) { super(name); } protected void setUp() throws Exception { super.setUp(); ToStringBuilder.setDefaultStyle(ToStringStyle.DEFAULT_STYLE); } protected void tearDown() throws Exception { super.tearDown(); ToStringBuilder.setDefaultStyle(ToStringStyle.DEFAULT_STYLE); } //---------------------------------------------------------------- public void testBlank() { assertEquals(baseStr + "[]", new ToStringBuilder(base).toString()); } public void testAppendSuper() { assertEquals(baseStr + "[]", new ToStringBuilder(base).appendSuper("Integer@8888[]").toString()); assertEquals(baseStr + "[]", new ToStringBuilder(base).appendSuper("Integer@8888[]").toString()); assertEquals(baseStr + "[a=hello]", new ToStringBuilder(base).appendSuper("Integer@8888[]").append("a", "hello").toString()); assertEquals(baseStr + "[,a=hello]", new ToStringBuilder(base).appendSuper("Integer@8888[]").append("a", "hello").toString()); assertEquals(baseStr + "[a=hello]", new ToStringBuilder(base).appendSuper(null).append("a", "hello").toString()); } public void testObject() { Integer i3 = new Integer(3); Integer i4 = new Integer(4); assertEquals(baseStr + "[]", new ToStringBuilder(base).append((Object) null).toString()); assertEquals(baseStr + "[3]", new ToStringBuilder(base).append(i3).toString()); assertEquals(baseStr + "[a=]", new ToStringBuilder(base).append("a", (Object) null).toString()); assertEquals(baseStr + "[a=3]", new ToStringBuilder(base).append("a", i3).toString()); assertEquals(baseStr + "[a=3,b=4]", new ToStringBuilder(base).append("a", i3).append("b", i4).toString()); assertEquals(baseStr + "[a=]", new ToStringBuilder(base).append("a", i3, false).toString()); assertEquals(baseStr + "[a=]", new ToStringBuilder(base).append("a", new ArrayList(), false).toString()); assertEquals(baseStr + "[a=[]]", new ToStringBuilder(base).append("a", new ArrayList(), true).toString()); assertEquals(baseStr + "[a=]", new ToStringBuilder(base).append("a", new HashMap(), false).toString()); assertEquals(baseStr + "[a={}]", new ToStringBuilder(base).append("a", new HashMap(), true).toString()); assertEquals(baseStr + "[a=]", new ToStringBuilder(base).append("a", (Object) new String[0], false).toString()); assertEquals(baseStr + "[a={}]", new ToStringBuilder(base).append("a", (Object) new String[0], true).toString()); } public void testPerson() { Person p = new Person(); p.name = "John Doe"; p.age = 33; p.smoker = false; String pBaseStr = p.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(p)); 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()); } public void testLong() { assertEquals(baseStr + "[3]", new ToStringBuilder(base).append(3L).toString()); assertEquals(baseStr + "[a=3]", new ToStringBuilder(base).append("a", 3L).toString()); assertEquals(baseStr + "[a=3,b=4]", new ToStringBuilder(base).append("a", 3L).append("b", 4L).toString()); } public void testObjectArray() { Object[] array = new Object[] {null, base, new int[] {3, 6}}; assertEquals(baseStr + "[{,5,{3,6}}]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[{,5,{3,6}}]", new ToStringBuilder(base).append((Object) array).toString()); array = null; assertEquals(baseStr + "[]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[]", new ToStringBuilder(base).append((Object) array).toString()); } public void testLongArray() { long[] array = new long[] {1, 2, -3, 4}; assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append((Object) array).toString()); array = null; assertEquals(baseStr + "[]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[]", new ToStringBuilder(base).append((Object) array).toString()); } public void testLongArrayArray() { long[][] array = new long[][] {{1, 2}, null, {5}}; assertEquals(baseStr + "[{{1,2},,{5}}]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[{{1,2},,{5}}]", new ToStringBuilder(base).append((Object) array).toString()); array = null; assertEquals(baseStr + "[]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[]", new ToStringBuilder(base).append((Object) array).toString()); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/builder/EqualsBuilderTest.java100644 0 0 115414 11513702436 26724 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.builder; import java.util.Arrays; import junit.framework.TestCase; /** * Unit tests {@link org.apache.commons.lang.builder.EqualsBuilder}. * * @author Apache Software Foundation * @author Steve Downey * @author Gary Gregory * @author Maarten Coene * @version $Id: EqualsBuilderTest.java 905636 2010-02-02 14:03:32Z niallp $ */ public class EqualsBuilderTest extends TestCase { public EqualsBuilderTest(String name) { super(name); } //----------------------------------------------------------------------- static class TestObject { private int a; public TestObject() { } public TestObject(int a) { this.a = a; } public boolean equals(Object o) { if (o == null) { return false; } if (o == this) { return true; } if (o.getClass() != getClass()) { return false; } TestObject rhs = (TestObject) o; return (a == rhs.a); } public void setA(int a) { this.a = a; } public int getA() { return a; } } static class TestSubObject extends TestObject { private int b; public TestSubObject() { super(0); } public TestSubObject(int a, int b) { super(a); this.b = b; } public boolean equals(Object o) { if (o == null) { return false; } if (o == this) { return true; } if (o.getClass() != getClass()) { return false; } TestSubObject rhs = (TestSubObject) o; return super.equals(o) && (b == rhs.b); } public void setB(int b) { this.b = b; } public int getB() { return b; } } static class TestEmptySubObject extends TestObject { public TestEmptySubObject(int a) { super(a); } } static class TestTSubObject extends TestObject { private transient int t; public TestTSubObject(int a, int t) { super(a); this.t = t; } } static class TestTTSubObject extends TestTSubObject { private transient int tt; public TestTTSubObject(int a, int t, int tt) { super(a, t); this.tt = tt; } } static class TestTTLeafObject extends TestTTSubObject { private int leafValue; public TestTTLeafObject(int a, int t, int tt, int leafValue) { super(a, t, tt); this.leafValue = leafValue; } } static class TestTSubObject2 extends TestObject { private transient int t; public TestTSubObject2(int a, int t) { super(a); } public int getT() { return t; } public void setT(int t) { this.t = t; } } public void testReflectionEquals() { TestObject o1 = new TestObject(4); TestObject o2 = new TestObject(5); assertTrue(EqualsBuilder.reflectionEquals(o1, o1)); assertTrue(!EqualsBuilder.reflectionEquals(o1, o2)); o2.setA(4); assertTrue(EqualsBuilder.reflectionEquals(o1, o2)); assertTrue(!EqualsBuilder.reflectionEquals(o1, this)); assertTrue(!EqualsBuilder.reflectionEquals(o1, null)); assertTrue(!EqualsBuilder.reflectionEquals(null, o2)); assertTrue(EqualsBuilder.reflectionEquals((Object) null, (Object) null)); } public void testReflectionHierarchyEquals() { testReflectionHierarchyEquals(false); testReflectionHierarchyEquals(true); // Transients assertTrue(EqualsBuilder.reflectionEquals(new TestTTLeafObject(1, 2, 3, 4), new TestTTLeafObject(1, 2, 3, 4), true)); assertTrue(EqualsBuilder.reflectionEquals(new TestTTLeafObject(1, 2, 3, 4), new TestTTLeafObject(1, 2, 3, 4), false)); assertTrue(!EqualsBuilder.reflectionEquals(new TestTTLeafObject(1, 0, 0, 4), new TestTTLeafObject(1, 2, 3, 4), true)); assertTrue(!EqualsBuilder.reflectionEquals(new TestTTLeafObject(1, 2, 3, 4), new TestTTLeafObject(1, 2, 3, 0), true)); assertTrue(!EqualsBuilder.reflectionEquals(new TestTTLeafObject(0, 2, 3, 4), new TestTTLeafObject(1, 2, 3, 4), true)); } public void testReflectionHierarchyEquals(boolean testTransients) { TestObject to1 = new TestObject(4); TestObject to1Bis = new TestObject(4); TestObject to1Ter = new TestObject(4); TestObject to2 = new TestObject(5); TestEmptySubObject teso = new TestEmptySubObject(4); TestTSubObject ttso = new TestTSubObject(4, 1); TestTTSubObject tttso = new TestTTSubObject(4, 1, 2); TestTTLeafObject ttlo = new TestTTLeafObject(4, 1, 2, 3); TestSubObject tso1 = new TestSubObject(1, 4); TestSubObject tso1bis = new TestSubObject(1, 4); TestSubObject tso1ter = new TestSubObject(1, 4); TestSubObject tso2 = new TestSubObject(2, 5); testReflectionEqualsEquivalenceRelationship(to1, to1Bis, to1Ter, to2, new TestObject(), testTransients); testReflectionEqualsEquivalenceRelationship(tso1, tso1bis, tso1ter, tso2, new TestSubObject(), testTransients); // More sanity checks: // same values assertTrue(EqualsBuilder.reflectionEquals(ttlo, ttlo, testTransients)); assertTrue(EqualsBuilder.reflectionEquals(new TestSubObject(1, 10), new TestSubObject(1, 10), testTransients)); // same super values, diff sub values assertTrue(!EqualsBuilder.reflectionEquals(new TestSubObject(1, 10), new TestSubObject(1, 11), testTransients)); assertTrue(!EqualsBuilder.reflectionEquals(new TestSubObject(1, 11), new TestSubObject(1, 10), testTransients)); // diff super values, same sub values assertTrue(!EqualsBuilder.reflectionEquals(new TestSubObject(0, 10), new TestSubObject(1, 10), testTransients)); assertTrue(!EqualsBuilder.reflectionEquals(new TestSubObject(1, 10), new TestSubObject(0, 10), testTransients)); // mix super and sub types: equals assertTrue(EqualsBuilder.reflectionEquals(to1, teso, testTransients)); assertTrue(EqualsBuilder.reflectionEquals(teso, to1, testTransients)); assertTrue(EqualsBuilder.reflectionEquals(to1, ttso, false)); // Force testTransients = false for this assert assertTrue(EqualsBuilder.reflectionEquals(ttso, to1, false)); // Force testTransients = false for this assert assertTrue(EqualsBuilder.reflectionEquals(to1, tttso, false)); // Force testTransients = false for this assert assertTrue(EqualsBuilder.reflectionEquals(tttso, to1, false)); // Force testTransients = false for this assert assertTrue(EqualsBuilder.reflectionEquals(ttso, tttso, false)); // Force testTransients = false for this assert assertTrue(EqualsBuilder.reflectionEquals(tttso, ttso, false)); // Force testTransients = false for this assert // mix super and sub types: NOT equals assertTrue(!EqualsBuilder.reflectionEquals(new TestObject(0), new TestEmptySubObject(1), testTransients)); assertTrue(!EqualsBuilder.reflectionEquals(new TestEmptySubObject(1), new TestObject(0), testTransients)); assertTrue(!EqualsBuilder.reflectionEquals(new TestObject(0), new TestTSubObject(1, 1), testTransients)); assertTrue(!EqualsBuilder.reflectionEquals(new TestTSubObject(1, 1), new TestObject(0), testTransients)); assertTrue(!EqualsBuilder.reflectionEquals(new TestObject(1), new TestSubObject(0, 10), testTransients)); assertTrue(!EqualsBuilder.reflectionEquals(new TestSubObject(0, 10), new TestObject(1), testTransients)); assertTrue(!EqualsBuilder.reflectionEquals(to1, ttlo)); assertTrue(!EqualsBuilder.reflectionEquals(tso1, this)); } /** * Equivalence relationship tests inspired by "Effective Java": *
      *
    • reflection
    • *
    • symmetry
    • *
    • transitive
    • *
    • consistency
    • *
    • non-null reference
    • *
    * @param to a TestObject * @param toBis a TestObject, equal to to and toTer * @param toTer Left hand side, equal to to and toBis * @param to2 a different TestObject * @param oToChange a TestObject that will be changed */ public void testReflectionEqualsEquivalenceRelationship( TestObject to, TestObject toBis, TestObject toTer, TestObject to2, TestObject oToChange, boolean testTransients) { // reflection test assertTrue(EqualsBuilder.reflectionEquals(to, to, testTransients)); assertTrue(EqualsBuilder.reflectionEquals(to2, to2, testTransients)); // symmetry test assertTrue(EqualsBuilder.reflectionEquals(to, toBis, testTransients) && EqualsBuilder.reflectionEquals(toBis, to, testTransients)); // transitive test assertTrue( EqualsBuilder.reflectionEquals(to, toBis, testTransients) && EqualsBuilder.reflectionEquals(toBis, toTer, testTransients) && EqualsBuilder.reflectionEquals(to, toTer, testTransients)); // consistency test oToChange.setA(to.getA()); if (oToChange instanceof TestSubObject) { ((TestSubObject) oToChange).setB(((TestSubObject) to).getB()); } assertTrue(EqualsBuilder.reflectionEquals(oToChange, to, testTransients)); assertTrue(EqualsBuilder.reflectionEquals(oToChange, to, testTransients)); oToChange.setA(to.getA() + 1); if (oToChange instanceof TestSubObject) { ((TestSubObject) oToChange).setB(((TestSubObject) to).getB() + 1); } assertTrue(!EqualsBuilder.reflectionEquals(oToChange, to, testTransients)); assertTrue(!EqualsBuilder.reflectionEquals(oToChange, to, testTransients)); // non-null reference test assertTrue(!EqualsBuilder.reflectionEquals(to, null, testTransients)); assertTrue(!EqualsBuilder.reflectionEquals(to2, null, testTransients)); assertTrue(!EqualsBuilder.reflectionEquals(null, to, testTransients)); assertTrue(!EqualsBuilder.reflectionEquals(null, to2, testTransients)); assertTrue(EqualsBuilder.reflectionEquals((Object) null, (Object) null, testTransients)); } public void testSuper() { TestObject o1 = new TestObject(4); TestObject o2 = new TestObject(5); assertEquals(true, new EqualsBuilder().appendSuper(true).append(o1, o1).isEquals()); assertEquals(false, new EqualsBuilder().appendSuper(false).append(o1, o1).isEquals()); assertEquals(false, new EqualsBuilder().appendSuper(true).append(o1, o2).isEquals()); assertEquals(false, new EqualsBuilder().appendSuper(false).append(o1, o2).isEquals()); } public void testObject() { TestObject o1 = new TestObject(4); TestObject o2 = new TestObject(5); assertTrue(new EqualsBuilder().append(o1, o1).isEquals()); assertTrue(!new EqualsBuilder().append(o1, o2).isEquals()); o2.setA(4); assertTrue(new EqualsBuilder().append(o1, o2).isEquals()); assertTrue(!new EqualsBuilder().append(o1, this).isEquals()); assertTrue(!new EqualsBuilder().append(o1, null).isEquals()); assertTrue(!new EqualsBuilder().append(null, o2).isEquals()); assertTrue(new EqualsBuilder().append((Object) null, (Object) null).isEquals()); } public void testLong() { long o1 = 1L; long o2 = 2L; assertTrue(new EqualsBuilder().append(o1, o1).isEquals()); assertTrue(!new EqualsBuilder().append(o1, o2).isEquals()); } public void testInt() { int o1 = 1; int o2 = 2; assertTrue(new EqualsBuilder().append(o1, o1).isEquals()); assertTrue(!new EqualsBuilder().append(o1, o2).isEquals()); } public void testShort() { short o1 = 1; short o2 = 2; assertTrue(new EqualsBuilder().append(o1, o1).isEquals()); assertTrue(!new EqualsBuilder().append(o1, o2).isEquals()); } public void testChar() { char o1 = 1; char o2 = 2; assertTrue(new EqualsBuilder().append(o1, o1).isEquals()); assertTrue(!new EqualsBuilder().append(o1, o2).isEquals()); } public void testByte() { byte o1 = 1; byte o2 = 2; assertTrue(new EqualsBuilder().append(o1, o1).isEquals()); assertTrue(!new EqualsBuilder().append(o1, o2).isEquals()); } public void testDouble() { double o1 = 1; double o2 = 2; assertTrue(new EqualsBuilder().append(o1, o1).isEquals()); assertTrue(!new EqualsBuilder().append(o1, o2).isEquals()); assertTrue(!new EqualsBuilder().append(o1, Double.NaN).isEquals()); assertTrue(new EqualsBuilder().append(Double.NaN, Double.NaN).isEquals()); assertTrue(new EqualsBuilder().append(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY).isEquals()); } public void testFloat() { float o1 = 1; float o2 = 2; assertTrue(new EqualsBuilder().append(o1, o1).isEquals()); assertTrue(!new EqualsBuilder().append(o1, o2).isEquals()); assertTrue(!new EqualsBuilder().append(o1, Float.NaN).isEquals()); assertTrue(new EqualsBuilder().append(Float.NaN, Float.NaN).isEquals()); assertTrue(new EqualsBuilder().append(Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY).isEquals()); } public void testAccessors() { EqualsBuilder equalsBuilder = new EqualsBuilder(); assertTrue(equalsBuilder.isEquals()); equalsBuilder.setEquals(true); assertTrue(equalsBuilder.isEquals()); equalsBuilder.setEquals(false); assertFalse(equalsBuilder.isEquals()); } public void testReset() { EqualsBuilder equalsBuilder = new EqualsBuilder(); assertTrue(equalsBuilder.isEquals()); equalsBuilder.setEquals(false); assertFalse(equalsBuilder.isEquals()); equalsBuilder.reset(); assertTrue(equalsBuilder.isEquals()); } public void testBoolean() { boolean o1 = true; boolean o2 = false; assertTrue(new EqualsBuilder().append(o1, o1).isEquals()); assertTrue(!new EqualsBuilder().append(o1, o2).isEquals()); } public void testObjectArray() { TestObject[] obj1 = new TestObject[3]; obj1[0] = new TestObject(4); obj1[1] = new TestObject(5); obj1[2] = null; TestObject[] obj2 = new TestObject[3]; obj2[0] = new TestObject(4); obj2[1] = new TestObject(5); obj2[2] = null; assertTrue(new EqualsBuilder().append(obj1, obj1).isEquals()); assertTrue(new EqualsBuilder().append(obj2, obj2).isEquals()); assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); obj1[1].setA(6); assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); obj1[1].setA(5); assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); obj1[2] = obj1[1]; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); obj1[2] = null; assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); obj2 = null; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); obj1 = null; assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); } public void testLongArray() { long[] obj1 = new long[2]; obj1[0] = 5L; obj1[1] = 6L; long[] obj2 = new long[2]; obj2[0] = 5L; obj2[1] = 6L; assertTrue(new EqualsBuilder().append(obj1, obj1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); obj1[1] = 7; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); obj2 = null; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); obj1 = null; assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); } public void testIntArray() { int[] obj1 = new int[2]; obj1[0] = 5; obj1[1] = 6; int[] obj2 = new int[2]; obj2[0] = 5; obj2[1] = 6; assertTrue(new EqualsBuilder().append(obj1, obj1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); obj1[1] = 7; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); obj2 = null; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); obj1 = null; assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); } public void testShortArray() { short[] obj1 = new short[2]; obj1[0] = 5; obj1[1] = 6; short[] obj2 = new short[2]; obj2[0] = 5; obj2[1] = 6; assertTrue(new EqualsBuilder().append(obj1, obj1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); obj1[1] = 7; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); obj2 = null; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); obj1 = null; assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); } public void testCharArray() { char[] obj1 = new char[2]; obj1[0] = 5; obj1[1] = 6; char[] obj2 = new char[2]; obj2[0] = 5; obj2[1] = 6; assertTrue(new EqualsBuilder().append(obj1, obj1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); obj1[1] = 7; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); obj2 = null; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); obj1 = null; assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); } public void testByteArray() { byte[] obj1 = new byte[2]; obj1[0] = 5; obj1[1] = 6; byte[] obj2 = new byte[2]; obj2[0] = 5; obj2[1] = 6; assertTrue(new EqualsBuilder().append(obj1, obj1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); obj1[1] = 7; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); obj2 = null; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); obj1 = null; assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); } public void testDoubleArray() { double[] obj1 = new double[2]; obj1[0] = 5; obj1[1] = 6; double[] obj2 = new double[2]; obj2[0] = 5; obj2[1] = 6; assertTrue(new EqualsBuilder().append(obj1, obj1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); obj1[1] = 7; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); obj2 = null; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); obj1 = null; assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); } public void testFloatArray() { float[] obj1 = new float[2]; obj1[0] = 5; obj1[1] = 6; float[] obj2 = new float[2]; obj2[0] = 5; obj2[1] = 6; assertTrue(new EqualsBuilder().append(obj1, obj1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); obj1[1] = 7; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); obj2 = null; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); obj1 = null; assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); } public void testBooleanArray() { boolean[] obj1 = new boolean[2]; obj1[0] = true; obj1[1] = false; boolean[] obj2 = new boolean[2]; obj2[0] = true; obj2[1] = false; assertTrue(new EqualsBuilder().append(obj1, obj1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); obj1[1] = true; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); obj2 = null; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); obj1 = null; assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); } public void testMultiLongArray() { long[][] array1 = new long[2][2]; long[][] array2 = new long[2][2]; for (int i = 0; i < array1.length; ++i) { for (int j = 0; j < array1[0].length; j++) { array1[i][j] = (i + 1) * (j + 1); array2[i][j] = (i + 1) * (j + 1); } } assertTrue(new EqualsBuilder().append(array1, array1).isEquals()); assertTrue(new EqualsBuilder().append(array1, array2).isEquals()); array1[1][1] = 0; assertTrue(!new EqualsBuilder().append(array1, array2).isEquals()); } public void testMultiIntArray() { int[][] array1 = new int[2][2]; int[][] array2 = new int[2][2]; for (int i = 0; i < array1.length; ++i) { for (int j = 0; j < array1[0].length; j++) { array1[i][j] = (i + 1) * (j + 1); array2[i][j] = (i + 1) * (j + 1); } } assertTrue(new EqualsBuilder().append(array1, array1).isEquals()); assertTrue(new EqualsBuilder().append(array1, array2).isEquals()); array1[1][1] = 0; assertTrue(!new EqualsBuilder().append(array1, array2).isEquals()); } public void testMultiShortArray() { short[][] array1 = new short[2][2]; short[][] array2 = new short[2][2]; for (short i = 0; i < array1.length; ++i) { for (short j = 0; j < array1[0].length; j++) { array1[i][j] = i; array2[i][j] = i; } } assertTrue(new EqualsBuilder().append(array1, array1).isEquals()); assertTrue(new EqualsBuilder().append(array1, array2).isEquals()); array1[1][1] = 0; assertTrue(!new EqualsBuilder().append(array1, array2).isEquals()); } public void testMultiCharArray() { char[][] array1 = new char[2][2]; char[][] array2 = new char[2][2]; for (char i = 0; i < array1.length; ++i) { for (char j = 0; j < array1[0].length; j++) { array1[i][j] = i; array2[i][j] = i; } } assertTrue(new EqualsBuilder().append(array1, array1).isEquals()); assertTrue(new EqualsBuilder().append(array1, array2).isEquals()); array1[1][1] = 0; assertTrue(!new EqualsBuilder().append(array1, array2).isEquals()); } public void testMultiByteArray() { byte[][] array1 = new byte[2][2]; byte[][] array2 = new byte[2][2]; for (byte i = 0; i < array1.length; ++i) { for (byte j = 0; j < array1[0].length; j++) { array1[i][j] = i; array2[i][j] = i; } } assertTrue(new EqualsBuilder().append(array1, array1).isEquals()); assertTrue(new EqualsBuilder().append(array1, array2).isEquals()); array1[1][1] = 0; assertTrue(!new EqualsBuilder().append(array1, array2).isEquals()); } public void testMultiFloatArray() { float[][] array1 = new float[2][2]; float[][] array2 = new float[2][2]; for (int i = 0; i < array1.length; ++i) { for (int j = 0; j < array1[0].length; j++) { array1[i][j] = (i + 1) * (j + 1); array2[i][j] = (i + 1) * (j + 1); } } assertTrue(new EqualsBuilder().append(array1, array1).isEquals()); assertTrue(new EqualsBuilder().append(array1, array2).isEquals()); array1[1][1] = 0; assertTrue(!new EqualsBuilder().append(array1, array2).isEquals()); } public void testMultiDoubleArray() { double[][] array1 = new double[2][2]; double[][] array2 = new double[2][2]; for (int i = 0; i < array1.length; ++i) { for (int j = 0; j < array1[0].length; j++) { array1[i][j] = (i + 1) * (j + 1); array2[i][j] = (i + 1) * (j + 1); } } assertTrue(new EqualsBuilder().append(array1, array1).isEquals()); assertTrue(new EqualsBuilder().append(array1, array2).isEquals()); array1[1][1] = 0; assertTrue(!new EqualsBuilder().append(array1, array2).isEquals()); } public void testMultiBooleanArray() { boolean[][] array1 = new boolean[2][2]; boolean[][] array2 = new boolean[2][2]; for (int i = 0; i < array1.length; ++i) { for (int j = 0; j < array1[0].length; j++) { array1[i][j] = (i == 1) || (j == 1); array2[i][j] = (i == 1) || (j == 1); } } assertTrue(new EqualsBuilder().append(array1, array1).isEquals()); assertTrue(new EqualsBuilder().append(array1, array2).isEquals()); array1[1][1] = false; assertTrue(!new EqualsBuilder().append(array1, array2).isEquals()); // compare 1 dim to 2. boolean[] array3 = new boolean[]{true, true}; assertFalse(new EqualsBuilder().append(array1, array3).isEquals()); assertFalse(new EqualsBuilder().append(array3, array1).isEquals()); assertFalse(new EqualsBuilder().append(array2, array3).isEquals()); assertFalse(new EqualsBuilder().append(array3, array2).isEquals()); } public void testRaggedArray() { long array1[][] = new long[2][]; long array2[][] = new long[2][]; for (int i = 0; i < array1.length; ++i) { array1[i] = new long[2]; array2[i] = new long[2]; for (int j = 0; j < array1[i].length; ++j) { array1[i][j] = (i + 1) * (j + 1); array2[i][j] = (i + 1) * (j + 1); } } assertTrue(new EqualsBuilder().append(array1, array1).isEquals()); assertTrue(new EqualsBuilder().append(array1, array2).isEquals()); array1[1][1] = 0; assertTrue(!new EqualsBuilder().append(array1, array2).isEquals()); } public void testMixedArray() { Object array1[] = new Object[2]; Object array2[] = new Object[2]; for (int i = 0; i < array1.length; ++i) { array1[i] = new long[2]; array2[i] = new long[2]; for (int j = 0; j < 2; ++j) { ((long[]) array1[i])[j] = (i + 1) * (j + 1); ((long[]) array2[i])[j] = (i + 1) * (j + 1); } } assertTrue(new EqualsBuilder().append(array1, array1).isEquals()); assertTrue(new EqualsBuilder().append(array1, array2).isEquals()); ((long[]) array1[1])[1] = 0; assertTrue(!new EqualsBuilder().append(array1, array2).isEquals()); } public void testObjectArrayHiddenByObject() { TestObject[] array1 = new TestObject[2]; array1[0] = new TestObject(4); array1[1] = new TestObject(5); TestObject[] array2 = new TestObject[2]; array2[0] = new TestObject(4); array2[1] = new TestObject(5); Object obj1 = array1; Object obj2 = array2; assertTrue(new EqualsBuilder().append(obj1, obj1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, array1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); assertTrue(new EqualsBuilder().append(obj1, array2).isEquals()); array1[1].setA(6); assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); } public void testLongArrayHiddenByObject() { long[] array1 = new long[2]; array1[0] = 5L; array1[1] = 6L; long[] array2 = new long[2]; array2[0] = 5L; array2[1] = 6L; Object obj1 = array1; Object obj2 = array2; assertTrue(new EqualsBuilder().append(obj1, obj1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, array1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); assertTrue(new EqualsBuilder().append(obj1, array2).isEquals()); array1[1] = 7; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); } public void testIntArrayHiddenByObject() { int[] array1 = new int[2]; array1[0] = 5; array1[1] = 6; int[] array2 = new int[2]; array2[0] = 5; array2[1] = 6; Object obj1 = array1; Object obj2 = array2; assertTrue(new EqualsBuilder().append(obj1, obj1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, array1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); assertTrue(new EqualsBuilder().append(obj1, array2).isEquals()); array1[1] = 7; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); } public void testShortArrayHiddenByObject() { short[] array1 = new short[2]; array1[0] = 5; array1[1] = 6; short[] array2 = new short[2]; array2[0] = 5; array2[1] = 6; Object obj1 = array1; Object obj2 = array2; assertTrue(new EqualsBuilder().append(obj1, obj1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, array1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); assertTrue(new EqualsBuilder().append(obj1, array2).isEquals()); array1[1] = 7; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); } public void testCharArrayHiddenByObject() { char[] array1 = new char[2]; array1[0] = 5; array1[1] = 6; char[] array2 = new char[2]; array2[0] = 5; array2[1] = 6; Object obj1 = array1; Object obj2 = array2; assertTrue(new EqualsBuilder().append(obj1, obj1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, array1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); assertTrue(new EqualsBuilder().append(obj1, array2).isEquals()); array1[1] = 7; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); } public void testByteArrayHiddenByObject() { byte[] array1 = new byte[2]; array1[0] = 5; array1[1] = 6; byte[] array2 = new byte[2]; array2[0] = 5; array2[1] = 6; Object obj1 = array1; Object obj2 = array2; assertTrue(new EqualsBuilder().append(obj1, obj1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, array1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); assertTrue(new EqualsBuilder().append(obj1, array2).isEquals()); array1[1] = 7; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); } public void testDoubleArrayHiddenByObject() { double[] array1 = new double[2]; array1[0] = 5; array1[1] = 6; double[] array2 = new double[2]; array2[0] = 5; array2[1] = 6; Object obj1 = array1; Object obj2 = array2; assertTrue(new EqualsBuilder().append(obj1, obj1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, array1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); assertTrue(new EqualsBuilder().append(obj1, array2).isEquals()); array1[1] = 7; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); } public void testFloatArrayHiddenByObject() { float[] array1 = new float[2]; array1[0] = 5; array1[1] = 6; float[] array2 = new float[2]; array2[0] = 5; array2[1] = 6; Object obj1 = array1; Object obj2 = array2; assertTrue(new EqualsBuilder().append(obj1, obj1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, array1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); assertTrue(new EqualsBuilder().append(obj1, array2).isEquals()); array1[1] = 7; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); } public void testBooleanArrayHiddenByObject() { boolean[] array1 = new boolean[2]; array1[0] = true; array1[1] = false; boolean[] array2 = new boolean[2]; array2[0] = true; array2[1] = false; Object obj1 = array1; Object obj2 = array2; assertTrue(new EqualsBuilder().append(obj1, obj1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, array1).isEquals()); assertTrue(new EqualsBuilder().append(obj1, obj2).isEquals()); assertTrue(new EqualsBuilder().append(obj1, array2).isEquals()); array1[1] = true; assertTrue(!new EqualsBuilder().append(obj1, obj2).isEquals()); } public static class TestACanEqualB { private int a; public TestACanEqualB(int a) { this.a = a; } public boolean equals(Object o) { if (o == this) return true; if (o instanceof TestACanEqualB) return this.a == ((TestACanEqualB) o).getA(); if (o instanceof TestBCanEqualA) return this.a == ((TestBCanEqualA) o).getB(); return false; } public int getA() { return this.a; } } public static class TestBCanEqualA { private int b; public TestBCanEqualA(int b) { this.b = b; } public boolean equals(Object o) { if (o == this) return true; if (o instanceof TestACanEqualB) return this.b == ((TestACanEqualB) o).getA(); if (o instanceof TestBCanEqualA) return this.b == ((TestBCanEqualA) o).getB(); return false; } public int getB() { return this.b; } } /** * Tests two instances of classes that can be equal and that are not "related". The two classes are not subclasses * of each other and do not share a parent aside from Object. * See http://issues.apache.org/bugzilla/show_bug.cgi?id=33069 */ public void testUnrelatedClasses() { Object[] x = new Object[]{new TestACanEqualB(1)}; Object[] y = new Object[]{new TestBCanEqualA(1)}; // sanity checks: assertTrue(Arrays.equals(x, x)); assertTrue(Arrays.equals(y, y)); assertTrue(Arrays.equals(x, y)); assertTrue(Arrays.equals(y, x)); // real tests: assertTrue(x[0].equals(x[0])); assertTrue(y[0].equals(y[0])); assertTrue(x[0].equals(y[0])); assertTrue(y[0].equals(x[0])); assertTrue(new EqualsBuilder().append(x, x).isEquals()); assertTrue(new EqualsBuilder().append(y, y).isEquals()); assertTrue(new EqualsBuilder().append(x, y).isEquals()); assertTrue(new EqualsBuilder().append(y, x).isEquals()); } /** * Test from http://issues.apache.org/bugzilla/show_bug.cgi?id=33067 */ public void testNpeForNullElement() { Object[] x1 = new Object[] { new Integer(1), null, new Integer(3) }; Object[] x2 = new Object[] { new Integer(1), new Integer(2), new Integer(3) }; // causes an NPE in 2.0 according to: // http://issues.apache.org/bugzilla/show_bug.cgi?id=33067 new EqualsBuilder().append(x1, x2); } public void testReflectionEqualsExcludeFields() throws Exception { TestObjectWithMultipleFields x1 = new TestObjectWithMultipleFields(1, 2, 3); TestObjectWithMultipleFields x2 = new TestObjectWithMultipleFields(1, 3, 4); // not equal when including all fields assertTrue(!EqualsBuilder.reflectionEquals(x1, x2)); // doesn't barf on null, empty array, or non-existent field, but still tests as not equal assertTrue(!EqualsBuilder.reflectionEquals(x1, x2, (String[]) null)); assertTrue(!EqualsBuilder.reflectionEquals(x1, x2, new String[] {})); assertTrue(!EqualsBuilder.reflectionEquals(x1, x2, new String[] {"xxx"})); // not equal if only one of the differing fields excluded assertTrue(!EqualsBuilder.reflectionEquals(x1, x2, new String[] {"two"})); assertTrue(!EqualsBuilder.reflectionEquals(x1, x2, new String[] {"three"})); // equal if both differing fields excluded assertTrue(EqualsBuilder.reflectionEquals(x1, x2, new String[] {"two", "three"})); // still equal as long as both differing fields are among excluded assertTrue(EqualsBuilder.reflectionEquals(x1, x2, new String[] {"one", "two", "three"})); assertTrue(EqualsBuilder.reflectionEquals(x1, x2, new String[] {"one", "two", "three", "xxx"})); } static class TestObjectWithMultipleFields { private TestObject one; private TestObject two; private TestObject three; public TestObjectWithMultipleFields(int one, int two, int three) { this.one = new TestObject(one); this.two = new TestObject(two); this.three = new TestObject(three); } } } ././@LongLink100644 0 0 154 11513702661 10255 Lustar 0 0 commons-lang-2.6-src/src/test/java/org/apache/commons/lang/builder/HashCodeBuilderAndEqualsBuilderTest.javacommons-lang-2.6-src/src/test/java/org/apache/commons/lang/builder/HashCodeBuilderAndEqualsBuilderTe100644 0 0 12042 11513702437 30740 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.builder; import junit.framework.TestCase; /** * Tests {@link org.apache.commons.lang.builder.HashCodeBuilder} and * {@link org.apache.commons.lang.builder.EqualsBuilderTest} to insure that equal * objects must have equal hash codes. * * @author Gary Gregory * @version $Id: HashCodeBuilderAndEqualsBuilderTest.java 905628 2010-02-02 13:29:55Z niallp $ */ public class HashCodeBuilderAndEqualsBuilderTest extends TestCase { /** * Constructor for HashCodeBuilderAndEqualsBuilderTest. * @param name */ public HashCodeBuilderAndEqualsBuilderTest(String name) { super(name); } //----------------------------------------------------------------------- public void testInteger(boolean testTransients) { Integer i1 = new Integer(12345); Integer i2 = new Integer(12345); assertEqualsAndHashCodeContract(i1, i2, testTransients); } public void testInteger() { testInteger(false); } public void testIntegerWithTransients() { testInteger(true); } public void testFixture() { testFixture(false); } public void testFixtureWithTransients() { testFixture(true); } public void testFixture(boolean testTransients) { assertEqualsAndHashCodeContract(new TestFixture(2, 'c', "Test", (short) 2), new TestFixture(2, 'c', "Test", (short) 2), testTransients); assertEqualsAndHashCodeContract( new AllTransientFixture(2, 'c', "Test", (short) 2), new AllTransientFixture(2, 'c', "Test", (short) 2), testTransients); assertEqualsAndHashCodeContract( new SubTestFixture(2, 'c', "Test", (short) 2, "Same"), new SubTestFixture(2, 'c', "Test", (short) 2, "Same"), testTransients); assertEqualsAndHashCodeContract( new SubAllTransientFixture(2, 'c', "Test", (short) 2, "Same"), new SubAllTransientFixture(2, 'c', "Test", (short) 2, "Same"), testTransients); } /** * Asserts that if lhs equals rhs * then their hash codes MUST be identical. * * @param lhs The Left-Hand-Side of the equals test * @param rhs The Right-Hand-Side of the equals test * @param testTransients wether to test transient fields */ public void assertEqualsAndHashCodeContract(Object lhs, Object rhs, boolean testTransients) { if (EqualsBuilder.reflectionEquals(lhs, rhs, testTransients)) { // test a couple of times for consistency. assertEquals(HashCodeBuilder.reflectionHashCode(lhs, testTransients), HashCodeBuilder.reflectionHashCode(rhs, testTransients)); assertEquals(HashCodeBuilder.reflectionHashCode(lhs, testTransients), HashCodeBuilder.reflectionHashCode(rhs, testTransients)); assertEquals(HashCodeBuilder.reflectionHashCode(lhs, testTransients), HashCodeBuilder.reflectionHashCode(rhs, testTransients)); } } static class TestFixture { int i; char c; String string; short s; TestFixture(int i, char c, String string, short s) { this.i = i; this.c = c; this.string = string; this.s = s; } } static class SubTestFixture extends TestFixture { transient String tString; SubTestFixture(int i, char c, String string, short s, String tString) { super(i, c, string, s); this.tString = tString; } } static class AllTransientFixture { transient int i; transient char c; transient String string; transient short s; AllTransientFixture(int i, char c, String string, short s) { this.i = i; this.c = c; this.string = string; this.s = s; } } static class SubAllTransientFixture extends AllTransientFixture { transient String tString; SubAllTransientFixture(int i, char c, String string, short s, String tString) { super(i, c, string, s); this.tString = tString; } } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/builder/HashCodeBuilderTest.java100644 0 0 53570 11513702437 27135 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.builder; import junit.framework.TestCase; /** * Unit tests {@link org.apache.commons.lang.builder.HashCodeBuilder}. * * @author Apache Software Foundation * @version $Id: HashCodeBuilderTest.java 907374 2010-02-07 03:32:04Z mbenson $ */ public class HashCodeBuilderTest extends TestCase { /** * A reflection test fixture. */ static class ReflectionTestCycleA { ReflectionTestCycleB b; public int hashCode() { return HashCodeBuilder.reflectionHashCode(this); } } /** * A reflection test fixture. */ static class ReflectionTestCycleB { ReflectionTestCycleA a; public int hashCode() { return HashCodeBuilder.reflectionHashCode(this); } } public HashCodeBuilderTest(String name) { super(name); } // ----------------------------------------------------------------------- public void testConstructorEx1() { try { new HashCodeBuilder(0, 0); } catch (IllegalArgumentException ex) { return; } fail(); } public void testConstructorEx2() { try { new HashCodeBuilder(2, 2); } catch (IllegalArgumentException ex) { return; } fail(); } static class TestObject { private int a; public TestObject(int a) { this.a = a; } public boolean equals(Object o) { if (o == this) { return true; } if (!(o instanceof TestObject)) { return false; } TestObject rhs = (TestObject) o; return (a == rhs.a); } public void setA(int a) { this.a = a; } public int getA() { return a; } } static class TestSubObject extends TestObject { private int b; transient private int t; public TestSubObject() { super(0); } public TestSubObject(int a, int b, int t) { super(a); this.b = b; this.t = t; } public boolean equals(Object o) { if (o == this) { return true; } if (!(o instanceof TestSubObject)) { return false; } TestSubObject rhs = (TestSubObject) o; return super.equals(o) && (b == rhs.b); } } public void testReflectionHashCode() { assertEquals(17 * 37, HashCodeBuilder.reflectionHashCode(new TestObject(0))); assertEquals(17 * 37 + 123456, HashCodeBuilder.reflectionHashCode(new TestObject(123456))); } public void testReflectionHierarchyHashCode() { assertEquals(17 * 37 * 37, HashCodeBuilder.reflectionHashCode(new TestSubObject(0, 0, 0))); assertEquals(17 * 37 * 37 * 37, HashCodeBuilder.reflectionHashCode(new TestSubObject(0, 0, 0), true)); assertEquals((17 * 37 + 7890) * 37 + 123456, HashCodeBuilder.reflectionHashCode(new TestSubObject(123456, 7890, 0))); assertEquals(((17 * 37 + 7890) * 37 + 0) * 37 + 123456, HashCodeBuilder.reflectionHashCode(new TestSubObject( 123456, 7890, 0), true)); } public void testReflectionHierarchyHashCodeEx1() { try { HashCodeBuilder.reflectionHashCode(0, 0, new TestSubObject(0, 0, 0), true); } catch (IllegalArgumentException ex) { return; } fail(); } public void testReflectionHierarchyHashCodeEx2() { try { HashCodeBuilder.reflectionHashCode(2, 2, new TestSubObject(0, 0, 0), true); } catch (IllegalArgumentException ex) { return; } fail(); } public void testReflectionHashCodeEx1() { try { HashCodeBuilder.reflectionHashCode(0, 0, new TestObject(0), true); } catch (IllegalArgumentException ex) { return; } fail(); } public void testReflectionHashCodeEx2() { try { HashCodeBuilder.reflectionHashCode(2, 2, new TestObject(0), true); } catch (IllegalArgumentException ex) { return; } fail(); } public void testReflectionHashCodeEx3() { try { HashCodeBuilder.reflectionHashCode(13, 19, null, true); } catch (IllegalArgumentException ex) { return; } fail(); } public void testSuper() { Object obj = new Object(); assertEquals(17 * 37 + (19 * 41 + obj.hashCode()), new HashCodeBuilder(17, 37).appendSuper( new HashCodeBuilder(19, 41).append(obj).toHashCode()).toHashCode()); } public void testObject() { Object obj = null; assertEquals(17 * 37, new HashCodeBuilder(17, 37).append(obj).toHashCode()); obj = new Object(); assertEquals(17 * 37 + obj.hashCode(), new HashCodeBuilder(17, 37).append(obj).toHashCode()); } public void testLong() { assertEquals(17 * 37, new HashCodeBuilder(17, 37).append((long) 0L).toHashCode()); assertEquals(17 * 37 + (int) (123456789L ^ (123456789L >> 32)), new HashCodeBuilder(17, 37).append( (long) 123456789L).toHashCode()); } public void testInt() { assertEquals(17 * 37, new HashCodeBuilder(17, 37).append((int) 0).toHashCode()); assertEquals(17 * 37 + 123456, new HashCodeBuilder(17, 37).append((int) 123456).toHashCode()); } public void testShort() { assertEquals(17 * 37, new HashCodeBuilder(17, 37).append((short) 0).toHashCode()); assertEquals(17 * 37 + 12345, new HashCodeBuilder(17, 37).append((short) 12345).toHashCode()); } public void testChar() { assertEquals(17 * 37, new HashCodeBuilder(17, 37).append((char) 0).toHashCode()); assertEquals(17 * 37 + 1234, new HashCodeBuilder(17, 37).append((char) 1234).toHashCode()); } public void testByte() { assertEquals(17 * 37, new HashCodeBuilder(17, 37).append((byte) 0).toHashCode()); assertEquals(17 * 37 + 123, new HashCodeBuilder(17, 37).append((byte) 123).toHashCode()); } public void testDouble() { assertEquals(17 * 37, new HashCodeBuilder(17, 37).append((double) 0d).toHashCode()); double d = 1234567.89; long l = Double.doubleToLongBits(d); assertEquals(17 * 37 + (int) (l ^ (l >> 32)), new HashCodeBuilder(17, 37).append(d).toHashCode()); } public void testFloat() { assertEquals(17 * 37, new HashCodeBuilder(17, 37).append((float) 0f).toHashCode()); float f = 1234.89f; int i = Float.floatToIntBits(f); assertEquals(17 * 37 + i, new HashCodeBuilder(17, 37).append(f).toHashCode()); } public void testBoolean() { assertEquals(17 * 37 + 0, new HashCodeBuilder(17, 37).append(true).toHashCode()); assertEquals(17 * 37 + 1, new HashCodeBuilder(17, 37).append(false).toHashCode()); } public void testObjectArray() { assertEquals(17 * 37, new HashCodeBuilder(17, 37).append((Object[]) null).toHashCode()); Object[] obj = new Object[2]; assertEquals((17 * 37) * 37, new HashCodeBuilder(17, 37).append(obj).toHashCode()); obj[0] = new Object(); assertEquals((17 * 37 + obj[0].hashCode()) * 37, new HashCodeBuilder(17, 37).append(obj).toHashCode()); obj[1] = new Object(); assertEquals((17 * 37 + obj[0].hashCode()) * 37 + obj[1].hashCode(), new HashCodeBuilder(17, 37).append(obj) .toHashCode()); } public void testObjectArrayAsObject() { Object[] obj = new Object[2]; assertEquals((17 * 37) * 37, new HashCodeBuilder(17, 37).append((Object) obj).toHashCode()); obj[0] = new Object(); assertEquals((17 * 37 + obj[0].hashCode()) * 37, new HashCodeBuilder(17, 37).append((Object) obj).toHashCode()); obj[1] = new Object(); assertEquals((17 * 37 + obj[0].hashCode()) * 37 + obj[1].hashCode(), new HashCodeBuilder(17, 37).append( (Object) obj).toHashCode()); } public void testLongArray() { assertEquals(17 * 37, new HashCodeBuilder(17, 37).append((long[]) null).toHashCode()); long[] obj = new long[2]; assertEquals((17 * 37) * 37, new HashCodeBuilder(17, 37).append(obj).toHashCode()); obj[0] = 5L; int h1 = (int) (5L ^ (5L >> 32)); assertEquals((17 * 37 + h1) * 37, new HashCodeBuilder(17, 37).append(obj).toHashCode()); obj[1] = 6L; int h2 = (int) (6L ^ (6L >> 32)); assertEquals((17 * 37 + h1) * 37 + h2, new HashCodeBuilder(17, 37).append(obj).toHashCode()); } public void testLongArrayAsObject() { long[] obj = new long[2]; assertEquals((17 * 37) * 37, new HashCodeBuilder(17, 37).append((Object) obj).toHashCode()); obj[0] = 5L; int h1 = (int) (5L ^ (5L >> 32)); assertEquals((17 * 37 + h1) * 37, new HashCodeBuilder(17, 37).append((Object) obj).toHashCode()); obj[1] = 6L; int h2 = (int) (6L ^ (6L >> 32)); assertEquals((17 * 37 + h1) * 37 + h2, new HashCodeBuilder(17, 37).append((Object) obj).toHashCode()); } public void testIntArray() { assertEquals(17 * 37, new HashCodeBuilder(17, 37).append((int[]) null).toHashCode()); int[] obj = new int[2]; assertEquals((17 * 37) * 37, new HashCodeBuilder(17, 37).append(obj).toHashCode()); obj[0] = 5; assertEquals((17 * 37 + 5) * 37, new HashCodeBuilder(17, 37).append(obj).toHashCode()); obj[1] = 6; assertEquals((17 * 37 + 5) * 37 + 6, new HashCodeBuilder(17, 37).append(obj).toHashCode()); } public void testIntArrayAsObject() { int[] obj = new int[2]; assertEquals((17 * 37) * 37, new HashCodeBuilder(17, 37).append((Object) obj).toHashCode()); obj[0] = 5; assertEquals((17 * 37 + 5) * 37, new HashCodeBuilder(17, 37).append((Object) obj).toHashCode()); obj[1] = 6; assertEquals((17 * 37 + 5) * 37 + 6, new HashCodeBuilder(17, 37).append((Object) obj).toHashCode()); } public void testShortArray() { assertEquals(17 * 37, new HashCodeBuilder(17, 37).append((short[]) null).toHashCode()); short[] obj = new short[2]; assertEquals((17 * 37) * 37, new HashCodeBuilder(17, 37).append(obj).toHashCode()); obj[0] = (short) 5; assertEquals((17 * 37 + 5) * 37, new HashCodeBuilder(17, 37).append(obj).toHashCode()); obj[1] = (short) 6; assertEquals((17 * 37 + 5) * 37 + 6, new HashCodeBuilder(17, 37).append(obj).toHashCode()); } public void testShortArrayAsObject() { short[] obj = new short[2]; assertEquals((17 * 37) * 37, new HashCodeBuilder(17, 37).append((Object) obj).toHashCode()); obj[0] = (short) 5; assertEquals((17 * 37 + 5) * 37, new HashCodeBuilder(17, 37).append((Object) obj).toHashCode()); obj[1] = (short) 6; assertEquals((17 * 37 + 5) * 37 + 6, new HashCodeBuilder(17, 37).append((Object) obj).toHashCode()); } public void testCharArray() { assertEquals(17 * 37, new HashCodeBuilder(17, 37).append((char[]) null).toHashCode()); char[] obj = new char[2]; assertEquals((17 * 37) * 37, new HashCodeBuilder(17, 37).append(obj).toHashCode()); obj[0] = (char) 5; assertEquals((17 * 37 + 5) * 37, new HashCodeBuilder(17, 37).append(obj).toHashCode()); obj[1] = (char) 6; assertEquals((17 * 37 + 5) * 37 + 6, new HashCodeBuilder(17, 37).append(obj).toHashCode()); } public void testCharArrayAsObject() { char[] obj = new char[2]; assertEquals((17 * 37) * 37, new HashCodeBuilder(17, 37).append((Object) obj).toHashCode()); obj[0] = (char) 5; assertEquals((17 * 37 + 5) * 37, new HashCodeBuilder(17, 37).append((Object) obj).toHashCode()); obj[1] = (char) 6; assertEquals((17 * 37 + 5) * 37 + 6, new HashCodeBuilder(17, 37).append((Object) obj).toHashCode()); } public void testByteArray() { assertEquals(17 * 37, new HashCodeBuilder(17, 37).append((byte[]) null).toHashCode()); byte[] obj = new byte[2]; assertEquals((17 * 37) * 37, new HashCodeBuilder(17, 37).append(obj).toHashCode()); obj[0] = (byte) 5; assertEquals((17 * 37 + 5) * 37, new HashCodeBuilder(17, 37).append(obj).toHashCode()); obj[1] = (byte) 6; assertEquals((17 * 37 + 5) * 37 + 6, new HashCodeBuilder(17, 37).append(obj).toHashCode()); } public void testByteArrayAsObject() { byte[] obj = new byte[2]; assertEquals((17 * 37) * 37, new HashCodeBuilder(17, 37).append((Object) obj).toHashCode()); obj[0] = (byte) 5; assertEquals((17 * 37 + 5) * 37, new HashCodeBuilder(17, 37).append((Object) obj).toHashCode()); obj[1] = (byte) 6; assertEquals((17 * 37 + 5) * 37 + 6, new HashCodeBuilder(17, 37).append((Object) obj).toHashCode()); } public void testDoubleArray() { assertEquals(17 * 37, new HashCodeBuilder(17, 37).append((double[]) null).toHashCode()); double[] obj = new double[2]; assertEquals((17 * 37) * 37, new HashCodeBuilder(17, 37).append(obj).toHashCode()); obj[0] = 5.4d; long l1 = Double.doubleToLongBits(5.4d); int h1 = (int) (l1 ^ (l1 >> 32)); assertEquals((17 * 37 + h1) * 37, new HashCodeBuilder(17, 37).append(obj).toHashCode()); obj[1] = 6.3d; long l2 = Double.doubleToLongBits(6.3d); int h2 = (int) (l2 ^ (l2 >> 32)); assertEquals((17 * 37 + h1) * 37 + h2, new HashCodeBuilder(17, 37).append(obj).toHashCode()); } public void testDoubleArrayAsObject() { double[] obj = new double[2]; assertEquals((17 * 37) * 37, new HashCodeBuilder(17, 37).append((Object) obj).toHashCode()); obj[0] = 5.4d; long l1 = Double.doubleToLongBits(5.4d); int h1 = (int) (l1 ^ (l1 >> 32)); assertEquals((17 * 37 + h1) * 37, new HashCodeBuilder(17, 37).append((Object) obj).toHashCode()); obj[1] = 6.3d; long l2 = Double.doubleToLongBits(6.3d); int h2 = (int) (l2 ^ (l2 >> 32)); assertEquals((17 * 37 + h1) * 37 + h2, new HashCodeBuilder(17, 37).append((Object) obj).toHashCode()); } public void testFloatArray() { assertEquals(17 * 37, new HashCodeBuilder(17, 37).append((float[]) null).toHashCode()); float[] obj = new float[2]; assertEquals((17 * 37) * 37, new HashCodeBuilder(17, 37).append(obj).toHashCode()); obj[0] = 5.4f; int h1 = Float.floatToIntBits(5.4f); assertEquals((17 * 37 + h1) * 37, new HashCodeBuilder(17, 37).append(obj).toHashCode()); obj[1] = 6.3f; int h2 = Float.floatToIntBits(6.3f); assertEquals((17 * 37 + h1) * 37 + h2, new HashCodeBuilder(17, 37).append(obj).toHashCode()); } public void testFloatArrayAsObject() { float[] obj = new float[2]; assertEquals((17 * 37) * 37, new HashCodeBuilder(17, 37).append((Object) obj).toHashCode()); obj[0] = 5.4f; int h1 = Float.floatToIntBits(5.4f); assertEquals((17 * 37 + h1) * 37, new HashCodeBuilder(17, 37).append((Object) obj).toHashCode()); obj[1] = 6.3f; int h2 = Float.floatToIntBits(6.3f); assertEquals((17 * 37 + h1) * 37 + h2, new HashCodeBuilder(17, 37).append((Object) obj).toHashCode()); } public void testBooleanArray() { assertEquals(17 * 37, new HashCodeBuilder(17, 37).append((boolean[]) null).toHashCode()); boolean[] obj = new boolean[2]; assertEquals((17 * 37 + 1) * 37 + 1, new HashCodeBuilder(17, 37).append(obj).toHashCode()); obj[0] = true; assertEquals((17 * 37 + 0) * 37 + 1, new HashCodeBuilder(17, 37).append(obj).toHashCode()); obj[1] = false; assertEquals((17 * 37 + 0) * 37 + 1, new HashCodeBuilder(17, 37).append(obj).toHashCode()); } public void testBooleanArrayAsObject() { boolean[] obj = new boolean[2]; assertEquals((17 * 37 + 1) * 37 + 1, new HashCodeBuilder(17, 37).append((Object) obj).toHashCode()); obj[0] = true; assertEquals((17 * 37 + 0) * 37 + 1, new HashCodeBuilder(17, 37).append((Object) obj).toHashCode()); obj[1] = false; assertEquals((17 * 37 + 0) * 37 + 1, new HashCodeBuilder(17, 37).append((Object) obj).toHashCode()); } public void testBooleanMultiArray() { boolean[][] obj = new boolean[2][]; assertEquals((17 * 37) * 37, new HashCodeBuilder(17, 37).append(obj).toHashCode()); obj[0] = new boolean[0]; assertEquals(17 * 37, new HashCodeBuilder(17, 37).append(obj).toHashCode()); obj[0] = new boolean[1]; assertEquals((17 * 37 + 1) * 37, new HashCodeBuilder(17, 37).append(obj).toHashCode()); obj[0] = new boolean[2]; assertEquals(((17 * 37 + 1) * 37 + 1) * 37, new HashCodeBuilder(17, 37).append(obj).toHashCode()); obj[0][0] = true; assertEquals(((17 * 37 + 0) * 37 + 1) * 37, new HashCodeBuilder(17, 37).append(obj).toHashCode()); obj[1] = new boolean[1]; assertEquals((((17 * 37 + 0) * 37 + 1) * 37 + 1), new HashCodeBuilder(17, 37).append(obj).toHashCode()); } public void testReflectionHashCodeExcludeFields() throws Exception { TestObjectWithMultipleFields x = new TestObjectWithMultipleFields(1, 2, 3); assertEquals((((17 * 37 + 1) * 37 + 2) * 37 + 3), HashCodeBuilder.reflectionHashCode(x)); assertEquals((((17 * 37 + 1) * 37 + 2) * 37 + 3), HashCodeBuilder.reflectionHashCode(x, (String[]) null)); assertEquals((((17 * 37 + 1) * 37 + 2) * 37 + 3), HashCodeBuilder.reflectionHashCode(x, new String[]{})); assertEquals((((17 * 37 + 1) * 37 + 2) * 37 + 3), HashCodeBuilder.reflectionHashCode(x, new String[]{"xxx"})); assertEquals(((17 * 37 + 1) * 37 + 3), HashCodeBuilder.reflectionHashCode(x, new String[]{"two"})); assertEquals(((17 * 37 + 1) * 37 + 2), HashCodeBuilder.reflectionHashCode(x, new String[]{"three"})); assertEquals((17 * 37 + 1), HashCodeBuilder.reflectionHashCode(x, new String[]{"two", "three"})); assertEquals(17, HashCodeBuilder.reflectionHashCode(x, new String[]{"one", "two", "three"})); assertEquals(17, HashCodeBuilder.reflectionHashCode(x, new String[]{"one", "two", "three", "xxx"})); } static class TestObjectWithMultipleFields { private int one = 0; private int two = 0; private int three = 0; public TestObjectWithMultipleFields(int one, int two, int three) { this.one = one; this.two = two; this.three = three; } } /** * Test Objects pointing to each other. */ public void testReflectionObjectCycle() { ReflectionTestCycleA a = new ReflectionTestCycleA(); ReflectionTestCycleB b = new ReflectionTestCycleB(); a.b = b; b.a = a; // Used to caused: // java.lang.StackOverflowError // at java.lang.ClassLoader.getCallerClassLoader(Native Method) // at java.lang.Class.getDeclaredFields(Class.java:992) // at org.apache.commons.lang.builder.HashCodeBuilder.reflectionAppend(HashCodeBuilder.java:373) // at org.apache.commons.lang.builder.HashCodeBuilder.reflectionHashCode(HashCodeBuilder.java:349) // at org.apache.commons.lang.builder.HashCodeBuilder.reflectionHashCode(HashCodeBuilder.java:155) // at // org.apache.commons.lang.builder.HashCodeBuilderTest$ReflectionTestCycleB.hashCode(HashCodeBuilderTest.java:53) // at org.apache.commons.lang.builder.HashCodeBuilder.append(HashCodeBuilder.java:422) // at org.apache.commons.lang.builder.HashCodeBuilder.reflectionAppend(HashCodeBuilder.java:383) // at org.apache.commons.lang.builder.HashCodeBuilder.reflectionHashCode(HashCodeBuilder.java:349) // at org.apache.commons.lang.builder.HashCodeBuilder.reflectionHashCode(HashCodeBuilder.java:155) // at // org.apache.commons.lang.builder.HashCodeBuilderTest$ReflectionTestCycleA.hashCode(HashCodeBuilderTest.java:42) // at org.apache.commons.lang.builder.HashCodeBuilder.append(HashCodeBuilder.java:422) a.hashCode(); assertNull(HashCodeBuilder.getRegistry()); b.hashCode(); assertNull(HashCodeBuilder.getRegistry()); } /** * Ensures LANG-520 remains true */ public void testToHashCodeEqualsHashCode() { HashCodeBuilder hcb = new HashCodeBuilder(17, 37).append(new Object()).append('a'); assertEquals("hashCode() is no longer returning the same value as toHashCode() - see LANG-520", hcb.toHashCode(), hcb.hashCode()); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/builder/MultiLineToStringStyleTest.java100644 0 0 22317 11513702437 30560 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.builder; import java.util.ArrayList; import java.util.HashMap; import junit.framework.TestCase; import org.apache.commons.lang.SystemUtils; import org.apache.commons.lang.builder.ToStringStyleTest.Person; /** * Unit tests {@link org.apache.commons.lang.builder.MultiLineToStringStyleTest}. * * @author Apache Software Foundation * @version $Id: MultiLineToStringStyleTest.java 905636 2010-02-02 14:03:32Z niallp $ */ public class MultiLineToStringStyleTest extends TestCase { private final Integer base = new Integer(5); private final String baseStr = base.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(base)); public MultiLineToStringStyleTest(String name) { super(name); } protected void setUp() throws Exception { super.setUp(); ToStringBuilder.setDefaultStyle(ToStringStyle.MULTI_LINE_STYLE); } protected void tearDown() throws Exception { super.tearDown(); ToStringBuilder.setDefaultStyle(ToStringStyle.DEFAULT_STYLE); } //---------------------------------------------------------------- public void testBlank() { assertEquals(baseStr + "[" + SystemUtils.LINE_SEPARATOR + "]", new ToStringBuilder(base).toString()); } public void testAppendSuper() { assertEquals(baseStr + "[" + SystemUtils.LINE_SEPARATOR + "]", new ToStringBuilder(base).appendSuper("Integer@8888[" + SystemUtils.LINE_SEPARATOR + "]").toString()); assertEquals(baseStr + "[" + SystemUtils.LINE_SEPARATOR + " " + SystemUtils.LINE_SEPARATOR + "]", new ToStringBuilder(base).appendSuper("Integer@8888[" + SystemUtils.LINE_SEPARATOR + " " + SystemUtils.LINE_SEPARATOR + "]").toString()); assertEquals(baseStr + "[" + SystemUtils.LINE_SEPARATOR + " a=hello" + SystemUtils.LINE_SEPARATOR + "]", new ToStringBuilder(base).appendSuper("Integer@8888[" + SystemUtils.LINE_SEPARATOR + "]").append("a", "hello").toString()); assertEquals(baseStr + "[" + SystemUtils.LINE_SEPARATOR + " " + SystemUtils.LINE_SEPARATOR + " a=hello" + SystemUtils.LINE_SEPARATOR + "]", new ToStringBuilder(base).appendSuper("Integer@8888[" + SystemUtils.LINE_SEPARATOR + " " + SystemUtils.LINE_SEPARATOR + "]").append("a", "hello").toString()); assertEquals(baseStr + "[" + SystemUtils.LINE_SEPARATOR + " a=hello" + SystemUtils.LINE_SEPARATOR + "]", new ToStringBuilder(base).appendSuper(null).append("a", "hello").toString()); } public void testObject() { Integer i3 = new Integer(3); Integer i4 = new Integer(4); assertEquals(baseStr + "[" + SystemUtils.LINE_SEPARATOR + " " + SystemUtils.LINE_SEPARATOR + "]", new ToStringBuilder(base).append((Object) null).toString()); assertEquals(baseStr + "[" + SystemUtils.LINE_SEPARATOR + " 3" + SystemUtils.LINE_SEPARATOR + "]", new ToStringBuilder(base).append(i3).toString()); assertEquals(baseStr + "[" + SystemUtils.LINE_SEPARATOR + " a=" + SystemUtils.LINE_SEPARATOR + "]", new ToStringBuilder(base).append("a", (Object) null).toString()); assertEquals(baseStr + "[" + SystemUtils.LINE_SEPARATOR + " a=3" + SystemUtils.LINE_SEPARATOR + "]", new ToStringBuilder(base).append("a", i3).toString()); assertEquals(baseStr + "[" + SystemUtils.LINE_SEPARATOR + " a=3" + SystemUtils.LINE_SEPARATOR + " b=4" + SystemUtils.LINE_SEPARATOR + "]", new ToStringBuilder(base).append("a", i3).append("b", i4).toString()); assertEquals(baseStr + "[" + SystemUtils.LINE_SEPARATOR + " a=" + SystemUtils.LINE_SEPARATOR + "]", new ToStringBuilder(base).append("a", i3, false).toString()); assertEquals(baseStr + "[" + SystemUtils.LINE_SEPARATOR + " a=" + SystemUtils.LINE_SEPARATOR + "]", new ToStringBuilder(base).append("a", new ArrayList(), false).toString()); assertEquals(baseStr + "[" + SystemUtils.LINE_SEPARATOR + " a=[]" + SystemUtils.LINE_SEPARATOR + "]", new ToStringBuilder(base).append("a", new ArrayList(), true).toString()); assertEquals(baseStr + "[" + SystemUtils.LINE_SEPARATOR + " a=" + SystemUtils.LINE_SEPARATOR + "]", new ToStringBuilder(base).append("a", new HashMap(), false).toString()); assertEquals(baseStr + "[" + SystemUtils.LINE_SEPARATOR + " a={}" + SystemUtils.LINE_SEPARATOR + "]", new ToStringBuilder(base).append("a", new HashMap(), true).toString()); assertEquals(baseStr + "[" + SystemUtils.LINE_SEPARATOR + " a=" + SystemUtils.LINE_SEPARATOR + "]", new ToStringBuilder(base).append("a", (Object) new String[0], false).toString()); assertEquals(baseStr + "[" + SystemUtils.LINE_SEPARATOR + " a={}" + SystemUtils.LINE_SEPARATOR + "]", new ToStringBuilder(base).append("a", (Object) new String[0], true).toString()); } public void testPerson() { Person p = new Person(); p.name = "Jane Doe"; p.age = 25; p.smoker = true; String pBaseStr = p.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(p)); 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()); } public void testLong() { assertEquals(baseStr + "[" + SystemUtils.LINE_SEPARATOR + " 3" + SystemUtils.LINE_SEPARATOR + "]", new ToStringBuilder(base).append(3L).toString()); assertEquals(baseStr + "[" + SystemUtils.LINE_SEPARATOR + " a=3" + SystemUtils.LINE_SEPARATOR + "]", new ToStringBuilder(base).append("a", 3L).toString()); assertEquals(baseStr + "[" + SystemUtils.LINE_SEPARATOR + " a=3" + SystemUtils.LINE_SEPARATOR + " b=4" + SystemUtils.LINE_SEPARATOR + "]", new ToStringBuilder(base).append("a", 3L).append("b", 4L).toString()); } public void testObjectArray() { Object[] array = new Object[] {null, base, new int[] {3, 6}}; assertEquals(baseStr + "[" + SystemUtils.LINE_SEPARATOR + " {,5,{3,6}}" + SystemUtils.LINE_SEPARATOR + "]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[" + SystemUtils.LINE_SEPARATOR + " {,5,{3,6}}" + SystemUtils.LINE_SEPARATOR + "]", new ToStringBuilder(base).append((Object) array).toString()); array = null; assertEquals(baseStr + "[" + SystemUtils.LINE_SEPARATOR + " " + SystemUtils.LINE_SEPARATOR + "]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[" + SystemUtils.LINE_SEPARATOR + " " + SystemUtils.LINE_SEPARATOR + "]", new ToStringBuilder(base).append((Object) array).toString()); } public void testLongArray() { long[] array = new long[] {1, 2, -3, 4}; assertEquals(baseStr + "[" + SystemUtils.LINE_SEPARATOR + " {1,2,-3,4}" + SystemUtils.LINE_SEPARATOR + "]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[" + SystemUtils.LINE_SEPARATOR + " {1,2,-3,4}" + SystemUtils.LINE_SEPARATOR + "]", new ToStringBuilder(base).append((Object) array).toString()); array = null; assertEquals(baseStr + "[" + SystemUtils.LINE_SEPARATOR + " " + SystemUtils.LINE_SEPARATOR + "]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[" + SystemUtils.LINE_SEPARATOR + " " + SystemUtils.LINE_SEPARATOR + "]", new ToStringBuilder(base).append((Object) array).toString()); } public void testLongArrayArray() { long[][] array = new long[][] {{1, 2}, null, {5}}; assertEquals(baseStr + "[" + SystemUtils.LINE_SEPARATOR + " {{1,2},,{5}}" + SystemUtils.LINE_SEPARATOR + "]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[" + SystemUtils.LINE_SEPARATOR + " {{1,2},,{5}}" + SystemUtils.LINE_SEPARATOR + "]", new ToStringBuilder(base).append((Object) array).toString()); array = null; assertEquals(baseStr + "[" + SystemUtils.LINE_SEPARATOR + " " + SystemUtils.LINE_SEPARATOR + "]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[" + SystemUtils.LINE_SEPARATOR + " " + SystemUtils.LINE_SEPARATOR + "]", new ToStringBuilder(base).append((Object) array).toString()); } } ././@LongLink100644 0 0 146 11513702661 10256 Lustar 0 0 commons-lang-2.6-src/src/test/java/org/apache/commons/lang/builder/NoFieldNamesToStringStyleTest.javacommons-lang-2.6-src/src/test/java/org/apache/commons/lang/builder/NoFieldNamesToStringStyleTest.jav100644 0 0 14775 11513702436 31031 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.builder; import java.util.ArrayList; import java.util.HashMap; import org.apache.commons.lang.builder.ToStringStyleTest.Person; import junit.framework.TestCase; /** * Unit tests {@link org.apache.commons.lang.builder.NoFieldNamesToStringStyleTest}. * * @author Apache Software Foundation * @version $Id: NoFieldNamesToStringStyleTest.java 905636 2010-02-02 14:03:32Z niallp $ */ public class NoFieldNamesToStringStyleTest extends TestCase { private final Integer base = new Integer(5); private final String baseStr = base.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(base)); public NoFieldNamesToStringStyleTest(String name) { super(name); } protected void setUp() throws Exception { super.setUp(); ToStringBuilder.setDefaultStyle(ToStringStyle.NO_FIELD_NAMES_STYLE); } protected void tearDown() throws Exception { super.tearDown(); ToStringBuilder.setDefaultStyle(ToStringStyle.DEFAULT_STYLE); } //---------------------------------------------------------------- public void testBlank() { assertEquals(baseStr + "[]", new ToStringBuilder(base).toString()); } public void testAppendSuper() { assertEquals(baseStr + "[]", new ToStringBuilder(base).appendSuper("Integer@8888[]").toString()); assertEquals(baseStr + "[]", new ToStringBuilder(base).appendSuper("Integer@8888[]").toString()); assertEquals(baseStr + "[hello]", new ToStringBuilder(base).appendSuper("Integer@8888[]").append("a", "hello").toString()); assertEquals(baseStr + "[,hello]", new ToStringBuilder(base).appendSuper("Integer@8888[]").append("a", "hello").toString()); assertEquals(baseStr + "[hello]", new ToStringBuilder(base).appendSuper(null).append("a", "hello").toString()); } public void testObject() { Integer i3 = new Integer(3); Integer i4 = new Integer(4); assertEquals(baseStr + "[]", new ToStringBuilder(base).append((Object) null).toString()); assertEquals(baseStr + "[3]", new ToStringBuilder(base).append(i3).toString()); assertEquals(baseStr + "[]", new ToStringBuilder(base).append("a", (Object) null).toString()); assertEquals(baseStr + "[3]", new ToStringBuilder(base).append("a", i3).toString()); assertEquals(baseStr + "[3,4]", new ToStringBuilder(base).append("a", i3).append("b", i4).toString()); assertEquals(baseStr + "[]", new ToStringBuilder(base).append("a", i3, false).toString()); assertEquals(baseStr + "[]", new ToStringBuilder(base).append("a", new ArrayList(), false).toString()); assertEquals(baseStr + "[[]]", new ToStringBuilder(base).append("a", new ArrayList(), true).toString()); assertEquals(baseStr + "[]", new ToStringBuilder(base).append("a", new HashMap(), false).toString()); assertEquals(baseStr + "[{}]", new ToStringBuilder(base).append("a", new HashMap(), true).toString()); assertEquals(baseStr + "[]", new ToStringBuilder(base).append("a", (Object) new String[0], false).toString()); assertEquals(baseStr + "[{}]", new ToStringBuilder(base).append("a", (Object) new String[0], true).toString()); } public void testPerson() { Person p = new Person(); p.name = "Ron Paul"; p.age = 72; p.smoker = false; String pBaseStr = p.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(p)); assertEquals(pBaseStr + "[Ron Paul,72,false]", new ToStringBuilder(p).append("name", p.name).append("age", p.age).append("smoker", p.smoker).toString()); } public void testLong() { assertEquals(baseStr + "[3]", new ToStringBuilder(base).append(3L).toString()); assertEquals(baseStr + "[3]", new ToStringBuilder(base).append("a", 3L).toString()); assertEquals(baseStr + "[3,4]", new ToStringBuilder(base).append("a", 3L).append("b", 4L).toString()); } public void testObjectArray() { Object[] array = new Object[] {null, base, new int[] {3, 6}}; assertEquals(baseStr + "[{,5,{3,6}}]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[{,5,{3,6}}]", new ToStringBuilder(base).append((Object) array).toString()); array = null; assertEquals(baseStr + "[]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[]", new ToStringBuilder(base).append((Object) array).toString()); } public void testLongArray() { long[] array = new long[] {1, 2, -3, 4}; assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append((Object) array).toString()); array = null; assertEquals(baseStr + "[]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[]", new ToStringBuilder(base).append((Object) array).toString()); } public void testLongArrayArray() { long[][] array = new long[][] {{1, 2}, null, {5}}; assertEquals(baseStr + "[{{1,2},,{5}}]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[{{1,2},,{5}}]", new ToStringBuilder(base).append((Object) array).toString()); array = null; assertEquals(baseStr + "[]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[]", new ToStringBuilder(base).append((Object) array).toString()); } } ././@LongLink100644 0 0 155 11513702661 10256 Lustar 0 0 commons-lang-2.6-src/src/test/java/org/apache/commons/lang/builder/ReflectionToStringBuilderExcludeTest.javacommons-lang-2.6-src/src/test/java/org/apache/commons/lang/builder/ReflectionToStringBuilderExcludeT100644 0 0 11741 11513702437 31113 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.builder; import java.util.ArrayList; import java.util.Collection; import java.util.List; import junit.framework.Assert; import junit.framework.TestCase; import org.apache.commons.lang.ArrayUtils; /** * @author ggregory * @version $Id: ReflectionToStringBuilderExcludeTest.java 437554 2006-08-28 06:21:41Z bayard $ */ public class ReflectionToStringBuilderExcludeTest extends TestCase { class TestFixture { private String secretField = SECRET_VALUE; private String showField = NOT_SECRET_VALUE; } private static final String NOT_SECRET_FIELD = "showField"; private static final String NOT_SECRET_VALUE = "Hello World!"; private static final String SECRET_FIELD = "secretField"; private static final String SECRET_VALUE = "secret value"; public void test_toStringExclude() { String toString = ReflectionToStringBuilder.toStringExclude(new TestFixture(), SECRET_FIELD); this.validateSecretFieldAbsent(toString); } public void test_toStringExcludeArray() { String toString = ReflectionToStringBuilder.toStringExclude(new TestFixture(), new String[]{SECRET_FIELD}); this.validateSecretFieldAbsent(toString); } public void test_toStringExcludeArrayWithNull() { String toString = ReflectionToStringBuilder.toStringExclude(new TestFixture(), new String[]{null}); this.validateSecretFieldPresent(toString); } public void test_toStringExcludeArrayWithNulls() { String toString = ReflectionToStringBuilder.toStringExclude(new TestFixture(), new String[]{null, null}); this.validateSecretFieldPresent(toString); } public void test_toStringExcludeCollection() { List excludeList = new ArrayList(); excludeList.add(SECRET_FIELD); String toString = ReflectionToStringBuilder.toStringExclude(new TestFixture(), excludeList); this.validateSecretFieldAbsent(toString); } public void test_toStringExcludeCollectionWithNull() { List excludeList = new ArrayList(); excludeList.add(null); String toString = ReflectionToStringBuilder.toStringExclude(new TestFixture(), excludeList); this.validateSecretFieldPresent(toString); } public void test_toStringExcludeCollectionWithNulls() { List excludeList = new ArrayList(); excludeList.add(null); excludeList.add(null); String toString = ReflectionToStringBuilder.toStringExclude(new TestFixture(), excludeList); this.validateSecretFieldPresent(toString); } public void test_toStringExcludeEmptyArray() { String toString = ReflectionToStringBuilder.toStringExclude(new TestFixture(), ArrayUtils.EMPTY_STRING_ARRAY); this.validateSecretFieldPresent(toString); } public void test_toStringExcludeEmptyCollection() { String toString = ReflectionToStringBuilder.toStringExclude(new TestFixture(), new ArrayList()); this.validateSecretFieldPresent(toString); } public void test_toStringExcludeNullArray() { String toString = ReflectionToStringBuilder.toStringExclude(new TestFixture(), (String[]) null); this.validateSecretFieldPresent(toString); } public void test_toStringExcludeNullCollection() { String toString = ReflectionToStringBuilder.toStringExclude(new TestFixture(), (Collection) null); this.validateSecretFieldPresent(toString); } private void validateNonSecretField(String toString) { Assert.assertTrue(toString.indexOf(NOT_SECRET_FIELD) > ArrayUtils.INDEX_NOT_FOUND); Assert.assertTrue(toString.indexOf(NOT_SECRET_VALUE) > ArrayUtils.INDEX_NOT_FOUND); } private void validateSecretFieldAbsent(String toString) { Assert.assertEquals(ArrayUtils.INDEX_NOT_FOUND, toString.indexOf(SECRET_VALUE)); this.validateNonSecretField(toString); } private void validateSecretFieldPresent(String toString) { Assert.assertTrue(toString.indexOf(SECRET_VALUE) > 0); this.validateNonSecretField(toString); } } ././@LongLink100644 0 0 145 11513702661 10255 Lustar 0 0 commons-lang-2.6-src/src/test/java/org/apache/commons/lang/builder/ShortPrefixToStringStyleTest.javacommons-lang-2.6-src/src/test/java/org/apache/commons/lang/builder/ShortPrefixToStringStyleTest.java100644 0 0 14604 11513702437 31133 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.builder; import java.util.ArrayList; import java.util.HashMap; import org.apache.commons.lang.builder.ToStringStyleTest.Person; import junit.framework.TestCase; /** * Unit tests {@link org.apache.commons.lang.builder.ToStringStyle#SHORT_PREFIX_STYLE}. * * @author Gary Gregory * @version $Id: ShortPrefixToStringStyleTest.java 905242 2010-02-01 10:44:09Z niallp $ */ public class ShortPrefixToStringStyleTest extends TestCase { private final Integer base = new Integer(5); private final String baseStr = "Integer"; protected void setUp() throws Exception { super.setUp(); ToStringBuilder.setDefaultStyle(ToStringStyle.SHORT_PREFIX_STYLE); } protected void tearDown() throws Exception { super.tearDown(); ToStringBuilder.setDefaultStyle(ToStringStyle.DEFAULT_STYLE); } //---------------------------------------------------------------- public void testBlank() { assertEquals(baseStr + "[]", new ToStringBuilder(base).toString()); } public void testAppendSuper() { assertEquals(baseStr + "[]", new ToStringBuilder(base).appendSuper("Integer@8888[]").toString()); assertEquals(baseStr + "[]", new ToStringBuilder(base).appendSuper("Integer@8888[]").toString()); assertEquals(baseStr + "[a=hello]", new ToStringBuilder(base).appendSuper("Integer@8888[]").append("a", "hello").toString()); assertEquals(baseStr + "[,a=hello]", new ToStringBuilder(base).appendSuper("Integer@8888[]").append("a", "hello").toString()); assertEquals(baseStr + "[a=hello]", new ToStringBuilder(base).appendSuper(null).append("a", "hello").toString()); } public void testObject() { Integer i3 = new Integer(3); Integer i4 = new Integer(4); assertEquals(baseStr + "[]", new ToStringBuilder(base).append((Object) null).toString()); assertEquals(baseStr + "[3]", new ToStringBuilder(base).append(i3).toString()); assertEquals(baseStr + "[a=]", new ToStringBuilder(base).append("a", (Object) null).toString()); assertEquals(baseStr + "[a=3]", new ToStringBuilder(base).append("a", i3).toString()); assertEquals(baseStr + "[a=3,b=4]", new ToStringBuilder(base).append("a", i3).append("b", i4).toString()); assertEquals(baseStr + "[a=]", new ToStringBuilder(base).append("a", i3, false).toString()); assertEquals(baseStr + "[a=]", new ToStringBuilder(base).append("a", new ArrayList(), false).toString()); assertEquals(baseStr + "[a=[]]", new ToStringBuilder(base).append("a", new ArrayList(), true).toString()); assertEquals(baseStr + "[a=]", new ToStringBuilder(base).append("a", new HashMap(), false).toString()); assertEquals(baseStr + "[a={}]", new ToStringBuilder(base).append("a", new HashMap(), true).toString()); assertEquals(baseStr + "[a=]", new ToStringBuilder(base).append("a", (Object) new String[0], false).toString()); assertEquals(baseStr + "[a={}]", new ToStringBuilder(base).append("a", (Object) new String[0], true).toString()); } public void testPerson() { Person p = new Person(); p.name = "John Q. Public"; p.age = 45; p.smoker = true; String pBaseStr = "ToStringStyleTest.Person"; 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()); } public void testLong() { assertEquals(baseStr + "[3]", new ToStringBuilder(base).append(3L).toString()); assertEquals(baseStr + "[a=3]", new ToStringBuilder(base).append("a", 3L).toString()); assertEquals(baseStr + "[a=3,b=4]", new ToStringBuilder(base).append("a", 3L).append("b", 4L).toString()); } public void testObjectArray() { Object[] array = new Object[] {null, base, new int[] {3, 6}}; assertEquals(baseStr + "[{,5,{3,6}}]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[{,5,{3,6}}]", new ToStringBuilder(base).append((Object) array).toString()); array = null; assertEquals(baseStr + "[]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[]", new ToStringBuilder(base).append((Object) array).toString()); } public void testLongArray() { long[] array = new long[] {1, 2, -3, 4}; assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append((Object) array).toString()); array = null; assertEquals(baseStr + "[]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[]", new ToStringBuilder(base).append((Object) array).toString()); } public void testLongArrayArray() { long[][] array = new long[][] {{1, 2}, null, {5}}; assertEquals(baseStr + "[{{1,2},,{5}}]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[{{1,2},,{5}}]", new ToStringBuilder(base).append((Object) array).toString()); array = null; assertEquals(baseStr + "[]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[]", new ToStringBuilder(base).append((Object) array).toString()); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/builder/SimpleToStringStyleTest.java100644 0 0 13463 11513702437 30111 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.builder; import java.util.ArrayList; import java.util.HashMap; import org.apache.commons.lang.builder.ToStringStyleTest.Person; import junit.framework.TestCase; /** * Unit tests {@link org.apache.commons.lang.builder.SimpleToStringStyleTest}. * * @author Apache Software Foundation * @version $Id: SimpleToStringStyleTest.java 905636 2010-02-02 14:03:32Z niallp $ */ public class SimpleToStringStyleTest extends TestCase { private final Integer base = new Integer(5); public SimpleToStringStyleTest(String name) { super(name); } protected void setUp() throws Exception { super.setUp(); ToStringBuilder.setDefaultStyle(ToStringStyle.SIMPLE_STYLE); } protected void tearDown() throws Exception { super.tearDown(); ToStringBuilder.setDefaultStyle(ToStringStyle.DEFAULT_STYLE); } //---------------------------------------------------------------- public void testBlank() { assertEquals("", new ToStringBuilder(base).toString()); } public void testAppendSuper() { assertEquals("", new ToStringBuilder(base).appendSuper("").toString()); assertEquals("", new ToStringBuilder(base).appendSuper("").toString()); assertEquals("hello", new ToStringBuilder(base).appendSuper("").append("a", "hello").toString()); assertEquals(",hello", new ToStringBuilder(base).appendSuper("").append("a", "hello").toString()); assertEquals("hello", new ToStringBuilder(base).appendSuper(null).append("a", "hello").toString()); } public void testObject() { Integer i3 = new Integer(3); Integer i4 = new Integer(4); assertEquals("", new ToStringBuilder(base).append((Object) null).toString()); assertEquals("3", new ToStringBuilder(base).append(i3).toString()); assertEquals("", new ToStringBuilder(base).append("a", (Object) null).toString()); assertEquals("3", new ToStringBuilder(base).append("a", i3).toString()); assertEquals("3,4", new ToStringBuilder(base).append("a", i3).append("b", i4).toString()); assertEquals("", new ToStringBuilder(base).append("a", i3, false).toString()); assertEquals("", new ToStringBuilder(base).append("a", new ArrayList(), false).toString()); assertEquals("[]", new ToStringBuilder(base).append("a", new ArrayList(), true).toString()); assertEquals("", new ToStringBuilder(base).append("a", new HashMap(), false).toString()); assertEquals("{}", new ToStringBuilder(base).append("a", new HashMap(), true).toString()); assertEquals("", new ToStringBuilder(base).append("a", (Object) new String[0], false).toString()); assertEquals("{}", new ToStringBuilder(base).append("a", (Object) new String[0], true).toString()); } public void testPerson() { Person p = new Person(); p.name = "Jane Q. Public"; p.age = 47; p.smoker = false; assertEquals("Jane Q. Public,47,false", new ToStringBuilder(p).append("name", p.name).append("age", p.age).append("smoker", p.smoker).toString()); } public void testLong() { assertEquals("3", new ToStringBuilder(base).append(3L).toString()); assertEquals("3", new ToStringBuilder(base).append("a", 3L).toString()); assertEquals("3,4", new ToStringBuilder(base).append("a", 3L).append("b", 4L).toString()); } public void testObjectArray() { Object[] array = new Object[] {null, base, new int[] {3, 6}}; assertEquals("{,5,{3,6}}", new ToStringBuilder(base).append(array).toString()); assertEquals("{,5,{3,6}}", new ToStringBuilder(base).append((Object) array).toString()); array = null; assertEquals("", new ToStringBuilder(base).append(array).toString()); assertEquals("", new ToStringBuilder(base).append((Object) array).toString()); } public void testLongArray() { long[] array = new long[] {1, 2, -3, 4}; assertEquals("{1,2,-3,4}", new ToStringBuilder(base).append(array).toString()); assertEquals("{1,2,-3,4}", new ToStringBuilder(base).append((Object) array).toString()); array = null; assertEquals("", new ToStringBuilder(base).append(array).toString()); assertEquals("", new ToStringBuilder(base).append((Object) array).toString()); } public void testLongArrayArray() { long[][] array = new long[][] {{1, 2}, null, {5}}; assertEquals("{{1,2},,{5}}", new ToStringBuilder(base).append(array).toString()); assertEquals("{{1,2},,{5}}", new ToStringBuilder(base).append((Object) array).toString()); array = null; assertEquals("", new ToStringBuilder(base).append(array).toString()); assertEquals("", new ToStringBuilder(base).append((Object) array).toString()); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/builder/StandardToStringStyleTest.java100644 0 0 15633 11513702437 30421 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.builder; import java.util.ArrayList; import java.util.HashMap; import org.apache.commons.lang.builder.ToStringStyleTest.Person; import junit.framework.TestCase; /** * Unit tests {@link org.apache.commons.lang.builder.ToStringStyle}. * * @author Apache Software Foundation * @version $Id: StandardToStringStyleTest.java 905636 2010-02-02 14:03:32Z niallp $ */ public class StandardToStringStyleTest extends TestCase { private final Integer base = new Integer(5); private final String baseStr = "Integer"; private static final StandardToStringStyle STYLE = new StandardToStringStyle(); static { STYLE.setUseShortClassName(true); STYLE.setUseIdentityHashCode(false); STYLE.setArrayStart("["); STYLE.setArraySeparator(", "); STYLE.setArrayEnd("]"); STYLE.setNullText("%NULL%"); STYLE.setSizeStartText("%SIZE="); STYLE.setSizeEndText("%"); STYLE.setSummaryObjectStartText("%"); STYLE.setSummaryObjectEndText("%"); } public StandardToStringStyleTest(String name) { super(name); } protected void setUp() throws Exception { super.setUp(); ToStringBuilder.setDefaultStyle(STYLE); } protected void tearDown() throws Exception { super.tearDown(); ToStringBuilder.setDefaultStyle(ToStringStyle.DEFAULT_STYLE); } //---------------------------------------------------------------- public void testBlank() { assertEquals(baseStr + "[]", new ToStringBuilder(base).toString()); } public void testAppendSuper() { assertEquals(baseStr + "[]", new ToStringBuilder(base).appendSuper("Integer@8888[]").toString()); assertEquals(baseStr + "[%NULL%]", new ToStringBuilder(base).appendSuper("Integer@8888[%NULL%]").toString()); assertEquals(baseStr + "[a=hello]", new ToStringBuilder(base).appendSuper("Integer@8888[]").append("a", "hello").toString()); assertEquals(baseStr + "[%NULL%,a=hello]", new ToStringBuilder(base).appendSuper("Integer@8888[%NULL%]").append("a", "hello").toString()); assertEquals(baseStr + "[a=hello]", new ToStringBuilder(base).appendSuper(null).append("a", "hello").toString()); } public void testObject() { Integer i3 = new Integer(3); Integer i4 = new Integer(4); assertEquals(baseStr + "[%NULL%]", new ToStringBuilder(base).append((Object) null).toString()); assertEquals(baseStr + "[3]", new ToStringBuilder(base).append(i3).toString()); assertEquals(baseStr + "[a=%NULL%]", new ToStringBuilder(base).append("a", (Object) null).toString()); assertEquals(baseStr + "[a=3]", new ToStringBuilder(base).append("a", i3).toString()); assertEquals(baseStr + "[a=3,b=4]", new ToStringBuilder(base).append("a", i3).append("b", i4).toString()); assertEquals(baseStr + "[a=%Integer%]", new ToStringBuilder(base).append("a", i3, false).toString()); assertEquals(baseStr + "[a=%SIZE=0%]", new ToStringBuilder(base).append("a", new ArrayList(), false).toString()); assertEquals(baseStr + "[a=[]]", new ToStringBuilder(base).append("a", new ArrayList(), true).toString()); assertEquals(baseStr + "[a=%SIZE=0%]", new ToStringBuilder(base).append("a", new HashMap(), false).toString()); assertEquals(baseStr + "[a={}]", new ToStringBuilder(base).append("a", new HashMap(), true).toString()); assertEquals(baseStr + "[a=%SIZE=0%]", new ToStringBuilder(base).append("a", (Object) new String[0], false).toString()); assertEquals(baseStr + "[a=[]]", new ToStringBuilder(base).append("a", (Object) new String[0], true).toString()); } public void testPerson() { Person p = new Person(); p.name = "Suzy Queue"; p.age = 19; p.smoker = false; String pBaseStr = "ToStringStyleTest.Person"; 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()); } public void testLong() { assertEquals(baseStr + "[3]", new ToStringBuilder(base).append(3L).toString()); assertEquals(baseStr + "[a=3]", new ToStringBuilder(base).append("a", 3L).toString()); assertEquals(baseStr + "[a=3,b=4]", new ToStringBuilder(base).append("a", 3L).append("b", 4L).toString()); } public void testObjectArray() { Object[] array = new Object[] {null, base, new int[] {3, 6}}; assertEquals(baseStr + "[[%NULL%, 5, [3, 6]]]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[[%NULL%, 5, [3, 6]]]", new ToStringBuilder(base).append((Object) array).toString()); array = null; assertEquals(baseStr + "[%NULL%]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[%NULL%]", new ToStringBuilder(base).append((Object) array).toString()); } public void testLongArray() { long[] array = new long[] {1, 2, -3, 4}; assertEquals(baseStr + "[[1, 2, -3, 4]]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[[1, 2, -3, 4]]", new ToStringBuilder(base).append((Object) array).toString()); array = null; assertEquals(baseStr + "[%NULL%]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[%NULL%]", new ToStringBuilder(base).append((Object) array).toString()); } public void testLongArrayArray() { long[][] array = new long[][] {{1, 2}, null, {5}}; assertEquals(baseStr + "[[[1, 2], %NULL%, [5]]]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[[[1, 2], %NULL%, [5]]]", new ToStringBuilder(base).append((Object) array).toString()); array = null; assertEquals(baseStr + "[%NULL%]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[%NULL%]", new ToStringBuilder(base).append((Object) array).toString()); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/builder/ToStringBuilderTest.java100644 0 0 133223 11513702436 27241 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.builder; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import junit.framework.TestCase; /** * Unit tests for {@link org.apache.commons.lang.builder.ToStringBuilder}. * * @author Apache Software Foundation * @author Gary Gregory * @author Alex Chaffee * @version $Id: ToStringBuilderTest.java 1057966 2011-01-12 01:04:55Z niallp $ */ public class ToStringBuilderTest extends TestCase { private final Integer base = new Integer(5); private final String baseStr = base.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(base)); public ToStringBuilderTest(String name) { super(name); } //----------------------------------------------------------------------- public void testConstructorEx1() { assertEquals("", new ToStringBuilder(null).toString()); } public void testConstructorEx2() { assertEquals("", new ToStringBuilder(null, null).toString()); new ToStringBuilder(this.base, null).toString(); } public void testConstructorEx3() { assertEquals("", new ToStringBuilder(null, null, null).toString()); new ToStringBuilder(this.base, null, null); new ToStringBuilder(this.base, ToStringStyle.DEFAULT_STYLE, null); } public void testGetSetDefault() { try { ToStringBuilder.setDefaultStyle(ToStringStyle.NO_FIELD_NAMES_STYLE); assertSame(ToStringStyle.NO_FIELD_NAMES_STYLE, ToStringBuilder.getDefaultStyle()); } finally { // reset for other tests ToStringBuilder.setDefaultStyle(ToStringStyle.DEFAULT_STYLE); } } public void testSetDefaultEx() { try { ToStringBuilder.setDefaultStyle(null); } catch (IllegalArgumentException ex) { return; } fail(); } public void testBlank() { assertEquals(baseStr + "[]", new ToStringBuilder(base).toString()); } /** * Test wrapper for int primitive. */ public void testReflectionInteger() { assertEquals(baseStr + "[value=5]", ToStringBuilder.reflectionToString(base)); } /** * Test wrapper for char primitive. */ public void testReflectionCharacter() { Character c = new Character('A'); assertEquals(this.toBaseString(c) + "[value=A]", ToStringBuilder.reflectionToString(c)); } /** * Test wrapper for char boolean. */ public void testReflectionBoolean() { Boolean b; b = Boolean.TRUE; assertEquals(this.toBaseString(b) + "[value=true]", ToStringBuilder.reflectionToString(b)); b = Boolean.FALSE; assertEquals(this.toBaseString(b) + "[value=false]", ToStringBuilder.reflectionToString(b)); } /** * Create the same toString() as Object.toString(). * @param o the object to create the string for. * @return a String in the Object.toString format. */ private String toBaseString(Object o) { return o.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(o)); } // Reflection Array tests // // Note on the following line of code repeated in the reflection array tests. // // assertReflectionArray("", array); // // The expected value is not baseStr + "[]" since array==null and is typed as Object. // The null array does not carry array type information. // If we added a primitive array type constructor and pile of associated methods, // then type declaring type information could be carried forward. IMHO, null is null. // // Gary Gregory - 2003-03-12 - ggregory@seagullsw.com // public void assertReflectionArray(String expected, Object actual) { if (actual == null) { // Until ToStringBuilder supports null objects. return; } assertEquals(expected, ToStringBuilder.reflectionToString(actual)); assertEquals(expected, ToStringBuilder.reflectionToString(actual, null)); assertEquals(expected, ToStringBuilder.reflectionToString(actual, null, true)); assertEquals(expected, ToStringBuilder.reflectionToString(actual, null, false)); } public void testReflectionObjectArray() { Object[] array = new Object[] { null, base, new int[] { 3, 6 } }; String baseStr = this.toBaseString(array); assertEquals(baseStr + "[{,5,{3,6}}]", ToStringBuilder.reflectionToString(array)); array = null; assertReflectionArray("", array); this.validateNullToStringStyleRegistry(); } public void testReflectionLongArray() { long[] array = new long[] { 1, 2, -3, 4 }; String baseStr = this.toBaseString(array); assertEquals(baseStr + "[{1,2,-3,4}]", ToStringBuilder.reflectionToString(array)); array = null; assertReflectionArray("", array); this.validateNullToStringStyleRegistry(); } public void testReflectionIntArray() { int[] array = new int[] { 1, 2, -3, 4 }; String baseStr = this.toBaseString(array); assertEquals(baseStr + "[{1,2,-3,4}]", ToStringBuilder.reflectionToString(array)); array = null; assertReflectionArray("", array); this.validateNullToStringStyleRegistry(); } public void testReflectionShortArray() { short[] array = new short[] { 1, 2, -3, 4 }; String baseStr = this.toBaseString(array); assertEquals(baseStr + "[{1,2,-3,4}]", ToStringBuilder.reflectionToString(array)); array = null; assertReflectionArray("", array); this.validateNullToStringStyleRegistry(); } public void testReflectionyteArray() { byte[] array = new byte[] { 1, 2, -3, 4 }; String baseStr = this.toBaseString(array); assertEquals(baseStr + "[{1,2,-3,4}]", ToStringBuilder.reflectionToString(array)); array = null; assertReflectionArray("", array); this.validateNullToStringStyleRegistry(); } public void testReflectionCharArray() { char[] array = new char[] { 'A', '2', '_', 'D' }; String baseStr = this.toBaseString(array); assertEquals(baseStr + "[{A,2,_,D}]", ToStringBuilder.reflectionToString(array)); array = null; assertReflectionArray("", array); this.validateNullToStringStyleRegistry(); } public void testReflectionDoubleArray() { double[] array = new double[] { 1.0, 2.9876, -3.00001, 4.3 }; String baseStr = this.toBaseString(array); assertEquals(baseStr + "[{1.0,2.9876,-3.00001,4.3}]", ToStringBuilder.reflectionToString(array)); array = null; assertReflectionArray("", array); this.validateNullToStringStyleRegistry(); } public void testReflectionFloatArray() { float[] array = new float[] { 1.0f, 2.9876f, -3.00001f, 4.3f }; String baseStr = this.toBaseString(array); assertEquals(baseStr + "[{1.0,2.9876,-3.00001,4.3}]", ToStringBuilder.reflectionToString(array)); array = null; assertReflectionArray("", array); this.validateNullToStringStyleRegistry(); } public void testReflectionBooleanArray() { boolean[] array = new boolean[] { true, false, false }; String baseStr = this.toBaseString(array); assertEquals(baseStr + "[{true,false,false}]", ToStringBuilder.reflectionToString(array)); array = null; assertReflectionArray("", array); this.validateNullToStringStyleRegistry(); } // Reflection Array Array tests public void testReflectionFloatArrayArray() { float[][] array = new float[][] { { 1.0f, 2.29686f }, null, { Float.NaN } }; String baseStr = this.toBaseString(array); assertEquals(baseStr + "[{{1.0,2.29686},,{NaN}}]", ToStringBuilder.reflectionToString(array)); array = null; assertReflectionArray("", array); this.validateNullToStringStyleRegistry(); } public void testReflectionLongArrayArray() { long[][] array = new long[][] { { 1, 2 }, null, { 5 } }; String baseStr = this.toBaseString(array); assertEquals(baseStr + "[{{1,2},,{5}}]", ToStringBuilder.reflectionToString(array)); array = null; assertReflectionArray("", array); this.validateNullToStringStyleRegistry(); } public void testReflectionIntArrayArray() { int[][] array = new int[][] { { 1, 2 }, null, { 5 } }; String baseStr = this.toBaseString(array); assertEquals(baseStr + "[{{1,2},,{5}}]", ToStringBuilder.reflectionToString(array)); array = null; assertReflectionArray("", array); this.validateNullToStringStyleRegistry(); } public void testReflectionhortArrayArray() { short[][] array = new short[][] { { 1, 2 }, null, { 5 } }; String baseStr = this.toBaseString(array); assertEquals(baseStr + "[{{1,2},,{5}}]", ToStringBuilder.reflectionToString(array)); array = null; assertReflectionArray("", array); this.validateNullToStringStyleRegistry(); } public void testReflectionByteArrayArray() { byte[][] array = new byte[][] { { 1, 2 }, null, { 5 } }; String baseStr = this.toBaseString(array); assertEquals(baseStr + "[{{1,2},,{5}}]", ToStringBuilder.reflectionToString(array)); array = null; assertReflectionArray("", array); this.validateNullToStringStyleRegistry(); } public void testReflectionCharArrayArray() { char[][] array = new char[][] { { 'A', 'B' }, null, { 'p' } }; String baseStr = this.toBaseString(array); assertEquals(baseStr + "[{{A,B},,{p}}]", ToStringBuilder.reflectionToString(array)); array = null; assertReflectionArray("", array); this.validateNullToStringStyleRegistry(); } public void testReflectionDoubleArrayArray() { double[][] array = new double[][] { { 1.0, 2.29686 }, null, { Double.NaN } }; String baseStr = this.toBaseString(array); assertEquals(baseStr + "[{{1.0,2.29686},,{NaN}}]", ToStringBuilder.reflectionToString(array)); array = null; assertReflectionArray("", array); this.validateNullToStringStyleRegistry(); } public void testReflectionBooleanArrayArray() { boolean[][] array = new boolean[][] { { true, false }, null, { false } }; String baseStr = this.toBaseString(array); assertEquals(baseStr + "[{{true,false},,{false}}]", ToStringBuilder.reflectionToString(array)); assertEquals(baseStr + "[{{true,false},,{false}}]", ToStringBuilder.reflectionToString(array)); array = null; assertReflectionArray("", array); this.validateNullToStringStyleRegistry(); } // Reflection hierarchy tests /* Following Test removed because its dependant on the Java implementation * (currently passes using Sun/Oracle implementations, but fails for IBM's JDK 6) public void testReflectionHierarchyArrayList() { List base = new ArrayList(); String baseStr = this.toBaseString(base); assertEquals(baseStr + "[elementData={,,,,,,,,,},size=0,modCount=0]", ToStringBuilder.reflectionToString(base, null, true)); assertEquals(baseStr + "[size=0]", ToStringBuilder.reflectionToString(base, null, false)); this.validateNullToStringStyleRegistry(); } */ public void testReflectionHierarchy() { ReflectionTestFixtureA baseA = new ReflectionTestFixtureA(); String baseStr = this.toBaseString(baseA); assertEquals(baseStr + "[a=a]", ToStringBuilder.reflectionToString(baseA)); assertEquals(baseStr + "[a=a]", ToStringBuilder.reflectionToString(baseA, null)); assertEquals(baseStr + "[a=a]", ToStringBuilder.reflectionToString(baseA, null, false)); assertEquals(baseStr + "[a=a,transientA=t]", ToStringBuilder.reflectionToString(baseA, null, true)); assertEquals(baseStr + "[a=a]", ToStringBuilder.reflectionToString(baseA, null, false, null)); assertEquals(baseStr + "[a=a]", ToStringBuilder.reflectionToString(baseA, null, false, Object.class)); assertEquals(baseStr + "[a=a]", ToStringBuilder.reflectionToString(baseA, null, false, ReflectionTestFixtureA.class)); ReflectionTestFixtureB baseB = new ReflectionTestFixtureB(); baseStr = this.toBaseString(baseB); assertEquals(baseStr + "[b=b,a=a]", ToStringBuilder.reflectionToString(baseB)); assertEquals(baseStr + "[b=b,a=a]", ToStringBuilder.reflectionToString(baseB)); assertEquals(baseStr + "[b=b,a=a]", ToStringBuilder.reflectionToString(baseB, null)); assertEquals(baseStr + "[b=b,a=a]", ToStringBuilder.reflectionToString(baseB, null, false)); assertEquals(baseStr + "[b=b,transientB=t,a=a,transientA=t]", ToStringBuilder.reflectionToString(baseB, null, true)); assertEquals(baseStr + "[b=b,a=a]", ToStringBuilder.reflectionToString(baseB, null, false, null)); assertEquals(baseStr + "[b=b,a=a]", ToStringBuilder.reflectionToString(baseB, null, false, Object.class)); assertEquals(baseStr + "[b=b,a=a]", ToStringBuilder.reflectionToString(baseB, null, false, ReflectionTestFixtureA.class)); assertEquals(baseStr + "[b=b]", ToStringBuilder.reflectionToString(baseB, null, false, ReflectionTestFixtureB.class)); this.validateNullToStringStyleRegistry(); } static class ReflectionTestFixtureA { private char a='a'; private transient char transientA='t'; } static class ReflectionTestFixtureB extends ReflectionTestFixtureA { private char b='b'; private transient char transientB='t'; } public void testInnerClassReflection() { Outer outer = new Outer(); assertEquals(toBaseString(outer) + "[inner=" + toBaseString(outer.inner) + "[]]", outer.toString()); } static class Outer { Inner inner = new Inner(); class Inner { public String toString() { return ToStringBuilder.reflectionToString(this); } } public String toString() { return ToStringBuilder.reflectionToString(this); } } // Reflection cycle tests /** * Test an array element pointing to its container. */ public void testReflectionArrayCycle() throws Exception { Object[] objects = new Object[1]; objects[0] = objects; assertEquals( this.toBaseString(objects) + "[{" + this.toBaseString(objects) + "}]", ToStringBuilder.reflectionToString(objects)); this.validateNullToStringStyleRegistry(); } /** * Test an array element pointing to its container. */ public void testReflectionArrayCycleLevel2() throws Exception { Object[] objects = new Object[1]; Object[] objectsLevel2 = new Object[1]; objects[0] = objectsLevel2; objectsLevel2[0] = (Object) objects; assertEquals( this.toBaseString(objects) + "[{{" + this.toBaseString(objects) + "}}]", ToStringBuilder.reflectionToString(objects)); assertEquals( this.toBaseString(objectsLevel2) + "[{{" + this.toBaseString(objectsLevel2) + "}}]", ToStringBuilder.reflectionToString(objectsLevel2)); this.validateNullToStringStyleRegistry(); } public void testReflectionArrayArrayCycle() throws Exception { Object[][] objects = new Object[2][2]; objects[0][0] = objects; objects[0][1] = objects; objects[1][0] = objects; objects[1][1] = objects; String basicToString = this.toBaseString(objects); assertEquals( basicToString + "[{{" + basicToString + "," + basicToString + "},{" + basicToString + "," + basicToString + "}}]", ToStringBuilder.reflectionToString(objects)); this.validateNullToStringStyleRegistry(); } /** * A reflection test fixture. */ static class ReflectionTestCycleA { ReflectionTestCycleB b; public String toString() { return ToStringBuilder.reflectionToString(this); } } /** * A reflection test fixture. */ static class ReflectionTestCycleB { ReflectionTestCycleA a; public String toString() { return ToStringBuilder.reflectionToString(this); } } /** * A reflection test fixture. */ static class SimpleReflectionTestFixture { Object o; public SimpleReflectionTestFixture() { } public SimpleReflectionTestFixture(Object o) { this.o = o; } public String toString() { return ToStringBuilder.reflectionToString(this); } } private static class SelfInstanceVarReflectionTestFixture { private SelfInstanceVarReflectionTestFixture typeIsSelf; public SelfInstanceVarReflectionTestFixture() { this.typeIsSelf = this; } public String toString() { return ToStringBuilder.reflectionToString(this); } } private static class SelfInstanceTwoVarsReflectionTestFixture { private SelfInstanceTwoVarsReflectionTestFixture typeIsSelf; private String otherType = "The Other Type"; public SelfInstanceTwoVarsReflectionTestFixture() { this.typeIsSelf = this; } public String getOtherType(){ return this.otherType; } public String toString() { return ToStringBuilder.reflectionToString(this); } } /** * Test an Object pointing to itself, the simplest test. * * @throws Exception */ public void testSimpleReflectionObjectCycle() throws Exception { SimpleReflectionTestFixture simple = new SimpleReflectionTestFixture(); simple.o = simple; assertEquals(this.toBaseString(simple) + "[o=" + this.toBaseString(simple) + "]", simple.toString()); this.validateNullToStringStyleRegistry(); } /** * Test a class that defines an ivar pointing to itself. * * @throws Exception */ public void testSelfInstanceVarReflectionObjectCycle() throws Exception { SelfInstanceVarReflectionTestFixture test = new SelfInstanceVarReflectionTestFixture(); assertEquals(this.toBaseString(test) + "[typeIsSelf=" + this.toBaseString(test) + "]", test.toString()); this.validateNullToStringStyleRegistry(); } /** * Test a class that defines an ivar pointing to itself. This test was * created to show that handling cyclical object resulted in a missing endFieldSeparator call. * * @throws Exception */ public void testSelfInstanceTwoVarsReflectionObjectCycle() throws Exception { SelfInstanceTwoVarsReflectionTestFixture test = new SelfInstanceTwoVarsReflectionTestFixture(); assertEquals(this.toBaseString(test) + "[typeIsSelf=" + this.toBaseString(test) + ",otherType=" + test.getOtherType().toString() + "]", test.toString()); this.validateNullToStringStyleRegistry(); } /** * Test Objects pointing to each other. * * @throws Exception */ public void testReflectionObjectCycle() throws Exception { ReflectionTestCycleA a = new ReflectionTestCycleA(); ReflectionTestCycleB b = new ReflectionTestCycleB(); a.b = b; b.a = a; assertEquals( this.toBaseString(a) + "[b=" + this.toBaseString(b) + "[a=" + this.toBaseString(a) + "]]", a.toString()); this.validateNullToStringStyleRegistry(); } /** * Test a nasty combination of arrays and Objects pointing to each other. * objects[0] -> SimpleReflectionTestFixture[ o -> objects ] * * @throws Exception */ public void testReflectionArrayAndObjectCycle() throws Exception { Object[] objects = new Object[1]; SimpleReflectionTestFixture simple = new SimpleReflectionTestFixture(objects); objects[0] = (Object) simple; assertEquals( this.toBaseString(objects) + "[{" + this.toBaseString(simple) + "[o=" + this.toBaseString(objects) + "]" + "}]", ToStringBuilder.reflectionToString(objects)); assertEquals( this.toBaseString(simple) + "[o={" + this.toBaseString(simple) + "}]", ToStringBuilder.reflectionToString(simple)); this.validateNullToStringStyleRegistry(); } void validateNullToStringStyleRegistry() { if (ToStringStyle.getRegistry() != null) { System.out.println(ToStringStyle.getRegistry()); } assertNull(ToStringStyle.getRegistry()); } // End: Reflection cycle tests public void testAppendSuper() { assertEquals(baseStr + "[]", new ToStringBuilder(base).appendSuper("Integer@8888[]").toString()); assertEquals(baseStr + "[]", new ToStringBuilder(base).appendSuper("Integer@8888[]").toString()); assertEquals(baseStr + "[a=hello]", new ToStringBuilder(base).appendSuper("Integer@8888[]").append("a", "hello").toString()); assertEquals(baseStr + "[,a=hello]", new ToStringBuilder(base).appendSuper("Integer@8888[]").append("a", "hello").toString()); assertEquals(baseStr + "[a=hello]", new ToStringBuilder(base).appendSuper(null).append("a", "hello").toString()); } public void testAppendToString() { assertEquals(baseStr + "[]", new ToStringBuilder(base).appendToString("Integer@8888[]").toString()); assertEquals(baseStr + "[]", new ToStringBuilder(base).appendToString("Integer@8888[]").toString()); assertEquals(baseStr + "[a=hello]", new ToStringBuilder(base).appendToString("Integer@8888[]").append("a", "hello").toString()); assertEquals(baseStr + "[,a=hello]", new ToStringBuilder(base).appendToString("Integer@8888[]").append("a", "hello").toString()); assertEquals(baseStr + "[a=hello]", new ToStringBuilder(base).appendToString(null).append("a", "hello").toString()); } public void testObject() { Integer i3 = new Integer(3); Integer i4 = new Integer(4); assertEquals(baseStr + "[]", new ToStringBuilder(base).append((Object) null).toString()); assertEquals(baseStr + "[3]", new ToStringBuilder(base).append(i3).toString()); assertEquals(baseStr + "[a=]", new ToStringBuilder(base).append("a", (Object) null).toString()); assertEquals(baseStr + "[a=3]", new ToStringBuilder(base).append("a", i3).toString()); assertEquals(baseStr + "[a=3,b=4]", new ToStringBuilder(base).append("a", i3).append("b", i4).toString()); assertEquals(baseStr + "[a=]", new ToStringBuilder(base).append("a", i3, false).toString()); assertEquals(baseStr + "[a=]", new ToStringBuilder(base).append("a", new ArrayList(), false).toString()); assertEquals(baseStr + "[a=[]]", new ToStringBuilder(base).append("a", new ArrayList(), true).toString()); assertEquals(baseStr + "[a=]", new ToStringBuilder(base).append("a", new HashMap(), false).toString()); assertEquals(baseStr + "[a={}]", new ToStringBuilder(base).append("a", new HashMap(), true).toString()); assertEquals(baseStr + "[a=]", new ToStringBuilder(base).append("a", (Object) new String[0], false).toString()); assertEquals(baseStr + "[a={}]", new ToStringBuilder(base).append("a", (Object) new String[0], true).toString()); } public void testLong() { assertEquals(baseStr + "[3]", new ToStringBuilder(base).append(3L).toString()); assertEquals(baseStr + "[a=3]", new ToStringBuilder(base).append("a", 3L).toString()); assertEquals(baseStr + "[a=3,b=4]", new ToStringBuilder(base).append("a", 3L).append("b", 4L).toString()); } public void testInt() { assertEquals(baseStr + "[3]", new ToStringBuilder(base).append((int) 3).toString()); assertEquals(baseStr + "[a=3]", new ToStringBuilder(base).append("a", (int) 3).toString()); assertEquals(baseStr + "[a=3,b=4]", new ToStringBuilder(base).append("a", (int) 3).append("b", (int) 4).toString()); } public void testShort() { assertEquals(baseStr + "[3]", new ToStringBuilder(base).append((short) 3).toString()); assertEquals(baseStr + "[a=3]", new ToStringBuilder(base).append("a", (short) 3).toString()); assertEquals(baseStr + "[a=3,b=4]", new ToStringBuilder(base).append("a", (short) 3).append("b", (short) 4).toString()); } public void testChar() { assertEquals(baseStr + "[A]", new ToStringBuilder(base).append((char) 65).toString()); assertEquals(baseStr + "[a=A]", new ToStringBuilder(base).append("a", (char) 65).toString()); assertEquals(baseStr + "[a=A,b=B]", new ToStringBuilder(base).append("a", (char) 65).append("b", (char) 66).toString()); } public void testByte() { assertEquals(baseStr + "[3]", new ToStringBuilder(base).append((byte) 3).toString()); assertEquals(baseStr + "[a=3]", new ToStringBuilder(base).append("a", (byte) 3).toString()); assertEquals(baseStr + "[a=3,b=4]", new ToStringBuilder(base).append("a", (byte) 3).append("b", (byte) 4).toString()); } public void testDouble() { assertEquals(baseStr + "[3.2]", new ToStringBuilder(base).append((double) 3.2).toString()); assertEquals(baseStr + "[a=3.2]", new ToStringBuilder(base).append("a", (double) 3.2).toString()); assertEquals(baseStr + "[a=3.2,b=4.3]", new ToStringBuilder(base).append("a", (double) 3.2).append("b", (double) 4.3).toString()); } public void testFloat() { assertEquals(baseStr + "[3.2]", new ToStringBuilder(base).append((float) 3.2).toString()); assertEquals(baseStr + "[a=3.2]", new ToStringBuilder(base).append("a", (float) 3.2).toString()); assertEquals(baseStr + "[a=3.2,b=4.3]", new ToStringBuilder(base).append("a", (float) 3.2).append("b", (float) 4.3).toString()); } public void testBoolean() { assertEquals(baseStr + "[true]", new ToStringBuilder(base).append(true).toString()); assertEquals(baseStr + "[a=true]", new ToStringBuilder(base).append("a", true).toString()); assertEquals(baseStr + "[a=true,b=false]", new ToStringBuilder(base).append("a", true).append("b", false).toString()); } public void testObjectArray() { Object[] array = new Object[] {null, base, new int[] {3, 6}}; assertEquals(baseStr + "[{,5,{3,6}}]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[{,5,{3,6}}]", new ToStringBuilder(base).append((Object) array).toString()); array = null; assertEquals(baseStr + "[]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[]", new ToStringBuilder(base).append((Object) array).toString()); } public void testLongArray() { long[] array = new long[] {1, 2, -3, 4}; assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append((Object) array).toString()); array = null; assertEquals(baseStr + "[]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[]", new ToStringBuilder(base).append((Object) array).toString()); } public void testIntArray() { int[] array = new int[] {1, 2, -3, 4}; assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append((Object) array).toString()); array = null; assertEquals(baseStr + "[]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[]", new ToStringBuilder(base).append((Object) array).toString()); } public void testShortArray() { short[] array = new short[] {1, 2, -3, 4}; assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append((Object) array).toString()); array = null; assertEquals(baseStr + "[]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[]", new ToStringBuilder(base).append((Object) array).toString()); } public void testByteArray() { byte[] array = new byte[] {1, 2, -3, 4}; assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append((Object) array).toString()); array = null; assertEquals(baseStr + "[]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[]", new ToStringBuilder(base).append((Object) array).toString()); } public void testCharArray() { char[] array = new char[] {'A', '2', '_', 'D'}; assertEquals(baseStr + "[{A,2,_,D}]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[{A,2,_,D}]", new ToStringBuilder(base).append((Object) array).toString()); array = null; assertEquals(baseStr + "[]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[]", new ToStringBuilder(base).append((Object) array).toString()); } public void testDoubleArray() { double[] array = new double[] {1.0, 2.9876, -3.00001, 4.3}; assertEquals(baseStr + "[{1.0,2.9876,-3.00001,4.3}]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[{1.0,2.9876,-3.00001,4.3}]", new ToStringBuilder(base).append((Object) array).toString()); array = null; assertEquals(baseStr + "[]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[]", new ToStringBuilder(base).append((Object) array).toString()); } public void testFloatArray() { float[] array = new float[] {1.0f, 2.9876f, -3.00001f, 4.3f}; assertEquals(baseStr + "[{1.0,2.9876,-3.00001,4.3}]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[{1.0,2.9876,-3.00001,4.3}]", new ToStringBuilder(base).append((Object) array).toString()); array = null; assertEquals(baseStr + "[]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[]", new ToStringBuilder(base).append((Object) array).toString()); } public void testBooleanArray() { boolean[] array = new boolean[] {true, false, false}; assertEquals(baseStr + "[{true,false,false}]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[{true,false,false}]", new ToStringBuilder(base).append((Object) array).toString()); array = null; assertEquals(baseStr + "[]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[]", new ToStringBuilder(base).append((Object) array).toString()); } public void testLongArrayArray() { long[][] array = new long[][] {{1, 2}, null, {5}}; assertEquals(baseStr + "[{{1,2},,{5}}]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[{{1,2},,{5}}]", new ToStringBuilder(base).append((Object) array).toString()); array = null; assertEquals(baseStr + "[]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[]", new ToStringBuilder(base).append((Object) array).toString()); } public void testIntArrayArray() { int[][] array = new int[][] {{1, 2}, null, {5}}; assertEquals(baseStr + "[{{1,2},,{5}}]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[{{1,2},,{5}}]", new ToStringBuilder(base).append((Object) array).toString()); array = null; assertEquals(baseStr + "[]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[]", new ToStringBuilder(base).append((Object) array).toString()); } public void testShortArrayArray() { short[][] array = new short[][] {{1, 2}, null, {5}}; assertEquals(baseStr + "[{{1,2},,{5}}]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[{{1,2},,{5}}]", new ToStringBuilder(base).append((Object) array).toString()); array = null; assertEquals(baseStr + "[]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[]", new ToStringBuilder(base).append((Object) array).toString()); } public void testByteArrayArray() { byte[][] array = new byte[][] {{1, 2}, null, {5}}; assertEquals(baseStr + "[{{1,2},,{5}}]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[{{1,2},,{5}}]", new ToStringBuilder(base).append((Object) array).toString()); array = null; assertEquals(baseStr + "[]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[]", new ToStringBuilder(base).append((Object) array).toString()); } public void testCharArrayArray() { char[][] array = new char[][] {{'A', 'B'}, null, {'p'}}; assertEquals(baseStr + "[{{A,B},,{p}}]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[{{A,B},,{p}}]", new ToStringBuilder(base).append((Object) array).toString()); array = null; assertEquals(baseStr + "[]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[]", new ToStringBuilder(base).append((Object) array).toString()); } public void testDoubleArrayArray() { double[][] array = new double[][] {{1.0, 2.29686}, null, {Double.NaN}}; assertEquals(baseStr + "[{{1.0,2.29686},,{NaN}}]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[{{1.0,2.29686},,{NaN}}]", new ToStringBuilder(base).append((Object) array).toString()); array = null; assertEquals(baseStr + "[]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[]", new ToStringBuilder(base).append((Object) array).toString()); } public void testFloatArrayArray() { float[][] array = new float[][] {{1.0f, 2.29686f}, null, {Float.NaN}}; assertEquals(baseStr + "[{{1.0,2.29686},,{NaN}}]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[{{1.0,2.29686},,{NaN}}]", new ToStringBuilder(base).append((Object) array).toString()); array = null; assertEquals(baseStr + "[]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[]", new ToStringBuilder(base).append((Object) array).toString()); } public void testBooleanArrayArray() { boolean[][] array = new boolean[][] {{true, false}, null, {false}}; assertEquals(baseStr + "[{{true,false},,{false}}]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[{{true,false},,{false}}]", new ToStringBuilder(base).append((Object) array).toString()); array = null; assertEquals(baseStr + "[]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[]", new ToStringBuilder(base).append((Object) array).toString()); } public void testObjectCycle() { ObjectCycle a = new ObjectCycle(); ObjectCycle b = new ObjectCycle(); a.obj = b; b.obj = a; String expected = toBaseString(a) + "[" + toBaseString(b) + "[" + toBaseString(a) + "]]"; assertEquals(expected, a.toString()); validateNullToStringStyleRegistry(); } static class ObjectCycle { Object obj; public String toString() { return new ToStringBuilder(this).append(obj).toString(); } } public void testSimpleReflectionStatics() { SimpleReflectionStaticFieldsFixture instance1 = new SimpleReflectionStaticFieldsFixture(); assertEquals( this.toBaseString(instance1) + "[staticString=staticString,staticInt=12345]", ReflectionToStringBuilder.toString(instance1, null, false, true, SimpleReflectionStaticFieldsFixture.class)); assertEquals( this.toBaseString(instance1) + "[staticString=staticString,staticInt=12345]", ReflectionToStringBuilder.toString(instance1, null, true, true, SimpleReflectionStaticFieldsFixture.class)); assertEquals( this.toBaseString(instance1) + "[staticString=staticString,staticInt=12345]", this.toStringWithStatics(instance1, null, SimpleReflectionStaticFieldsFixture.class)); assertEquals( this.toBaseString(instance1) + "[staticString=staticString,staticInt=12345]", this.toStringWithStatics(instance1, null, SimpleReflectionStaticFieldsFixture.class)); } /** * Tests ReflectionToStringBuilder.toString() for statics. */ public void testReflectionStatics() { ReflectionStaticFieldsFixture instance1 = new ReflectionStaticFieldsFixture(); assertEquals( this.toBaseString(instance1) + "[staticString=staticString,staticInt=12345,instanceString=instanceString,instanceInt=67890]", ReflectionToStringBuilder.toString(instance1, null, false, true, ReflectionStaticFieldsFixture.class)); assertEquals( this.toBaseString(instance1) + "[staticString=staticString,staticInt=12345,staticTransientString=staticTransientString,staticTransientInt=54321,instanceString=instanceString,instanceInt=67890,transientString=transientString,transientInt=98765]", ReflectionToStringBuilder.toString(instance1, null, true, true, ReflectionStaticFieldsFixture.class)); assertEquals( this.toBaseString(instance1) + "[staticString=staticString,staticInt=12345,instanceString=instanceString,instanceInt=67890]", this.toStringWithStatics(instance1, null, ReflectionStaticFieldsFixture.class)); assertEquals( this.toBaseString(instance1) + "[staticString=staticString,staticInt=12345,instanceString=instanceString,instanceInt=67890]", this.toStringWithStatics(instance1, null, ReflectionStaticFieldsFixture.class)); } /** * Tests ReflectionToStringBuilder.toString() for statics. */ public void testInheritedReflectionStatics() { InheritedReflectionStaticFieldsFixture instance1 = new InheritedReflectionStaticFieldsFixture(); assertEquals( this.toBaseString(instance1) + "[staticString2=staticString2,staticInt2=67890]", ReflectionToStringBuilder.toString(instance1, null, false, true, InheritedReflectionStaticFieldsFixture.class)); assertEquals( this.toBaseString(instance1) + "[staticString2=staticString2,staticInt2=67890,staticString=staticString,staticInt=12345]", ReflectionToStringBuilder.toString(instance1, null, false, true, SimpleReflectionStaticFieldsFixture.class)); assertEquals( this.toBaseString(instance1) + "[staticString2=staticString2,staticInt2=67890,staticString=staticString,staticInt=12345]", this.toStringWithStatics(instance1, null, SimpleReflectionStaticFieldsFixture.class)); assertEquals( this.toBaseString(instance1) + "[staticString2=staticString2,staticInt2=67890,staticString=staticString,staticInt=12345]", this.toStringWithStatics(instance1, null, SimpleReflectionStaticFieldsFixture.class)); } /** *

    This method uses reflection to build a suitable * toString value which includes static fields.

    * *

    It uses AccessibleObject.setAccessible to gain access to private * fields. This means that it will throw a security exception if run * under a security manager, if the permissions are not set up correctly. * It is also not as efficient as testing explicitly.

    * *

    Transient fields are not output.

    * *

    Superclass fields will be appended up to and including the specified superclass. * A null superclass is treated as java.lang.Object.

    * *

    If the style is null, the default * ToStringStyle is used.

    * * @param object the Object to be output * @param style the style of the toString to create, * may be null * @param reflectUpToClass the superclass to reflect up to (inclusive), * may be null * @return the String result * @throws IllegalArgumentException if the Object is null */ public Object toStringWithStatics(Object object, ToStringStyle style, Class reflectUpToClass) { return ReflectionToStringBuilder.toString(object, style, false, true, reflectUpToClass); } /** * Tests ReflectionToStringBuilder setUpToClass(). */ public void test_setUpToClass_valid() { Integer val = new Integer(5); ReflectionToStringBuilder test = new ReflectionToStringBuilder(val); test.setUpToClass(Number.class); } /** * Tests ReflectionToStringBuilder setUpToClass(). */ public void test_setUpToClass_invalid() { Integer val = new Integer(5); ReflectionToStringBuilder test = new ReflectionToStringBuilder(val); try { test.setUpToClass(String.class); fail(); } catch (IllegalArgumentException ex) { // expected } } /** * Tests ReflectionToStringBuilder.toString() for statics. */ class ReflectionStaticFieldsFixture { static final String staticString = "staticString"; static final int staticInt = 12345; static final transient String staticTransientString = "staticTransientString"; static final transient int staticTransientInt = 54321; String instanceString = "instanceString"; int instanceInt = 67890; transient String transientString = "transientString"; transient int transientInt = 98765; } /** * Test fixture for ReflectionToStringBuilder.toString() for statics. */ class SimpleReflectionStaticFieldsFixture { static final String staticString = "staticString"; static final int staticInt = 12345; } /** * Test fixture for ReflectionToStringBuilder.toString() for statics. */ class InheritedReflectionStaticFieldsFixture extends SimpleReflectionStaticFieldsFixture { static final String staticString2 = "staticString2"; static final int staticInt2 = 67890; } public void testReflectionNull() { assertEquals("", ReflectionToStringBuilder.toString(null)); } /** * Points out failure to print anything from appendToString methods using MULTI_LINE_STYLE. * See issue LANG-372. */ class MultiLineTestObject { Integer i = new Integer(31337); public String toString() { return new ToStringBuilder(this).append("testInt", i).toString(); } } public void testAppendToStringUsingMultiLineStyle() { MultiLineTestObject obj = new MultiLineTestObject(); ToStringBuilder testBuilder = new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE) .appendToString(obj.toString()); assertEquals(testBuilder.toString().indexOf("testInt=31337"), -1); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/builder/ToStringStyleTest.java100644 0 0 10056 11513702437 26732 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.builder; import junit.framework.TestCase; /** * Test case for ToStringStyle. * * @author Masato Tezuka * @version $Id: ToStringStyleTest.java 905628 2010-02-02 13:29:55Z niallp $ */ public class ToStringStyleTest extends TestCase { public ToStringStyleTest(String name) { super(name); } private static class ToStringStyleImpl extends ToStringStyle { } //----------------------------------------------------------------------- public void testSetArrayStart() { ToStringStyle style = new ToStringStyleImpl(); style.setArrayStart(null); assertEquals("", style.getArrayStart()); } public void testSetArrayEnd() { ToStringStyle style = new ToStringStyleImpl(); style.setArrayEnd(null); assertEquals("", style.getArrayEnd()); } public void testSetArraySeparator() { ToStringStyle style = new ToStringStyleImpl(); style.setArraySeparator(null); assertEquals("", style.getArraySeparator()); } public void testSetContentStart() { ToStringStyle style = new ToStringStyleImpl(); style.setContentStart(null); assertEquals("", style.getContentStart()); } public void testSetContentEnd() { ToStringStyle style = new ToStringStyleImpl(); style.setContentEnd(null); assertEquals("", style.getContentEnd()); } public void testSetFieldNameValueSeparator() { ToStringStyle style = new ToStringStyleImpl(); style.setFieldNameValueSeparator(null); assertEquals("", style.getFieldNameValueSeparator()); } public void testSetFieldSeparator() { ToStringStyle style = new ToStringStyleImpl(); style.setFieldSeparator(null); assertEquals("", style.getFieldSeparator()); } public void testSetNullText() { ToStringStyle style = new ToStringStyleImpl(); style.setNullText(null); assertEquals("", style.getNullText()); } public void testSetSizeStartText() { ToStringStyle style = new ToStringStyleImpl(); style.setSizeStartText(null); assertEquals("", style.getSizeStartText()); } public void testSetSizeEndText() { ToStringStyle style = new ToStringStyleImpl(); style.setSizeEndText(null); assertEquals("", style.getSizeEndText()); } public void testSetSummaryObjectStartText() { ToStringStyle style = new ToStringStyleImpl(); style.setSummaryObjectStartText(null); assertEquals("", style.getSummaryObjectStartText()); } public void testSetSummaryObjectEndText() { ToStringStyle style = new ToStringStyleImpl(); style.setSummaryObjectEndText(null); assertEquals("", style.getSummaryObjectEndText()); } /** * An object used to test {@link ToStringStyle}. * * @author Scott Bassin */ static class Person { /** * Test String field. */ String name; /** * Test integer field. */ int age; /** * Test boolean field. */ boolean smoker; } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/CharEncodingTest.java100644 0 0 7252 11513702440 25014 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang; import junit.framework.TestCase; /** * Tests CharEncoding. * * @see CharEncoding * @author Gary D. Gregory * @version $Id: CharEncodingTest.java 905628 2010-02-02 13:29:55Z niallp $ */ public class CharEncodingTest extends TestCase { private void assertSupportedEncoding(String name) { assertTrue("Encoding should be supported: " + name, CharEncoding.isSupported(name)); } /** * The class can be instantiated. */ public void testConstructor() { new CharEncoding(); } public void testMustBeSupportedJava1_3_1() { if (SystemUtils.isJavaVersionAtLeast(1.3f)) { this.assertSupportedEncoding(CharEncoding.ISO_8859_1); this.assertSupportedEncoding(CharEncoding.US_ASCII); this.assertSupportedEncoding(CharEncoding.UTF_16); this.assertSupportedEncoding(CharEncoding.UTF_16BE); this.assertSupportedEncoding(CharEncoding.UTF_16LE); this.assertSupportedEncoding(CharEncoding.UTF_8); } else { this.warn("Java 1.3 tests not run since the current version is " + SystemUtils.JAVA_VERSION); } } public void testNotSupported() { assertFalse(CharEncoding.isSupported(null)); assertFalse(CharEncoding.isSupported("")); assertFalse(CharEncoding.isSupported(" ")); assertFalse(CharEncoding.isSupported("\t\r\n")); assertFalse(CharEncoding.isSupported("DOESNOTEXIST")); assertFalse(CharEncoding.isSupported("this is not a valid encoding name")); } public void testWorksOnJava1_1_8() { // // In this test, I simply deleted the encodings from the 1.3.1 list. // The Javadoc do not specify which encodings are required. // if (SystemUtils.isJavaVersionAtLeast(1.1f)) { this.assertSupportedEncoding(CharEncoding.ISO_8859_1); this.assertSupportedEncoding(CharEncoding.US_ASCII); this.assertSupportedEncoding(CharEncoding.UTF_8); } else { this.warn("Java 1.1 tests not run since the current version is " + SystemUtils.JAVA_VERSION); } } public void testWorksOnJava1_2_2() { // // In this test, I simply deleted the encodings from the 1.3.1 list. // The Javadoc do not specify which encodings are required. // if (SystemUtils.isJavaVersionAtLeast(1.2f)) { this.assertSupportedEncoding(CharEncoding.ISO_8859_1); this.assertSupportedEncoding(CharEncoding.US_ASCII); this.assertSupportedEncoding(CharEncoding.UTF_8); } else { this.warn("Java 1.2 tests not run since the current version is " + SystemUtils.JAVA_VERSION); } } void warn(String msg) { System.err.println(msg); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/CharRangeTest.java100644 0 0 47312 11513702440 24343 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "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 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.commons.lang; import java.lang.reflect.Modifier; import java.util.Iterator; import java.util.NoSuchElementException; import junit.framework.TestCase; /** * Unit tests {@link org.apache.commons.lang.CharRange}. * * @author Apache Software Foundation * @version $Id: CharRangeTest.java 906758 2010-02-05 01:23:22Z sebb $ */ public class CharRangeTest extends TestCase { public CharRangeTest(String name) { super(name); } //----------------------------------------------------------------------- public void testClass() { assertEquals(true, Modifier.isPublic(CharRange.class.getModifiers())); assertEquals(true, Modifier.isFinal(CharRange.class.getModifiers())); } //----------------------------------------------------------------------- public void testConstructorAccessors_is() { CharRange rangea = CharRange.is('a'); assertEquals('a', rangea.getStart()); assertEquals('a', rangea.getEnd()); assertEquals(false, rangea.isNegated()); assertEquals("a", rangea.toString()); } public void testConstructorAccessors_isNot() { CharRange rangea = CharRange.isNot('a'); assertEquals('a', rangea.getStart()); assertEquals('a', rangea.getEnd()); assertEquals(true, rangea.isNegated()); assertEquals("^a", rangea.toString()); } public void testConstructorAccessors_isIn_Same() { CharRange rangea = CharRange.isIn('a', 'a'); assertEquals('a', rangea.getStart()); assertEquals('a', rangea.getEnd()); assertEquals(false, rangea.isNegated()); assertEquals("a", rangea.toString()); } public void testConstructorAccessors_isIn_Normal() { CharRange rangea = CharRange.isIn('a', 'e'); assertEquals('a', rangea.getStart()); assertEquals('e', rangea.getEnd()); assertEquals(false, rangea.isNegated()); assertEquals("a-e", rangea.toString()); } public void testConstructorAccessors_isIn_Reversed() { CharRange rangea = CharRange.isIn('e', 'a'); assertEquals('a', rangea.getStart()); assertEquals('e', rangea.getEnd()); assertEquals(false, rangea.isNegated()); assertEquals("a-e", rangea.toString()); } public void testConstructorAccessors_isNotIn_Same() { CharRange rangea = CharRange.isNotIn('a', 'a'); assertEquals('a', rangea.getStart()); assertEquals('a', rangea.getEnd()); assertEquals(true, rangea.isNegated()); assertEquals("^a", rangea.toString()); } public void testConstructorAccessors_isNotIn_Normal() { CharRange rangea = CharRange.isNotIn('a', 'e'); assertEquals('a', rangea.getStart()); assertEquals('e', rangea.getEnd()); assertEquals(true, rangea.isNegated()); assertEquals("^a-e", rangea.toString()); } public void testConstructorAccessors_isNotIn_Reversed() { CharRange rangea = CharRange.isNotIn('e', 'a'); assertEquals('a', rangea.getStart()); assertEquals('e', rangea.getEnd()); assertEquals(true, rangea.isNegated()); assertEquals("^a-e", rangea.toString()); } //----------------------------------------------------------------------- public void testConstructorAccessors_Char() { CharRange rangea = new CharRange('a'); assertEquals('a', rangea.getStart()); assertEquals('a', rangea.getEnd()); assertEquals(false, rangea.isNegated()); assertEquals("a", rangea.toString()); } public void testConstructorAccessors_CharBoolean_Normal() { CharRange rangea = new CharRange('a'); assertEquals('a', rangea.getStart()); assertEquals('a', rangea.getEnd()); assertEquals(false, rangea.isNegated()); assertEquals("a", rangea.toString()); } public void testConstructorAccessors_CharBoolean_Negated() { CharRange rangea = new CharRange('a', true); assertEquals('a', rangea.getStart()); assertEquals('a', rangea.getEnd()); assertEquals(true, rangea.isNegated()); assertEquals("^a", rangea.toString()); } public void testConstructorAccessors_CharChar_Same() { CharRange rangea = new CharRange('a', 'a'); assertEquals('a', rangea.getStart()); assertEquals('a', rangea.getEnd()); assertEquals(false, rangea.isNegated()); assertEquals("a", rangea.toString()); } public void testConstructorAccessors_CharChar_Normal() { CharRange rangea = new CharRange('a', 'e'); assertEquals('a', rangea.getStart()); assertEquals('e', rangea.getEnd()); assertEquals(false, rangea.isNegated()); assertEquals("a-e", rangea.toString()); } public void testConstructorAccessors_CharChar_Reversed() { CharRange rangea = new CharRange('e', 'a'); assertEquals('a', rangea.getStart()); assertEquals('e', rangea.getEnd()); assertEquals(false, rangea.isNegated()); assertEquals("a-e", rangea.toString()); } public void testConstructorAccessors_CharCharBoolean_Same() { CharRange rangea = new CharRange('a', 'a', false); assertEquals('a', rangea.getStart()); assertEquals('a', rangea.getEnd()); assertEquals(false, rangea.isNegated()); assertEquals("a", rangea.toString()); } public void testConstructorAccessors_CharCharBoolean_Normal() { CharRange rangea = new CharRange('a', 'e', false); assertEquals('a', rangea.getStart()); assertEquals('e', rangea.getEnd()); assertEquals(false, rangea.isNegated()); assertEquals("a-e", rangea.toString()); } public void testConstructorAccessors_CharCharBoolean_Reversed() { CharRange rangea = new CharRange('e', 'a', false); assertEquals('a', rangea.getStart()); assertEquals('e', rangea.getEnd()); assertEquals(false, rangea.isNegated()); assertEquals("a-e", rangea.toString()); } public void testConstructorAccessors_CharCharBoolean_SameNegated() { CharRange rangea = new CharRange('a', 'a', true); assertEquals('a', rangea.getStart()); assertEquals('a', rangea.getEnd()); assertEquals(true, rangea.isNegated()); assertEquals("^a", rangea.toString()); } public void testConstructorAccessors_CharCharBoolean_NormalNegated() { CharRange rangea = new CharRange('a', 'e', true); assertEquals('a', rangea.getStart()); assertEquals('e', rangea.getEnd()); assertEquals(true, rangea.isNegated()); assertEquals("^a-e", rangea.toString()); } public void testConstructorAccessors_CharCharBoolean_ReversedNegated() { CharRange rangea = new CharRange('e', 'a', true); assertEquals('a', rangea.getStart()); assertEquals('e', rangea.getEnd()); assertEquals(true, rangea.isNegated()); assertEquals("^a-e", rangea.toString()); } //----------------------------------------------------------------------- public void testEquals_Object() { CharRange rangea = CharRange.is('a'); CharRange rangeae = CharRange.isIn('a', 'e'); CharRange rangenotbf = CharRange.isIn('b', 'f'); assertEquals(false, rangea.equals(null)); assertEquals(true, rangea.equals(rangea)); assertEquals(true, rangea.equals(CharRange.is('a'))); assertEquals(true, rangeae.equals(rangeae)); assertEquals(true, rangeae.equals(CharRange.isIn('a', 'e'))); assertEquals(true, rangenotbf.equals(rangenotbf)); assertEquals(true, rangenotbf.equals(CharRange.isIn('b', 'f'))); assertEquals(false, rangea.equals(rangeae)); assertEquals(false, rangea.equals(rangenotbf)); assertEquals(false, rangeae.equals(rangea)); assertEquals(false, rangeae.equals(rangenotbf)); assertEquals(false, rangenotbf.equals(rangea)); assertEquals(false, rangenotbf.equals(rangeae)); } public void testHashCode() { CharRange rangea = CharRange.is('a'); CharRange rangeae = CharRange.isIn('a', 'e'); CharRange rangenotbf = CharRange.isIn('b', 'f'); assertEquals(true, rangea.hashCode() == rangea.hashCode()); assertEquals(true, rangea.hashCode() == CharRange.is('a').hashCode()); assertEquals(true, rangeae.hashCode() == rangeae.hashCode()); assertEquals(true, rangeae.hashCode() == CharRange.isIn('a', 'e').hashCode()); assertEquals(true, rangenotbf.hashCode() == rangenotbf.hashCode()); assertEquals(true, rangenotbf.hashCode() == CharRange.isIn('b', 'f').hashCode()); assertEquals(false, rangea.hashCode() == rangeae.hashCode()); assertEquals(false, rangea.hashCode() == rangenotbf.hashCode()); assertEquals(false, rangeae.hashCode() == rangea.hashCode()); assertEquals(false, rangeae.hashCode() == rangenotbf.hashCode()); assertEquals(false, rangenotbf.hashCode() == rangea.hashCode()); assertEquals(false, rangenotbf.hashCode() == rangeae.hashCode()); } //----------------------------------------------------------------------- public void testContains_Char() { CharRange range = CharRange.is('c'); assertEquals(false, range.contains('b')); assertEquals(true, range.contains('c')); assertEquals(false, range.contains('d')); assertEquals(false, range.contains('e')); range = CharRange.isIn('c', 'd'); assertEquals(false, range.contains('b')); assertEquals(true, range.contains('c')); assertEquals(true, range.contains('d')); assertEquals(false, range.contains('e')); range = CharRange.isIn('d', 'c'); assertEquals(false, range.contains('b')); assertEquals(true, range.contains('c')); assertEquals(true, range.contains('d')); assertEquals(false, range.contains('e')); range = CharRange.isIn('c', 'd'); assertEquals(false, range.contains('b')); assertEquals(true, range.contains('c')); assertEquals(true, range.contains('d')); assertEquals(false, range.contains('e')); range = CharRange.isNotIn('c', 'd'); assertEquals(true, range.contains('b')); assertEquals(false, range.contains('c')); assertEquals(false, range.contains('d')); assertEquals(true, range.contains('e')); assertEquals(true, range.contains((char) 0)); assertEquals(true, range.contains(Character.MAX_VALUE)); } //----------------------------------------------------------------------- public void testContains_Charrange() { CharRange a = CharRange.is('a'); CharRange b = CharRange.is('b'); CharRange c = CharRange.is('c'); CharRange c2 = CharRange.is('c'); CharRange d = CharRange.is('d'); CharRange e = CharRange.is('e'); CharRange cd = CharRange.isIn('c', 'd'); CharRange bd = CharRange.isIn('b', 'd'); CharRange bc = CharRange.isIn('b', 'c'); CharRange ab = CharRange.isIn('a', 'b'); CharRange de = CharRange.isIn('d', 'e'); CharRange ef = CharRange.isIn('e', 'f'); CharRange ae = CharRange.isIn('a', 'e'); // normal/normal assertEquals(false, c.contains(b)); assertEquals(true, c.contains(c)); assertEquals(true, c.contains(c2)); assertEquals(false, c.contains(d)); assertEquals(false, c.contains(cd)); assertEquals(false, c.contains(bd)); assertEquals(false, c.contains(bc)); assertEquals(false, c.contains(ab)); assertEquals(false, c.contains(de)); assertEquals(true, cd.contains(c)); assertEquals(true, bd.contains(c)); assertEquals(true, bc.contains(c)); assertEquals(false, ab.contains(c)); assertEquals(false, de.contains(c)); assertEquals(true, ae.contains(b)); assertEquals(true, ae.contains(ab)); assertEquals(true, ae.contains(bc)); assertEquals(true, ae.contains(cd)); assertEquals(true, ae.contains(de)); CharRange notb = CharRange.isNot('b'); CharRange notc = CharRange.isNot('c'); CharRange notd = CharRange.isNot('d'); CharRange notab = CharRange.isNotIn('a', 'b'); CharRange notbc = CharRange.isNotIn('b', 'c'); CharRange notbd = CharRange.isNotIn('b', 'd'); CharRange notcd = CharRange.isNotIn('c', 'd'); CharRange notde = CharRange.isNotIn('d', 'e'); CharRange notae = CharRange.isNotIn('a', 'e'); CharRange all = CharRange.isIn((char) 0, Character.MAX_VALUE); CharRange allbutfirst = CharRange.isIn((char) 1, Character.MAX_VALUE); // normal/negated assertEquals(false, c.contains(notc)); assertEquals(false, c.contains(notbd)); assertEquals(true, all.contains(notc)); assertEquals(true, all.contains(notbd)); assertEquals(false, allbutfirst.contains(notc)); assertEquals(false, allbutfirst.contains(notbd)); // negated/normal assertEquals(true, notc.contains(a)); assertEquals(true, notc.contains(b)); assertEquals(false, notc.contains(c)); assertEquals(true, notc.contains(d)); assertEquals(true, notc.contains(e)); assertEquals(true, notc.contains(ab)); assertEquals(false, notc.contains(bc)); assertEquals(false, notc.contains(bd)); assertEquals(false, notc.contains(cd)); assertEquals(true, notc.contains(de)); assertEquals(false, notc.contains(ae)); assertEquals(false, notc.contains(all)); assertEquals(false, notc.contains(allbutfirst)); assertEquals(true, notbd.contains(a)); assertEquals(false, notbd.contains(b)); assertEquals(false, notbd.contains(c)); assertEquals(false, notbd.contains(d)); assertEquals(true, notbd.contains(e)); assertEquals(true, notcd.contains(ab)); assertEquals(false, notcd.contains(bc)); assertEquals(false, notcd.contains(bd)); assertEquals(false, notcd.contains(cd)); assertEquals(false, notcd.contains(de)); assertEquals(false, notcd.contains(ae)); assertEquals(true, notcd.contains(ef)); assertEquals(false, notcd.contains(all)); assertEquals(false, notcd.contains(allbutfirst)); // negated/negated assertEquals(false, notc.contains(notb)); assertEquals(true, notc.contains(notc)); assertEquals(false, notc.contains(notd)); assertEquals(false, notc.contains(notab)); assertEquals(true, notc.contains(notbc)); assertEquals(true, notc.contains(notbd)); assertEquals(true, notc.contains(notcd)); assertEquals(false, notc.contains(notde)); assertEquals(false, notbd.contains(notb)); assertEquals(false, notbd.contains(notc)); assertEquals(false, notbd.contains(notd)); assertEquals(false, notbd.contains(notab)); assertEquals(false, notbd.contains(notbc)); assertEquals(true, notbd.contains(notbd)); assertEquals(false, notbd.contains(notcd)); assertEquals(false, notbd.contains(notde)); assertEquals(true, notbd.contains(notae)); } public void testContainsNullArg() { CharRange range = CharRange.is('a'); try { boolean contains = range.contains(null); } catch(IllegalArgumentException e) { assertEquals("The Range must not be null", e.getMessage()); } } public void testIterator() { CharRange a = CharRange.is('a'); CharRange ad = CharRange.isIn('a', 'd'); CharRange nota = CharRange.isNot('a'); CharRange emptySet = CharRange.isNotIn((char) 0, Character.MAX_VALUE); CharRange notFirst = CharRange.isNotIn((char) 1, Character.MAX_VALUE); CharRange notLast = CharRange.isNotIn((char) 0, (char) (Character.MAX_VALUE - 1)); Iterator aIt = a.iterator(); assertNotNull(aIt); assertTrue(aIt.hasNext()); assertEquals(new Character('a'), aIt.next()); assertFalse(aIt.hasNext()); Iterator adIt = ad.iterator(); assertNotNull(adIt); assertTrue(adIt.hasNext()); assertEquals(new Character('a'), adIt.next()); assertEquals(new Character('b'), adIt.next()); assertEquals(new Character('c'), adIt.next()); assertEquals(new Character('d'), adIt.next()); assertFalse(adIt.hasNext()); Iterator notaIt = nota.iterator(); assertNotNull(notaIt); assertTrue(notaIt.hasNext()); while (notaIt.hasNext()) { Character c = (Character) notaIt.next(); assertFalse('a' == c.charValue()); } Iterator emptySetIt = emptySet.iterator(); assertNotNull(emptySetIt); assertFalse(emptySetIt.hasNext()); try { emptySetIt.next(); fail("Should throw NoSuchElementException"); } catch (NoSuchElementException e) { assertTrue(true); } Iterator notFirstIt = notFirst.iterator(); assertNotNull(notFirstIt); assertTrue(notFirstIt.hasNext()); assertEquals(new Character((char) 0), notFirstIt.next()); assertFalse(notFirstIt.hasNext()); try { notFirstIt.next(); fail("Should throw NoSuchElementException"); } catch (NoSuchElementException e) { assertTrue(true); } Iterator notLastIt = notLast.iterator(); assertNotNull(notLastIt); assertTrue(notLastIt.hasNext()); assertEquals(new Character(Character.MAX_VALUE), notLastIt.next()); assertFalse(notLastIt.hasNext()); try { notLastIt.next(); fail("Should throw NoSuchElementException"); } catch (NoSuchElementException e) { assertTrue(true); } } //----------------------------------------------------------------------- public void testSerialization() { CharRange range = CharRange.is('a'); assertEquals(range, SerializationUtils.clone(range)); range = CharRange.isIn('a', 'e'); assertEquals(range, SerializationUtils.clone(range)); range = CharRange.isNotIn('a', 'e'); assertEquals(range, SerializationUtils.clone(range)); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/CharSetTest.java100644 0 0 47301 11513702440 24040 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "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 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.commons.lang; import java.lang.reflect.Modifier; import junit.framework.TestCase; /** * Unit tests {@link org.apache.commons.lang.CharSet}. * * @author Apache Software Foundation * @author Phil Steitz * @version $Id: CharSetTest.java 905636 2010-02-02 14:03:32Z niallp $ */ public class CharSetTest extends TestCase { public CharSetTest(String name) { super(name); } //----------------------------------------------------------------------- public void testClass() { assertEquals(true, Modifier.isPublic(CharSet.class.getModifiers())); assertEquals(false, Modifier.isFinal(CharSet.class.getModifiers())); } //----------------------------------------------------------------------- public void testGetInstance() { assertSame(CharSet.EMPTY, CharSet.getInstance( (String) null)); assertSame(CharSet.EMPTY, CharSet.getInstance("")); assertSame(CharSet.ASCII_ALPHA, CharSet.getInstance("a-zA-Z")); assertSame(CharSet.ASCII_ALPHA, CharSet.getInstance("A-Za-z")); assertSame(CharSet.ASCII_ALPHA_LOWER, CharSet.getInstance("a-z")); assertSame(CharSet.ASCII_ALPHA_UPPER, CharSet.getInstance("A-Z")); assertSame(CharSet.ASCII_NUMERIC, CharSet.getInstance("0-9")); } //----------------------------------------------------------------------- public void testGetInstance_Stringarray() { assertEquals(null, CharSet.getInstance((String[]) null)); assertEquals("[]", CharSet.getInstance(new String[0]).toString()); assertEquals("[]", CharSet.getInstance(new String[] {null}).toString()); assertEquals("[a-e]", CharSet.getInstance(new String[] {"a-e"}).toString()); } //----------------------------------------------------------------------- public void testConstructor_String_simple() { CharSet set; CharRange[] array; set = CharSet.getInstance((String) null); array = set.getCharRanges(); assertEquals("[]", set.toString()); assertEquals(0, array.length); set = CharSet.getInstance(""); array = set.getCharRanges(); assertEquals("[]", set.toString()); assertEquals(0, array.length); set = CharSet.getInstance("a"); array = set.getCharRanges(); assertEquals("[a]", set.toString()); assertEquals(1, array.length); assertEquals("a", array[0].toString()); set = CharSet.getInstance("^a"); array = set.getCharRanges(); assertEquals("[^a]", set.toString()); assertEquals(1, array.length); assertEquals("^a", array[0].toString()); set = CharSet.getInstance("a-e"); array = set.getCharRanges(); assertEquals("[a-e]", set.toString()); assertEquals(1, array.length); assertEquals("a-e", array[0].toString()); set = CharSet.getInstance("^a-e"); array = set.getCharRanges(); assertEquals("[^a-e]", set.toString()); assertEquals(1, array.length); assertEquals("^a-e", array[0].toString()); } public void testConstructor_String_combo() { CharSet set; CharRange[] array; set = CharSet.getInstance("abc"); array = set.getCharRanges(); assertEquals(3, array.length); assertEquals(true, ArrayUtils.contains(array, CharRange.is('a'))); assertEquals(true, ArrayUtils.contains(array, CharRange.is('b'))); assertEquals(true, ArrayUtils.contains(array, CharRange.is('c'))); set = CharSet.getInstance("a-ce-f"); array = set.getCharRanges(); assertEquals(2, array.length); assertEquals(true, ArrayUtils.contains(array, CharRange.isIn('a', 'c'))); assertEquals(true, ArrayUtils.contains(array, CharRange.isIn('e', 'f'))); set = CharSet.getInstance("ae-f"); array = set.getCharRanges(); assertEquals(2, array.length); assertEquals(true, ArrayUtils.contains(array, CharRange.is('a'))); assertEquals(true, ArrayUtils.contains(array, CharRange.isIn('e', 'f'))); set = CharSet.getInstance("e-fa"); array = set.getCharRanges(); assertEquals(2, array.length); assertEquals(true, ArrayUtils.contains(array, CharRange.is('a'))); assertEquals(true, ArrayUtils.contains(array, CharRange.isIn('e', 'f'))); set = CharSet.getInstance("ae-fm-pz"); array = set.getCharRanges(); assertEquals(4, array.length); assertEquals(true, ArrayUtils.contains(array, CharRange.is('a'))); assertEquals(true, ArrayUtils.contains(array, CharRange.isIn('e', 'f'))); assertEquals(true, ArrayUtils.contains(array, CharRange.isIn('m', 'p'))); assertEquals(true, ArrayUtils.contains(array, CharRange.is('z'))); } public void testConstructor_String_comboNegated() { CharSet set; CharRange[] array; set = CharSet.getInstance("^abc"); array = set.getCharRanges(); assertEquals(3, array.length); assertEquals(true, ArrayUtils.contains(array, CharRange.isNot('a'))); assertEquals(true, ArrayUtils.contains(array, CharRange.is('b'))); assertEquals(true, ArrayUtils.contains(array, CharRange.is('c'))); set = CharSet.getInstance("b^ac"); array = set.getCharRanges(); assertEquals(3, array.length); assertEquals(true, ArrayUtils.contains(array, CharRange.is('b'))); assertEquals(true, ArrayUtils.contains(array, CharRange.isNot('a'))); assertEquals(true, ArrayUtils.contains(array, CharRange.is('c'))); set = CharSet.getInstance("db^ac"); array = set.getCharRanges(); assertEquals(4, array.length); assertEquals(true, ArrayUtils.contains(array, CharRange.is('d'))); assertEquals(true, ArrayUtils.contains(array, CharRange.is('b'))); assertEquals(true, ArrayUtils.contains(array, CharRange.isNot('a'))); assertEquals(true, ArrayUtils.contains(array, CharRange.is('c'))); set = CharSet.getInstance("^b^a"); array = set.getCharRanges(); assertEquals(2, array.length); assertEquals(true, ArrayUtils.contains(array, CharRange.isNot('b'))); assertEquals(true, ArrayUtils.contains(array, CharRange.isNot('a'))); set = CharSet.getInstance("b^a-c^z"); array = set.getCharRanges(); assertEquals(3, array.length); assertEquals(true, ArrayUtils.contains(array, CharRange.isNotIn('a', 'c'))); assertEquals(true, ArrayUtils.contains(array, CharRange.isNot('z'))); assertEquals(true, ArrayUtils.contains(array, CharRange.is('b'))); } public void testConstructor_String_oddDash() { CharSet set; CharRange[] array; set = CharSet.getInstance("-"); array = set.getCharRanges(); assertEquals(1, array.length); assertEquals(true, ArrayUtils.contains(array, CharRange.is('-'))); set = CharSet.getInstance("--"); array = set.getCharRanges(); assertEquals(1, array.length); assertEquals(true, ArrayUtils.contains(array, CharRange.is('-'))); set = CharSet.getInstance("---"); array = set.getCharRanges(); assertEquals(1, array.length); assertEquals(true, ArrayUtils.contains(array, CharRange.is('-'))); set = CharSet.getInstance("----"); array = set.getCharRanges(); assertEquals(1, array.length); assertEquals(true, ArrayUtils.contains(array, CharRange.is('-'))); set = CharSet.getInstance("-a"); array = set.getCharRanges(); assertEquals(2, array.length); assertEquals(true, ArrayUtils.contains(array, CharRange.is('-'))); assertEquals(true, ArrayUtils.contains(array, CharRange.is('a'))); set = CharSet.getInstance("a-"); array = set.getCharRanges(); assertEquals(2, array.length); assertEquals(true, ArrayUtils.contains(array, CharRange.is('a'))); assertEquals(true, ArrayUtils.contains(array, CharRange.is('-'))); set = CharSet.getInstance("a--"); array = set.getCharRanges(); assertEquals(1, array.length); assertEquals(true, ArrayUtils.contains(array, CharRange.isIn('a', '-'))); set = CharSet.getInstance("--a"); array = set.getCharRanges(); assertEquals(1, array.length); assertEquals(true, ArrayUtils.contains(array, CharRange.isIn('-', 'a'))); } public void testConstructor_String_oddNegate() { CharSet set; CharRange[] array; set = CharSet.getInstance("^"); array = set.getCharRanges(); assertEquals(1, array.length); assertEquals(true, ArrayUtils.contains(array, CharRange.is('^'))); // "^" set = CharSet.getInstance("^^"); array = set.getCharRanges(); assertEquals(1, array.length); assertEquals(true, ArrayUtils.contains(array, CharRange.isNot('^'))); // "^^" set = CharSet.getInstance("^^^"); array = set.getCharRanges(); assertEquals(2, array.length); assertEquals(true, ArrayUtils.contains(array, CharRange.isNot('^'))); // "^^" assertEquals(true, ArrayUtils.contains(array, CharRange.is('^'))); // "^" set = CharSet.getInstance("^^^^"); array = set.getCharRanges(); assertEquals(1, array.length); assertEquals(true, ArrayUtils.contains(array, CharRange.isNot('^'))); // "^^" x2 set = CharSet.getInstance("a^"); array = set.getCharRanges(); assertEquals(2, array.length); assertEquals(true, ArrayUtils.contains(array, CharRange.is('a'))); // "a" assertEquals(true, ArrayUtils.contains(array, CharRange.is('^'))); // "^" set = CharSet.getInstance("^a-"); array = set.getCharRanges(); assertEquals(2, array.length); assertEquals(true, ArrayUtils.contains(array, CharRange.isNot('a'))); // "^a" assertEquals(true, ArrayUtils.contains(array, CharRange.is('-'))); // "-" set = CharSet.getInstance("^^-c"); array = set.getCharRanges(); assertEquals(1, array.length); assertEquals(true, ArrayUtils.contains(array, CharRange.isNotIn('^', 'c'))); // "^^-c" set = CharSet.getInstance("^c-^"); array = set.getCharRanges(); assertEquals(1, array.length); assertEquals(true, ArrayUtils.contains(array, CharRange.isNotIn('c', '^'))); // "^c-^" set = CharSet.getInstance("^c-^d"); array = set.getCharRanges(); assertEquals(2, array.length); assertEquals(true, ArrayUtils.contains(array, CharRange.isNotIn('c', '^'))); // "^c-^" assertEquals(true, ArrayUtils.contains(array, CharRange.is('d'))); // "d" set = CharSet.getInstance("^^-"); array = set.getCharRanges(); assertEquals(2, array.length); assertEquals(true, ArrayUtils.contains(array, CharRange.isNot('^'))); // "^^" assertEquals(true, ArrayUtils.contains(array, CharRange.is('-'))); // "-" } public void testConstructor_String_oddCombinations() { CharSet set; CharRange[] array = null; set = CharSet.getInstance("a-^c"); array = set.getCharRanges(); assertEquals(true, ArrayUtils.contains(array, CharRange.isIn('a', '^'))); // "a-^" assertEquals(true, ArrayUtils.contains(array, CharRange.is('c'))); // "c" assertEquals(false, set.contains('b')); assertEquals(true, set.contains('^')); assertEquals(true, set.contains('_')); // between ^ and a assertEquals(true, set.contains('c')); set = CharSet.getInstance("^a-^c"); array = set.getCharRanges(); assertEquals(true, ArrayUtils.contains(array, CharRange.isNotIn('a', '^'))); // "^a-^" assertEquals(true, ArrayUtils.contains(array, CharRange.is('c'))); // "c" assertEquals(true, set.contains('b')); assertEquals(false, set.contains('^')); assertEquals(false, set.contains('_')); // between ^ and a set = CharSet.getInstance("a- ^-- "); //contains everything array = set.getCharRanges(); assertEquals(true, ArrayUtils.contains(array, CharRange.isIn('a', ' '))); // "a- " assertEquals(true, ArrayUtils.contains(array, CharRange.isNotIn('-', ' '))); // "^-- " assertEquals(true, set.contains('#')); assertEquals(true, set.contains('^')); assertEquals(true, set.contains('a')); assertEquals(true, set.contains('*')); assertEquals(true, set.contains('A')); set = CharSet.getInstance("^-b"); array = set.getCharRanges(); assertEquals(true, ArrayUtils.contains(array, CharRange.isIn('^','b'))); // "^-b" assertEquals(true, set.contains('b')); assertEquals(true, set.contains('_')); // between ^ and a assertEquals(false, set.contains('A')); assertEquals(true, set.contains('^')); set = CharSet.getInstance("b-^"); array = set.getCharRanges(); assertEquals(true, ArrayUtils.contains(array, CharRange.isIn('^','b'))); // "b-^" assertEquals(true, set.contains('b')); assertEquals(true, set.contains('^')); assertEquals(true, set.contains('a')); // between ^ and b assertEquals(false, set.contains('c')); } //----------------------------------------------------------------------- public void testEquals_Object() { CharSet abc = CharSet.getInstance("abc"); CharSet abc2 = CharSet.getInstance("abc"); CharSet atoc = CharSet.getInstance("a-c"); CharSet atoc2 = CharSet.getInstance("a-c"); CharSet notatoc = CharSet.getInstance("^a-c"); CharSet notatoc2 = CharSet.getInstance("^a-c"); assertEquals(false, abc.equals(null)); assertEquals(true, abc.equals(abc)); assertEquals(true, abc.equals(abc2)); assertEquals(false, abc.equals(atoc)); assertEquals(false, abc.equals(notatoc)); assertEquals(false, atoc.equals(abc)); assertEquals(true, atoc.equals(atoc)); assertEquals(true, atoc.equals(atoc2)); assertEquals(false, atoc.equals(notatoc)); assertEquals(false, notatoc.equals(abc)); assertEquals(false, notatoc.equals(atoc)); assertEquals(true, notatoc.equals(notatoc)); assertEquals(true, notatoc.equals(notatoc2)); } public void testHashCode() { CharSet abc = CharSet.getInstance("abc"); CharSet abc2 = CharSet.getInstance("abc"); CharSet atoc = CharSet.getInstance("a-c"); CharSet atoc2 = CharSet.getInstance("a-c"); CharSet notatoc = CharSet.getInstance("^a-c"); CharSet notatoc2 = CharSet.getInstance("^a-c"); assertEquals(abc.hashCode(), abc.hashCode()); assertEquals(abc.hashCode(), abc2.hashCode()); assertEquals(atoc.hashCode(), atoc.hashCode()); assertEquals(atoc.hashCode(), atoc2.hashCode()); assertEquals(notatoc.hashCode(), notatoc.hashCode()); assertEquals(notatoc.hashCode(), notatoc2.hashCode()); } //----------------------------------------------------------------------- public void testContains_Char() { CharSet btod = CharSet.getInstance("b-d"); CharSet dtob = CharSet.getInstance("d-b"); CharSet bcd = CharSet.getInstance("bcd"); CharSet bd = CharSet.getInstance("bd"); CharSet notbtod = CharSet.getInstance("^b-d"); assertEquals(false, btod.contains('a')); assertEquals(true, btod.contains('b')); assertEquals(true, btod.contains('c')); assertEquals(true, btod.contains('d')); assertEquals(false, btod.contains('e')); assertEquals(false, bcd.contains('a')); assertEquals(true, bcd.contains('b')); assertEquals(true, bcd.contains('c')); assertEquals(true, bcd.contains('d')); assertEquals(false, bcd.contains('e')); assertEquals(false, bd.contains('a')); assertEquals(true, bd.contains('b')); assertEquals(false, bd.contains('c')); assertEquals(true, bd.contains('d')); assertEquals(false, bd.contains('e')); assertEquals(true, notbtod.contains('a')); assertEquals(false, notbtod.contains('b')); assertEquals(false, notbtod.contains('c')); assertEquals(false, notbtod.contains('d')); assertEquals(true, notbtod.contains('e')); assertEquals(false, dtob.contains('a')); assertEquals(true, dtob.contains('b')); assertEquals(true, dtob.contains('c')); assertEquals(true, dtob.contains('d')); assertEquals(false, dtob.contains('e')); CharRange[] array = dtob.getCharRanges(); assertEquals("[b-d]", dtob.toString()); assertEquals(1, array.length); } //----------------------------------------------------------------------- public void testSerialization() { CharSet set = CharSet.getInstance("a"); assertEquals(set, SerializationUtils.clone(set)); set = CharSet.getInstance("a-e"); assertEquals(set, SerializationUtils.clone(set)); set = CharSet.getInstance("be-f^a-z"); assertEquals(set, SerializationUtils.clone(set)); } //----------------------------------------------------------------------- public void testStatics() { CharRange[] array; array = CharSet.EMPTY.getCharRanges(); assertEquals(0, array.length); array = CharSet.ASCII_ALPHA.getCharRanges(); assertEquals(2, array.length); assertEquals(true, ArrayUtils.contains(array, CharRange.isIn('a', 'z'))); assertEquals(true, ArrayUtils.contains(array, CharRange.isIn('A', 'Z'))); array = CharSet.ASCII_ALPHA_LOWER.getCharRanges(); assertEquals(1, array.length); assertEquals(true, ArrayUtils.contains(array, CharRange.isIn('a', 'z'))); array = CharSet.ASCII_ALPHA_UPPER.getCharRanges(); assertEquals(1, array.length); assertEquals(true, ArrayUtils.contains(array, CharRange.isIn('A', 'Z'))); array = CharSet.ASCII_NUMERIC.getCharRanges(); assertEquals(1, array.length); assertEquals(true, ArrayUtils.contains(array, CharRange.isIn('0', '9'))); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/CharSetUtilsTest.java100644 0 0 31566 11513702440 25067 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import junit.framework.TestCase; /** * Unit tests {@link org.apache.commons.lang.CharSetUtils}. * * @author Apache Software Foundation * @author Ringo De Smet * @author Gary D. Gregory * @version $Id: CharSetUtilsTest.java 905636 2010-02-02 14:03:32Z niallp $ */ public class CharSetUtilsTest extends TestCase { public CharSetUtilsTest(String name) { super(name); } //----------------------------------------------------------------------- public void testConstructor() { assertNotNull(new CharSetUtils()); Constructor[] cons = CharSetUtils.class.getDeclaredConstructors(); assertEquals(1, cons.length); assertEquals(true, Modifier.isPublic(cons[0].getModifiers())); assertEquals(true, Modifier.isPublic(CharSetUtils.class.getModifiers())); assertEquals(false, Modifier.isFinal(CharSetUtils.class.getModifiers())); } //----------------------------------------------------------------------- public void testEvaluateSet_Stringarray() { assertEquals(null, CharSetUtils.evaluateSet((String[]) null)); assertEquals("[]", CharSetUtils.evaluateSet(new String[0]).toString()); assertEquals("[]", CharSetUtils.evaluateSet(new String[] {null}).toString()); assertEquals("[a-e]", CharSetUtils.evaluateSet(new String[] {"a-e"}).toString()); } //----------------------------------------------------------------------- public void testSqueeze_StringString() { assertEquals(null, CharSetUtils.squeeze(null, (String) null)); assertEquals(null, CharSetUtils.squeeze(null, "")); assertEquals("", CharSetUtils.squeeze("", (String) null)); assertEquals("", CharSetUtils.squeeze("", "")); assertEquals("", CharSetUtils.squeeze("", "a-e")); assertEquals("hello", CharSetUtils.squeeze("hello", (String) null)); assertEquals("hello", CharSetUtils.squeeze("hello", "")); assertEquals("hello", CharSetUtils.squeeze("hello", "a-e")); assertEquals("helo", CharSetUtils.squeeze("hello", "l-p")); assertEquals("heloo", CharSetUtils.squeeze("helloo", "l")); assertEquals("hello", CharSetUtils.squeeze("helloo", "^l")); } public void testSqueeze_StringStringarray() { assertEquals(null, CharSetUtils.squeeze(null, (String[]) null)); assertEquals(null, CharSetUtils.squeeze(null, new String[0])); assertEquals(null, CharSetUtils.squeeze(null, new String[] {null})); assertEquals(null, CharSetUtils.squeeze(null, new String[] {"el"})); assertEquals("", CharSetUtils.squeeze("", (String[]) null)); assertEquals("", CharSetUtils.squeeze("", new String[0])); assertEquals("", CharSetUtils.squeeze("", new String[] {null})); assertEquals("", CharSetUtils.squeeze("", new String[] {"a-e"})); assertEquals("hello", CharSetUtils.squeeze("hello", (String[]) null)); assertEquals("hello", CharSetUtils.squeeze("hello", new String[0])); assertEquals("hello", CharSetUtils.squeeze("hello", new String[] {null})); assertEquals("hello", CharSetUtils.squeeze("hello", new String[] {"a-e"})); assertEquals("helo", CharSetUtils.squeeze("hello", new String[] { "el" })); assertEquals("hello", CharSetUtils.squeeze("hello", new String[] { "e" })); assertEquals("fofof", CharSetUtils.squeeze("fooffooff", new String[] { "of" })); assertEquals("fof", CharSetUtils.squeeze("fooooff", new String[] { "fo" })); } //----------------------------------------------------------------------- public void testCount_StringString() { assertEquals(0, CharSetUtils.count(null, (String) null)); assertEquals(0, CharSetUtils.count(null, "")); assertEquals(0, CharSetUtils.count("", (String) null)); assertEquals(0, CharSetUtils.count("", "")); assertEquals(0, CharSetUtils.count("", "a-e")); assertEquals(0, CharSetUtils.count("hello", (String) null)); assertEquals(0, CharSetUtils.count("hello", "")); assertEquals(1, CharSetUtils.count("hello", "a-e")); assertEquals(3, CharSetUtils.count("hello", "l-p")); } public void testCount_StringStringarray() { assertEquals(0, CharSetUtils.count(null, (String[]) null)); assertEquals(0, CharSetUtils.count(null, new String[0])); assertEquals(0, CharSetUtils.count(null, new String[] {null})); assertEquals(0, CharSetUtils.count(null, new String[] {"a-e"})); assertEquals(0, CharSetUtils.count("", (String[]) null)); assertEquals(0, CharSetUtils.count("", new String[0])); assertEquals(0, CharSetUtils.count("", new String[] {null})); assertEquals(0, CharSetUtils.count("", new String[] {"a-e"})); assertEquals(0, CharSetUtils.count("hello", (String[]) null)); assertEquals(0, CharSetUtils.count("hello", new String[0])); assertEquals(0, CharSetUtils.count("hello", new String[] {null})); assertEquals(1, CharSetUtils.count("hello", new String[] {"a-e"})); assertEquals(3, CharSetUtils.count("hello", new String[] { "el" })); assertEquals(0, CharSetUtils.count("hello", new String[] { "x" })); assertEquals(2, CharSetUtils.count("hello", new String[] { "e-i" })); assertEquals(5, CharSetUtils.count("hello", new String[] { "a-z" })); assertEquals(0, CharSetUtils.count("hello", new String[] { "" })); } //----------------------------------------------------------------------- public void testKeep_StringString() { assertEquals(null, CharSetUtils.keep(null, (String) null)); assertEquals(null, CharSetUtils.keep(null, "")); assertEquals("", CharSetUtils.keep("", (String) null)); assertEquals("", CharSetUtils.keep("", "")); assertEquals("", CharSetUtils.keep("", "a-e")); assertEquals("", CharSetUtils.keep("hello", (String) null)); assertEquals("", CharSetUtils.keep("hello", "")); assertEquals("", CharSetUtils.keep("hello", "xyz")); assertEquals("hello", CharSetUtils.keep("hello", "a-z")); assertEquals("hello", CharSetUtils.keep("hello", "oleh")); assertEquals("ell", CharSetUtils.keep("hello", "el")); } public void testKeep_StringStringarray() { assertEquals(null, CharSetUtils.keep(null, (String[]) null)); assertEquals(null, CharSetUtils.keep(null, new String[0])); assertEquals(null, CharSetUtils.keep(null, new String[] {null})); assertEquals(null, CharSetUtils.keep(null, new String[] {"a-e"})); assertEquals("", CharSetUtils.keep("", (String[]) null)); assertEquals("", CharSetUtils.keep("", new String[0])); assertEquals("", CharSetUtils.keep("", new String[] {null})); assertEquals("", CharSetUtils.keep("", new String[] {"a-e"})); assertEquals("", CharSetUtils.keep("hello", (String[]) null)); assertEquals("", CharSetUtils.keep("hello", new String[0])); assertEquals("", CharSetUtils.keep("hello", new String[] {null})); assertEquals("e", CharSetUtils.keep("hello", new String[] {"a-e"})); assertEquals("e", CharSetUtils.keep("hello", new String[] { "a-e" })); assertEquals("ell", CharSetUtils.keep("hello", new String[] { "el" })); assertEquals("hello", CharSetUtils.keep("hello", new String[] { "elho" })); assertEquals("hello", CharSetUtils.keep("hello", new String[] { "a-z" })); assertEquals("----", CharSetUtils.keep("----", new String[] { "-" })); assertEquals("ll", CharSetUtils.keep("hello", new String[] { "l" })); } //----------------------------------------------------------------------- public void testDelete_StringString() { assertEquals(null, CharSetUtils.delete(null, (String) null)); assertEquals(null, CharSetUtils.delete(null, "")); assertEquals("", CharSetUtils.delete("", (String) null)); assertEquals("", CharSetUtils.delete("", "")); assertEquals("", CharSetUtils.delete("", "a-e")); assertEquals("hello", CharSetUtils.delete("hello", (String) null)); assertEquals("hello", CharSetUtils.delete("hello", "")); assertEquals("hllo", CharSetUtils.delete("hello", "a-e")); assertEquals("he", CharSetUtils.delete("hello", "l-p")); assertEquals("hello", CharSetUtils.delete("hello", "z")); } public void testDelete_StringStringarray() { assertEquals(null, CharSetUtils.delete(null, (String[]) null)); assertEquals(null, CharSetUtils.delete(null, new String[0])); assertEquals(null, CharSetUtils.delete(null, new String[] {null})); assertEquals(null, CharSetUtils.delete(null, new String[] {"el"})); assertEquals("", CharSetUtils.delete("", (String[]) null)); assertEquals("", CharSetUtils.delete("", new String[0])); assertEquals("", CharSetUtils.delete("", new String[] {null})); assertEquals("", CharSetUtils.delete("", new String[] {"a-e"})); assertEquals("hello", CharSetUtils.delete("hello", (String[]) null)); assertEquals("hello", CharSetUtils.delete("hello", new String[0])); assertEquals("hello", CharSetUtils.delete("hello", new String[] {null})); assertEquals("hello", CharSetUtils.delete("hello", new String[] {"xyz"})); assertEquals("ho", CharSetUtils.delete("hello", new String[] { "el" })); assertEquals("", CharSetUtils.delete("hello", new String[] { "elho" })); assertEquals("hello", CharSetUtils.delete("hello", new String[] { "" })); assertEquals("hello", CharSetUtils.delete("hello", "")); assertEquals("", CharSetUtils.delete("hello", new String[] { "a-z" })); assertEquals("", CharSetUtils.delete("----", new String[] { "-" })); assertEquals("heo", CharSetUtils.delete("hello", new String[] { "l" })); } public void testTranslate() { assertEquals(null, CharSetUtils.translate(null, null, null)); assertEquals("", CharSetUtils.translate("", "a", "b")); assertEquals("jelly", CharSetUtils.translate("hello", "ho", "jy")); assertEquals("jellj", CharSetUtils.translate("hello", "ho", "j")); assertEquals("jelly", CharSetUtils.translate("hello", "ho", "jyx")); assertEquals("\rhello\r", CharSetUtils.translate("\nhello\n", "\n", "\r")); assertEquals("hello", CharSetUtils.translate("hello", "", "x")); assertEquals("hello", CharSetUtils.translate("hello", "", "")); assertEquals("hello", CharSetUtils.translate("hello", "", "")); // From http://issues.apache.org/bugzilla/show_bug.cgi?id=25454 assertEquals("q651.506bera", CharSetUtils.translate("d216.102oren", "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789", "nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM567891234")); } public void testTranslateNullPointerException() { try { CharSetUtils.translate("hello", null, null); fail("Expecting NullPointerException"); } catch (NullPointerException ex) { } try { CharSetUtils.translate("hello", "h", null); fail("Expecting NullPointerException"); } catch (NullPointerException ex) { } try { CharSetUtils.translate("hello", null, "a"); fail("Expecting NullPointerException"); } catch (NullPointerException ex) { } try { CharSetUtils.translate("hello", "h", ""); fail("Expecting ArrayIndexOutOfBoundsException"); } catch (ArrayIndexOutOfBoundsException ex) { } } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/CharUtilsPerfRun.java100644 0 0 14107 11513702440 25045 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang; import java.text.NumberFormat; import java.util.Calendar; /** * Tests the difference in performance between CharUtils and CharSet. * * Sample runs: Now: Thu Mar 18 14:29:48 PST 2004 Sun Microsystems Inc. Java(TM) 2 Runtime Environment, Standard Edition 1.3.1_10-b03 Sun Microsystems Inc. Java HotSpot(TM) Client VM 1.3.1_10-b03 Windows XP 5.1 x86 pentium i486 i386 Do nohting: 0 milliseconds. run_CharUtils_isAsciiNumeric: 4,545 milliseconds. run_inlined_CharUtils_isAsciiNumeric: 3,417 milliseconds. run_inlined_CharUtils_isAsciiNumeric: 85,679 milliseconds. Now: Thu Mar 18 14:24:51 PST 2004 Sun Microsystems Inc. Java(TM) 2 Runtime Environment, Standard Edition 1.4.2_04-b05 Sun Microsystems Inc. Java HotSpot(TM) Client VM 1.4.2_04-b05 Windows XP 5.1 x86 pentium i486 i386 Do nohting: 0 milliseconds. run_CharUtils_isAsciiNumeric: 2,578 milliseconds. run_inlined_CharUtils_isAsciiNumeric: 2,477 milliseconds. run_inlined_CharUtils_isAsciiNumeric: 114,429 milliseconds. Now: Thu Mar 18 14:27:55 PST 2004 Sun Microsystems Inc. Java(TM) 2 Runtime Environment, Standard Edition 1.4.2_04-b05 Sun Microsystems Inc. Java HotSpot(TM) Server VM 1.4.2_04-b05 Windows XP 5.1 x86 pentium i486 i386 Do nohting: 0 milliseconds. run_CharUtils_isAsciiNumeric: 630 milliseconds. run_inlined_CharUtils_isAsciiNumeric: 709 milliseconds. run_inlined_CharUtils_isAsciiNumeric: 84,420 milliseconds. * @version $Id: CharUtilsPerfRun.java 905239 2010-02-01 10:35:17Z niallp $ */ public class CharUtilsPerfRun { final static String VERSION = "$Id: CharUtilsPerfRun.java 905239 2010-02-01 10:35:17Z niallp $"; final static int WARM_UP = 100; final static int COUNT = 5000; final static char[] CHAR_SAMPLES; static { CHAR_SAMPLES = new char[Character.MAX_VALUE]; for (char i = Character.MIN_VALUE; i < Character.MAX_VALUE; i++) { CHAR_SAMPLES[i] = i; } } public static void main(String[] args) { new CharUtilsPerfRun().run(); } private void printSysInfo() { System.out.println(VERSION); System.out.println("Now: " + Calendar.getInstance().getTime()); System.out.println(System.getProperty("java.vendor") + " " + System.getProperty("java.runtime.name") + " " + System.getProperty("java.runtime.version")); System.out.println(System.getProperty("java.vm.vendor") + " " + System.getProperty("java.vm.name") + " " + System.getProperty("java.vm.version")); System.out.println(System.getProperty("os.name") + " " + System.getProperty("os.version") + " " + System.getProperty("os.arch") + " " + System.getProperty("sun.cpu.isalist")); } private void run() { this.printSysInfo(); long start; start = System.currentTimeMillis(); this.printlnTotal("Do nohting", start); //System.out.println("Warming up..."); run_CharUtils_isAsciiNumeric(WARM_UP); //System.out.println("Measuring..."); start = System.currentTimeMillis(); run_CharUtils_isAsciiNumeric(COUNT); this.printlnTotal("run_CharUtils_isAsciiNumeric", start); //System.out.println("Warming up..."); run_inlined_CharUtils_isAsciiNumeric(WARM_UP); //System.out.println("Measuring..."); start = System.currentTimeMillis(); run_inlined_CharUtils_isAsciiNumeric(COUNT); this.printlnTotal("run_inlined_CharUtils_isAsciiNumeric", start); //System.out.println("Warming up..."); run_CharSet(WARM_UP); //System.out.println("Measuring..."); start = System.currentTimeMillis(); run_CharSet(COUNT); this.printlnTotal("run_CharSet", start); } private int run_CharSet(int loopCount) { int t = 0; for (int i = 0; i < loopCount; i++) { for (int j = 0; j < CHAR_SAMPLES.length; j++) { char ch = CHAR_SAMPLES[j]; boolean b = CharSet.ASCII_NUMERIC.contains(ch); t += b ? 1 : 0; } } return t; } private int run_CharUtils_isAsciiNumeric(int loopCount) { int t = 0; for (int i = 0; i < loopCount; i++) { for (int j = 0; j < CHAR_SAMPLES.length; j++) { char ch = CHAR_SAMPLES[j]; boolean b = CharUtils.isAsciiNumeric(ch); t += b ? 1 : 0; } } return t; } private int run_inlined_CharUtils_isAsciiNumeric(int loopCount) { int t = 0; for (int i = 0; i < loopCount; i++) { for (int j = 0; j < CHAR_SAMPLES.length; j++) { char ch = CHAR_SAMPLES[j]; boolean b = (ch >= '0' && ch <= '9'); t += b ? 1 : 0; } } return t; } private void printlnTotal(String prefix, long start) { long total = System.currentTimeMillis() - start; System.out.println(prefix + ": " + NumberFormat.getInstance().format(total) + " milliseconds."); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/CharUtilsTest.java100644 0 0 35447 11513702441 24416 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import junit.framework.TestCase; /** * Unit tests {@link org.apache.commons.lang.CharUtils}. * * @author Apache Software Foundation * @version $Id: CharUtilsTest.java 905636 2010-02-02 14:03:32Z niallp $ */ public class CharUtilsTest extends TestCase { private static final Character CHARACTER_A = new Character('A'); private static final Character CHARACTER_B = new Character('B'); private static final char CHAR_COPY = '\u00a9'; public CharUtilsTest(String name) { super(name); } //----------------------------------------------------------------------- public void testConstructor() { assertNotNull(new CharUtils()); Constructor[] cons = CharUtils.class.getDeclaredConstructors(); assertEquals(1, cons.length); assertEquals(true, Modifier.isPublic(cons[0].getModifiers())); assertEquals(true, Modifier.isPublic(BooleanUtils.class.getModifiers())); assertEquals(false, Modifier.isFinal(BooleanUtils.class.getModifiers())); } //----------------------------------------------------------------------- public void testToCharacterObject_char() { assertEquals(new Character('a'), CharUtils.toCharacterObject('a')); assertSame(CharUtils.toCharacterObject('a'), CharUtils.toCharacterObject('a')); for (int i = 0; i < 128; i++) { Character ch = CharUtils.toCharacterObject((char) i); Character ch2 = CharUtils.toCharacterObject((char) i); assertSame(ch, ch2); assertEquals(i, ch.charValue()); } for (int i = 128; i < 196; i++) { Character ch = CharUtils.toCharacterObject((char) i); Character ch2 = CharUtils.toCharacterObject((char) i); assertEquals(ch, ch2); assertTrue(ch != ch2); assertEquals(i, ch.charValue()); assertEquals(i, ch2.charValue()); } } public void testToCharacterObject_String() { assertEquals(null, CharUtils.toCharacterObject(null)); assertEquals(null, CharUtils.toCharacterObject("")); assertEquals(new Character('a'), CharUtils.toCharacterObject("a")); assertEquals(new Character('a'), CharUtils.toCharacterObject("abc")); assertSame(CharUtils.toCharacterObject("a"), CharUtils.toCharacterObject("a")); assertSame(CharUtils.toCharacterObject("a"), CharUtils.toCharacterObject('a')); } //----------------------------------------------------------------------- public void testToChar_Character() { assertEquals('A', CharUtils.toChar(CHARACTER_A)); assertEquals('B', CharUtils.toChar(CHARACTER_B)); try { CharUtils.toChar((Character) null); } catch (IllegalArgumentException ex) {} } public void testToChar_Character_char() { assertEquals('A', CharUtils.toChar(CHARACTER_A, 'X')); assertEquals('B', CharUtils.toChar(CHARACTER_B, 'X')); assertEquals('X', CharUtils.toChar((Character) null, 'X')); } //----------------------------------------------------------------------- public void testToChar_String() { assertEquals('A', CharUtils.toChar("A")); assertEquals('B', CharUtils.toChar("BA")); try { CharUtils.toChar((String) null); } catch (IllegalArgumentException ex) {} try { CharUtils.toChar(""); } catch (IllegalArgumentException ex) {} } public void testToChar_String_char() { assertEquals('A', CharUtils.toChar("A", 'X')); assertEquals('B', CharUtils.toChar("BA", 'X')); assertEquals('X', CharUtils.toChar("", 'X')); assertEquals('X', CharUtils.toChar((String) null, 'X')); } //----------------------------------------------------------------------- public void testToIntValue_char() { assertEquals(0, CharUtils.toIntValue('0')); assertEquals(1, CharUtils.toIntValue('1')); assertEquals(2, CharUtils.toIntValue('2')); assertEquals(3, CharUtils.toIntValue('3')); assertEquals(4, CharUtils.toIntValue('4')); assertEquals(5, CharUtils.toIntValue('5')); assertEquals(6, CharUtils.toIntValue('6')); assertEquals(7, CharUtils.toIntValue('7')); assertEquals(8, CharUtils.toIntValue('8')); assertEquals(9, CharUtils.toIntValue('9')); try { CharUtils.toIntValue('a'); } catch (IllegalArgumentException ex) {} } public void testToIntValue_char_int() { assertEquals(0, CharUtils.toIntValue('0', -1)); assertEquals(3, CharUtils.toIntValue('3', -1)); assertEquals(-1, CharUtils.toIntValue('a', -1)); } //----------------------------------------------------------------------- public void testToIntValue_Character() { assertEquals(0, CharUtils.toIntValue(new Character('0'))); assertEquals(3, CharUtils.toIntValue(new Character('3'))); try { CharUtils.toIntValue(null); } catch (IllegalArgumentException ex) {} try { CharUtils.toIntValue(CHARACTER_A); } catch (IllegalArgumentException ex) {} } public void testToIntValue_Character_int() { assertEquals(0, CharUtils.toIntValue(new Character('0'), -1)); assertEquals(3, CharUtils.toIntValue(new Character('3'), -1)); assertEquals(-1, CharUtils.toIntValue(new Character('A'), -1)); assertEquals(-1, CharUtils.toIntValue(null, -1)); } //----------------------------------------------------------------------- public void testToString_char() { assertEquals("a", CharUtils.toString('a')); assertSame(CharUtils.toString('a'), CharUtils.toString('a')); for (int i = 0; i < 128; i++) { String str = CharUtils.toString((char) i); String str2 = CharUtils.toString((char) i); assertSame(str, str2); assertEquals(1, str.length()); assertEquals(i, str.charAt(0)); } for (int i = 128; i < 196; i++) { String str = CharUtils.toString((char) i); String str2 = CharUtils.toString((char) i); assertEquals(str, str2); assertTrue(str != str2); assertEquals(1, str.length()); assertEquals(i, str.charAt(0)); assertEquals(1, str2.length()); assertEquals(i, str2.charAt(0)); } } public void testToString_Character() { assertEquals(null, CharUtils.toString(null)); assertEquals("A", CharUtils.toString(CHARACTER_A)); assertSame(CharUtils.toString(CHARACTER_A), CharUtils.toString(CHARACTER_A)); } //----------------------------------------------------------------------- public void testToUnicodeEscaped_char() { assertEquals("\\u0041", CharUtils.unicodeEscaped('A')); for (int i = 0; i < 196; i++) { String str = CharUtils.unicodeEscaped((char) i); assertEquals(6, str.length()); int val = Integer.parseInt(str.substring(2), 16); assertEquals(i, val); } assertEquals("\\u0999", CharUtils.unicodeEscaped((char) 0x999)); assertEquals("\\u1001", CharUtils.unicodeEscaped((char) 0x1001)); } public void testToUnicodeEscaped_Character() { assertEquals(null, CharUtils.unicodeEscaped(null)); assertEquals("\\u0041", CharUtils.unicodeEscaped(CHARACTER_A)); } //----------------------------------------------------------------------- public void testIsAscii_char() { assertEquals(true, CharUtils.isAscii('a')); assertEquals(true, CharUtils.isAscii('A')); assertEquals(true, CharUtils.isAscii('3')); assertEquals(true, CharUtils.isAscii('-')); assertEquals(true, CharUtils.isAscii('\n')); assertEquals(false, CharUtils.isAscii(CHAR_COPY)); for (int i = 0; i < 128; i++) { if (i < 128) { assertEquals(true, CharUtils.isAscii((char) i)); } else { assertEquals(false, CharUtils.isAscii((char) i)); } } } //----------------------------------------------------------------------- public void testIsAsciiPrintable_char() { assertEquals(true, CharUtils.isAsciiPrintable('a')); assertEquals(true, CharUtils.isAsciiPrintable('A')); assertEquals(true, CharUtils.isAsciiPrintable('3')); assertEquals(true, CharUtils.isAsciiPrintable('-')); assertEquals(false, CharUtils.isAsciiPrintable('\n')); assertEquals(false, CharUtils.isAscii(CHAR_COPY)); for (int i = 0; i < 196; i++) { if (i >= 32 && i <= 126) { assertEquals(true, CharUtils.isAsciiPrintable((char) i)); } else { assertEquals(false, CharUtils.isAsciiPrintable((char) i)); } } } //----------------------------------------------------------------------- public void testIsAsciiControl_char() { assertEquals(false, CharUtils.isAsciiControl('a')); assertEquals(false, CharUtils.isAsciiControl('A')); assertEquals(false, CharUtils.isAsciiControl('3')); assertEquals(false, CharUtils.isAsciiControl('-')); assertEquals(true, CharUtils.isAsciiControl('\n')); assertEquals(false, CharUtils.isAsciiControl(CHAR_COPY)); for (int i = 0; i < 196; i++) { if (i < 32 || i == 127) { assertEquals(true, CharUtils.isAsciiControl((char) i)); } else { assertEquals(false, CharUtils.isAsciiControl((char) i)); } } } //----------------------------------------------------------------------- public void testIsAsciiAlpha_char() { assertEquals(true, CharUtils.isAsciiAlpha('a')); assertEquals(true, CharUtils.isAsciiAlpha('A')); assertEquals(false, CharUtils.isAsciiAlpha('3')); assertEquals(false, CharUtils.isAsciiAlpha('-')); assertEquals(false, CharUtils.isAsciiAlpha('\n')); assertEquals(false, CharUtils.isAsciiAlpha(CHAR_COPY)); for (int i = 0; i < 196; i++) { if ((i >= 'A' && i <= 'Z') || (i >= 'a' && i <= 'z')) { assertEquals(true, CharUtils.isAsciiAlpha((char) i)); } else { assertEquals(false, CharUtils.isAsciiAlpha((char) i)); } } } //----------------------------------------------------------------------- public void testIsAsciiAlphaUpper_char() { assertEquals(false, CharUtils.isAsciiAlphaUpper('a')); assertEquals(true, CharUtils.isAsciiAlphaUpper('A')); assertEquals(false, CharUtils.isAsciiAlphaUpper('3')); assertEquals(false, CharUtils.isAsciiAlphaUpper('-')); assertEquals(false, CharUtils.isAsciiAlphaUpper('\n')); assertEquals(false, CharUtils.isAsciiAlphaUpper(CHAR_COPY)); for (int i = 0; i < 196; i++) { if (i >= 'A' && i <= 'Z') { assertEquals(true, CharUtils.isAsciiAlphaUpper((char) i)); } else { assertEquals(false, CharUtils.isAsciiAlphaUpper((char) i)); } } } //----------------------------------------------------------------------- public void testIsAsciiAlphaLower_char() { assertEquals(true, CharUtils.isAsciiAlphaLower('a')); assertEquals(false, CharUtils.isAsciiAlphaLower('A')); assertEquals(false, CharUtils.isAsciiAlphaLower('3')); assertEquals(false, CharUtils.isAsciiAlphaLower('-')); assertEquals(false, CharUtils.isAsciiAlphaLower('\n')); assertEquals(false, CharUtils.isAsciiAlphaLower(CHAR_COPY)); for (int i = 0; i < 196; i++) { if (i >= 'a' && i <= 'z') { assertEquals(true, CharUtils.isAsciiAlphaLower((char) i)); } else { assertEquals(false, CharUtils.isAsciiAlphaLower((char) i)); } } } //----------------------------------------------------------------------- public void testIsAsciiNumeric_char() { assertEquals(false, CharUtils.isAsciiNumeric('a')); assertEquals(false, CharUtils.isAsciiNumeric('A')); assertEquals(true, CharUtils.isAsciiNumeric('3')); assertEquals(false, CharUtils.isAsciiNumeric('-')); assertEquals(false, CharUtils.isAsciiNumeric('\n')); assertEquals(false, CharUtils.isAsciiNumeric(CHAR_COPY)); for (int i = 0; i < 196; i++) { if (i >= '0' && i <= '9') { assertEquals(true, CharUtils.isAsciiNumeric((char) i)); } else { assertEquals(false, CharUtils.isAsciiNumeric((char) i)); } } } //----------------------------------------------------------------------- public void testIsAsciiAlphanumeric_char() { assertEquals(true, CharUtils.isAsciiAlphanumeric('a')); assertEquals(true, CharUtils.isAsciiAlphanumeric('A')); assertEquals(true, CharUtils.isAsciiAlphanumeric('3')); assertEquals(false, CharUtils.isAsciiAlphanumeric('-')); assertEquals(false, CharUtils.isAsciiAlphanumeric('\n')); assertEquals(false, CharUtils.isAsciiAlphanumeric(CHAR_COPY)); for (int i = 0; i < 196; i++) { if ((i >= 'A' && i <= 'Z') || (i >= 'a' && i <= 'z') || (i >= '0' && i <= '9')) { assertEquals(true, CharUtils.isAsciiAlphanumeric((char) i)); } else { assertEquals(false, CharUtils.isAsciiAlphanumeric((char) i)); } } } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/ClassUtilsTest.java100644 0 0 130501 11513702440 24610 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import junit.framework.TestCase; /** * Unit tests {@link org.apache.commons.lang.ClassUtils}. * * @author Apache Software Foundation * @author Gary D. Gregory * @author Tomasz Blachowicz * @version $Id: ClassUtilsTest.java 1056767 2011-01-08 19:11:50Z niallp $ */ public class ClassUtilsTest extends TestCase { public ClassUtilsTest(String name) { super(name); } private static class Inner { private class DeeplyNested{} } //----------------------------------------------------------------------- public void testConstructor() { assertNotNull(new ClassUtils()); Constructor[] cons = ClassUtils.class.getDeclaredConstructors(); assertEquals(1, cons.length); assertEquals(true, Modifier.isPublic(cons[0].getModifiers())); assertEquals(true, Modifier.isPublic(ClassUtils.class.getModifiers())); assertEquals(false, Modifier.isFinal(ClassUtils.class.getModifiers())); } // ------------------------------------------------------------------------- public void test_getShortClassName_Object() { assertEquals("ClassUtils", ClassUtils.getShortClassName(new ClassUtils(), "")); assertEquals("ClassUtilsTest.Inner", ClassUtils.getShortClassName(new Inner(), "")); assertEquals("String", ClassUtils.getShortClassName("hello", "")); assertEquals("", ClassUtils.getShortClassName(null, "")); } public void test_getShortClassName_Class() { assertEquals("ClassUtils", ClassUtils.getShortClassName(ClassUtils.class)); assertEquals("Map.Entry", ClassUtils.getShortClassName(Map.Entry.class)); assertEquals("", ClassUtils.getShortClassName((Class) null)); // LANG-535 assertEquals("String[]", ClassUtils.getShortClassName(String[].class)); assertEquals("Map.Entry[]", ClassUtils.getShortClassName(Map.Entry[].class)); // Primitives assertEquals("boolean", ClassUtils.getShortClassName(boolean.class)); assertEquals("byte", ClassUtils.getShortClassName(byte.class)); assertEquals("char", ClassUtils.getShortClassName(char.class)); assertEquals("short", ClassUtils.getShortClassName(short.class)); assertEquals("int", ClassUtils.getShortClassName(int.class)); assertEquals("long", ClassUtils.getShortClassName(long.class)); assertEquals("float", ClassUtils.getShortClassName(float.class)); assertEquals("double", ClassUtils.getShortClassName(double.class)); // Primitive Arrays assertEquals("boolean[]", ClassUtils.getShortClassName(boolean[].class)); assertEquals("byte[]", ClassUtils.getShortClassName(byte[].class)); assertEquals("char[]", ClassUtils.getShortClassName(char[].class)); assertEquals("short[]", ClassUtils.getShortClassName(short[].class)); assertEquals("int[]", ClassUtils.getShortClassName(int[].class)); assertEquals("long[]", ClassUtils.getShortClassName(long[].class)); assertEquals("float[]", ClassUtils.getShortClassName(float[].class)); assertEquals("double[]", ClassUtils.getShortClassName(double[].class)); // Arrays of arrays of ... assertEquals("String[][]", ClassUtils.getShortClassName(String[][].class)); assertEquals("String[][][]", ClassUtils.getShortClassName(String[][][].class)); assertEquals("String[][][][]", ClassUtils.getShortClassName(String[][][][].class)); } public void test_getShortClassName_String() { assertEquals("ClassUtils", ClassUtils.getShortClassName(ClassUtils.class.getName())); assertEquals("Map.Entry", ClassUtils.getShortClassName(Map.Entry.class.getName())); assertEquals("", ClassUtils.getShortClassName((String) null)); assertEquals("", ClassUtils.getShortClassName("")); } // ------------------------------------------------------------------------- public void test_getPackageName_Object() { assertEquals("org.apache.commons.lang", ClassUtils.getPackageName(new ClassUtils(), "")); assertEquals("org.apache.commons.lang", ClassUtils.getPackageName(new Inner(), "")); assertEquals("", ClassUtils.getPackageName(null, "")); } public void test_getPackageName_Class() { assertEquals("java.lang", ClassUtils.getPackageName(String.class)); assertEquals("java.util", ClassUtils.getPackageName(Map.Entry.class)); assertEquals("", ClassUtils.getPackageName((Class)null)); // LANG-535 assertEquals("java.lang", ClassUtils.getPackageName(String[].class)); // Primitive Arrays assertEquals("", ClassUtils.getPackageName(boolean[].class)); assertEquals("", ClassUtils.getPackageName(byte[].class)); assertEquals("", ClassUtils.getPackageName(char[].class)); assertEquals("", ClassUtils.getPackageName(short[].class)); assertEquals("", ClassUtils.getPackageName(int[].class)); assertEquals("", ClassUtils.getPackageName(long[].class)); assertEquals("", ClassUtils.getPackageName(float[].class)); assertEquals("", ClassUtils.getPackageName(double[].class)); // Arrays of arrays of ... assertEquals("java.lang", ClassUtils.getPackageName(String[][].class)); assertEquals("java.lang", ClassUtils.getPackageName(String[][][].class)); assertEquals("java.lang", ClassUtils.getPackageName(String[][][][].class)); } public void test_getPackageName_String() { assertEquals("org.apache.commons.lang", ClassUtils.getPackageName(ClassUtils.class.getName())); assertEquals("java.util", ClassUtils.getPackageName(Map.Entry.class.getName())); assertEquals("", ClassUtils.getPackageName((String)null)); assertEquals("", ClassUtils.getPackageName("")); } // ------------------------------------------------------------------------- public void test_getAllSuperclasses_Class() { List list = ClassUtils.getAllSuperclasses(CY.class); assertEquals(2, list.size()); assertEquals(CX.class, list.get(0)); assertEquals(Object.class, list.get(1)); assertEquals(null, ClassUtils.getAllSuperclasses(null)); } public void test_getAllInterfaces_Class() { List list = ClassUtils.getAllInterfaces(CY.class); assertEquals(6, list.size()); assertEquals(IB.class, list.get(0)); assertEquals(IC.class, list.get(1)); assertEquals(ID.class, list.get(2)); assertEquals(IE.class, list.get(3)); assertEquals(IF.class, list.get(4)); assertEquals(IA.class, list.get(5)); assertEquals(null, ClassUtils.getAllInterfaces(null)); } private static interface IA { } private static interface IB { } private static interface IC extends ID, IE { } private static interface ID { } private static interface IE extends IF { } private static interface IF { } private static class CX implements IB, IA, IE { } private static class CY extends CX implements IB, IC { } // ------------------------------------------------------------------------- public void test_convertClassNamesToClasses_List() { List list = new ArrayList(); List result = ClassUtils.convertClassNamesToClasses(list); assertEquals(0, result.size()); list.add("java.lang.String"); list.add("java.lang.xxx"); list.add("java.lang.Object"); result = ClassUtils.convertClassNamesToClasses(list); assertEquals(3, result.size()); assertEquals(String.class, result.get(0)); assertEquals(null, result.get(1)); assertEquals(Object.class, result.get(2)); list.add(new Object()); try { ClassUtils.convertClassNamesToClasses(list); fail("Should not have been able to convert list"); } catch (ClassCastException expected) {} assertEquals(null, ClassUtils.convertClassNamesToClasses(null)); } public void test_convertClassesToClassNames_List() { List list = new ArrayList(); List result = ClassUtils.convertClassesToClassNames(list); assertEquals(0, result.size()); list.add(String.class); list.add(null); list.add(Object.class); result = ClassUtils.convertClassesToClassNames(list); assertEquals(3, result.size()); assertEquals("java.lang.String", result.get(0)); assertEquals(null, result.get(1)); assertEquals("java.lang.Object", result.get(2)); list.add(new Object()); try { ClassUtils.convertClassesToClassNames(list); fail("Should not have been able to convert list"); } catch (ClassCastException expected) {} assertEquals(null, ClassUtils.convertClassesToClassNames(null)); } // ------------------------------------------------------------------------- public void test_isInnerClass_Class() { assertEquals(true, ClassUtils.isInnerClass(Inner.class)); assertEquals(true, ClassUtils.isInnerClass(Map.Entry.class)); assertEquals(true, ClassUtils.isInnerClass(new Cloneable() { }.getClass())); assertEquals(false, ClassUtils.isInnerClass(this.getClass())); assertEquals(false, ClassUtils.isInnerClass(String.class)); assertEquals(false, ClassUtils.isInnerClass(null)); } // ------------------------------------------------------------------------- public void test_isAssignable_ClassArray_ClassArray() throws Exception { Class[] array2 = new Class[] {Object.class, Object.class}; Class[] array1 = new Class[] {Object.class}; Class[] array1s = new Class[] {String.class}; Class[] array0 = new Class[] {}; assertFalse(ClassUtils.isAssignable(array1, array2)); assertFalse(ClassUtils.isAssignable(null, array2)); assertTrue(ClassUtils.isAssignable(null, array0)); assertTrue(ClassUtils.isAssignable(array0, array0)); assertTrue(ClassUtils.isAssignable(array0, null)); assertTrue(ClassUtils.isAssignable((Class[]) null, (Class[]) null)); assertFalse(ClassUtils.isAssignable(array1, array1s)); assertTrue(ClassUtils.isAssignable(array1s, array1s)); assertTrue(ClassUtils.isAssignable(array1s, array1)); } public void test_isAssignable() throws Exception { assertFalse(ClassUtils.isAssignable((Class) null, null)); assertFalse(ClassUtils.isAssignable(String.class, null)); assertTrue(ClassUtils.isAssignable(null, Object.class)); assertTrue(ClassUtils.isAssignable(null, Integer.class)); assertFalse(ClassUtils.isAssignable(null, Integer.TYPE)); assertTrue(ClassUtils.isAssignable(String.class, Object.class)); assertTrue(ClassUtils.isAssignable(String.class, String.class)); assertFalse(ClassUtils.isAssignable(Object.class, String.class)); assertFalse(ClassUtils.isAssignable(Integer.TYPE, Integer.class)); assertFalse(ClassUtils.isAssignable(Integer.class, Integer.TYPE)); assertTrue(ClassUtils.isAssignable(Integer.TYPE, Integer.TYPE)); assertTrue(ClassUtils.isAssignable(Integer.class, Integer.class)); assertFalse(ClassUtils.isAssignable(Boolean.TYPE, Boolean.class)); assertFalse(ClassUtils.isAssignable(Boolean.class, Boolean.TYPE)); assertTrue(ClassUtils.isAssignable(Boolean.TYPE, Boolean.TYPE)); assertTrue(ClassUtils.isAssignable(Boolean.class, Boolean.class)); } public void test_isAssignable_Autoboxing() throws Exception { assertFalse(ClassUtils.isAssignable((Class) null, null, true)); assertFalse(ClassUtils.isAssignable(String.class, null, true)); assertTrue(ClassUtils.isAssignable(null, Object.class, true)); assertTrue(ClassUtils.isAssignable(null, Integer.class, true)); assertFalse(ClassUtils.isAssignable(null, Integer.TYPE, true)); assertTrue(ClassUtils.isAssignable(String.class, Object.class, true)); assertTrue(ClassUtils.isAssignable(String.class, String.class, true)); assertFalse(ClassUtils.isAssignable(Object.class, String.class, true)); assertTrue(ClassUtils.isAssignable(Integer.TYPE, Integer.class, true)); assertTrue(ClassUtils.isAssignable(Integer.class, Integer.TYPE, true)); assertTrue(ClassUtils.isAssignable(Integer.TYPE, Integer.TYPE, true)); assertTrue(ClassUtils.isAssignable(Integer.class, Integer.class, true)); assertTrue(ClassUtils.isAssignable(Boolean.TYPE, Boolean.class, true)); assertTrue(ClassUtils.isAssignable(Boolean.class, Boolean.TYPE, true)); assertTrue(ClassUtils.isAssignable(Boolean.TYPE, Boolean.TYPE, true)); assertTrue(ClassUtils.isAssignable(Boolean.class, Boolean.class, true)); } public void test_isAssignable_Widening() throws Exception { // test byte conversions assertFalse("byte -> char", ClassUtils.isAssignable(Byte.TYPE, Character.TYPE)); assertTrue("byte -> byte", ClassUtils.isAssignable(Byte.TYPE, Byte.TYPE)); assertTrue("byte -> short", ClassUtils.isAssignable(Byte.TYPE, Short.TYPE)); assertTrue("byte -> int", ClassUtils.isAssignable(Byte.TYPE, Integer.TYPE)); assertTrue("byte -> long", ClassUtils.isAssignable(Byte.TYPE, Long.TYPE)); assertTrue("byte -> float", ClassUtils.isAssignable(Byte.TYPE, Float.TYPE)); assertTrue("byte -> double", ClassUtils.isAssignable(Byte.TYPE, Double.TYPE)); assertFalse("byte -> boolean", ClassUtils.isAssignable(Byte.TYPE, Boolean.TYPE)); // test short conversions assertFalse("short -> char", ClassUtils.isAssignable(Short.TYPE, Character.TYPE)); assertFalse("short -> byte", ClassUtils.isAssignable(Short.TYPE, Byte.TYPE)); assertTrue("short -> short", ClassUtils.isAssignable(Short.TYPE, Short.TYPE)); assertTrue("short -> int", ClassUtils.isAssignable(Short.TYPE, Integer.TYPE)); assertTrue("short -> long", ClassUtils.isAssignable(Short.TYPE, Long.TYPE)); assertTrue("short -> float", ClassUtils.isAssignable(Short.TYPE, Float.TYPE)); assertTrue("short -> double", ClassUtils.isAssignable(Short.TYPE, Double.TYPE)); assertFalse("short -> boolean", ClassUtils.isAssignable(Short.TYPE, Boolean.TYPE)); // test char conversions assertTrue("char -> char", ClassUtils.isAssignable(Character.TYPE, Character.TYPE)); assertFalse("char -> byte", ClassUtils.isAssignable(Character.TYPE, Byte.TYPE)); assertFalse("char -> short", ClassUtils.isAssignable(Character.TYPE, Short.TYPE)); assertTrue("char -> int", ClassUtils.isAssignable(Character.TYPE, Integer.TYPE)); assertTrue("char -> long", ClassUtils.isAssignable(Character.TYPE, Long.TYPE)); assertTrue("char -> float", ClassUtils.isAssignable(Character.TYPE, Float.TYPE)); assertTrue("char -> double", ClassUtils.isAssignable(Character.TYPE, Double.TYPE)); assertFalse("char -> boolean", ClassUtils.isAssignable(Character.TYPE, Boolean.TYPE)); // test int conversions assertFalse("int -> char", ClassUtils.isAssignable(Integer.TYPE, Character.TYPE)); assertFalse("int -> byte", ClassUtils.isAssignable(Integer.TYPE, Byte.TYPE)); assertFalse("int -> short", ClassUtils.isAssignable(Integer.TYPE, Short.TYPE)); assertTrue("int -> int", ClassUtils.isAssignable(Integer.TYPE, Integer.TYPE)); assertTrue("int -> long", ClassUtils.isAssignable(Integer.TYPE, Long.TYPE)); assertTrue("int -> float", ClassUtils.isAssignable(Integer.TYPE, Float.TYPE)); assertTrue("int -> double", ClassUtils.isAssignable(Integer.TYPE, Double.TYPE)); assertFalse("int -> boolean", ClassUtils.isAssignable(Integer.TYPE, Boolean.TYPE)); // test long conversions assertFalse("long -> char", ClassUtils.isAssignable(Long.TYPE, Character.TYPE)); assertFalse("long -> byte", ClassUtils.isAssignable(Long.TYPE, Byte.TYPE)); assertFalse("long -> short", ClassUtils.isAssignable(Long.TYPE, Short.TYPE)); assertFalse("long -> int", ClassUtils.isAssignable(Long.TYPE, Integer.TYPE)); assertTrue("long -> long", ClassUtils.isAssignable(Long.TYPE, Long.TYPE)); assertTrue("long -> float", ClassUtils.isAssignable(Long.TYPE, Float.TYPE)); assertTrue("long -> double", ClassUtils.isAssignable(Long.TYPE, Double.TYPE)); assertFalse("long -> boolean", ClassUtils.isAssignable(Long.TYPE, Boolean.TYPE)); // test float conversions assertFalse("float -> char", ClassUtils.isAssignable(Float.TYPE, Character.TYPE)); assertFalse("float -> byte", ClassUtils.isAssignable(Float.TYPE, Byte.TYPE)); assertFalse("float -> short", ClassUtils.isAssignable(Float.TYPE, Short.TYPE)); assertFalse("float -> int", ClassUtils.isAssignable(Float.TYPE, Integer.TYPE)); assertFalse("float -> long", ClassUtils.isAssignable(Float.TYPE, Long.TYPE)); assertTrue("float -> float", ClassUtils.isAssignable(Float.TYPE, Float.TYPE)); assertTrue("float -> double", ClassUtils.isAssignable(Float.TYPE, Double.TYPE)); assertFalse("float -> boolean", ClassUtils.isAssignable(Float.TYPE, Boolean.TYPE)); // test double conversions assertFalse("double -> char", ClassUtils.isAssignable(Double.TYPE, Character.TYPE)); assertFalse("double -> byte", ClassUtils.isAssignable(Double.TYPE, Byte.TYPE)); assertFalse("double -> short", ClassUtils.isAssignable(Double.TYPE, Short.TYPE)); assertFalse("double -> int", ClassUtils.isAssignable(Double.TYPE, Integer.TYPE)); assertFalse("double -> long", ClassUtils.isAssignable(Double.TYPE, Long.TYPE)); assertFalse("double -> float", ClassUtils.isAssignable(Double.TYPE, Float.TYPE)); assertTrue("double -> double", ClassUtils.isAssignable(Double.TYPE, Double.TYPE)); assertFalse("double -> boolean", ClassUtils.isAssignable(Double.TYPE, Boolean.TYPE)); // test boolean conversions assertFalse("boolean -> char", ClassUtils.isAssignable(Boolean.TYPE, Character.TYPE)); assertFalse("boolean -> byte", ClassUtils.isAssignable(Boolean.TYPE, Byte.TYPE)); assertFalse("boolean -> short", ClassUtils.isAssignable(Boolean.TYPE, Short.TYPE)); assertFalse("boolean -> int", ClassUtils.isAssignable(Boolean.TYPE, Integer.TYPE)); assertFalse("boolean -> long", ClassUtils.isAssignable(Boolean.TYPE, Long.TYPE)); assertFalse("boolean -> float", ClassUtils.isAssignable(Boolean.TYPE, Float.TYPE)); assertFalse("boolean -> double", ClassUtils.isAssignable(Boolean.TYPE, Double.TYPE)); assertTrue("boolean -> boolean", ClassUtils.isAssignable(Boolean.TYPE, Boolean.TYPE)); } public void test_isAssignable_Unboxing_Widening() throws Exception { // test byte conversions assertFalse("byte -> char", ClassUtils.isAssignable(Byte.class, Character.TYPE, true)); assertTrue("byte -> byte", ClassUtils.isAssignable(Byte.class, Byte.TYPE, true)); assertTrue("byte -> short", ClassUtils.isAssignable(Byte.class, Short.TYPE, true)); assertTrue("byte -> int", ClassUtils.isAssignable(Byte.class, Integer.TYPE, true)); assertTrue("byte -> long", ClassUtils.isAssignable(Byte.class, Long.TYPE, true)); assertTrue("byte -> float", ClassUtils.isAssignable(Byte.class, Float.TYPE, true)); assertTrue("byte -> double", ClassUtils.isAssignable(Byte.class, Double.TYPE, true)); assertFalse("byte -> boolean", ClassUtils.isAssignable(Byte.class, Boolean.TYPE, true)); // test short conversions assertFalse("short -> char", ClassUtils.isAssignable(Short.class, Character.TYPE, true)); assertFalse("short -> byte", ClassUtils.isAssignable(Short.class, Byte.TYPE, true)); assertTrue("short -> short", ClassUtils.isAssignable(Short.class, Short.TYPE, true)); assertTrue("short -> int", ClassUtils.isAssignable(Short.class, Integer.TYPE, true)); assertTrue("short -> long", ClassUtils.isAssignable(Short.class, Long.TYPE, true)); assertTrue("short -> float", ClassUtils.isAssignable(Short.class, Float.TYPE, true)); assertTrue("short -> double", ClassUtils.isAssignable(Short.class, Double.TYPE, true)); assertFalse("short -> boolean", ClassUtils.isAssignable(Short.class, Boolean.TYPE, true)); // test char conversions assertTrue("char -> char", ClassUtils.isAssignable(Character.class, Character.TYPE, true)); assertFalse("char -> byte", ClassUtils.isAssignable(Character.class, Byte.TYPE, true)); assertFalse("char -> short", ClassUtils.isAssignable(Character.class, Short.TYPE, true)); assertTrue("char -> int", ClassUtils.isAssignable(Character.class, Integer.TYPE, true)); assertTrue("char -> long", ClassUtils.isAssignable(Character.class, Long.TYPE, true)); assertTrue("char -> float", ClassUtils.isAssignable(Character.class, Float.TYPE, true)); assertTrue("char -> double", ClassUtils.isAssignable(Character.class, Double.TYPE, true)); assertFalse("char -> boolean", ClassUtils.isAssignable(Character.class, Boolean.TYPE, true)); // test int conversions assertFalse("int -> char", ClassUtils.isAssignable(Integer.class, Character.TYPE, true)); assertFalse("int -> byte", ClassUtils.isAssignable(Integer.class, Byte.TYPE, true)); assertFalse("int -> short", ClassUtils.isAssignable(Integer.class, Short.TYPE, true)); assertTrue("int -> int", ClassUtils.isAssignable(Integer.class, Integer.TYPE, true)); assertTrue("int -> long", ClassUtils.isAssignable(Integer.class, Long.TYPE, true)); assertTrue("int -> float", ClassUtils.isAssignable(Integer.class, Float.TYPE, true)); assertTrue("int -> double", ClassUtils.isAssignable(Integer.class, Double.TYPE, true)); assertFalse("int -> boolean", ClassUtils.isAssignable(Integer.class, Boolean.TYPE, true)); // test long conversions assertFalse("long -> char", ClassUtils.isAssignable(Long.class, Character.TYPE, true)); assertFalse("long -> byte", ClassUtils.isAssignable(Long.class, Byte.TYPE, true)); assertFalse("long -> short", ClassUtils.isAssignable(Long.class, Short.TYPE, true)); assertFalse("long -> int", ClassUtils.isAssignable(Long.class, Integer.TYPE, true)); assertTrue("long -> long", ClassUtils.isAssignable(Long.class, Long.TYPE, true)); assertTrue("long -> float", ClassUtils.isAssignable(Long.class, Float.TYPE, true)); assertTrue("long -> double", ClassUtils.isAssignable(Long.class, Double.TYPE, true)); assertFalse("long -> boolean", ClassUtils.isAssignable(Long.class, Boolean.TYPE, true)); // test float conversions assertFalse("float -> char", ClassUtils.isAssignable(Float.class, Character.TYPE, true)); assertFalse("float -> byte", ClassUtils.isAssignable(Float.class, Byte.TYPE, true)); assertFalse("float -> short", ClassUtils.isAssignable(Float.class, Short.TYPE, true)); assertFalse("float -> int", ClassUtils.isAssignable(Float.class, Integer.TYPE, true)); assertFalse("float -> long", ClassUtils.isAssignable(Float.class, Long.TYPE, true)); assertTrue("float -> float", ClassUtils.isAssignable(Float.class, Float.TYPE, true)); assertTrue("float -> double", ClassUtils.isAssignable(Float.class, Double.TYPE, true)); assertFalse("float -> boolean", ClassUtils.isAssignable(Float.class, Boolean.TYPE, true)); // test double conversions assertFalse("double -> char", ClassUtils.isAssignable(Double.class, Character.TYPE, true)); assertFalse("double -> byte", ClassUtils.isAssignable(Double.class, Byte.TYPE, true)); assertFalse("double -> short", ClassUtils.isAssignable(Double.class, Short.TYPE, true)); assertFalse("double -> int", ClassUtils.isAssignable(Double.class, Integer.TYPE, true)); assertFalse("double -> long", ClassUtils.isAssignable(Double.class, Long.TYPE, true)); assertFalse("double -> float", ClassUtils.isAssignable(Double.class, Float.TYPE, true)); assertTrue("double -> double", ClassUtils.isAssignable(Double.class, Double.TYPE, true)); assertFalse("double -> boolean", ClassUtils.isAssignable(Double.class, Boolean.TYPE, true)); // test boolean conversions assertFalse("boolean -> char", ClassUtils.isAssignable(Boolean.class, Character.TYPE, true)); assertFalse("boolean -> byte", ClassUtils.isAssignable(Boolean.class, Byte.TYPE, true)); assertFalse("boolean -> short", ClassUtils.isAssignable(Boolean.class, Short.TYPE, true)); assertFalse("boolean -> int", ClassUtils.isAssignable(Boolean.class, Integer.TYPE, true)); assertFalse("boolean -> long", ClassUtils.isAssignable(Boolean.class, Long.TYPE, true)); assertFalse("boolean -> float", ClassUtils.isAssignable(Boolean.class, Float.TYPE, true)); assertFalse("boolean -> double", ClassUtils.isAssignable(Boolean.class, Double.TYPE, true)); assertTrue("boolean -> boolean", ClassUtils.isAssignable(Boolean.class, Boolean.TYPE, true)); } public void testPrimitiveToWrapper() { // test primitive classes assertEquals("boolean -> Boolean.class", Boolean.class, ClassUtils.primitiveToWrapper(Boolean.TYPE)); assertEquals("byte -> Byte.class", Byte.class, ClassUtils.primitiveToWrapper(Byte.TYPE)); assertEquals("char -> Character.class", Character.class, ClassUtils.primitiveToWrapper(Character.TYPE)); assertEquals("short -> Short.class", Short.class, ClassUtils.primitiveToWrapper(Short.TYPE)); assertEquals("int -> Integer.class", Integer.class, ClassUtils.primitiveToWrapper(Integer.TYPE)); assertEquals("long -> Long.class", Long.class, ClassUtils.primitiveToWrapper(Long.TYPE)); assertEquals("double -> Double.class", Double.class, ClassUtils.primitiveToWrapper(Double.TYPE)); assertEquals("float -> Float.class", Float.class, ClassUtils.primitiveToWrapper(Float.TYPE)); // test a few other classes assertEquals("String.class -> String.class", String.class, ClassUtils.primitiveToWrapper(String.class)); assertEquals("ClassUtils.class -> ClassUtils.class", org.apache.commons.lang.ClassUtils.class, ClassUtils.primitiveToWrapper(org.apache.commons.lang.ClassUtils.class)); assertEquals("Void.TYPE -> Void.TYPE", Void.TYPE, ClassUtils.primitiveToWrapper(Void.TYPE)); // test null assertNull("null -> null", ClassUtils.primitiveToWrapper(null)); } public void testPrimitivesToWrappers() { // test null assertNull("null -> null", ClassUtils.primitivesToWrappers(null)); // test empty array assertEquals("empty -> empty", ArrayUtils.EMPTY_CLASS_ARRAY, ClassUtils.primitivesToWrappers(ArrayUtils.EMPTY_CLASS_ARRAY)); // test an array of various classes final Class[] primitives = new Class[] { Boolean.TYPE, Byte.TYPE, Character.TYPE, Short.TYPE, Integer.TYPE, Long.TYPE, Double.TYPE, Float.TYPE, String.class, ClassUtils.class }; Class[] wrappers= ClassUtils.primitivesToWrappers(primitives); for (int i=0; i < primitives.length; i++) { // test each returned wrapper Class primitive = primitives[i]; Class expectedWrapper = ClassUtils.primitiveToWrapper(primitive); assertEquals(primitive + " -> " + expectedWrapper, expectedWrapper, wrappers[i]); } // test an array of no primitive classes final Class[] noPrimitives = new Class[] { String.class, ClassUtils.class, Void.TYPE }; // This used to return the exact same array, but no longer does. assertNotSame("unmodified", noPrimitives, ClassUtils.primitivesToWrappers(noPrimitives)); } public void testWrapperToPrimitive() { // an array with classes to convert final Class[] primitives = { Boolean.TYPE, Byte.TYPE, Character.TYPE, Short.TYPE, Integer.TYPE, Long.TYPE, Float.TYPE, Double.TYPE }; for (int i = 0; i < primitives.length; i++) { Class wrapperCls = ClassUtils.primitiveToWrapper(primitives[i]); assertFalse("Still primitive", wrapperCls.isPrimitive()); assertEquals(wrapperCls + " -> " + primitives[i], primitives[i], ClassUtils.wrapperToPrimitive(wrapperCls)); } } public void testWrapperToPrimitiveNoWrapper() { assertNull("Wrong result for non wrapper class", ClassUtils.wrapperToPrimitive(String.class)); } public void testWrapperToPrimitiveNull() { assertNull("Wrong result for null class", ClassUtils.wrapperToPrimitive(null)); } public void testWrappersToPrimitives() { // an array with classes to test final Class[] classes = { Boolean.class, Byte.class, Character.class, Short.class, Integer.class, Long.class, Float.class, Double.class, String.class, ClassUtils.class, null }; Class[] primitives = ClassUtils.wrappersToPrimitives(classes); // now test the result assertEquals("Wrong length of result array", classes.length, primitives.length); for (int i = 0; i < classes.length; i++) { Class expectedPrimitive = ClassUtils.wrapperToPrimitive(classes[i]); assertEquals(classes[i] + " -> " + expectedPrimitive, expectedPrimitive, primitives[i]); } } public void testWrappersToPrimitivesNull() { assertNull("Wrong result for null input", ClassUtils.wrappersToPrimitives(null)); } public void testWrappersToPrimitivesEmpty() { Class[] empty = new Class[0]; assertEquals("Wrong result for empty input", empty, ClassUtils.wrappersToPrimitives(empty)); } public void testGetClassClassNotFound() throws Exception { assertGetClassThrowsClassNotFound( "bool" ); assertGetClassThrowsClassNotFound( "bool[]" ); assertGetClassThrowsClassNotFound( "integer[]" ); } public void testGetClassInvalidArguments() throws Exception { assertGetClassThrowsIllegalArgument( null ); assertGetClassThrowsClassNotFound( "[][][]" ); assertGetClassThrowsClassNotFound( "[[]" ); assertGetClassThrowsClassNotFound( "[" ); assertGetClassThrowsClassNotFound( "java.lang.String][" ); assertGetClassThrowsClassNotFound( ".hello.world" ); assertGetClassThrowsClassNotFound( "hello..world" ); } public void testWithInterleavingWhitespace() throws ClassNotFoundException { assertEquals( int[].class, ClassUtils.getClass( " int [ ] " ) ); assertEquals( long[].class, ClassUtils.getClass( "\rlong\t[\n]\r" ) ); assertEquals( short[].class, ClassUtils.getClass( "\tshort \t\t[]" ) ); assertEquals( byte[].class, ClassUtils.getClass( "byte[\t\t\n\r] " ) ); } public void testGetInnerClass() throws ClassNotFoundException { assertEquals( Inner.DeeplyNested.class, ClassUtils.getClass( "org.apache.commons.lang.ClassUtilsTest.Inner.DeeplyNested" ) ); assertEquals( Inner.DeeplyNested.class, ClassUtils.getClass( "org.apache.commons.lang.ClassUtilsTest.Inner$DeeplyNested" ) ); assertEquals( Inner.DeeplyNested.class, ClassUtils.getClass( "org.apache.commons.lang.ClassUtilsTest$Inner$DeeplyNested" ) ); assertEquals( Inner.DeeplyNested.class, ClassUtils.getClass( "org.apache.commons.lang.ClassUtilsTest$Inner.DeeplyNested" ) ); } public void testGetClassByNormalNameArrays() throws ClassNotFoundException { assertEquals( int[].class, ClassUtils.getClass( "int[]" ) ); assertEquals( long[].class, ClassUtils.getClass( "long[]" ) ); assertEquals( short[].class, ClassUtils.getClass( "short[]" ) ); assertEquals( byte[].class, ClassUtils.getClass( "byte[]" ) ); assertEquals( char[].class, ClassUtils.getClass( "char[]" ) ); assertEquals( float[].class, ClassUtils.getClass( "float[]" ) ); assertEquals( double[].class, ClassUtils.getClass( "double[]" ) ); assertEquals( boolean[].class, ClassUtils.getClass( "boolean[]" ) ); assertEquals( String[].class, ClassUtils.getClass( "java.lang.String[]" ) ); assertEquals( java.util.Map.Entry[].class, ClassUtils.getClass( "java.util.Map.Entry[]" ) ); assertEquals( java.util.Map.Entry[].class, ClassUtils.getClass( "java.util.Map$Entry[]" ) ); assertEquals( java.util.Map.Entry[].class, ClassUtils.getClass( "[Ljava.util.Map.Entry;" ) ); assertEquals( java.util.Map.Entry[].class, ClassUtils.getClass( "[Ljava.util.Map$Entry;" ) ); } public void testGetClassByNormalNameArrays2D() throws ClassNotFoundException { assertEquals( int[][].class, ClassUtils.getClass( "int[][]" ) ); assertEquals( long[][].class, ClassUtils.getClass( "long[][]" ) ); assertEquals( short[][].class, ClassUtils.getClass( "short[][]" ) ); assertEquals( byte[][].class, ClassUtils.getClass( "byte[][]" ) ); assertEquals( char[][].class, ClassUtils.getClass( "char[][]" ) ); assertEquals( float[][].class, ClassUtils.getClass( "float[][]" ) ); assertEquals( double[][].class, ClassUtils.getClass( "double[][]" ) ); assertEquals( boolean[][].class, ClassUtils.getClass( "boolean[][]" ) ); assertEquals( String[][].class, ClassUtils.getClass( "java.lang.String[][]" ) ); } public void testGetClassWithArrayClasses2D() throws Exception { assertGetClassReturnsClass( String[][].class ); assertGetClassReturnsClass( int[][].class ); assertGetClassReturnsClass( long[][].class ); assertGetClassReturnsClass( short[][].class ); assertGetClassReturnsClass( byte[][].class ); assertGetClassReturnsClass( char[][].class ); assertGetClassReturnsClass( float[][].class ); assertGetClassReturnsClass( double[][].class ); assertGetClassReturnsClass( boolean[][].class ); } public void testGetClassWithArrayClasses() throws Exception { assertGetClassReturnsClass( String[].class ); assertGetClassReturnsClass( int[].class ); assertGetClassReturnsClass( long[].class ); assertGetClassReturnsClass( short[].class ); assertGetClassReturnsClass( byte[].class ); assertGetClassReturnsClass( char[].class ); assertGetClassReturnsClass( float[].class ); assertGetClassReturnsClass( double[].class ); assertGetClassReturnsClass( boolean[].class ); } public void testGetClassRawPrimitives() throws ClassNotFoundException { assertEquals( int.class, ClassUtils.getClass( "int" ) ); assertEquals( long.class, ClassUtils.getClass( "long" ) ); assertEquals( short.class, ClassUtils.getClass( "short" ) ); assertEquals( byte.class, ClassUtils.getClass( "byte" ) ); assertEquals( char.class, ClassUtils.getClass( "char" ) ); assertEquals( float.class, ClassUtils.getClass( "float" ) ); assertEquals( double.class, ClassUtils.getClass( "double" ) ); assertEquals( boolean.class, ClassUtils.getClass( "boolean" ) ); } private void assertGetClassReturnsClass( Class c ) throws Exception { assertEquals( c, ClassUtils.getClass( c.getName() ) ); } private void assertGetClassThrowsException( String className, Class exceptionType ) throws Exception { try { ClassUtils.getClass( className ); fail( "ClassUtils.getClass() should fail with an exception of type " + exceptionType.getName() + " when given class name \"" + className + "\"." ); } catch( Exception e ) { assertTrue( exceptionType.isAssignableFrom( e.getClass() ) ); } } private void assertGetClassThrowsIllegalArgument( String className ) throws Exception { assertGetClassThrowsException( className, IllegalArgumentException.class ); } private void assertGetClassThrowsClassNotFound( String className ) throws Exception { assertGetClassThrowsException( className, ClassNotFoundException.class ); } // Show the Java bug: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4071957 // We may have to delete this if a JDK fixes the bug. public void testShowJavaBug() throws Exception { // Tests with Collections$UnmodifiableSet Set set = Collections.unmodifiableSet(new HashSet()); Method isEmptyMethod = set.getClass().getMethod("isEmpty", new Class[0]); try { isEmptyMethod.invoke(set, new Object[0]); fail("Failed to throw IllegalAccessException as expected"); } catch(IllegalAccessException iae) { // expected } } public void testGetPublicMethod() throws Exception { // Tests with Collections$UnmodifiableSet Set set = Collections.unmodifiableSet(new HashSet()); Method isEmptyMethod = ClassUtils.getPublicMethod(set.getClass(), "isEmpty", new Class[0]); assertTrue(Modifier.isPublic(isEmptyMethod.getDeclaringClass().getModifiers())); try { isEmptyMethod.invoke(set, new Object[0]); } catch(java.lang.IllegalAccessException iae) { fail("Should not have thrown IllegalAccessException"); } // Tests with a public Class Method toStringMethod = ClassUtils.getPublicMethod(Object.class, "toString", new Class[0]); assertEquals(Object.class.getMethod("toString", new Class[0]), toStringMethod); } public void testToClass_object() { assertNull(ClassUtils.toClass(null)); assertSame(ArrayUtils.EMPTY_CLASS_ARRAY, ClassUtils.toClass(ArrayUtils.EMPTY_OBJECT_ARRAY)); assertTrue(Arrays.equals(new Class[] { String.class, Integer.class, Double.class }, ClassUtils.toClass(new Object[] { "Test", new Integer(1), new Double(99d) }))); assertTrue(Arrays.equals(new Class[] { String.class, null, Double.class }, ClassUtils.toClass(new Object[] { "Test", null, new Double(99d) }))); } public void test_getShortCanonicalName_Object() { assertEquals("", ClassUtils.getShortCanonicalName(null, "")); assertEquals("ClassUtils", ClassUtils.getShortCanonicalName(new ClassUtils(), "")); assertEquals("ClassUtils[]", ClassUtils.getShortCanonicalName(new ClassUtils[0], "")); assertEquals("ClassUtils[][]", ClassUtils.getShortCanonicalName(new ClassUtils[0][0], "")); assertEquals("int[]", ClassUtils.getShortCanonicalName(new int[0], "")); assertEquals("int[][]", ClassUtils.getShortCanonicalName(new int[0][0], "")); } public void test_getShortCanonicalName_Class() { assertEquals("ClassUtils", ClassUtils.getShortCanonicalName(ClassUtils.class)); assertEquals("ClassUtils[]", ClassUtils.getShortCanonicalName(ClassUtils[].class)); assertEquals("ClassUtils[][]", ClassUtils.getShortCanonicalName(ClassUtils[][].class)); assertEquals("int[]", ClassUtils.getShortCanonicalName(int[].class)); assertEquals("int[][]", ClassUtils.getShortCanonicalName(int[][].class)); } public void test_getShortCanonicalName_String() { assertEquals("ClassUtils", ClassUtils.getShortCanonicalName("org.apache.commons.lang.ClassUtils")); assertEquals("ClassUtils[]", ClassUtils.getShortCanonicalName("[Lorg.apache.commons.lang.ClassUtils;")); assertEquals("ClassUtils[][]", ClassUtils.getShortCanonicalName("[[Lorg.apache.commons.lang.ClassUtils;")); assertEquals("ClassUtils[]", ClassUtils.getShortCanonicalName("org.apache.commons.lang.ClassUtils[]")); assertEquals("ClassUtils[][]", ClassUtils.getShortCanonicalName("org.apache.commons.lang.ClassUtils[][]")); assertEquals("int[]", ClassUtils.getShortCanonicalName("[I")); assertEquals("int[][]", ClassUtils.getShortCanonicalName("[[I")); assertEquals("int[]", ClassUtils.getShortCanonicalName("int[]")); assertEquals("int[][]", ClassUtils.getShortCanonicalName("int[][]")); } public void test_getPackageCanonicalName_Object() { assertEquals("", ClassUtils.getPackageCanonicalName(null, "")); assertEquals("org.apache.commons.lang", ClassUtils.getPackageCanonicalName(new ClassUtils(), "")); assertEquals("org.apache.commons.lang", ClassUtils.getPackageCanonicalName(new ClassUtils[0], "")); assertEquals("org.apache.commons.lang", ClassUtils.getPackageCanonicalName(new ClassUtils[0][0], "")); assertEquals("", ClassUtils.getPackageCanonicalName(new int[0], "")); assertEquals("", ClassUtils.getPackageCanonicalName(new int[0][0], "")); } public void test_getPackageCanonicalName_Class() { assertEquals("org.apache.commons.lang", ClassUtils.getPackageCanonicalName(ClassUtils.class)); assertEquals("org.apache.commons.lang", ClassUtils.getPackageCanonicalName(ClassUtils[].class)); assertEquals("org.apache.commons.lang", ClassUtils.getPackageCanonicalName(ClassUtils[][].class)); assertEquals("", ClassUtils.getPackageCanonicalName(int[].class)); assertEquals("", ClassUtils.getPackageCanonicalName(int[][].class)); } public void test_getPackageCanonicalName_String() { assertEquals("org.apache.commons.lang", ClassUtils.getPackageCanonicalName("org.apache.commons.lang.ClassUtils")); assertEquals("org.apache.commons.lang", ClassUtils.getPackageCanonicalName("[Lorg.apache.commons.lang.ClassUtils;")); assertEquals("org.apache.commons.lang", ClassUtils.getPackageCanonicalName("[[Lorg.apache.commons.lang.ClassUtils;")); assertEquals("org.apache.commons.lang", ClassUtils.getPackageCanonicalName("org.apache.commons.lang.ClassUtils[]")); assertEquals("org.apache.commons.lang", ClassUtils.getPackageCanonicalName("org.apache.commons.lang.ClassUtils[][]")); assertEquals("", ClassUtils.getPackageCanonicalName("[I")); assertEquals("", ClassUtils.getPackageCanonicalName("[[I")); assertEquals("", ClassUtils.getPackageCanonicalName("int[]")); assertEquals("", ClassUtils.getPackageCanonicalName("int[][]")); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/EntitiesPerformanceTest.java100644 0 0 14032 11513702441 26451 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang; import junit.framework.TestCase; public class EntitiesPerformanceTest extends TestCase { private int COUNT = 10000; private int STRING_LENGTH = 1000; private static String stringWithUnicode; private static String stringWithEntities; private static Entities treeEntities; private static Entities hashEntities; private static Entities arrayEntities; private static Entities binaryEntities; private static Entities primitiveEntities; private static Entities lookupEntities; public EntitiesPerformanceTest(String name) { super(name); } public void setUp() { if (stringWithUnicode == null) { StringBuffer buf = new StringBuffer(STRING_LENGTH); for (int i = 0; i < STRING_LENGTH / 5; ++i) { buf.append("xxxx"); char ch = isovalue(i); buf.append(ch); } stringWithUnicode = buf.toString(); stringWithEntities = Entities.HTML40.unescape(stringWithUnicode); } } private char html40value(int i) { String entityValue = Entities.HTML40_ARRAY[i % Entities.HTML40_ARRAY.length][1]; char ch = (char) Integer.parseInt(entityValue); return ch; } private char isovalue(int i) { String entityValue = Entities.ISO8859_1_ARRAY[i % Entities.ISO8859_1_ARRAY.length][1]; char ch = (char) Integer.parseInt(entityValue); return ch; } public void testBuildHash() throws Exception { for (int i = 0; i < COUNT; ++i) { hashEntities = build(new Entities.HashEntityMap()); } } public void testBuildTree() throws Exception { for (int i = 0; i < COUNT; ++i) { treeEntities = build(new Entities.TreeEntityMap()); } } public void testBuildArray() throws Exception { for (int i = 0; i < COUNT; ++i) { arrayEntities = build(new Entities.ArrayEntityMap()); } } public void testBuildBinary() throws Exception { for (int i = 0; i < COUNT; ++i) { binaryEntities = build(new Entities.BinaryEntityMap()); } } public void testBuildPrimitive() throws Exception { for (int i = 0; i < COUNT; ++i) { buildPrimitive(); } } private void buildPrimitive() { primitiveEntities = build(new Entities.PrimitiveEntityMap()); } public void testBuildLookup() throws Exception { for (int i = 0; i < COUNT; ++i) { buildLookup(); } } private void buildLookup() { lookupEntities = build(new Entities.LookupEntityMap()); } private Entities build(Entities.EntityMap intMap) { Entities entities = new Entities(intMap); Entities.fillWithHtml40Entities(entities); return entities; } public void testLookupHash() throws Exception { lookup(hashEntities); } public void testLookupTree() throws Exception { lookup(treeEntities); } public void testLookupArray() throws Exception { lookup(arrayEntities); } public void testLookupBinary() throws Exception { lookup(binaryEntities); } public void testLookupPrimitive() throws Exception { if (primitiveEntities == null) buildPrimitive(); lookup(primitiveEntities); } public void testLookupLookup() throws Exception { if (lookupEntities == null) buildLookup(); lookup(lookupEntities); } public void testEscapeHash() throws Exception { escapeIt(hashEntities); } public void testEscapeTree() throws Exception { escapeIt(treeEntities); } public void testEscapeArray() throws Exception { escapeIt(arrayEntities); } public void testEscapeBinary() throws Exception { escapeIt(binaryEntities); } public void testEscapePrimitive() throws Exception { escapeIt(primitiveEntities); } public void testEscapeLookup() throws Exception { escapeIt(lookupEntities); } public void testUnescapeHash() throws Exception { unescapeIt(hashEntities); } public void testUnescapeTree() throws Exception { unescapeIt(treeEntities); } public void testUnescapeArray() throws Exception { unescapeIt(arrayEntities); } public void testUnescapeBinary() throws Exception { unescapeIt(binaryEntities); } private void lookup(Entities entities) { for (int i = 0; i < COUNT * 1000; ++i) { entities.entityName(isovalue(i)); } } private void escapeIt(Entities entities) { for (int i = 0; i < COUNT; ++i) { String escaped = entities.escape(stringWithUnicode); assertEquals("xxxx ", escaped.substring(0, 10)); } } private void unescapeIt(Entities entities) { for (int i = 0; i < COUNT; ++i) { String unescaped = entities.unescape(stringWithEntities); assertEquals("xxxx\u00A0", unescaped.substring(0, 5)); } } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/EntitiesTest.java100644 0 0 15352 11513702441 24275 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang; import java.io.StringWriter; import junit.framework.TestCase; /** * Unit tests for {@link StringEscapeUtils}. * * @author Alexander Day Chaffee * @author Gary Gregory * @version $Id: EntitiesTest.java 905846 2010-02-03 00:20:01Z niallp $ */ public class EntitiesTest extends TestCase { public EntitiesTest(String name) { super(name); } Entities entities; public void setUp() { entities = new Entities(); entities.addEntity("foo", 161); entities.addEntity("bar", 162); } public void testEscapeNamedEntity() throws Exception { doTestEscapeNamedEntity("&foo;", "\u00A1"); doTestEscapeNamedEntity("x&foo;", "x\u00A1"); doTestEscapeNamedEntity("&foo;x", "\u00A1x"); doTestEscapeNamedEntity("x&foo;x", "x\u00A1x"); doTestEscapeNamedEntity("&foo;&bar;", "\u00A1\u00A2"); } private void doTestEscapeNamedEntity(final String expected, final String entity) throws Exception { assertEquals(expected, entities.escape(entity)); StringWriter writer = new StringWriter(); entities.escape(writer, entity); assertEquals(expected, writer.toString()); } public void testUnescapeNamedEntity() throws Exception { assertEquals("\u00A1", entities.unescape("&foo;")); assertEquals("x\u00A1", entities.unescape("x&foo;")); assertEquals("\u00A1x", entities.unescape("&foo;x")); assertEquals("x\u00A1x", entities.unescape("x&foo;x")); assertEquals("\u00A1\u00A2", entities.unescape("&foo;&bar;")); } public void testUnescapeUnknownEntity() throws Exception { doTestUnescapeEntity("&zzzz;", "&zzzz;"); } public void testUnescapeMiscellaneous() throws Exception { doTestUnescapeEntity("&hello", "&hello"); doTestUnescapeEntity("&;", "&;"); doTestUnescapeEntity("&#;", "&#;"); doTestUnescapeEntity("&#invalid;", "&#invalid;"); doTestUnescapeEntity("A", "A"); } private void doTestUnescapeEntity(final String expected, final String entity) throws Exception { assertEquals(expected, entities.unescape(entity)); StringWriter writer = new StringWriter(); entities.unescape(writer, entity); assertEquals(expected, writer.toString()); } public void testAddEntitiesArray() throws Exception { String[][] array = {{"foo", "100"}, {"bar", "101"}}; Entities e = new Entities(); e.addEntities(array); assertEquals("foo", e.entityName(100)); assertEquals("bar", e.entityName(101)); assertEquals(100, e.entityValue("foo")); assertEquals(101, e.entityValue("bar")); } public void testEntitiesXmlObject() throws Exception { assertEquals("gt", Entities.XML.entityName('>')); assertEquals('>', Entities.XML.entityValue("gt")); assertEquals(-1, Entities.XML.entityValue("xyzzy")); } public void testArrayIntMap() throws Exception { Entities.ArrayEntityMap map = new Entities.ArrayEntityMap(2); checkSomeEntityMap(map); Entities.ArrayEntityMap map1 = new Entities.ArrayEntityMap(); checkSomeEntityMap(map1); assertEquals(-1, map.value("null")); assertNull(map.name(-1)); } public void testTreeIntMap() throws Exception { Entities.EntityMap map = new Entities.TreeEntityMap(); checkSomeEntityMap(map); } public void testHashIntMap() throws Exception { Entities.EntityMap map = new Entities.HashEntityMap(); checkSomeEntityMap(map); assertEquals(-1, map.value("noname")); } public void testBinaryIntMap() throws Exception { Entities.BinaryEntityMap map = new Entities.BinaryEntityMap(2); checkSomeEntityMap(map); Entities.BinaryEntityMap map1 = new Entities.BinaryEntityMap(); checkSomeEntityMap(map1); // value cannot be added twice map1.add("baz4a", 4); map1.add("baz4b", 4); assertEquals(-1, map1.value("baz4b")); assertEquals("baz4a", map1.name(4)); assertNull(map1.name(99)); Entities.BinaryEntityMap map2 = new Entities.BinaryEntityMap(); map2.add("val1", 1); map2.add("val2", 2); map2.add("val3", 3); map2.add("val4", 4); map2.add("val5", 5); assertEquals("val5", map2.name(5)); assertEquals("val4", map2.name(4)); assertEquals("val3", map2.name(3)); assertEquals("val2", map2.name(2)); assertEquals("val1", map2.name(1)); } public void testPrimitiveIntMap() throws Exception { Entities.PrimitiveEntityMap map = new Entities.PrimitiveEntityMap(); checkSomeEntityMap(map); } private void checkSomeEntityMap(Entities.EntityMap map) { map.add("foo", 1); assertEquals(1, map.value("foo")); assertEquals("foo", map.name(1)); map.add("bar", 2); map.add("baz", 3); assertEquals(3, map.value("baz")); assertEquals("baz", map.name(3)); } public void testHtml40Nbsp() throws Exception { assertEquals(" ", Entities.HTML40.escape("\u00A0")); Entities e = new Entities(new Entities.PrimitiveEntityMap()); Entities.fillWithHtml40Entities(e); assertEquals(" ", e.escape("\u00A0")); } public void testNumberOverflow() throws Exception { doTestUnescapeEntity("�", "�"); doTestUnescapeEntity("x�y", "x�y"); doTestUnescapeEntity("�", "�"); doTestUnescapeEntity("x�y", "x�y"); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/enum/Broken1Enum.java100644 0 0 3516 11513702440 24721 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.enum; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Broken color enumeration. * * @author Apache Software Foundation * @version $Id: Broken1Enum.java 905636 2010-02-02 14:03:32Z niallp $ */ public final class Broken1Enum extends Enum { public static final Broken1Enum RED = new Broken1Enum("Red"); public static final Broken1Enum GREEN = new Broken1Enum("Green"); public static final Broken1Enum GREENISH = new Broken1Enum("Green"); // duplicate not allowed private Broken1Enum(String color) { super(color); } public static Broken1Enum getEnum(String color) { return (Broken1Enum) getEnum(Broken1Enum.class, color); } public static Map getEnumMap() { return getEnumMap(Broken1Enum.class); } public static List getEnumList() { return getEnumList(Broken1Enum.class); } public static Iterator iterator() { return iterator(Broken1Enum.class); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/enum/Broken1OperationEnum.java100644 0 0 5547 11513702440 26610 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.enum; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Broken Operator enumeration, null class. * * @author Apache Software Foundation * @version $Id: Broken1OperationEnum.java 905636 2010-02-02 14:03:32Z niallp $ */ public abstract class Broken1OperationEnum extends Enum { // This syntax works for JDK 1.3 and upwards: // public static final OperationEnum PLUS = new OperationEnum("Plus") { // public int eval(int a, int b) { // return (a + b); // } // }; // public static final OperationEnum MINUS = new OperationEnum("Minus") { // public int eval(int a, int b) { // return (a - b); // } // }; // This syntax works for JDK 1.2 and upwards: public static final Broken1OperationEnum PLUS = new PlusOperation(); private static class PlusOperation extends Broken1OperationEnum { private PlusOperation() { super("Plus"); } public int eval(int a, int b) { return (a + b); } } public static final Broken1OperationEnum MINUS = new MinusOperation(); private static class MinusOperation extends Broken1OperationEnum { private MinusOperation() { super("Minus"); } public int eval(int a, int b) { return (a - b); } } private Broken1OperationEnum(String name) { super(name); } public final Class getEnumClass() { return null; } public abstract int eval(int a, int b); public static Broken1OperationEnum getEnum(String name) { return (Broken1OperationEnum) getEnum(Broken1OperationEnum.class, name); } public static Map getEnumMap() { return getEnumMap(Broken1OperationEnum.class); } public static List getEnumList() { return getEnumList(Broken1OperationEnum.class); } public static Iterator iterator() { return iterator(Broken1OperationEnum.class); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/enum/Broken2Enum.java100644 0 0 3501 11513702440 24714 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.enum; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Broken color enumeration. * * @author Apache Software Foundation * @version $Id: Broken2Enum.java 905636 2010-02-02 14:03:32Z niallp $ */ public final class Broken2Enum extends Enum { public static final Broken2Enum RED = new Broken2Enum("Red"); public static final Broken2Enum GREEN = new Broken2Enum("Green"); public static final Broken2Enum BLUE = new Broken2Enum(""); // blank not allowed private Broken2Enum(String color) { super(color); } public static Broken2Enum getEnum(String color) { return (Broken2Enum) getEnum(Broken2Enum.class, color); } public static Map getEnumMap() { return getEnumMap(Broken2Enum.class); } public static List getEnumList() { return getEnumList(Broken2Enum.class); } public static Iterator iterator() { return iterator(Broken2Enum.class); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/enum/Broken2OperationEnum.java100644 0 0 5605 11513702440 26604 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.enum; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Broken Operator enumeration, getEnumClass() not superclass. * * @author Apache Software Foundation * @version $Id: Broken2OperationEnum.java 905636 2010-02-02 14:03:32Z niallp $ */ public abstract class Broken2OperationEnum extends Enum { // This syntax works for JDK 1.3 and upwards: // public static final OperationEnum PLUS = new OperationEnum("Plus") { // public int eval(int a, int b) { // return (a + b); // } // }; // public static final OperationEnum MINUS = new OperationEnum("Minus") { // public int eval(int a, int b) { // return (a - b); // } // }; // This syntax works for JDK 1.2 and upwards: public static final Broken2OperationEnum PLUS = new PlusOperation(); private static class PlusOperation extends Broken2OperationEnum { private PlusOperation() { super("Plus"); } public int eval(int a, int b) { return (a + b); } } public static final Broken2OperationEnum MINUS = new MinusOperation(); private static class MinusOperation extends Broken2OperationEnum { private MinusOperation() { super("Minus"); } public int eval(int a, int b) { return (a - b); } } private Broken2OperationEnum(String name) { super(name); } public final Class getEnumClass() { return ColorEnum.class; } public abstract int eval(int a, int b); public static Broken2OperationEnum getEnum(String name) { return (Broken2OperationEnum) getEnum(Broken2OperationEnum.class, name); } public static Map getEnumMap() { return getEnumMap(Broken2OperationEnum.class); } public static List getEnumList() { return getEnumList(Broken2OperationEnum.class); } public static Iterator iterator() { return iterator(Broken2OperationEnum.class); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/enum/Broken3Enum.java100644 0 0 3502 11513702440 24716 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.enum; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Broken color enumeration. * * @author Apache Software Foundation * @version $Id: Broken3Enum.java 905636 2010-02-02 14:03:32Z niallp $ */ public final class Broken3Enum extends Enum { public static final Broken3Enum RED = new Broken3Enum("Red"); public static final Broken3Enum GREEN = new Broken3Enum("Green"); public static final Broken3Enum BLUE = new Broken3Enum(null); // null not allowed private Broken3Enum(String color) { super(color); } public static Broken3Enum getEnum(String color) { return (Broken3Enum) getEnum(Broken3Enum.class, color); } public static Map getEnumMap() { return getEnumMap(Broken3Enum.class); } public static List getEnumList() { return getEnumList(Broken3Enum.class); } public static Iterator iterator() { return iterator(Broken3Enum.class); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/enum/Broken3OperationEnum.java100644 0 0 5577 11513702440 26615 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.enum; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Broken Operator enumeration, getEnumClass() is Enum.class. * * @author Apache Software Foundation * @version $Id: Broken3OperationEnum.java 905636 2010-02-02 14:03:32Z niallp $ */ public abstract class Broken3OperationEnum extends Enum { // This syntax works for JDK 1.3 and upwards: // public static final OperationEnum PLUS = new OperationEnum("Plus") { // public int eval(int a, int b) { // return (a + b); // } // }; // public static final OperationEnum MINUS = new OperationEnum("Minus") { // public int eval(int a, int b) { // return (a - b); // } // }; // This syntax works for JDK 1.2 and upwards: public static final Broken3OperationEnum PLUS = new PlusOperation(); private static class PlusOperation extends Broken3OperationEnum { private PlusOperation() { super("Plus"); } public int eval(int a, int b) { return (a + b); } } public static final Broken3OperationEnum MINUS = new MinusOperation(); private static class MinusOperation extends Broken3OperationEnum { private MinusOperation() { super("Minus"); } public int eval(int a, int b) { return (a - b); } } private Broken3OperationEnum(String name) { super(name); } public final Class getEnumClass() { return Enum.class; } public abstract int eval(int a, int b); public static Broken3OperationEnum getEnum(String name) { return (Broken3OperationEnum) getEnum(Broken3OperationEnum.class, name); } public static Map getEnumMap() { return getEnumMap(Broken3OperationEnum.class); } public static List getEnumList() { return getEnumList(Broken3OperationEnum.class); } public static Iterator iterator() { return iterator(Broken3OperationEnum.class); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/enum/Broken4OperationEnum.java100644 0 0 5613 11513702440 26605 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.enum; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Broken Operator enumeration, getEnumClass() is ValuedEnum.class. * * @author Apache Software Foundation * @version $Id: Broken4OperationEnum.java 905636 2010-02-02 14:03:32Z niallp $ */ public abstract class Broken4OperationEnum extends Enum { // This syntax works for JDK 1.3 and upwards: // public static final OperationEnum PLUS = new OperationEnum("Plus") { // public int eval(int a, int b) { // return (a + b); // } // }; // public static final OperationEnum MINUS = new OperationEnum("Minus") { // public int eval(int a, int b) { // return (a - b); // } // }; // This syntax works for JDK 1.2 and upwards: public static final Broken4OperationEnum PLUS = new PlusOperation(); private static class PlusOperation extends Broken4OperationEnum { private PlusOperation() { super("Plus"); } public int eval(int a, int b) { return (a + b); } } public static final Broken4OperationEnum MINUS = new MinusOperation(); private static class MinusOperation extends Broken4OperationEnum { private MinusOperation() { super("Minus"); } public int eval(int a, int b) { return (a - b); } } private Broken4OperationEnum(String name) { super(name); } public final Class getEnumClass() { return ValuedEnum.class; } public abstract int eval(int a, int b); public static Broken4OperationEnum getEnum(String name) { return (Broken4OperationEnum) getEnum(Broken4OperationEnum.class, name); } public static Map getEnumMap() { return getEnumMap(Broken4OperationEnum.class); } public static List getEnumList() { return getEnumList(Broken4OperationEnum.class); } public static Iterator iterator() { return iterator(Broken4OperationEnum.class); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/enum/Broken5OperationEnum.java100644 0 0 5610 11513702440 26603 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.enum; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Broken Operator enumeration, getEnumClass() is not an Enum class. * * @author Apache Software Foundation * @version $Id: Broken5OperationEnum.java 905636 2010-02-02 14:03:32Z niallp $ */ public abstract class Broken5OperationEnum extends Enum { // This syntax works for JDK 1.3 and upwards: // public static final OperationEnum PLUS = new OperationEnum("Plus") { // public int eval(int a, int b) { // return (a + b); // } // }; // public static final OperationEnum MINUS = new OperationEnum("Minus") { // public int eval(int a, int b) { // return (a - b); // } // }; // This syntax works for JDK 1.2 and upwards: public static final Broken5OperationEnum PLUS = new PlusOperation(); private static class PlusOperation extends Broken5OperationEnum { private PlusOperation() { super("Plus"); } public int eval(int a, int b) { return (a + b); } } public static final Broken5OperationEnum MINUS = new MinusOperation(); private static class MinusOperation extends Broken5OperationEnum { private MinusOperation() { super("Minus"); } public int eval(int a, int b) { return (a - b); } } private Broken5OperationEnum(String name) { super(name); } public final Class getEnumClass() { return String.class; } public abstract int eval(int a, int b); public static Broken5OperationEnum getEnum(String name) { return (Broken5OperationEnum) getEnum(Broken5OperationEnum.class, name); } public static Map getEnumMap() { return getEnumMap(Broken5OperationEnum.class); } public static List getEnumList() { return getEnumList(Broken5OperationEnum.class); } public static Iterator iterator() { return iterator(Broken5OperationEnum.class); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/enum/ColorEnum.java100644 0 0 3414 11513702440 24473 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.enum; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Color enumeration. * * @author Apache Software Foundation * @version $Id: ColorEnum.java 905636 2010-02-02 14:03:32Z niallp $ */ public final class ColorEnum extends Enum { public static final ColorEnum RED = new ColorEnum("Red"); public static final ColorEnum GREEN = new ColorEnum("Green"); public static final ColorEnum BLUE = new ColorEnum("Blue"); private ColorEnum(String color) { super(color); } public static ColorEnum getEnum(String color) { return (ColorEnum) getEnum(ColorEnum.class, color); } public static Map getEnumMap() { return getEnumMap(ColorEnum.class); } public static List getEnumList() { return getEnumList(ColorEnum.class); } public static Iterator iterator() { return iterator(ColorEnum.class); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/enum/DummyEnum.java100644 0 0 2166 11513702440 24513 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.enum; /** * Dummy enumeration - no values. * * @author Apache Software Foundation * @version $Id: DummyEnum.java 905636 2010-02-02 14:03:32Z niallp $ */ public abstract class DummyEnum extends Enum { private DummyEnum(String name) { super(name); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/enum/EnumTest.java100644 0 0 54442 11513702440 24363 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.enum; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import junit.framework.AssertionFailedError; import junit.framework.TestCase; import org.apache.commons.lang.SerializationUtils; /** * Test cases for the {@link Enum} class. * * @author Apache Software Foundation * @author Gary D. Gregory * @version $Id: EnumTest.java 905636 2010-02-02 14:03:32Z niallp $ */ public final class EnumTest extends TestCase { private static final String ENUM_CLASS_NAME = "org.apache.commons.lang.enum.ColorEnum"; public EnumTest(String name) { super(name); } public void setUp() { } public void testName() { assertEquals("Red", ColorEnum.RED.getName()); assertEquals("Green", ColorEnum.GREEN.getName()); assertEquals("Blue", ColorEnum.BLUE.getName()); } public void testCompareTo() { assertTrue(ColorEnum.BLUE.compareTo(ColorEnum.BLUE) == 0); assertTrue(ColorEnum.RED.compareTo(ColorEnum.BLUE) > 0); assertTrue(ColorEnum.BLUE.compareTo(ColorEnum.RED) < 0); try { ColorEnum.RED.compareTo(null); fail(); } catch (NullPointerException ex) { } try { ColorEnum.RED.compareTo(new Object()); fail(); } catch (ClassCastException ex) { } } public void testEquals() { assertSame(ColorEnum.RED, ColorEnum.RED); assertSame(ColorEnum.getEnum("Red"), ColorEnum.RED); assertEquals(false, ColorEnum.RED.equals(null)); assertEquals(true, ColorEnum.RED.equals(ColorEnum.RED)); assertEquals(true, ColorEnum.RED.equals(ColorEnum.getEnum("Red"))); } public void testHashCode() { assertEquals(ColorEnum.RED.hashCode(), ColorEnum.RED.hashCode()); assertEquals(7 + ColorEnum.class.hashCode() + 3 * "Red".hashCode(), ColorEnum.RED.hashCode()); } public void testToString() { String toString = ColorEnum.RED.toString(); assertEquals("ColorEnum[Red]", toString); assertSame(toString, ColorEnum.RED.toString()); } public void testIterator() { Iterator it = ColorEnum.iterator(); assertSame(ColorEnum.RED, it.next()); assertSame(ColorEnum.GREEN, it.next()); assertSame(ColorEnum.BLUE, it.next()); } public void testList() { List list = new ArrayList(ColorEnum.getEnumList()); assertNotNull(list); assertEquals(list.size(), ColorEnum.getEnumMap().keySet().size()); Iterator it = list.iterator(); assertSame(ColorEnum.RED, it.next()); assertSame(ColorEnum.GREEN, it.next()); assertSame(ColorEnum.BLUE, it.next()); } public void testMap() { Map map = new HashMap(ColorEnum.getEnumMap()); assertNotNull(map); assertTrue(map.containsValue(ColorEnum.RED)); assertTrue(map.containsValue(ColorEnum.GREEN)); assertTrue(map.containsValue(ColorEnum.BLUE)); assertSame(ColorEnum.RED, map.get("Red")); assertSame(ColorEnum.GREEN, map.get("Green")); assertSame(ColorEnum.BLUE, map.get("Blue")); assertEquals(map.keySet().size(), ColorEnum.getEnumList().size()); } public void testGet() { assertSame(ColorEnum.RED, ColorEnum.getEnum("Red")); assertSame(ColorEnum.GREEN, ColorEnum.getEnum("Green")); assertSame(ColorEnum.BLUE, ColorEnum.getEnum("Blue")); assertSame(null, ColorEnum.getEnum("Pink")); } public void testSerialization() { int hashCode = ColorEnum.RED.hashCode(); assertSame(ColorEnum.RED, SerializationUtils.clone(ColorEnum.RED)); assertEquals(hashCode, SerializationUtils.clone(ColorEnum.RED).hashCode()); assertSame(ColorEnum.GREEN, SerializationUtils.clone(ColorEnum.GREEN)); assertSame(ColorEnum.BLUE, SerializationUtils.clone(ColorEnum.BLUE)); } public void testBroken1() { try { Broken1Enum.RED.getName(); fail(); } catch (ExceptionInInitializerError ex) { assertTrue(ex.getException() instanceof IllegalArgumentException); } } public void testBroken2() { try { Broken2Enum.RED.getName(); fail(); } catch (ExceptionInInitializerError ex) { assertTrue(ex.getException() instanceof IllegalArgumentException); } } public void testBroken3() { try { Broken3Enum.RED.getName(); fail(); } catch (ExceptionInInitializerError ex) { assertTrue(ex.getException() instanceof IllegalArgumentException); } } public void testBroken1Operation() { try { Broken1OperationEnum.PLUS.getName(); fail(); } catch (ExceptionInInitializerError ex) { assertTrue(ex.getException() instanceof IllegalArgumentException); } } public void testBroken2Operation() { try { Broken2OperationEnum.PLUS.getName(); fail(); } catch (ExceptionInInitializerError ex) { assertTrue(ex.getException() instanceof IllegalArgumentException); } } public void testBroken3Operation() { try { Broken3OperationEnum.PLUS.getName(); fail(); } catch (ExceptionInInitializerError ex) { assertTrue(ex.getException() instanceof IllegalArgumentException); } } public void testBroken4Operation() { try { Broken4OperationEnum.PLUS.getName(); fail(); } catch (ExceptionInInitializerError ex) { assertTrue(ex.getException() instanceof IllegalArgumentException); } } public void testBroken5Operation() { try { Broken5OperationEnum.PLUS.getName(); fail(); } catch (ExceptionInInitializerError ex) { assertTrue(ex.getException() instanceof IllegalArgumentException); } } public void testOperationGet() { assertSame(OperationEnum.PLUS, OperationEnum.getEnum("Plus")); assertSame(OperationEnum.MINUS, OperationEnum.getEnum("Minus")); assertSame(null, OperationEnum.getEnum("Pink")); } public void testOperationSerialization() { assertSame(OperationEnum.PLUS, SerializationUtils.clone(OperationEnum.PLUS)); assertSame(OperationEnum.MINUS, SerializationUtils.clone(OperationEnum.MINUS)); } public void testOperationToString() { assertEquals("OperationEnum[Plus]", OperationEnum.PLUS.toString()); } public void testOperationList() { List list = OperationEnum.getEnumList(); assertNotNull(list); assertEquals(2, list.size()); assertEquals(list.size(), OperationEnum.getEnumMap().keySet().size()); Iterator it = list.iterator(); assertSame(OperationEnum.PLUS, it.next()); assertSame(OperationEnum.MINUS, it.next()); } public void testOperationMap() { Map map = OperationEnum.getEnumMap(); assertNotNull(map); assertEquals(map.keySet().size(), OperationEnum.getEnumList().size()); assertTrue(map.containsValue(OperationEnum.PLUS)); assertTrue(map.containsValue(OperationEnum.MINUS)); assertSame(OperationEnum.PLUS, map.get("Plus")); assertSame(OperationEnum.MINUS, map.get("Minus")); } public void testOperationCalculation() { assertEquals(3, OperationEnum.PLUS.eval(1, 2)); assertEquals(-1, OperationEnum.MINUS.eval(1, 2)); } // ----------------------------------------------------------------------- public void testExtended1Get() { assertSame(Extended1Enum.ALPHA, Extended1Enum.getEnum("Alpha")); assertSame(Extended1Enum.BETA, Extended1Enum.getEnum("Beta")); assertSame(null, Extended1Enum.getEnum("Gamma")); assertSame(null, Extended1Enum.getEnum("Delta")); } public void testExtended2Get() { assertSame(Extended1Enum.ALPHA, Extended2Enum.ALPHA); assertSame(Extended1Enum.BETA, Extended2Enum.BETA); assertSame(Extended2Enum.ALPHA, Extended2Enum.getEnum("Alpha")); assertSame(Extended2Enum.BETA, Extended2Enum.getEnum("Beta")); assertSame(Extended2Enum.GAMMA, Extended2Enum.getEnum("Gamma")); assertSame(null, Extended2Enum.getEnum("Delta")); } public void testExtended3Get() { assertSame(Extended2Enum.ALPHA, Extended3Enum.ALPHA); assertSame(Extended2Enum.BETA, Extended3Enum.BETA); assertSame(Extended2Enum.GAMMA, Extended3Enum.GAMMA); assertSame(Extended3Enum.ALPHA, Extended3Enum.getEnum("Alpha")); assertSame(Extended3Enum.BETA, Extended3Enum.getEnum("Beta")); assertSame(Extended3Enum.GAMMA, Extended3Enum.getEnum("Gamma")); assertSame(Extended3Enum.DELTA, Extended3Enum.getEnum("Delta")); } public void testExtendedSerialization() { assertSame(Extended1Enum.ALPHA, SerializationUtils.clone(Extended1Enum.ALPHA)); assertSame(Extended1Enum.BETA, SerializationUtils.clone(Extended1Enum.BETA)); assertSame(Extended2Enum.GAMMA, SerializationUtils.clone(Extended2Enum.GAMMA)); assertSame(Extended3Enum.DELTA, SerializationUtils.clone(Extended3Enum.DELTA)); } public void testExtendedToString() { assertEquals("Extended1Enum[Alpha]", Extended1Enum.ALPHA.toString()); assertEquals("Extended1Enum[Beta]", Extended1Enum.BETA.toString()); assertEquals("Extended1Enum[Alpha]", Extended2Enum.ALPHA.toString()); assertEquals("Extended1Enum[Beta]", Extended2Enum.BETA.toString()); assertEquals("Extended2Enum[Gamma]", Extended2Enum.GAMMA.toString()); assertEquals("Extended1Enum[Alpha]", Extended3Enum.ALPHA.toString()); assertEquals("Extended1Enum[Beta]", Extended3Enum.BETA.toString()); assertEquals("Extended2Enum[Gamma]", Extended3Enum.GAMMA.toString()); assertEquals("Extended3Enum[Delta]", Extended3Enum.DELTA.toString()); } public void testExtended1List() { List list = Extended1Enum.getEnumList(); assertNotNull(list); assertEquals(2, list.size()); assertEquals(list.size(), Extended1Enum.getEnumMap().keySet().size()); Iterator it = list.iterator(); assertSame(Extended1Enum.ALPHA, it.next()); assertSame(Extended1Enum.BETA, it.next()); } public void testExtended2List() { List list = Extended2Enum.getEnumList(); assertNotNull(list); assertEquals(3, list.size()); assertEquals(list.size(), Extended2Enum.getEnumMap().keySet().size()); Iterator it = list.iterator(); assertSame(Extended2Enum.ALPHA, it.next()); assertSame(Extended2Enum.BETA, it.next()); assertSame(Extended2Enum.GAMMA, it.next()); } public void testExtended3List() { List list = Extended3Enum.getEnumList(); assertNotNull(list); assertEquals(4, list.size()); assertEquals(list.size(), Extended3Enum.getEnumMap().keySet().size()); Iterator it = list.iterator(); assertSame(Extended3Enum.ALPHA, it.next()); assertSame(Extended3Enum.BETA, it.next()); assertSame(Extended3Enum.GAMMA, it.next()); assertSame(Extended3Enum.DELTA, it.next()); } public void testExtended1Map() { Map map = Extended1Enum.getEnumMap(); assertNotNull(map); assertEquals(map.keySet().size(), Extended1Enum.getEnumList().size()); assertTrue(map.containsValue(Extended1Enum.ALPHA)); assertTrue(map.containsValue(Extended1Enum.BETA)); assertSame(Extended1Enum.ALPHA, map.get("Alpha")); assertSame(Extended1Enum.BETA, map.get("Beta")); } public void testExtended2Map() { Map map = Extended2Enum.getEnumMap(); assertNotNull(map); assertEquals(map.keySet().size(), Extended2Enum.getEnumList().size()); assertTrue(map.containsValue(Extended2Enum.ALPHA)); assertTrue(map.containsValue(Extended2Enum.BETA)); assertTrue(map.containsValue(Extended2Enum.GAMMA)); assertSame(Extended2Enum.ALPHA, map.get("Alpha")); assertSame(Extended2Enum.BETA, map.get("Beta")); assertSame(Extended2Enum.GAMMA, map.get("Gamma")); } public void testExtended3Map() { Map map = Extended3Enum.getEnumMap(); assertNotNull(map); assertEquals(map.keySet().size(), Extended3Enum.getEnumList().size()); assertTrue(map.containsValue(Extended3Enum.ALPHA)); assertTrue(map.containsValue(Extended3Enum.BETA)); assertTrue(map.containsValue(Extended3Enum.GAMMA)); assertTrue(map.containsValue(Extended3Enum.DELTA)); assertSame(Extended3Enum.ALPHA, map.get("Alpha")); assertSame(Extended3Enum.BETA, map.get("Beta")); assertSame(Extended3Enum.GAMMA, map.get("Gamma")); assertSame(Extended3Enum.DELTA, map.get("Delta")); } // ----------------------------------------------------------------------- public void testNested() { List list = new ArrayList(Nest.ColorEnum.getEnumList()); assertEquals(3, list.size()); // all is well Iterator it = list.iterator(); assertSame(Nest.ColorEnum.RED, it.next()); assertSame(Nest.ColorEnum.GREEN, it.next()); assertSame(Nest.ColorEnum.BLUE, it.next()); // This nesting works because the enum constants are defined in the SAME // class as the getEnumList(). It just acts as a normal enum. } public void testNestedBroken() { List list = new ArrayList(NestBroken.ColorEnum.getEnumList()); try { assertEquals(0, list.size()); // no enums!!! // this is BROKEN because the enum constants are defined in a DIFFERENT // class from getEnumList(). Once NestBroken class is referenced, // and thus class loaded with its enum constants, the getEnumList works: } catch (AssertionFailedError ex) { // this actually works and isn't broken on Linux SunJDK1.4.1, so... assertEquals(3, list.size()); } new NestBroken(); list = new ArrayList(NestBroken.ColorEnum.getEnumList()); assertEquals(3, list.size()); // all is well!!! Iterator it = list.iterator(); assertSame(NestBroken.RED, it.next()); assertSame(NestBroken.GREEN, it.next()); assertSame(NestBroken.BLUE, it.next()); } public void testNestedLinked() { List list = new ArrayList(NestLinked.ColorEnum.getEnumList()); assertEquals(3, list.size()); // all is well Iterator it = list.iterator(); assertSame(NestLinked.RED, it.next()); assertSame(NestLinked.GREEN, it.next()); assertSame(NestLinked.BLUE, it.next()); // This nesting works because a static block in the enum class forces a // class load of the outer class which defines the enum constants. } public void testNestedReferenced() { List list = new ArrayList(NestReferenced.ColorEnum.getEnumList()); assertEquals(3, list.size()); // all is well Iterator it = list.iterator(); assertSame(NestReferenced.RED, it.next()); assertSame(NestReferenced.GREEN, it.next()); assertSame(NestReferenced.BLUE, it.next()); // This nesting works because the enum constants are actually defined in // the SAME class as the getEnumList(). The references in the outer class // are just extra references. } public void testColorEnumEqualsWithDifferentClassLoaders() throws SecurityException, IllegalArgumentException, ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException { this.testWithDifferentClassLoaders(ColorEnum.BLUE); this.testWithDifferentClassLoaders(ColorEnum.GREEN); this.testWithDifferentClassLoaders(ColorEnum.RED); } void testWithDifferentClassLoaders(ColorEnum colorEnum) throws ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException { // Sanity checks: assertTrue(colorEnum.equals(colorEnum)); assertNotNull(ColorEnum.class.getClassLoader()); // set up: ClassLoader myClassLoader = EnumTest.class.getClassLoader(); if (!(myClassLoader instanceof URLClassLoader)) { fail("EnumTest ClassLoader = " + (myClassLoader == null ? null : myClassLoader.getClass().getName())); } ClassLoader classLoader = URLClassLoader.newInstance( ((URLClassLoader)myClassLoader).getURLs(), null); Object enumObjectFromOtherClassLoader = this.getColorEnum(classLoader, colorEnum.getName()); // the real test, part 1. try { ColorEnum testCase = (ColorEnum) enumObjectFromOtherClassLoader; fail("Should have thrown a ClassCastException for " + testCase); } catch (ClassCastException e) { // normal. } // the real test, part 2. assertEquals("The two objects should match even though they are from different class loaders", colorEnum, enumObjectFromOtherClassLoader); // the real test, part 3 - testing equals(Object) int falseCount = 0; for (Iterator iter = ColorEnum.iterator(); iter.hasNext();) { ColorEnum element = (ColorEnum) iter.next(); if (!colorEnum.equals(element)) { falseCount++; assertFalse(enumObjectFromOtherClassLoader.equals(element)); } } assertEquals(ColorEnum.getEnumList().size() - 1, falseCount); // the real test, part 4 - testing compareTo(Object) == 0 falseCount = 0; for (Iterator iter = ColorEnum.iterator(); iter.hasNext();) { ColorEnum element = (ColorEnum) iter.next(); if (!colorEnum.equals(element)) { falseCount++; assertFalse( ((Comparable)enumObjectFromOtherClassLoader).compareTo(element) == 0); } } assertEquals(ColorEnum.getEnumList().size() - 1, falseCount); } Object getColorEnum(ClassLoader classLoader, String color) throws ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException { // Sanity check: ColorEnum.RED.equals(ColorEnum.RED); assertNotNull(ColorEnum.class.getClassLoader()); // set up: assertNotNull(classLoader); assertFalse(classLoader.equals(ColorEnum.class.getClassLoader())); Class otherColorEnumClass = null; try { otherColorEnumClass = classLoader.loadClass(ENUM_CLASS_NAME); } catch (ClassNotFoundException e) { // Dump some information to help debug class loader issues under different JREs, Ant, Eclipse. System.err.println("Could not load " + ENUM_CLASS_NAME + " from the class loader " + classLoader); URLClassLoader urlCl = (URLClassLoader) classLoader; URL[] urls = urlCl.getURLs(); System.err.println("Class loader has " + urls.length + " URLs:"); for (int i = 0; i < urls.length; i++) { System.err.println("URL[" + i + "] = " + urls[i]); } e.printStackTrace(); throw e; } assertNotNull(otherColorEnumClass); assertNotNull(otherColorEnumClass.getClassLoader()); assertTrue(classLoader.equals(otherColorEnumClass.getClassLoader())); assertFalse(otherColorEnumClass.getClassLoader().equals(ColorEnum.class.getClassLoader())); Method method = otherColorEnumClass.getMethod("getEnum", new Class[]{String.class}); Object enumObject = method.invoke(otherColorEnumClass, new Object[]{color}); assertNotNull(enumObject); assertFalse(ColorEnum.class.equals(enumObject.getClass())); assertFalse(ColorEnum.class == enumObject.getClass()); return enumObject; } public void testEqualsToWrongInstance() { for (Iterator iter = ColorEnum.iterator(); iter.hasNext();) { ColorEnum element = (ColorEnum) iter.next(); this.testEqualsToWrongInstance(element); } } void testEqualsToWrongInstance(ColorEnum colorEnum) { assertEquals(false, colorEnum.equals("test")); assertEquals(false, colorEnum.equals(new Integer(1))); assertEquals(false, colorEnum.equals(new Boolean(true))); assertEquals(false, colorEnum.equals(new StringBuffer("test"))); assertEquals(false, colorEnum.equals(new Object())); assertEquals(false, colorEnum.equals(null)); assertEquals(false, colorEnum.equals("")); assertEquals(false, colorEnum.equals(ColorEnum.getEnum(null))); assertEquals(false, colorEnum.equals(ColorEnum.getEnum(""))); assertEquals(false, colorEnum.equals(ColorEnum.getEnum("This ColorEnum does not exist."))); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/enum/EnumUtilsTest.java100644 0 0 13450 11513702440 25376 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.enum; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.util.Iterator; import java.util.List; import java.util.Map; import junit.framework.TestCase; /** * Test cases for the {@link Enum} class. * * @author Apache Software Foundation * @version $Id: EnumUtilsTest.java 905636 2010-02-02 14:03:32Z niallp $ */ public final class EnumUtilsTest extends TestCase { public EnumUtilsTest(String name) { super(name); } public void setUp() { } //----------------------------------------------------------------------- public void testConstructor() { assertNotNull(new EnumUtils()); Constructor[] cons = EnumUtils.class.getDeclaredConstructors(); assertEquals(1, cons.length); assertEquals(true, Modifier.isPublic(cons[0].getModifiers())); assertEquals(true, Modifier.isPublic(EnumUtils.class.getModifiers())); assertEquals(false, Modifier.isFinal(EnumUtils.class.getModifiers())); } //----------------------------------------------------------------------- public void testIterator() { Iterator it = EnumUtils.iterator(ColorEnum.class); assertSame(ColorEnum.RED, it.next()); assertSame(ColorEnum.GREEN, it.next()); assertSame(ColorEnum.BLUE, it.next()); it = EnumUtils.iterator(DummyEnum.class); assertEquals(false, it.hasNext()); } public void testIteratorEx() { try { EnumUtils.iterator(null); fail(); } catch (IllegalArgumentException ex) {} try { EnumUtils.iterator(Object.class); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testList() { List list = EnumUtils.getEnumList(ColorEnum.class); Iterator it = list.iterator(); assertSame(ColorEnum.RED, it.next()); assertSame(ColorEnum.GREEN, it.next()); assertSame(ColorEnum.BLUE, it.next()); list = EnumUtils.getEnumList(DummyEnum.class); assertEquals(0, list.size()); } public void testListEx() { try { EnumUtils.getEnumList(null); fail(); } catch (IllegalArgumentException ex) {} try { EnumUtils.getEnumList(Object.class); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testMap() { Map map = EnumUtils.getEnumMap(ColorEnum.class); assertTrue(map.containsValue(ColorEnum.RED)); assertTrue(map.containsValue(ColorEnum.GREEN)); assertTrue(map.containsValue(ColorEnum.BLUE)); assertSame(ColorEnum.RED, map.get("Red")); assertSame(ColorEnum.GREEN, map.get("Green")); assertSame(ColorEnum.BLUE, map.get("Blue")); map = EnumUtils.getEnumMap(DummyEnum.class); assertEquals(0, map.size()); } public void testMapEx() { try { EnumUtils.getEnumMap(null); fail(); } catch (IllegalArgumentException ex) {} try { EnumUtils.getEnumMap(Object.class); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testGet() { assertSame(ColorEnum.RED, EnumUtils.getEnum(ColorEnum.class, "Red")); assertSame(ColorEnum.GREEN, EnumUtils.getEnum(ColorEnum.class, "Green")); assertSame(ColorEnum.BLUE, EnumUtils.getEnum(ColorEnum.class, "Blue")); assertSame(null, EnumUtils.getEnum(ColorEnum.class, "Pink")); assertSame(null, EnumUtils.getEnum(DummyEnum.class, "Pink")); } public void testGetEx() { try { EnumUtils.getEnum(null, ""); fail(); } catch (IllegalArgumentException ex) {} try { EnumUtils.getEnum(Object.class, "Red"); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testGetValue() { assertSame(ValuedColorEnum.RED, EnumUtils.getEnum(ValuedColorEnum.class, 1)); assertSame(ValuedColorEnum.GREEN, EnumUtils.getEnum(ValuedColorEnum.class, 2)); assertSame(ValuedColorEnum.BLUE, EnumUtils.getEnum(ValuedColorEnum.class, 3)); assertSame(null, EnumUtils.getEnum(ValuedColorEnum.class, 4)); assertSame(null, EnumUtils.getEnum(DummyEnum.class, 5)); } public void testGetValueEx() { try { EnumUtils.getEnum(null, 0); fail(); } catch (IllegalArgumentException ex) {} try { EnumUtils.getEnum(Object.class, 2); fail(); } catch (IllegalArgumentException ex) {} } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/enum/Extended1Enum.java100644 0 0 3404 11513702440 25235 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "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 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.commons.lang.enum; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Base extended enumeration. * * @author Apache Software Foundation * @version $Id: Extended1Enum.java 905636 2010-02-02 14:03:32Z niallp $ */ public class Extended1Enum extends Enum { public static final Extended1Enum ALPHA = new Extended1Enum("Alpha"); public static final Extended1Enum BETA = new Extended1Enum("Beta"); protected Extended1Enum(String name) { super(name); } public static Extended1Enum getEnum(String name) { return (Extended1Enum) getEnum(Extended1Enum.class, name); } public static Map getEnumMap() { return getEnumMap(Extended1Enum.class); } public static List getEnumList() { return getEnumList(Extended1Enum.class); } public static Iterator iterator() { return iterator(Extended1Enum.class); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/enum/Extended2Enum.java100644 0 0 3301 11513702440 25232 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "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 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.commons.lang.enum; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Extended enumeration. * * @author Apache Software Foundation * @version $Id: Extended2Enum.java 905636 2010-02-02 14:03:32Z niallp $ */ public class Extended2Enum extends Extended1Enum { public static final Extended1Enum GAMMA = new Extended2Enum("Gamma"); protected Extended2Enum(String color) { super(color); } public static Extended1Enum getEnum(String name) { return (Extended1Enum) getEnum(Extended2Enum.class, name); } public static Map getEnumMap() { return getEnumMap(Extended2Enum.class); } public static List getEnumList() { return getEnumList(Extended2Enum.class); } public static Iterator iterator() { return iterator(Extended2Enum.class); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/enum/Extended3Enum.java100644 0 0 3323 11513702440 25237 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "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 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.commons.lang.enum; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Extended enumeration. * * @author Apache Software Foundation * @version $Id: Extended3Enum.java 905636 2010-02-02 14:03:32Z niallp $ */ public class Extended3Enum extends Extended2Enum { public static final Extended1Enum DELTA = new Extended3Enum("Delta"); protected Extended3Enum(String name) { super(name); } public static Extended1Enum getEnum(String name) { return (Extended1Enum) Enum.getEnum(Extended3Enum.class, name); } public static Map getEnumMap() { return Enum.getEnumMap(Extended3Enum.class); } public static List getEnumList() { return Enum.getEnumList(Extended3Enum.class); } public static Iterator iterator() { return Enum.iterator(Extended3Enum.class); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/enum/Nest.java100644 0 0 4076 11513702440 23506 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.enum; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Color enumeration demonstrating a normal simple nesting case. * All is well here as the nested enum class is really no different * to any other class. * * @author Apache Software Foundation * @version $Id: Nest.java 905636 2010-02-02 14:03:32Z niallp $ */ public final class Nest { public Nest() { super(); } public static final class ColorEnum extends Enum { public static final ColorEnum RED = new ColorEnum("Red"); public static final ColorEnum GREEN = new ColorEnum("Green"); public static final ColorEnum BLUE = new ColorEnum("Blue"); private ColorEnum(String color) { super(color); } public static ColorEnum getEnum(String color) { return (ColorEnum) getEnum(ColorEnum.class, color); } public static Map getEnumMap() { return getEnumMap(ColorEnum.class); } public static List getEnumList() { return getEnumList(ColorEnum.class); } public static Iterator iterator() { return iterator(ColorEnum.class); } } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/enum/NestBroken.java100644 0 0 4347 11513702440 24650 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.enum; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Color enumeration which demonstrates how to break the enum system. *

    * The class loader sees the two classes here as independent - the enum * class is nested, not an inner class. Calling getEnumList() on ColorEnum * will return an empty list, unless and until the NestBroken class is * referenced. * * @author Apache Software Foundation * @version $Id: NestBroken.java 905636 2010-02-02 14:03:32Z niallp $ */ public final class NestBroken { public static final ColorEnum RED = new ColorEnum("Red"); public static final ColorEnum GREEN = new ColorEnum("Green"); public static final ColorEnum BLUE = new ColorEnum("Blue"); public NestBroken() { super(); } public static final class ColorEnum extends Enum { private ColorEnum(String color) { super(color); } public static ColorEnum getEnum(String color) { return (ColorEnum) getEnum(ColorEnum.class, color); } public static Map getEnumMap() { return getEnumMap(ColorEnum.class); } public static List getEnumList() { return getEnumList(ColorEnum.class); } public static Iterator iterator() { return iterator(ColorEnum.class); } } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/enum/NestLinked.java100644 0 0 5064 11513702440 24633 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.enum; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Color enumeration which demonstrates how to define the constants in a * different class to the Enum. The extra static{} block is * needed to ensure that the enum constants are created before the * static methods on the ColorEnum are used. *

    * The class loader sees the two classes here as independent - the enum * class is nested, not an inner class. The static block thus forces the * class load of the outer class, which is needed to initialise the enums. * * @author Apache Software Foundation * @version $Id: NestLinked.java 905636 2010-02-02 14:03:32Z niallp $ */ public final class NestLinked { public static final ColorEnum RED = new ColorEnum("Red"); public static final ColorEnum GREEN = new ColorEnum("Green"); public static final ColorEnum BLUE = new ColorEnum("Blue"); public NestLinked() { super(); } public static final class ColorEnum extends Enum { static { // Explicitly reference the class where the enums are defined Object obj = NestLinked.RED; } private ColorEnum(String color) { super(color); } public static ColorEnum getEnum(String color) { return (ColorEnum) getEnum(ColorEnum.class, color); } public static Map getEnumMap() { return getEnumMap(ColorEnum.class); } public static List getEnumList() { return getEnumList(ColorEnum.class); } public static Iterator iterator() { return iterator(ColorEnum.class); } } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/enum/NestReferenced.java100644 0 0 4715 11513702440 25471 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.enum; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Color enumeration which demonstrates how to provide a view of the constants * in a different class to the Enum. This technique is the safest, however it * is obviously inconvenient as it involves defining two sets of constants. * See NestedLinked for an alternative. * * @author Apache Software Foundation * @version $Id: NestReferenced.java 905636 2010-02-02 14:03:32Z niallp $ */ public final class NestReferenced { public static final ColorEnum RED = ColorEnum.RED; public static final ColorEnum GREEN = ColorEnum.GREEN; public static final ColorEnum BLUE = ColorEnum.BLUE; public NestReferenced() { super(); } public static final class ColorEnum extends Enum { // must be defined here, not just in outer class private static final ColorEnum RED = new ColorEnum("Red"); private static final ColorEnum GREEN = new ColorEnum("Green"); private static final ColorEnum BLUE = new ColorEnum("Blue"); private ColorEnum(String color) { super(color); } public static ColorEnum getEnum(String color) { return (ColorEnum) getEnum(ColorEnum.class, color); } public static Map getEnumMap() { return getEnumMap(ColorEnum.class); } public static List getEnumList() { return getEnumList(ColorEnum.class); } public static Iterator iterator() { return iterator(ColorEnum.class); } } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/enum/OperationEnum.java100644 0 0 5410 11513702440 25353 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.enum; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Operator enumeration. * * @author Apache Software Foundation * @version $Id: OperationEnum.java 905636 2010-02-02 14:03:32Z niallp $ */ public abstract class OperationEnum extends Enum { // This syntax works for JDK 1.3 and upwards: // public static final OperationEnum PLUS = new OperationEnum("Plus") { // public int eval(int a, int b) { // return (a + b); // } // }; // public static final OperationEnum MINUS = new OperationEnum("Minus") { // public int eval(int a, int b) { // return (a - b); // } // }; // This syntax works for JDK 1.2 and upwards: public static final OperationEnum PLUS = new PlusOperation(); private static class PlusOperation extends OperationEnum { private PlusOperation() { super("Plus"); } public int eval(int a, int b) { return (a + b); } } public static final OperationEnum MINUS = new MinusOperation(); private static class MinusOperation extends OperationEnum { private MinusOperation() { super("Minus"); } public int eval(int a, int b) { return (a - b); } } private OperationEnum(String name) { super(name); } public final Class getEnumClass() { return OperationEnum.class; } public abstract int eval(int a, int b); public static OperationEnum getEnum(String name) { return (OperationEnum) getEnum(OperationEnum.class, name); } public static Map getEnumMap() { return getEnumMap(OperationEnum.class); } public static List getEnumList() { return getEnumList(OperationEnum.class); } public static Iterator iterator() { return iterator(OperationEnum.class); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/enum/ValuedColorEnum.java100644 0 0 4021 11513702440 25627 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.enum; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Color enumeration. * * @author Apache Software Foundation * @version $Id: ValuedColorEnum.java 905636 2010-02-02 14:03:32Z niallp $ */ public final class ValuedColorEnum extends ValuedEnum { public static final ValuedColorEnum RED = new ValuedColorEnum("Red", 1); public static final ValuedColorEnum GREEN = new ValuedColorEnum("Green", 2); public static final ValuedColorEnum BLUE = new ValuedColorEnum("Blue", 3); private ValuedColorEnum(String color, int value) { super(color, value); } public static ValuedColorEnum getEnum(String color) { return (ValuedColorEnum) getEnum(ValuedColorEnum.class, color); } public static ValuedColorEnum getEnum(int value) { return (ValuedColorEnum) getEnum(ValuedColorEnum.class, value); } public static Map getEnumMap() { return getEnumMap(ValuedColorEnum.class); } public static List getEnumList() { return getEnumList(ValuedColorEnum.class); } public static Iterator iterator() { return iterator(ValuedColorEnum.class); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/enum/ValuedEnumTest.java100644 0 0 11277 11513702440 25523 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.enum; import java.util.Iterator; import java.util.List; import java.util.Map; import junit.framework.TestCase; import org.apache.commons.lang.SerializationUtils; /** * Test cases for the {@link Enum} class. * * @author Apache Software Foundation * @version $Id: ValuedEnumTest.java 905636 2010-02-02 14:03:32Z niallp $ */ public final class ValuedEnumTest extends TestCase { public ValuedEnumTest(String name) { super(name); } public void setUp() { } public void testName() { assertEquals("Red", ValuedColorEnum.RED.getName()); assertEquals("Green", ValuedColorEnum.GREEN.getName()); assertEquals("Blue", ValuedColorEnum.BLUE.getName()); } public void testValue() { assertEquals(1, ValuedColorEnum.RED.getValue()); assertEquals(2, ValuedColorEnum.GREEN.getValue()); assertEquals(3, ValuedColorEnum.BLUE.getValue()); } public void testCompareTo() { assertTrue(ValuedColorEnum.BLUE.compareTo(ValuedColorEnum.BLUE) == 0); assertTrue(ValuedColorEnum.RED.compareTo(ValuedColorEnum.BLUE) < 0); assertTrue(ValuedColorEnum.BLUE.compareTo(ValuedColorEnum.RED) > 0); } public void testEquals() { assertSame(ValuedColorEnum.RED, ValuedColorEnum.RED); assertSame(ValuedColorEnum.getEnum("Red"), ValuedColorEnum.RED); } public void testToString() { String toString = ValuedColorEnum.RED.toString(); assertEquals("ValuedColorEnum[Red=1]", toString); assertSame(toString, ValuedColorEnum.RED.toString()); } public void testIterator() { Iterator it = ValuedColorEnum.iterator(); assertSame(ValuedColorEnum.RED, it.next()); assertSame(ValuedColorEnum.GREEN, it.next()); assertSame(ValuedColorEnum.BLUE, it.next()); } public void testList() { List list = ValuedColorEnum.getEnumList(); assertNotNull(list); assertEquals( list.size(), ValuedColorEnum.getEnumMap().keySet().size()); Iterator it = list.iterator(); assertSame(ValuedColorEnum.RED, it.next()); assertSame(ValuedColorEnum.GREEN, it.next()); assertSame(ValuedColorEnum.BLUE, it.next()); } public void testMap() { Map map = ValuedColorEnum.getEnumMap(); assertNotNull(map); assertEquals( map.keySet().size(), ValuedColorEnum.getEnumList().size()); assertTrue(map.containsValue(ValuedColorEnum.RED)); assertTrue(map.containsValue(ValuedColorEnum.GREEN)); assertTrue(map.containsValue(ValuedColorEnum.BLUE)); assertSame(ValuedColorEnum.RED, map.get("Red")); assertSame(ValuedColorEnum.GREEN, map.get("Green")); assertSame(ValuedColorEnum.BLUE, map.get("Blue")); } public void testGet() { assertSame(ValuedColorEnum.RED, ValuedColorEnum.getEnum("Red")); assertSame(ValuedColorEnum.GREEN, ValuedColorEnum.getEnum("Green")); assertSame(ValuedColorEnum.BLUE, ValuedColorEnum.getEnum("Blue")); assertSame(null, ValuedColorEnum.getEnum("Pink")); } public void testGetValue() { assertSame(ValuedColorEnum.RED, ValuedColorEnum.getEnum(1)); assertSame(ValuedColorEnum.GREEN, ValuedColorEnum.getEnum(2)); assertSame(ValuedColorEnum.BLUE, ValuedColorEnum.getEnum(3)); assertSame(null, ValuedColorEnum.getEnum(4)); } public void testSerialization() { assertSame(ValuedColorEnum.RED, SerializationUtils.clone(ValuedColorEnum.RED)); assertSame(ValuedColorEnum.GREEN, SerializationUtils.clone(ValuedColorEnum.GREEN)); assertSame(ValuedColorEnum.BLUE, SerializationUtils.clone(ValuedColorEnum.BLUE)); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/enums/Broken1Enum.java100644 0 0 3517 11513702434 25110 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.enums; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Broken color enumeration. * * @author Apache Software Foundation * @version $Id: Broken1Enum.java 905636 2010-02-02 14:03:32Z niallp $ */ public final class Broken1Enum extends Enum { public static final Broken1Enum RED = new Broken1Enum("Red"); public static final Broken1Enum GREEN = new Broken1Enum("Green"); public static final Broken1Enum GREENISH = new Broken1Enum("Green"); // duplicate not allowed private Broken1Enum(String color) { super(color); } public static Broken1Enum getEnum(String color) { return (Broken1Enum) getEnum(Broken1Enum.class, color); } public static Map getEnumMap() { return getEnumMap(Broken1Enum.class); } public static List getEnumList() { return getEnumList(Broken1Enum.class); } public static Iterator iterator() { return iterator(Broken1Enum.class); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/enums/Broken1OperationEnum.java100644 0 0 5550 11513702434 26770 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.enums; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Broken Operator enumeration, null class. * * @author Apache Software Foundation * @version $Id: Broken1OperationEnum.java 905636 2010-02-02 14:03:32Z niallp $ */ public abstract class Broken1OperationEnum extends Enum { // This syntax works for JDK 1.3 and upwards: // public static final OperationEnum PLUS = new OperationEnum("Plus") { // public int eval(int a, int b) { // return (a + b); // } // }; // public static final OperationEnum MINUS = new OperationEnum("Minus") { // public int eval(int a, int b) { // return (a - b); // } // }; // This syntax works for JDK 1.2 and upwards: public static final Broken1OperationEnum PLUS = new PlusOperation(); private static class PlusOperation extends Broken1OperationEnum { private PlusOperation() { super("Plus"); } public int eval(int a, int b) { return (a + b); } } public static final Broken1OperationEnum MINUS = new MinusOperation(); private static class MinusOperation extends Broken1OperationEnum { private MinusOperation() { super("Minus"); } public int eval(int a, int b) { return (a - b); } } private Broken1OperationEnum(String name) { super(name); } public final Class getEnumClass() { return null; } public abstract int eval(int a, int b); public static Broken1OperationEnum getEnum(String name) { return (Broken1OperationEnum) getEnum(Broken1OperationEnum.class, name); } public static Map getEnumMap() { return getEnumMap(Broken1OperationEnum.class); } public static List getEnumList() { return getEnumList(Broken1OperationEnum.class); } public static Iterator iterator() { return iterator(Broken1OperationEnum.class); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/enums/Broken2Enum.java100644 0 0 3502 11513702434 25103 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.enums; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Broken color enumeration. * * @author Apache Software Foundation * @version $Id: Broken2Enum.java 905636 2010-02-02 14:03:32Z niallp $ */ public final class Broken2Enum extends Enum { public static final Broken2Enum RED = new Broken2Enum("Red"); public static final Broken2Enum GREEN = new Broken2Enum("Green"); public static final Broken2Enum BLUE = new Broken2Enum(""); // blank not allowed private Broken2Enum(String color) { super(color); } public static Broken2Enum getEnum(String color) { return (Broken2Enum) getEnum(Broken2Enum.class, color); } public static Map getEnumMap() { return getEnumMap(Broken2Enum.class); } public static List getEnumList() { return getEnumList(Broken2Enum.class); } public static Iterator iterator() { return iterator(Broken2Enum.class); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/enums/Broken2OperationEnum.java100644 0 0 5606 11513702434 26773 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.enums; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Broken Operator enumeration, getEnumClass() not superclass. * * @author Apache Software Foundation * @version $Id: Broken2OperationEnum.java 905636 2010-02-02 14:03:32Z niallp $ */ public abstract class Broken2OperationEnum extends Enum { // This syntax works for JDK 1.3 and upwards: // public static final OperationEnum PLUS = new OperationEnum("Plus") { // public int eval(int a, int b) { // return (a + b); // } // }; // public static final OperationEnum MINUS = new OperationEnum("Minus") { // public int eval(int a, int b) { // return (a - b); // } // }; // This syntax works for JDK 1.2 and upwards: public static final Broken2OperationEnum PLUS = new PlusOperation(); private static class PlusOperation extends Broken2OperationEnum { private PlusOperation() { super("Plus"); } public int eval(int a, int b) { return (a + b); } } public static final Broken2OperationEnum MINUS = new MinusOperation(); private static class MinusOperation extends Broken2OperationEnum { private MinusOperation() { super("Minus"); } public int eval(int a, int b) { return (a - b); } } private Broken2OperationEnum(String name) { super(name); } public final Class getEnumClass() { return ColorEnum.class; } public abstract int eval(int a, int b); public static Broken2OperationEnum getEnum(String name) { return (Broken2OperationEnum) getEnum(Broken2OperationEnum.class, name); } public static Map getEnumMap() { return getEnumMap(Broken2OperationEnum.class); } public static List getEnumList() { return getEnumList(Broken2OperationEnum.class); } public static Iterator iterator() { return iterator(Broken2OperationEnum.class); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/enums/Broken3Enum.java100644 0 0 3503 11513702434 25105 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.enums; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Broken color enumeration. * * @author Apache Software Foundation * @version $Id: Broken3Enum.java 905636 2010-02-02 14:03:32Z niallp $ */ public final class Broken3Enum extends Enum { public static final Broken3Enum RED = new Broken3Enum("Red"); public static final Broken3Enum GREEN = new Broken3Enum("Green"); public static final Broken3Enum BLUE = new Broken3Enum(null); // null not allowed private Broken3Enum(String color) { super(color); } public static Broken3Enum getEnum(String color) { return (Broken3Enum) getEnum(Broken3Enum.class, color); } public static Map getEnumMap() { return getEnumMap(Broken3Enum.class); } public static List getEnumList() { return getEnumList(Broken3Enum.class); } public static Iterator iterator() { return iterator(Broken3Enum.class); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/enums/Broken3OperationEnum.java100644 0 0 5600 11513702434 26766 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.enums; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Broken Operator enumeration, getEnumClass() is Enum.class. * * @author Apache Software Foundation * @version $Id: Broken3OperationEnum.java 905636 2010-02-02 14:03:32Z niallp $ */ public abstract class Broken3OperationEnum extends Enum { // This syntax works for JDK 1.3 and upwards: // public static final OperationEnum PLUS = new OperationEnum("Plus") { // public int eval(int a, int b) { // return (a + b); // } // }; // public static final OperationEnum MINUS = new OperationEnum("Minus") { // public int eval(int a, int b) { // return (a - b); // } // }; // This syntax works for JDK 1.2 and upwards: public static final Broken3OperationEnum PLUS = new PlusOperation(); private static class PlusOperation extends Broken3OperationEnum { private PlusOperation() { super("Plus"); } public int eval(int a, int b) { return (a + b); } } public static final Broken3OperationEnum MINUS = new MinusOperation(); private static class MinusOperation extends Broken3OperationEnum { private MinusOperation() { super("Minus"); } public int eval(int a, int b) { return (a - b); } } private Broken3OperationEnum(String name) { super(name); } public final Class getEnumClass() { return Enum.class; } public abstract int eval(int a, int b); public static Broken3OperationEnum getEnum(String name) { return (Broken3OperationEnum) getEnum(Broken3OperationEnum.class, name); } public static Map getEnumMap() { return getEnumMap(Broken3OperationEnum.class); } public static List getEnumList() { return getEnumList(Broken3OperationEnum.class); } public static Iterator iterator() { return iterator(Broken3OperationEnum.class); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/enums/Broken4OperationEnum.java100644 0 0 5614 11513702434 26774 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.enums; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Broken Operator enumeration, getEnumClass() is ValuedEnum.class. * * @author Apache Software Foundation * @version $Id: Broken4OperationEnum.java 905636 2010-02-02 14:03:32Z niallp $ */ public abstract class Broken4OperationEnum extends Enum { // This syntax works for JDK 1.3 and upwards: // public static final OperationEnum PLUS = new OperationEnum("Plus") { // public int eval(int a, int b) { // return (a + b); // } // }; // public static final OperationEnum MINUS = new OperationEnum("Minus") { // public int eval(int a, int b) { // return (a - b); // } // }; // This syntax works for JDK 1.2 and upwards: public static final Broken4OperationEnum PLUS = new PlusOperation(); private static class PlusOperation extends Broken4OperationEnum { private PlusOperation() { super("Plus"); } public int eval(int a, int b) { return (a + b); } } public static final Broken4OperationEnum MINUS = new MinusOperation(); private static class MinusOperation extends Broken4OperationEnum { private MinusOperation() { super("Minus"); } public int eval(int a, int b) { return (a - b); } } private Broken4OperationEnum(String name) { super(name); } public final Class getEnumClass() { return ValuedEnum.class; } public abstract int eval(int a, int b); public static Broken4OperationEnum getEnum(String name) { return (Broken4OperationEnum) getEnum(Broken4OperationEnum.class, name); } public static Map getEnumMap() { return getEnumMap(Broken4OperationEnum.class); } public static List getEnumList() { return getEnumList(Broken4OperationEnum.class); } public static Iterator iterator() { return iterator(Broken4OperationEnum.class); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/enums/Broken5OperationEnum.java100644 0 0 5611 11513702434 26772 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.enums; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Broken Operator enumeration, getEnumClass() is not an Enum class. * * @author Apache Software Foundation * @version $Id: Broken5OperationEnum.java 905636 2010-02-02 14:03:32Z niallp $ */ public abstract class Broken5OperationEnum extends Enum { // This syntax works for JDK 1.3 and upwards: // public static final OperationEnum PLUS = new OperationEnum("Plus") { // public int eval(int a, int b) { // return (a + b); // } // }; // public static final OperationEnum MINUS = new OperationEnum("Minus") { // public int eval(int a, int b) { // return (a - b); // } // }; // This syntax works for JDK 1.2 and upwards: public static final Broken5OperationEnum PLUS = new PlusOperation(); private static class PlusOperation extends Broken5OperationEnum { private PlusOperation() { super("Plus"); } public int eval(int a, int b) { return (a + b); } } public static final Broken5OperationEnum MINUS = new MinusOperation(); private static class MinusOperation extends Broken5OperationEnum { private MinusOperation() { super("Minus"); } public int eval(int a, int b) { return (a - b); } } private Broken5OperationEnum(String name) { super(name); } public final Class getEnumClass() { return String.class; } public abstract int eval(int a, int b); public static Broken5OperationEnum getEnum(String name) { return (Broken5OperationEnum) getEnum(Broken5OperationEnum.class, name); } public static Map getEnumMap() { return getEnumMap(Broken5OperationEnum.class); } public static List getEnumList() { return getEnumList(Broken5OperationEnum.class); } public static Iterator iterator() { return iterator(Broken5OperationEnum.class); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/enums/ColorEnum.java100644 0 0 3415 11513702434 24662 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.enums; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Color enumeration. * * @author Apache Software Foundation * @version $Id: ColorEnum.java 905636 2010-02-02 14:03:32Z niallp $ */ public final class ColorEnum extends Enum { public static final ColorEnum RED = new ColorEnum("Red"); public static final ColorEnum GREEN = new ColorEnum("Green"); public static final ColorEnum BLUE = new ColorEnum("Blue"); private ColorEnum(String color) { super(color); } public static ColorEnum getEnum(String color) { return (ColorEnum) getEnum(ColorEnum.class, color); } public static Map getEnumMap() { return getEnumMap(ColorEnum.class); } public static List getEnumList() { return getEnumList(ColorEnum.class); } public static Iterator iterator() { return iterator(ColorEnum.class); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/enums/DummyEnum.java100644 0 0 2167 11513702434 24702 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.enums; /** * Dummy enumeration - no values. * * @author Apache Software Foundation * @version $Id: DummyEnum.java 905636 2010-02-02 14:03:32Z niallp $ */ public abstract class DummyEnum extends Enum { private DummyEnum(String name) { super(name); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/enums/EnumEqualsTest.java100644 0 0 13647 11513702434 25726 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.enums; import java.net.URLClassLoader; import junit.framework.TestCase; /** * Test cases for the {@link Enum} class equals method. * * @author Apache Software Foundation * @author Matthias Eichel * @version $Id: EnumEqualsTest.java 905636 2010-02-02 14:03:32Z niallp $ */ public final class EnumEqualsTest extends TestCase { public EnumEqualsTest(String name) { super(name); } public void setUp() { } //----------------------------------------------------------------------- static final class CarColorEnum extends Enum { public static final CarColorEnum BLACK = new CarColorEnum("black"); public static final CarColorEnum BROWN = new CarColorEnum("brown"); public static final CarColorEnum YELLOW = new CarColorEnum("yellow"); public static final CarColorEnum BLUE = new CarColorEnum("blue"); public static final CarColorEnum RED = new CarColorEnum("red"); private CarColorEnum(String enumAsString) { super(enumAsString); } } static final class TrafficlightColorEnum extends Enum { public static final TrafficlightColorEnum RED = new TrafficlightColorEnum("red"); public static final TrafficlightColorEnum YELLOW = new TrafficlightColorEnum("yellow"); public static final TrafficlightColorEnum GREEN = new TrafficlightColorEnum("green"); private TrafficlightColorEnum(String enumAsString) { super(enumAsString); } } static class TotallyUnrelatedClass { private final String name; public TotallyUnrelatedClass(final String name) { this.name = name; } public String getName() { return name; } } //----------------------------------------------------------------------- public void testEquals() { assertEquals(false, CarColorEnum.RED.equals(TrafficlightColorEnum.RED)); assertEquals(false, CarColorEnum.YELLOW.equals(TrafficlightColorEnum.YELLOW)); assertEquals(false, TrafficlightColorEnum.RED.equals(new TotallyUnrelatedClass("red"))); assertEquals(false, CarColorEnum.RED.equals(new TotallyUnrelatedClass("red"))); assertEquals(false, TrafficlightColorEnum.RED.equals(new TotallyUnrelatedClass("some"))); assertEquals(false, CarColorEnum.RED.equals(new TotallyUnrelatedClass("some"))); } public void testEquals_classloader_equal() throws Exception { ClassLoader cl = ColorEnum.class.getClassLoader(); if (cl instanceof URLClassLoader) { URLClassLoader urlCL = (URLClassLoader) cl; URLClassLoader urlCL1 = new URLClassLoader(urlCL.getURLs(), null); URLClassLoader urlCL2 = new URLClassLoader(urlCL.getURLs(), null); Class otherEnumClass1 = urlCL1.loadClass("org.apache.commons.lang.enums.ColorEnum"); Class otherEnumClass2 = urlCL2.loadClass("org.apache.commons.lang.enums.ColorEnum"); Object blue1 = otherEnumClass1.getDeclaredField("BLUE").get(null); Object blue2 = otherEnumClass2.getDeclaredField("BLUE").get(null); assertEquals(true, blue1.equals(blue2)); } } public void testEquals_classloader_different() throws Exception { ClassLoader cl = ColorEnum.class.getClassLoader(); if (cl instanceof URLClassLoader) { URLClassLoader urlCL = (URLClassLoader) cl; URLClassLoader urlCL1 = new URLClassLoader(urlCL.getURLs(), null); URLClassLoader urlCL2 = new URLClassLoader(urlCL.getURLs(), null); Class otherEnumClass1 = urlCL1.loadClass("org.apache.commons.lang.enums.ColorEnum"); Class otherEnumClass2 = urlCL2.loadClass("org.apache.commons.lang.enums.ColorEnum"); Object blue1 = otherEnumClass1.getDeclaredField("BLUE").get(null); Object blue2 = otherEnumClass2.getDeclaredField("RED").get(null); assertEquals(false, blue1.equals(blue2)); } } //----------------------------------------------------------------------- public void testCompareTo() { try { CarColorEnum.RED.compareTo(TrafficlightColorEnum.RED); fail(); } catch (ClassCastException ex) {} try { CarColorEnum.YELLOW.compareTo(TrafficlightColorEnum.YELLOW); fail(); } catch (ClassCastException ex) {} try { TrafficlightColorEnum.RED.compareTo(new TotallyUnrelatedClass("red")); fail(); } catch (ClassCastException ex) {} try { CarColorEnum.RED.compareTo(new TotallyUnrelatedClass("red")); fail(); } catch (ClassCastException ex) {} try { TrafficlightColorEnum.RED.compareTo(new TotallyUnrelatedClass("some")); fail(); } catch (ClassCastException ex) {} try { CarColorEnum.RED.compareTo(new TotallyUnrelatedClass("some")); fail(); } catch (ClassCastException ex) {} } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/enums/EnumTest.java100644 0 0 54734 11513702434 24555 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.enums; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import junit.framework.AssertionFailedError; import junit.framework.TestCase; import org.apache.commons.lang.SerializationUtils; /** * Test cases for the {@link Enum} class. * * @author Apache Software Foundation * @author Gary D. Gregory * @version $Id: EnumTest.java 905636 2010-02-02 14:03:32Z niallp $ */ public final class EnumTest extends TestCase { private static final String ENUMS_CLASS_NAME = "org.apache.commons.lang.enums.ColorEnum"; public EnumTest(String name) { super(name); } public void setUp() { } public void testName() { assertEquals("Red", ColorEnum.RED.getName()); assertEquals("Green", ColorEnum.GREEN.getName()); assertEquals("Blue", ColorEnum.BLUE.getName()); } public void testCompareTo() { assertTrue(ColorEnum.BLUE.compareTo(ColorEnum.BLUE) == 0); assertTrue(ColorEnum.RED.compareTo(ColorEnum.BLUE) > 0); assertTrue(ColorEnum.BLUE.compareTo(ColorEnum.RED) < 0); try { ColorEnum.RED.compareTo(null); fail(); } catch (NullPointerException ex) {} try { ColorEnum.RED.compareTo(new Object()); fail(); } catch (ClassCastException ex) {} } public void testEquals() { assertSame(ColorEnum.RED, ColorEnum.RED); assertSame(ColorEnum.getEnum("Red"), ColorEnum.RED); assertEquals(false, ColorEnum.RED.equals(null)); assertEquals(true, ColorEnum.RED.equals(ColorEnum.RED)); assertEquals(true, ColorEnum.RED.equals(ColorEnum.getEnum("Red"))); } public void testHashCode() { assertEquals(ColorEnum.RED.hashCode(), ColorEnum.RED.hashCode()); assertEquals(7 + ColorEnum.class.hashCode() + 3 * "Red".hashCode(), ColorEnum.RED.hashCode()); } public void testToString() { String toString = ColorEnum.RED.toString(); assertEquals("ColorEnum[Red]", toString); assertSame(toString, ColorEnum.RED.toString()); } public void testIterator() { Iterator it = ColorEnum.iterator(); assertSame(ColorEnum.RED, it.next()); assertSame(ColorEnum.GREEN, it.next()); assertSame(ColorEnum.BLUE, it.next()); } public void testList() { List list = new ArrayList(ColorEnum.getEnumList()); assertNotNull(list); assertEquals( list.size(), ColorEnum.getEnumMap().keySet().size()); Iterator it = list.iterator(); assertSame(ColorEnum.RED, it.next()); assertSame(ColorEnum.GREEN, it.next()); assertSame(ColorEnum.BLUE, it.next()); } public void testMap() { Map map = new HashMap(ColorEnum.getEnumMap()); assertNotNull(map); assertTrue(map.containsValue(ColorEnum.RED)); assertTrue(map.containsValue(ColorEnum.GREEN)); assertTrue(map.containsValue(ColorEnum.BLUE)); assertSame(ColorEnum.RED, map.get("Red")); assertSame(ColorEnum.GREEN, map.get("Green")); assertSame(ColorEnum.BLUE, map.get("Blue")); assertEquals( map.keySet().size(), ColorEnum.getEnumList().size()); } public void testGet() { assertSame(ColorEnum.RED, ColorEnum.getEnum("Red")); assertSame(ColorEnum.GREEN, ColorEnum.getEnum("Green")); assertSame(ColorEnum.BLUE, ColorEnum.getEnum("Blue")); assertSame(null, ColorEnum.getEnum("Pink")); } public void testSerialization() { int hashCode = ColorEnum.RED.hashCode(); assertSame(ColorEnum.RED, SerializationUtils.clone(ColorEnum.RED)); assertEquals(hashCode, SerializationUtils.clone(ColorEnum.RED).hashCode()); assertSame(ColorEnum.GREEN, SerializationUtils.clone(ColorEnum.GREEN)); assertSame(ColorEnum.BLUE, SerializationUtils.clone(ColorEnum.BLUE)); } public void testBroken1() { try { Broken1Enum.RED.getName(); fail(); } catch (ExceptionInInitializerError ex) { assertTrue(ex.getException() instanceof IllegalArgumentException); } } public void testBroken2() { try { Broken2Enum.RED.getName(); fail(); } catch (ExceptionInInitializerError ex) { assertTrue(ex.getException() instanceof IllegalArgumentException); } } public void testBroken3() { try { Broken3Enum.RED.getName(); fail(); } catch (ExceptionInInitializerError ex) { assertTrue(ex.getException() instanceof IllegalArgumentException); } } public void testBroken1Operation() { try { Broken1OperationEnum.PLUS.getName(); fail(); } catch (ExceptionInInitializerError ex) { assertTrue(ex.getException() instanceof IllegalArgumentException); } } public void testBroken2Operation() { try { Broken2OperationEnum.PLUS.getName(); fail(); } catch (ExceptionInInitializerError ex) { assertTrue(ex.getException() instanceof IllegalArgumentException); } } public void testBroken3Operation() { try { Broken3OperationEnum.PLUS.getName(); fail(); } catch (ExceptionInInitializerError ex) { assertTrue(ex.getException() instanceof IllegalArgumentException); } } public void testBroken4Operation() { try { Broken4OperationEnum.PLUS.getName(); fail(); } catch (ExceptionInInitializerError ex) { assertTrue(ex.getException() instanceof IllegalArgumentException); } } public void testBroken5Operation() { try { Broken5OperationEnum.PLUS.getName(); fail(); } catch (ExceptionInInitializerError ex) { assertTrue(ex.getException() instanceof IllegalArgumentException); } } public void testOperationGet() { assertSame(OperationEnum.PLUS, OperationEnum.getEnum("Plus")); assertSame(OperationEnum.MINUS, OperationEnum.getEnum("Minus")); assertSame(null, OperationEnum.getEnum("Pink")); } public void testOperationSerialization() { assertSame(OperationEnum.PLUS, SerializationUtils.clone(OperationEnum.PLUS)); assertSame(OperationEnum.MINUS, SerializationUtils.clone(OperationEnum.MINUS)); } public void testOperationToString() { assertEquals("OperationEnum[Plus]", OperationEnum.PLUS.toString()); } public void testOperationList() { List list = OperationEnum.getEnumList(); assertNotNull(list); assertEquals(2, list.size()); assertEquals(list.size(), OperationEnum.getEnumMap().keySet().size()); Iterator it = list.iterator(); assertSame(OperationEnum.PLUS, it.next()); assertSame(OperationEnum.MINUS, it.next()); } public void testOperationMap() { Map map = OperationEnum.getEnumMap(); assertNotNull(map); assertEquals(map.keySet().size(), OperationEnum.getEnumList().size()); assertTrue(map.containsValue(OperationEnum.PLUS)); assertTrue(map.containsValue(OperationEnum.MINUS)); assertSame(OperationEnum.PLUS, map.get("Plus")); assertSame(OperationEnum.MINUS, map.get("Minus")); } public void testOperationCalculation() { assertEquals(3, OperationEnum.PLUS.eval(1, 2)); assertEquals(-1, OperationEnum.MINUS.eval(1, 2)); } //----------------------------------------------------------------------- public void testExtended1Get() { assertSame(Extended1Enum.ALPHA, Extended1Enum.getEnum("Alpha")); assertSame(Extended1Enum.BETA, Extended1Enum.getEnum("Beta")); assertSame(null, Extended1Enum.getEnum("Gamma")); assertSame(null, Extended1Enum.getEnum("Delta")); } public void testExtended2Get() { assertSame(Extended1Enum.ALPHA, Extended2Enum.ALPHA); assertSame(Extended1Enum.BETA, Extended2Enum.BETA); assertSame(Extended2Enum.ALPHA, Extended2Enum.getEnum("Alpha")); assertSame(Extended2Enum.BETA, Extended2Enum.getEnum("Beta")); assertSame(Extended2Enum.GAMMA, Extended2Enum.getEnum("Gamma")); assertSame(null, Extended2Enum.getEnum("Delta")); } public void testExtended3Get() { assertSame(Extended2Enum.ALPHA, Extended3Enum.ALPHA); assertSame(Extended2Enum.BETA, Extended3Enum.BETA); assertSame(Extended2Enum.GAMMA, Extended3Enum.GAMMA); assertSame(Extended3Enum.ALPHA, Extended3Enum.getEnum("Alpha")); assertSame(Extended3Enum.BETA, Extended3Enum.getEnum("Beta")); assertSame(Extended3Enum.GAMMA, Extended3Enum.getEnum("Gamma")); assertSame(Extended3Enum.DELTA, Extended3Enum.getEnum("Delta")); } public void testExtendedSerialization() { assertSame(Extended1Enum.ALPHA, SerializationUtils.clone(Extended1Enum.ALPHA)); assertSame(Extended1Enum.BETA, SerializationUtils.clone(Extended1Enum.BETA)); assertSame(Extended2Enum.GAMMA, SerializationUtils.clone(Extended2Enum.GAMMA)); assertSame(Extended3Enum.DELTA, SerializationUtils.clone(Extended3Enum.DELTA)); } public void testExtendedToString() { assertEquals("Extended1Enum[Alpha]", Extended1Enum.ALPHA.toString()); assertEquals("Extended1Enum[Beta]", Extended1Enum.BETA.toString()); assertEquals("Extended1Enum[Alpha]", Extended2Enum.ALPHA.toString()); assertEquals("Extended1Enum[Beta]", Extended2Enum.BETA.toString()); assertEquals("Extended2Enum[Gamma]", Extended2Enum.GAMMA.toString()); assertEquals("Extended1Enum[Alpha]", Extended3Enum.ALPHA.toString()); assertEquals("Extended1Enum[Beta]", Extended3Enum.BETA.toString()); assertEquals("Extended2Enum[Gamma]", Extended3Enum.GAMMA.toString()); assertEquals("Extended3Enum[Delta]", Extended3Enum.DELTA.toString()); } public void testExtended1List() { List list = Extended1Enum.getEnumList(); assertNotNull(list); assertEquals(2, list.size()); assertEquals(list.size(), Extended1Enum.getEnumMap().keySet().size()); Iterator it = list.iterator(); assertSame(Extended1Enum.ALPHA, it.next()); assertSame(Extended1Enum.BETA, it.next()); } public void testExtended2List() { List list = Extended2Enum.getEnumList(); assertNotNull(list); assertEquals(3, list.size()); assertEquals(list.size(), Extended2Enum.getEnumMap().keySet().size()); Iterator it = list.iterator(); assertSame(Extended2Enum.ALPHA, it.next()); assertSame(Extended2Enum.BETA, it.next()); assertSame(Extended2Enum.GAMMA, it.next()); } public void testExtended3List() { List list = Extended3Enum.getEnumList(); assertNotNull(list); assertEquals(4, list.size()); assertEquals(list.size(), Extended3Enum.getEnumMap().keySet().size()); Iterator it = list.iterator(); assertSame(Extended3Enum.ALPHA, it.next()); assertSame(Extended3Enum.BETA, it.next()); assertSame(Extended3Enum.GAMMA, it.next()); assertSame(Extended3Enum.DELTA, it.next()); } public void testExtended1Map() { Map map = Extended1Enum.getEnumMap(); assertNotNull(map); assertEquals(map.keySet().size(), Extended1Enum.getEnumList().size()); assertTrue(map.containsValue(Extended1Enum.ALPHA)); assertTrue(map.containsValue(Extended1Enum.BETA)); assertSame(Extended1Enum.ALPHA, map.get("Alpha")); assertSame(Extended1Enum.BETA, map.get("Beta")); } public void testExtended2Map() { Map map = Extended2Enum.getEnumMap(); assertNotNull(map); assertEquals(map.keySet().size(), Extended2Enum.getEnumList().size()); assertTrue(map.containsValue(Extended2Enum.ALPHA)); assertTrue(map.containsValue(Extended2Enum.BETA)); assertTrue(map.containsValue(Extended2Enum.GAMMA)); assertSame(Extended2Enum.ALPHA, map.get("Alpha")); assertSame(Extended2Enum.BETA, map.get("Beta")); assertSame(Extended2Enum.GAMMA, map.get("Gamma")); } public void testExtended3Map() { Map map = Extended3Enum.getEnumMap(); assertNotNull(map); assertEquals(map.keySet().size(), Extended3Enum.getEnumList().size()); assertTrue(map.containsValue(Extended3Enum.ALPHA)); assertTrue(map.containsValue(Extended3Enum.BETA)); assertTrue(map.containsValue(Extended3Enum.GAMMA)); assertTrue(map.containsValue(Extended3Enum.DELTA)); assertSame(Extended3Enum.ALPHA, map.get("Alpha")); assertSame(Extended3Enum.BETA, map.get("Beta")); assertSame(Extended3Enum.GAMMA, map.get("Gamma")); assertSame(Extended3Enum.DELTA, map.get("Delta")); } //----------------------------------------------------------------------- public void testNested() { List list = new ArrayList(Nest.ColorEnum.getEnumList()); assertEquals(3, list.size()); // all is well Iterator it = list.iterator(); assertSame(Nest.ColorEnum.RED, it.next()); assertSame(Nest.ColorEnum.GREEN, it.next()); assertSame(Nest.ColorEnum.BLUE, it.next()); // This nesting works because the enum constants are defined in the SAME // class as the getEnumList(). It just acts as a normal enum. } public void testNestedBroken() { List list = new ArrayList(NestBroken.ColorEnum.getEnumList()); try { assertEquals(0, list.size()); // no enums!!! // this is BROKEN because the enum constants are defined in a DIFFERENT // class from getEnumList(). Once NestBroken class is referenced, // and thus class loaded with its enum constants, the getEnumList works: } catch (AssertionFailedError ex) { // this actually works and isn't broken on Linux SunJDK1.4.1, so... assertEquals(3, list.size()); } new NestBroken(); list = new ArrayList(NestBroken.ColorEnum.getEnumList()); assertEquals(3, list.size()); // all is well!!! Iterator it = list.iterator(); assertSame(NestBroken.RED, it.next()); assertSame(NestBroken.GREEN, it.next()); assertSame(NestBroken.BLUE, it.next()); } public void testNestedLinked() { List list = new ArrayList(NestLinked.ColorEnum.getEnumList()); assertEquals(3, list.size()); // all is well Iterator it = list.iterator(); assertSame(NestLinked.RED, it.next()); assertSame(NestLinked.GREEN, it.next()); assertSame(NestLinked.BLUE, it.next()); // This nesting works because a static block in the enum class forces a // class load of the outer class which defines the enum constants. } public void testNestedReferenced() { List list = new ArrayList(NestReferenced.ColorEnum.getEnumList()); assertEquals(3, list.size()); // all is well Iterator it = list.iterator(); assertSame(NestReferenced.RED, it.next()); assertSame(NestReferenced.GREEN, it.next()); assertSame(NestReferenced.BLUE, it.next()); // This nesting works because the enum constants are actually defined in // the SAME class as the getEnumList(). The references in the outer class // are just extra references. } public void testColorEnumEqualsWithDifferentClassLoaders() throws SecurityException, IllegalArgumentException, ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException { this.testWithDifferentClassLoaders(ColorEnum.BLUE); this.testWithDifferentClassLoaders(ColorEnum.GREEN); this.testWithDifferentClassLoaders(ColorEnum.RED); } void testWithDifferentClassLoaders(ColorEnum colorEnum) throws ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException { // Sanity checks: assertTrue(colorEnum.equals(colorEnum)); assertNotNull(ColorEnum.class.getClassLoader()); // set up: ClassLoader myClassLoader = EnumTest.class.getClassLoader(); if (!(myClassLoader instanceof URLClassLoader)) { fail("EnumTest ClassLoader = " + (myClassLoader == null ? null : myClassLoader.getClass().getName())); } ClassLoader classLoader = URLClassLoader.newInstance( ((URLClassLoader)myClassLoader).getURLs(), null); Object enumObjectFromOtherClassLoader = this.getColorEnum(classLoader, colorEnum.getName()); // the real test, part 1. try { ColorEnum testCase = (ColorEnum) enumObjectFromOtherClassLoader; fail("Should have thrown a ClassCastException for " + testCase); } catch (ClassCastException e) { // normal. } // the real test, part 2. assertEquals("The two objects should match even though they are from different class loaders", colorEnum, enumObjectFromOtherClassLoader); // the real test, part 3 - testing equals(Object) int falseCount = 0; for (Iterator iter = ColorEnum.iterator(); iter.hasNext();) { ColorEnum element = (ColorEnum) iter.next(); if (!colorEnum.equals(element)) { falseCount++; assertFalse(enumObjectFromOtherClassLoader.equals(element)); } } assertEquals(ColorEnum.getEnumList().size() - 1, falseCount); // the real test, part 4 - testing compareTo(Object) == 0 falseCount = 0; for (Iterator iter = ColorEnum.iterator(); iter.hasNext();) { ColorEnum element = (ColorEnum) iter.next(); if (!colorEnum.equals(element)) { falseCount++; assertFalse( ((Comparable)enumObjectFromOtherClassLoader).compareTo(element) == 0); } } assertEquals(ColorEnum.getEnumList().size() - 1, falseCount); } Object getColorEnum(ClassLoader classLoader, String color) throws ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException { // Sanity check: ColorEnum.RED.equals(ColorEnum.RED); assertNotNull(ColorEnum.class.getClassLoader()); // set up: assertNotNull(classLoader); assertFalse(classLoader.equals(ColorEnum.class.getClassLoader())); Class otherColorEnumClass = null; try { otherColorEnumClass = classLoader.loadClass(ENUMS_CLASS_NAME); } catch (ClassNotFoundException e) { // Dump some information to help debug class loader issues under different JREs, Ant, Eclipse. System.err.println("Could not load " + ENUMS_CLASS_NAME + " from the class loader " + classLoader); URLClassLoader urlCl = (URLClassLoader) classLoader; URL[] urls = urlCl.getURLs(); System.err.println("Class loader has " + urls.length + " URLs:"); for (int i = 0; i < urls.length; i++) { System.err.println("URL[" + i + "] = " + urls[i]); } e.printStackTrace(); throw e; } assertNotNull(otherColorEnumClass); assertNotNull(otherColorEnumClass.getClassLoader()); assertTrue(classLoader.equals(otherColorEnumClass.getClassLoader())); assertFalse(otherColorEnumClass.getClassLoader().equals(ColorEnum.class.getClassLoader())); Method method = otherColorEnumClass.getMethod("getEnum", new Class[]{String.class}); Object enumObject = method.invoke(otherColorEnumClass, new Object[]{color}); assertNotNull(enumObject); assertFalse(ColorEnum.class.equals(enumObject.getClass())); assertFalse(ColorEnum.class == enumObject.getClass()); return enumObject; } public void testEqualsToWrongInstance() { for (Iterator iter = ColorEnum.iterator(); iter.hasNext();) { ColorEnum element = (ColorEnum) iter.next(); this.testEqualsToWrongInstance(element); } } void testEqualsToWrongInstance(ColorEnum colorEnum) { assertEquals(false, colorEnum.equals("test")); assertEquals(false, colorEnum.equals(new Integer(1))); assertEquals(false, colorEnum.equals(new Boolean(true))); assertEquals(false, colorEnum.equals(new StringBuffer("test"))); assertEquals(false, colorEnum.equals(new Object())); assertEquals(false, colorEnum.equals(null)); assertEquals(false, colorEnum.equals("")); assertEquals(false, colorEnum.equals(ColorEnum.getEnum(null))); assertEquals(false, colorEnum.equals(ColorEnum.getEnum(""))); assertEquals(false, colorEnum.equals(ColorEnum.getEnum("This ColorEnum does not exist."))); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/enums/EnumUtilsLang76Test.java100644 0 0 3662 11513702434 26527 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.enums; import junit.framework.TestCase; /** * Test cases for the LANG-76 issue with {@link EnumUtils}. * * NOTE: this needs to be compiled with source/target versions set to 1.5 * in order to replicate/test the issue properly */ public class EnumUtilsLang76Test extends TestCase { public EnumUtilsLang76Test(String name) { super(name); } /** * Test LANG-76 */ public void test_EnumUtils_getEnum_LANG76() { Object obj = EnumUtils.getEnum(TestEnum.class, "1"); assertNotNull("Enum is not intialized", obj); assertEquals("EnumUtilsLang76Test.TestEnum[1]", obj.toString()); } /** Test Enum for LANG-76 **/ public static final class TestEnum extends Enum { private static final long serialVersionUID = 1L; public static final TestEnum ONE = new TestEnum("1"); public static final TestEnum TWO = new TestEnum("2"); public static final TestEnum THREE = new TestEnum("3"); private TestEnum(String value) { super(value); } } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/enums/EnumUtilsTest.java100644 0 0 13447 11513702434 25572 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.enums; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.util.Iterator; import java.util.List; import java.util.Map; import junit.framework.TestCase; /** * Test cases for the {@link Enum} class. * * @author Apache Software Foundation * @version $Id: EnumUtilsTest.java 912292 2010-02-21 02:52:56Z niallp $ */ public final class EnumUtilsTest extends TestCase { public EnumUtilsTest(String name) { super(name); } public void setUp() { } //----------------------------------------------------------------------- public void testConstructor() { assertNotNull(new EnumUtils()); Constructor[] cons = EnumUtils.class.getDeclaredConstructors(); assertEquals(1, cons.length); assertEquals(true, Modifier.isPublic(cons[0].getModifiers())); assertEquals(true, Modifier.isPublic(EnumUtils.class.getModifiers())); assertEquals(false, Modifier.isFinal(EnumUtils.class.getModifiers())); } //----------------------------------------------------------------------- public void testIterator() { Iterator it = EnumUtils.iterator(ColorEnum.class); assertSame(ColorEnum.RED, it.next()); assertSame(ColorEnum.GREEN, it.next()); assertSame(ColorEnum.BLUE, it.next()); it = EnumUtils.iterator(DummyEnum.class); assertEquals(false, it.hasNext()); } public void testIteratorEx() { try { EnumUtils.iterator(null); fail(); } catch (IllegalArgumentException ex) {} try { EnumUtils.iterator(Object.class); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testList() { List list = EnumUtils.getEnumList(ColorEnum.class); Iterator it = list.iterator(); assertSame(ColorEnum.RED, it.next()); assertSame(ColorEnum.GREEN, it.next()); assertSame(ColorEnum.BLUE, it.next()); list = EnumUtils.getEnumList(DummyEnum.class); assertEquals(0, list.size()); } public void testListEx() { try { EnumUtils.getEnumList(null); fail(); } catch (IllegalArgumentException ex) {} try { EnumUtils.getEnumList(Object.class); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testMap() { Map map = EnumUtils.getEnumMap(ColorEnum.class); assertTrue(map.containsValue(ColorEnum.RED)); assertTrue(map.containsValue(ColorEnum.GREEN)); assertTrue(map.containsValue(ColorEnum.BLUE)); assertSame(ColorEnum.RED, map.get("Red")); assertSame(ColorEnum.GREEN, map.get("Green")); assertSame(ColorEnum.BLUE, map.get("Blue")); map = EnumUtils.getEnumMap(DummyEnum.class); assertEquals(0, map.size()); } public void testMapEx() { try { EnumUtils.getEnumMap(null); fail(); } catch (IllegalArgumentException ex) {} try { EnumUtils.getEnumMap(Object.class); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testGet() { assertSame(ColorEnum.RED, EnumUtils.getEnum(ColorEnum.class, "Red")); assertSame(ColorEnum.GREEN, EnumUtils.getEnum(ColorEnum.class, "Green")); assertSame(ColorEnum.BLUE, EnumUtils.getEnum(ColorEnum.class, "Blue")); assertSame(null, EnumUtils.getEnum(ColorEnum.class, "Pink")); assertSame(null, EnumUtils.getEnum(DummyEnum.class, "Pink")); } public void testGetEx() { try { EnumUtils.getEnum(null, ""); fail(); } catch (IllegalArgumentException ex) {} try { EnumUtils.getEnum(Object.class, "Red"); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testGetValue() { assertSame(ValuedColorEnum.RED, EnumUtils.getEnum(ValuedColorEnum.class, 1)); assertSame(ValuedColorEnum.GREEN, EnumUtils.getEnum(ValuedColorEnum.class, 2)); assertSame(ValuedColorEnum.BLUE, EnumUtils.getEnum(ValuedColorEnum.class, 3)); assertSame(null, EnumUtils.getEnum(ValuedColorEnum.class, 4)); assertSame(null, EnumUtils.getEnum(DummyEnum.class, 5)); } public void testGetValueEx() { try { EnumUtils.getEnum(null, 0); fail(); } catch (IllegalArgumentException ex) {} try { EnumUtils.getEnum(Object.class, 2); fail(); } catch (IllegalArgumentException ex) {} } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/enums/Extended1Enum.java100644 0 0 3405 11513702434 25424 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "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 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.commons.lang.enums; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Base extended enumeration. * * @author Apache Software Foundation * @version $Id: Extended1Enum.java 905636 2010-02-02 14:03:32Z niallp $ */ public class Extended1Enum extends Enum { public static final Extended1Enum ALPHA = new Extended1Enum("Alpha"); public static final Extended1Enum BETA = new Extended1Enum("Beta"); protected Extended1Enum(String name) { super(name); } public static Extended1Enum getEnum(String name) { return (Extended1Enum) getEnum(Extended1Enum.class, name); } public static Map getEnumMap() { return getEnumMap(Extended1Enum.class); } public static List getEnumList() { return getEnumList(Extended1Enum.class); } public static Iterator iterator() { return iterator(Extended1Enum.class); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/enums/Extended2Enum.java100644 0 0 3302 11513702434 25421 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "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 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.commons.lang.enums; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Extended enumeration. * * @author Apache Software Foundation * @version $Id: Extended2Enum.java 905636 2010-02-02 14:03:32Z niallp $ */ public class Extended2Enum extends Extended1Enum { public static final Extended1Enum GAMMA = new Extended2Enum("Gamma"); protected Extended2Enum(String color) { super(color); } public static Extended1Enum getEnum(String name) { return (Extended1Enum) getEnum(Extended2Enum.class, name); } public static Map getEnumMap() { return getEnumMap(Extended2Enum.class); } public static List getEnumList() { return getEnumList(Extended2Enum.class); } public static Iterator iterator() { return iterator(Extended2Enum.class); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/enums/Extended3Enum.java100644 0 0 3324 11513702434 25426 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "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 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.commons.lang.enums; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Extended enumeration. * * @author Apache Software Foundation * @version $Id: Extended3Enum.java 905636 2010-02-02 14:03:32Z niallp $ */ public class Extended3Enum extends Extended2Enum { public static final Extended1Enum DELTA = new Extended3Enum("Delta"); protected Extended3Enum(String name) { super(name); } public static Extended1Enum getEnum(String name) { return (Extended1Enum) Enum.getEnum(Extended3Enum.class, name); } public static Map getEnumMap() { return Enum.getEnumMap(Extended3Enum.class); } public static List getEnumList() { return Enum.getEnumList(Extended3Enum.class); } public static Iterator iterator() { return Enum.iterator(Extended3Enum.class); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/enums/Nest.java100644 0 0 4077 11513702434 23675 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.enums; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Color enumeration demonstrating a normal simple nesting case. * All is well here as the nested enum class is really no different * to any other class. * * @author Apache Software Foundation * @version $Id: Nest.java 905636 2010-02-02 14:03:32Z niallp $ */ public final class Nest { public Nest() { super(); } public static final class ColorEnum extends Enum { public static final ColorEnum RED = new ColorEnum("Red"); public static final ColorEnum GREEN = new ColorEnum("Green"); public static final ColorEnum BLUE = new ColorEnum("Blue"); private ColorEnum(String color) { super(color); } public static ColorEnum getEnum(String color) { return (ColorEnum) getEnum(ColorEnum.class, color); } public static Map getEnumMap() { return getEnumMap(ColorEnum.class); } public static List getEnumList() { return getEnumList(ColorEnum.class); } public static Iterator iterator() { return iterator(ColorEnum.class); } } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/enums/NestBroken.java100644 0 0 4350 11513702434 25030 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.enums; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Color enumeration which demonstrates how to break the enum system. *

    * The class loader sees the two classes here as independent - the enum * class is nested, not an inner class. Calling getEnumList() on ColorEnum * will return an empty list, unless and until the NestBroken class is * referenced. * * @author Apache Software Foundation * @version $Id: NestBroken.java 905636 2010-02-02 14:03:32Z niallp $ */ public final class NestBroken { public static final ColorEnum RED = new ColorEnum("Red"); public static final ColorEnum GREEN = new ColorEnum("Green"); public static final ColorEnum BLUE = new ColorEnum("Blue"); public NestBroken() { super(); } public static final class ColorEnum extends Enum { private ColorEnum(String color) { super(color); } public static ColorEnum getEnum(String color) { return (ColorEnum) getEnum(ColorEnum.class, color); } public static Map getEnumMap() { return getEnumMap(ColorEnum.class); } public static List getEnumList() { return getEnumList(ColorEnum.class); } public static Iterator iterator() { return iterator(ColorEnum.class); } } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/enums/NestLinked.java100644 0 0 5065 11513702434 25022 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.enums; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Color enumeration which demonstrates how to define the constants in a * different class to the Enum. The extra static{} block is * needed to ensure that the enum constants are created before the * static methods on the ColorEnum are used. *

    * The class loader sees the two classes here as independent - the enum * class is nested, not an inner class. The static block thus forces the * class load of the outer class, which is needed to initialise the enums. * * @author Apache Software Foundation * @version $Id: NestLinked.java 905636 2010-02-02 14:03:32Z niallp $ */ public final class NestLinked { public static final ColorEnum RED = new ColorEnum("Red"); public static final ColorEnum GREEN = new ColorEnum("Green"); public static final ColorEnum BLUE = new ColorEnum("Blue"); public NestLinked() { super(); } public static final class ColorEnum extends Enum { static { // Explicitly reference the class where the enums are defined Object obj = NestLinked.RED; } private ColorEnum(String color) { super(color); } public static ColorEnum getEnum(String color) { return (ColorEnum) getEnum(ColorEnum.class, color); } public static Map getEnumMap() { return getEnumMap(ColorEnum.class); } public static List getEnumList() { return getEnumList(ColorEnum.class); } public static Iterator iterator() { return iterator(ColorEnum.class); } } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/enums/NestReferenced.java100644 0 0 4716 11513702434 25660 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.enums; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Color enumeration which demonstrates how to provide a view of the constants * in a different class to the Enum. This technique is the safest, however it * is obviously inconvenient as it involves defining two sets of constants. * See NestedLinked for an alternative. * * @author Apache Software Foundation * @version $Id: NestReferenced.java 905636 2010-02-02 14:03:32Z niallp $ */ public final class NestReferenced { public static final ColorEnum RED = ColorEnum.RED; public static final ColorEnum GREEN = ColorEnum.GREEN; public static final ColorEnum BLUE = ColorEnum.BLUE; public NestReferenced() { super(); } public static final class ColorEnum extends Enum { // must be defined here, not just in outer class private static final ColorEnum RED = new ColorEnum("Red"); private static final ColorEnum GREEN = new ColorEnum("Green"); private static final ColorEnum BLUE = new ColorEnum("Blue"); private ColorEnum(String color) { super(color); } public static ColorEnum getEnum(String color) { return (ColorEnum) getEnum(ColorEnum.class, color); } public static Map getEnumMap() { return getEnumMap(ColorEnum.class); } public static List getEnumList() { return getEnumList(ColorEnum.class); } public static Iterator iterator() { return iterator(ColorEnum.class); } } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/enums/OperationEnum.java100644 0 0 5411 11513702434 25542 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.enums; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Operator enumeration. * * @author Apache Software Foundation * @version $Id: OperationEnum.java 905636 2010-02-02 14:03:32Z niallp $ */ public abstract class OperationEnum extends Enum { // This syntax works for JDK 1.3 and upwards: // public static final OperationEnum PLUS = new OperationEnum("Plus") { // public int eval(int a, int b) { // return (a + b); // } // }; // public static final OperationEnum MINUS = new OperationEnum("Minus") { // public int eval(int a, int b) { // return (a - b); // } // }; // This syntax works for JDK 1.2 and upwards: public static final OperationEnum PLUS = new PlusOperation(); private static class PlusOperation extends OperationEnum { private PlusOperation() { super("Plus"); } public int eval(int a, int b) { return (a + b); } } public static final OperationEnum MINUS = new MinusOperation(); private static class MinusOperation extends OperationEnum { private MinusOperation() { super("Minus"); } public int eval(int a, int b) { return (a - b); } } private OperationEnum(String name) { super(name); } public final Class getEnumClass() { return OperationEnum.class; } public abstract int eval(int a, int b); public static OperationEnum getEnum(String name) { return (OperationEnum) getEnum(OperationEnum.class, name); } public static Map getEnumMap() { return getEnumMap(OperationEnum.class); } public static List getEnumList() { return getEnumList(OperationEnum.class); } public static Iterator iterator() { return iterator(OperationEnum.class); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/enums/ValuedColorEnum.java100644 0 0 4022 11513702434 26016 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.enums; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Color enumeration. * * @author Apache Software Foundation * @version $Id: ValuedColorEnum.java 905636 2010-02-02 14:03:32Z niallp $ */ public final class ValuedColorEnum extends ValuedEnum { public static final ValuedColorEnum RED = new ValuedColorEnum("Red", 1); public static final ValuedColorEnum GREEN = new ValuedColorEnum("Green", 2); public static final ValuedColorEnum BLUE = new ValuedColorEnum("Blue", 3); private ValuedColorEnum(String color, int value) { super(color, value); } public static ValuedColorEnum getEnum(String color) { return (ValuedColorEnum) getEnum(ValuedColorEnum.class, color); } public static ValuedColorEnum getEnum(int value) { return (ValuedColorEnum) getEnum(ValuedColorEnum.class, value); } public static Map getEnumMap() { return getEnumMap(ValuedColorEnum.class); } public static List getEnumList() { return getEnumList(ValuedColorEnum.class); } public static Iterator iterator() { return iterator(ValuedColorEnum.class); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/enums/ValuedEnumTest.java100644 0 0 22466 11513702434 25713 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.enums; import java.net.URLClassLoader; import java.util.Iterator; import java.util.List; import java.util.Map; import junit.framework.TestCase; import org.apache.commons.lang.SerializationUtils; /** * Test cases for the {@link Enum} class. * * @author Apache Software Foundation * @version $Id: ValuedEnumTest.java 905636 2010-02-02 14:03:32Z niallp $ */ public final class ValuedEnumTest extends TestCase { public ValuedEnumTest(String name) { super(name); } public void setUp() { } public void testName() { assertEquals("Red", ValuedColorEnum.RED.getName()); assertEquals("Green", ValuedColorEnum.GREEN.getName()); assertEquals("Blue", ValuedColorEnum.BLUE.getName()); } public void testValue() { assertEquals(1, ValuedColorEnum.RED.getValue()); assertEquals(2, ValuedColorEnum.GREEN.getValue()); assertEquals(3, ValuedColorEnum.BLUE.getValue()); } public void testCompareTo() { assertTrue(ValuedColorEnum.BLUE.compareTo(ValuedColorEnum.BLUE) == 0); assertTrue(ValuedColorEnum.RED.compareTo(ValuedColorEnum.BLUE) < 0); assertTrue(ValuedColorEnum.BLUE.compareTo(ValuedColorEnum.RED) > 0); } public void testCompareTo_classloader_equal() throws Exception { ClassLoader cl = ValuedColorEnum.class.getClassLoader(); if (cl instanceof URLClassLoader) { URLClassLoader urlCL = (URLClassLoader) cl; URLClassLoader urlCL1 = new URLClassLoader(urlCL.getURLs(), null); URLClassLoader urlCL2 = new URLClassLoader(urlCL.getURLs(), null); Class otherEnumClass1 = urlCL1.loadClass("org.apache.commons.lang.enums.ValuedColorEnum"); Class otherEnumClass2 = urlCL2.loadClass("org.apache.commons.lang.enums.ValuedColorEnum"); Object blue1 = otherEnumClass1.getDeclaredField("BLUE").get(null); Object blue2 = otherEnumClass2.getDeclaredField("BLUE").get(null); assertTrue(((Comparable) blue1).compareTo(blue2) == 0); } } public void testCompareTo_classloader_different() throws Exception { ClassLoader cl = ValuedColorEnum.class.getClassLoader(); if (cl instanceof URLClassLoader) { URLClassLoader urlCL = (URLClassLoader) cl; URLClassLoader urlCL1 = new URLClassLoader(urlCL.getURLs(), null); URLClassLoader urlCL2 = new URLClassLoader(urlCL.getURLs(), null); Class otherEnumClass1 = urlCL1.loadClass("org.apache.commons.lang.enums.ValuedColorEnum"); Class otherEnumClass2 = urlCL2.loadClass("org.apache.commons.lang.enums.ValuedColorEnum"); Object blue1 = otherEnumClass1.getDeclaredField("BLUE").get(null); Object blue2 = otherEnumClass2.getDeclaredField("RED").get(null); assertTrue(((Comparable) blue1).compareTo(blue2) != 0); } } public void testCompareTo_nonEnumType() { try { ValuedColorEnum.BLUE.compareTo(new TotallyUnrelatedClass(ValuedColorEnum.BLUE.getValue())); fail(); } catch (ClassCastException ex) { // expected } } public void testCompareTo_otherEnumType() { try { ValuedColorEnum.BLUE.compareTo(ValuedLanguageEnum.ENGLISH); fail(); } catch (ClassCastException ex) { // expected } } public void testCompareTo_otherType() { try { ValuedColorEnum.BLUE.compareTo("Blue"); fail(); } catch (ClassCastException ex) { // expected } } public void testCompareTo_null() { try { ValuedColorEnum.BLUE.compareTo(null); fail(); } catch (NullPointerException ex) { // expected } } public void testEquals() { assertSame(ValuedColorEnum.RED, ValuedColorEnum.RED); assertSame(ValuedColorEnum.getEnum("Red"), ValuedColorEnum.RED); } public void testEquals_classloader_equal() throws Exception { ClassLoader cl = ValuedColorEnum.class.getClassLoader(); if (cl instanceof URLClassLoader) { URLClassLoader urlCL = (URLClassLoader) cl; URLClassLoader urlCL1 = new URLClassLoader(urlCL.getURLs(), null); URLClassLoader urlCL2 = new URLClassLoader(urlCL.getURLs(), null); Class otherEnumClass1 = urlCL1.loadClass("org.apache.commons.lang.enums.ValuedColorEnum"); Class otherEnumClass2 = urlCL2.loadClass("org.apache.commons.lang.enums.ValuedColorEnum"); Object blue1 = otherEnumClass1.getDeclaredField("BLUE").get(null); Object blue2 = otherEnumClass2.getDeclaredField("BLUE").get(null); assertEquals(true, blue1.equals(blue2)); } } public void testEquals_classloader_different() throws Exception { ClassLoader cl = ValuedColorEnum.class.getClassLoader(); if (cl instanceof URLClassLoader) { URLClassLoader urlCL = (URLClassLoader) cl; URLClassLoader urlCL1 = new URLClassLoader(urlCL.getURLs(), null); URLClassLoader urlCL2 = new URLClassLoader(urlCL.getURLs(), null); Class otherEnumClass1 = urlCL1.loadClass("org.apache.commons.lang.enums.ValuedColorEnum"); Class otherEnumClass2 = urlCL2.loadClass("org.apache.commons.lang.enums.ValuedColorEnum"); Object blue1 = otherEnumClass1.getDeclaredField("BLUE").get(null); Object blue2 = otherEnumClass2.getDeclaredField("RED").get(null); assertEquals(false, blue1.equals(blue2)); } } public void testToString() { String toString = ValuedColorEnum.RED.toString(); assertEquals("ValuedColorEnum[Red=1]", toString); assertSame(toString, ValuedColorEnum.RED.toString()); } public void testIterator() { Iterator it = ValuedColorEnum.iterator(); assertSame(ValuedColorEnum.RED, it.next()); assertSame(ValuedColorEnum.GREEN, it.next()); assertSame(ValuedColorEnum.BLUE, it.next()); } public void testList() { List list = ValuedColorEnum.getEnumList(); assertNotNull(list); assertEquals( list.size(), ValuedColorEnum.getEnumMap().keySet().size()); Iterator it = list.iterator(); assertSame(ValuedColorEnum.RED, it.next()); assertSame(ValuedColorEnum.GREEN, it.next()); assertSame(ValuedColorEnum.BLUE, it.next()); } public void testMap() { Map map = ValuedColorEnum.getEnumMap(); assertNotNull(map); assertEquals( map.keySet().size(), ValuedColorEnum.getEnumList().size()); assertTrue(map.containsValue(ValuedColorEnum.RED)); assertTrue(map.containsValue(ValuedColorEnum.GREEN)); assertTrue(map.containsValue(ValuedColorEnum.BLUE)); assertSame(ValuedColorEnum.RED, map.get("Red")); assertSame(ValuedColorEnum.GREEN, map.get("Green")); assertSame(ValuedColorEnum.BLUE, map.get("Blue")); } public void testGet() { assertSame(ValuedColorEnum.RED, ValuedColorEnum.getEnum("Red")); assertSame(ValuedColorEnum.GREEN, ValuedColorEnum.getEnum("Green")); assertSame(ValuedColorEnum.BLUE, ValuedColorEnum.getEnum("Blue")); assertSame(null, ValuedColorEnum.getEnum("Pink")); } public void testGetValue() { assertSame(ValuedColorEnum.RED, ValuedColorEnum.getEnum(1)); assertSame(ValuedColorEnum.GREEN, ValuedColorEnum.getEnum(2)); assertSame(ValuedColorEnum.BLUE, ValuedColorEnum.getEnum(3)); assertSame(null, ValuedColorEnum.getEnum(4)); } public void testSerialization() { assertSame(ValuedColorEnum.RED, SerializationUtils.clone(ValuedColorEnum.RED)); assertSame(ValuedColorEnum.GREEN, SerializationUtils.clone(ValuedColorEnum.GREEN)); assertSame(ValuedColorEnum.BLUE, SerializationUtils.clone(ValuedColorEnum.BLUE)); } //-----------------------------------------------------------------------s static class TotallyUnrelatedClass { private final int value; public TotallyUnrelatedClass(final int value) { this.value = value; } public int getValue() { return value; } } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/enums/ValuedLanguageEnum.java100644 0 0 4127 11513702434 26471 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.enums; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Language enumeration. * * @author Apache Software Foundation * @version $Id: ValuedLanguageEnum.java 905636 2010-02-02 14:03:32Z niallp $ */ public final class ValuedLanguageEnum extends ValuedEnum { public static final ValuedLanguageEnum ENGLISH = new ValuedLanguageEnum("English", 1); public static final ValuedLanguageEnum FRENCH = new ValuedLanguageEnum("French", 2); public static final ValuedLanguageEnum GERMAN = new ValuedLanguageEnum("German", 3); private ValuedLanguageEnum(String color, int value) { super(color, value); } public static ValuedLanguageEnum getEnum(String color) { return (ValuedLanguageEnum) getEnum(ValuedLanguageEnum.class, color); } public static ValuedLanguageEnum getEnum(int value) { return (ValuedLanguageEnum) getEnum(ValuedLanguageEnum.class, value); } public static Map getEnumMap() { return getEnumMap(ValuedLanguageEnum.class); } public static List getEnumList() { return getEnumList(ValuedLanguageEnum.class); } public static Iterator iterator() { return iterator(ValuedLanguageEnum.class); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/exception/AbstractNestableTest.java100644 0 0 60101 11513702435 27723 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.exception; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.io.PrintWriter; import junit.framework.TestCase; /** * Tests implementations of the org.apache.commons.lang.exception.Nestable * interface. * * @author Steven Caswell * @version $Id: AbstractNestableTest.java 904021 2010-01-28 10:00:21Z niallp $ */ public abstract class AbstractNestableTest extends TestCase { /** * Constructs an instance of * AbstractNestableTestCase. * * @param name the test name */ public AbstractNestableTest(String name) { super(name); } /** * Tests the getCause() operation. */ public void testGetCause() { Nestable ne1 = getNestable(); assertNull("nestable exception() cause is null", ne1.getCause()); Nestable ne2 = getNestable("ne2"); assertNull("nestable exception(\"ne2\") cause is null", ne2.getCause()); Nestable ne3 = getNestable(getThrowable("ne3 exception")); assertNotNull("nestable exception(Throwable(\"ne3 exception\") cause is not null", ne3.getCause()); assertTrue("nestable exception(Throwable(\"ne3 exception\") cause message == ne3 exception", ne3.getCause().getMessage().equals("ne3 exception")); Nestable ne4 = getNestable("ne4", getThrowable("ne4 exception")); assertNotNull("nestable exception(\"ne4\", Throwable(\"ne4 exception\") cause is not null", ne4.getCause()); Nestable ne5 = getNestable("ne5", (Throwable) null); assertNull("nestable exception(\"ne5\", null) cause is null", ne5.getCause()); Nestable ne6 = getNestable(null, getThrowable("ne6 exception")); assertNotNull("nestable exception(null, Throwable(\"ne6 exception\") cause is not null", ne6.getCause()); } /** * Tests the getThrowableCount() operation. */ public void testGetThrowableCount() { Nestable ne1 = getNestable(); assertEquals("ne1 throwable count", 1, ne1.getThrowableCount()); Nestable ne2 = getNestable("ne2"); assertEquals("ne2 throwable count", 1, ne2.getThrowableCount()); Nestable ne3 = getNestable(getThrowable("ne3 exception")); assertEquals("ne3 throwable count", 2, ne3.getThrowableCount()); Nestable ne4 = getNestable("ne4", getThrowable("ne4 exception")); assertEquals("ne4 throwable count", 2, ne4.getThrowableCount()); Nestable ne5 = getNestable("ne5", (Throwable) null); assertEquals("ne 5 throwable count", 1, ne5.getThrowableCount()); Nestable ne6 = getNestable(null, getThrowable("ne6 exception")); assertEquals("ne 6 throwable count", 2, ne6.getThrowableCount()); Nestable ne7 = getNestable("ne7o", getNestable("ne7i", getThrowable("ne7 exception"))); assertEquals("ne 7 throwable count", 3, ne7.getThrowableCount()); Nestable ne8 = getNestable("level 1", getNestable("level 2", getNestable(getNestable("level 4", getThrowable("level 5"))))); assertEquals("ne 8 throwable count", 5, ne8.getThrowableCount()); } /** * Tests the getMessage() operation. */ public void testGetMessage() { Nestable ne1 = getNestable(); assertNull("nestable exception() message is null", ne1.getMessage()); Nestable ne2 = getNestable("ne2"); assertNotNull("nestable exception(\"ne2\") message is not null", ne2.getMessage()); assertEquals("nestable exception(\"ne2\") message == ne2", ne2.getMessage(), "ne2"); Nestable ne3 = getNestable(getThrowable("ne3 exception")); assertNotNull("nestable exception(Throwable(\"ne3 exception\") message is not null", ne3.getMessage()); assertEquals("nestable exception(Throwable(\"ne3 exception\") message equals cause.toString()", ne3.getMessage(), ne3.getCause().toString()); Nestable ne4 = getNestable("ne4", getThrowable("ne4 exception")); assertNotNull("nestable exception(\"ne4\", Throwable(\"ne4 exception\") message is not null", ne4.getMessage()); assertEquals("nestable exception(\"ne4\", Throwable(\"ne4 exception\") message == ne4", ne4.getMessage(), "ne4"); Nestable ne5 = getNestable("ne5", (Throwable) null); assertNotNull("nestable exception(\"ne5\", null) message is not null", ne5.getMessage()); assertEquals("nestable exception(\"ne5\", null) message == ne5", ne5.getMessage(), "ne5"); Throwable t6 = getThrowable("ne6 exception"); Nestable ne6 = getNestable(null, t6); assertNotNull("nestable exception(null, Throwable(\"ne6 exception\") message is not null", ne6.getMessage()); assertEquals("nestable exception(null, Throwable(\"ne6 exception\") message equals cause.toString()", ne6.getMessage(), ne6.getCause().toString()); Nestable ne7 = getNestable("ne7o", getNestable("ne7i", getThrowable("ne7 exception"))); assertEquals("nestable exception(\"ne7o\", getNestable(\"ne7i\", Throwable(\"ne7 exception\"))) message is ne7o: ne7i: ne7 exception", ne7.getMessage(), "ne7o"); Nestable ne8 = getNestable(); assertNull("nestable exception() message is null", ne8.getMessage()); } /** * Tests the getMessage(int) operation. */ public void testGetMessageI() { String[] msgs = new String[5]; msgs[0] = "level 1"; msgs[1] = "level 2"; msgs[2] = null; msgs[3] = "level 4"; msgs[4] = "level 5"; Nestable ne = getNestable(msgs[0], getNestable(msgs[1], getNestable(getNestable(msgs[3], getThrowable(msgs[4]))))); for(int i = 0; i < msgs.length; i++) { assertEquals("message " + i, msgs[i], ne.getMessage(i)); } // Test for index out of bounds try { String msg = ne.getMessage(-1); fail("getMessage(-1) should have thrown IndexOutOfBoundsException"); } catch(IndexOutOfBoundsException ioode) { } try { String msg = ne.getMessage(msgs.length + 100); fail("getMessage(999) should have thrown IndexOutOfBoundsException"); } catch(IndexOutOfBoundsException ioode) { } } /** * Tests the getMessages() operation. */ public void testGetMessages() { String[] msgs = new String[5]; msgs[0] = "level 1"; msgs[1] = "level 2"; msgs[2] = null; msgs[3] = "level 4"; msgs[4] = "level 5"; Nestable ne = getNestable(msgs[0], getNestable(msgs[1], getNestable(getNestable(msgs[3], getThrowable(msgs[4]))))); String[] nMsgs = ne.getMessages(); assertEquals("messages length", msgs.length, nMsgs.length); for(int i = 0; i < nMsgs.length; i++) { assertEquals("message " + i, msgs[i], nMsgs[i]); } } /** * Tests the getThrowable(int) operation. */ public void testGetThrowableI() { Nestable n = null; String msgs[] = null; Class[] throwables = null; msgs = new String[2]; msgs[0] = null; msgs[1] = "level 2"; throwables = new Class[2]; throwables[0] = getTester1Class(); throwables[1] = getThrowableClass(); n = getTester1(getThrowable(msgs[1])); doNestableExceptionGetThrowableI(n, throwables, msgs); msgs = new String[5]; msgs[0] = "level 1"; msgs[1] = "level 2"; msgs[2] = null; msgs[3] = "level 4"; msgs[4] = "level 5"; throwables = new Class[5]; throwables[0] = getTester1Class(); throwables[1] = getTester2Class(); throwables[2] = getTester1Class(); throwables[3] = getTester2Class(); throwables[4] = getThrowableClass(); n = getTester1(msgs[0], getTester2(msgs[1], getTester1(getTester2(msgs[3], getThrowable(msgs[4]))))); doNestableExceptionGetThrowableI(n, throwables, msgs); } private void doNestableExceptionGetThrowableI(Nestable n, Class[] classes, String[] msgs) { Throwable t = null; String msg = null; for(int i = 0; i < classes.length; i++) { t = n.getThrowable(i); assertEquals("throwable class", classes[i], t.getClass()); if(Nestable.class.isInstance(t)) { msg = ((Nestable) t).getMessage(0); } else { msg = t.getMessage(); } assertEquals("throwable message", msgs[i], msg); } // Test for index out of bounds try { t = n.getThrowable(-1); fail("getThrowable(-1) should have thrown IndexOutOfBoundsException"); } catch(IndexOutOfBoundsException ioobe) { } try { t = n.getThrowable(999); fail("getThrowable(999) should have thrown IndexOutOfBoundsException"); } catch(IndexOutOfBoundsException ioobe) { } } /** * Tests the getThrowables() operation. */ public void testGetThrowables() { Nestable n = null; String msgs[] = null; Class[] throwables = null; msgs = new String[2]; msgs[0] = null; msgs[1] = "level 2"; throwables = new Class[2]; throwables[0] = getTester1Class(); throwables[1] = getThrowableClass(); n = getTester1(getThrowable(msgs[1])); doNestableExceptionGetThrowables(n, throwables, msgs); msgs = new String[5]; msgs[0] = "level 1"; msgs[1] = "level 2"; msgs[2] = null; msgs[3] = "level 4"; msgs[4] = "level 5"; throwables = new Class[5]; throwables[0] = getTester1Class(); throwables[1] = getTester2Class(); throwables[2] = getTester1Class(); throwables[3] = getTester2Class(); throwables[4] = getThrowableClass(); n = getTester1(msgs[0], getTester2(msgs[1], getTester1(getTester2(msgs[3], getThrowable(msgs[4]))))); doNestableExceptionGetThrowables(n, throwables, msgs); } private void doNestableExceptionGetThrowables(Nestable n, Class[] classes, String[] msgs) { String msg = null; Throwable throwables[] = n.getThrowables(); assertEquals("throwables length", classes.length, throwables.length); for(int i = 0; i < classes.length; i++) { assertEquals("throwable class", classes[i], throwables[i].getClass()); Throwable t = throwables[i]; if(Nestable.class.isInstance(t)) { msg = ((Nestable) t).getMessage(0); } else { msg = t.getMessage(); } assertEquals("throwable message", msgs[i], msg); } } /** * Tests the indexOfThrowable() operation. */ public void testIndexOfThrowable() { Nestable n = null; String msgs[] = null; Class[] throwables = null; msgs = new String[5]; msgs[0] = "level 1"; msgs[1] = "level 2"; msgs[2] = null; msgs[3] = "level 4"; msgs[4] = "level 5"; throwables = new Class[5]; throwables[0] = getTester1Class(); throwables[1] = getTester2Class(); throwables[2] = getTester1Class(); throwables[3] = getTester2Class(); throwables[4] = getThrowableClass(); int[] indexes = {0, 1, 0, 1, 4}; n = getTester1(msgs[0], getTester2(msgs[1], getTester1(getTester2(msgs[3], getThrowable(msgs[4]))))); for(int i = 0; i < throwables.length; i++) { doNestableExceptionIndexOfThrowable(n, throwables[i], indexes[i], msgs[indexes[i]]); } doNestableExceptionIndexOfThrowable(n, getBaseThrowableClass(), 0, msgs[0]); doNestableExceptionIndexOfThrowable(n, java.util.Date.class, -1, null); doNestableExceptionIndexOfThrowable(n, null, -1, null); } private void doNestableExceptionIndexOfThrowable(Nestable n, Class type, int expectedIndex, String expectedMsg) { Throwable t = null; int index = n.indexOfThrowable(type); assertEquals("index of throwable " + (type == null ? "null" : type.getName()), expectedIndex, index); if(expectedIndex > -1) { t = n.getThrowable(index); if(expectedMsg != null) { String msg = null; if(Nestable.class.isInstance(t)) { msg = ((Nestable) t).getMessage(0); } else { msg = t.getMessage(); } assertEquals("message of indexed throwable", expectedMsg, msg); } } } /** * Tests the indexOfThrowable(int) operation. */ public void testIndexOfThrowableI() { Nestable n = null; String msgs[] = null; Class[] throwables = null; msgs = new String[5]; msgs[0] = "level 1"; msgs[1] = "level 2"; msgs[2] = null; msgs[3] = "level 4"; msgs[4] = "level 5"; throwables = new Class[5]; throwables[0] = getTester1Class(); throwables[1] = getTester2Class(); throwables[2] = getTester1Class(); throwables[3] = getTester2Class(); throwables[4] = getThrowableClass(); int[] indexes = {0, 1, 0, 1, 4}; n = getTester1(msgs[0], getTester2(msgs[1], getTester1(getTester2(msgs[3], getThrowable(msgs[4]))))); for(int i = 0; i < throwables.length; i++) { doNestableExceptionIndexOfThrowableI(n, throwables[i], 0, indexes[i], msgs[indexes[i]]); } doNestableExceptionIndexOfThrowableI(n, getTester2Class(), 2, 3, msgs[3]); doNestableExceptionIndexOfThrowableI(n, getTester1Class(), 1, 2, msgs[2]); doNestableExceptionIndexOfThrowableI(n, getTester1Class(), 3, -1, null); doNestableExceptionIndexOfThrowableI(n, getTester1Class(), 4, -1, null); doNestableExceptionIndexOfThrowableI(n, getThrowableClass(), 2, 4, msgs[4]); doNestableExceptionIndexOfThrowableI(n, java.util.Date.class, 0, -1, null); doNestableExceptionIndexOfThrowableI(n, null, 0, -1, null); // Test for index out of bounds try { int index = n.indexOfThrowable(getTester1Class(), -1); fail("method should have thrown IndexOutOfBoundsException"); } catch(IndexOutOfBoundsException iooob) { } try { int index = n.indexOfThrowable(getTester1Class(), 5); fail("method should have thrown IndexOutOfBoundsException"); } catch(IndexOutOfBoundsException iooob) { } } private void doNestableExceptionIndexOfThrowableI(Nestable n, Class type, int fromIndex, int expectedIndex, String expectedMsg) { Throwable t = null; int index = n.indexOfThrowable(type, fromIndex); assertEquals("index of throwable " + (type == null ? "null" : type.getName()), expectedIndex, index); if(expectedIndex > -1) { t = n.getThrowable(index); if(expectedMsg != null) { String msg = null; if(Nestable.class.isInstance(t)) { msg = ((Nestable) t).getMessage(0); } else { msg = t.getMessage(); } assertEquals("message of indexed throwable", expectedMsg, msg); } } } /** * Tests the printPartialStackTrace() operation. */ public void testPrintPartialStackTrace() { Nestable ne9 = getNestable("ne9", getThrowable("ne9 exception")); ByteArrayOutputStream baos2 = new ByteArrayOutputStream(); PrintStream ps2 = new PrintStream(baos2); PrintWriter pw2 = new PrintWriter(ps2, true); ne9.printPartialStackTrace(pw2); String stack2 = baos2.toString(); String startsWith = ne9.getClass().getName() + ": ne9"; assertTrue("stack trace startsWith == " + startsWith, stack2.startsWith(startsWith)); assertEquals("stack trace indexOf rethrown == -1", stack2.indexOf("rethrown"), -1); } /** * Tests the printStackTrace() operation. */ public void testPrintStackTrace() { Nestable ne8 = getNestable("ne8", getThrowable("ne8 exception")); ByteArrayOutputStream baos1 = new ByteArrayOutputStream(); PrintStream ps1 = new PrintStream(baos1); PrintWriter pw1 = new PrintWriter(ps1, true); ne8.printStackTrace(pw1); String stack1 = baos1.toString(); String startsWith = ne8.getClass().getName() + ": ne8"; assertTrue("stack trace startsWith == " + startsWith, stack1.startsWith(startsWith)); String indexOf = getThrowableClass().getName() + ": ne8 exception"; assertTrue("stack trace indexOf " + indexOf + " > -1", stack1.indexOf(indexOf) > -1); } /** * Returns an instance of the Nestable implementation being * tested. * * @return the instance */ public abstract Nestable getNestable(); /** * Returns an instance of the Nestable implementation being * tested. * * @param n Nestable argument to be provided to the instance * constructor * @return the instance */ public abstract Nestable getNestable(Nestable n); /** * Returns an instance of the Nestable implementation being * tested. * * @param msg String argument to be provided to the instance * constructor * @return the instance */ public abstract Nestable getNestable(String msg); /** * Returns an instance of the Nestable implementation being * tested. * * @param msg String argument to be provided to the instance * constructor * @param n Nestable argument to be provided to the instance * constructor * @return the instance */ public abstract Nestable getNestable(String msg, Nestable n); /** * Returns an instance of the Nestable implementation being * tested. * * @param msg String argument to be provided to the instance * constructor * @param t Throwable argument to be provided to the instance * constructor * @return the instance */ public abstract Nestable getNestable(String msg, Throwable t); /** * Returns an instance of the Nestable implementation being * tested. * * @param t Throwable argument to be provided to the instance * constructor * @return the instance */ public abstract Nestable getNestable(Throwable t); /** * Returns an instance of a Throwable to be used in * constructing instances of the Nestable implementation being * tested. * * @param msg String argument to be provided to the instance * constructor * @return the instance */ public abstract Throwable getThrowable(String msg); /** * Returns an instance of one tester Nestable implementation. * * @param n Nestable argument to be provided to the instance * constructor * @return the instance */ public abstract Nestable getTester1(Nestable n); /** * Returns an instance of one tester Nestable implementation. * * @param t Throwable argument to be provided to the instance * constructor * @return the instance */ public abstract Nestable getTester1(Throwable t); /** * Returns an instance of one tester Nestable implementation. * * @param msg String argument to be provided to the instance * constructor * @param n Nestable argument to be provided to the instance * constructor * @return the instance */ public abstract Nestable getTester1(String msg, Nestable n); /** * Returns an instance of one tester Nestable implementation. * * @param msg String argument to be provided to the instance * constructor * @param t Throwable argument to be provided to the instance * constructor * @return the instance */ public abstract Nestable getTester1(String msg, Throwable t); /** * Returns an instance of a second tester Nestable * implementation. * * @param msg String argument to be provided to the instance * constructor * @param n Nestable argument to be provided to the instance * constructor * @return the instance */ public abstract Nestable getTester2(String msg, Nestable n); /** * Returns an instance of a second tester Nestable * implementation. * * @param msg String argument to be provided to the instance * constructor * @param t Throwable argument to be provided to the instance * constructor * @return the instance */ public abstract Nestable getTester2(String msg, Throwable t); /** * Returns the class of the first tester Nestable * implementation. * * @return the class */ public abstract Class getTester1Class(); /** * Returns the class of the second tester Nestable * implementation. * * @return the class */ public abstract Class getTester2Class(); /** * Returns the class of the Throwable used in constructing * instances of the Nestable implementation being tested. * * @return the class */ public abstract Class getThrowableClass(); /** * Returns the base class being used, typically Error, Eception or RuntimeException. * * @return the class */ public abstract Class getBaseThrowableClass(); } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/exception/ExceptionUtilsTest.java100644 0 0 66005 11513702435 27472 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.exception; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintStream; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Modifier; import java.sql.SQLException; import java.util.List; import junit.framework.Assert; import org.apache.commons.lang.SystemUtils; /** * Tests {@link org.apache.commons.lang.exception.ExceptionUtils}. * *

    Notes

    *

    * Make sure this exception code does not depend on Java 1.4 nested exceptions. SVN revision 38990 does not compile with * Java 1.3.1. *

    *
      *
    • Compiled with Sun Java 1.3.1_15
    • *
    • Tested with Sun Java 1.3.1_15
    • *
    • Tested with Sun Java 1.4.2_12
    • *
    • Tested with Sun Java 1.5.0_08
    • *
    • All of the above on Windows XP SP2 + patches.
    • *
    *

    * Gary Gregory; August 16, 2006. *

    * * @author Apache Software Foundation * @author Daniel L. Rall * @author Steven Caswell * @author Gary Gregory * @since 1.0 */ public class ExceptionUtilsTest extends junit.framework.TestCase { private NestableException nested; private Throwable withCause; private Throwable withoutCause; private Throwable jdkNoCause; private ExceptionWithCause selfCause; private ExceptionWithCause cyclicCause; public ExceptionUtilsTest(String name) { super(name); } public void setUp() { withoutCause = createExceptionWithoutCause(); nested = new NestableException(withoutCause); withCause = new ExceptionWithCause(nested); jdkNoCause = new NullPointerException(); selfCause = new ExceptionWithCause(null); selfCause.setCause(selfCause); ExceptionWithCause a = new ExceptionWithCause(null); ExceptionWithCause b = new ExceptionWithCause(a); a.setCause(b); cyclicCause = new ExceptionWithCause(a); } protected void tearDown() throws Exception { withoutCause = null; nested = null; withCause = null; jdkNoCause = null; selfCause = null; cyclicCause = null; } //----------------------------------------------------------------------- private Throwable createExceptionWithoutCause() { try { throw new ExceptionWithoutCause(); } catch (Throwable t) { return t; } } private Throwable createExceptionWithCause() { try { try { throw new ExceptionWithCause(createExceptionWithoutCause()); } catch (Throwable t) { throw new ExceptionWithCause(t); } } catch (Throwable t) { return t; } } //----------------------------------------------------------------------- public void testConstructor() { assertNotNull(new ExceptionUtils()); Constructor[] cons = ExceptionUtils.class.getDeclaredConstructors(); assertEquals(1, cons.length); assertEquals(true, Modifier.isPublic(cons[0].getModifiers())); assertEquals(true, Modifier.isPublic(ExceptionUtils.class.getModifiers())); assertEquals(false, Modifier.isFinal(ExceptionUtils.class.getModifiers())); } //----------------------------------------------------------------------- public void testCauseMethodNameOps() { this.testCauseMethodNameOps(null); this.testCauseMethodNameOps(""); this.testCauseMethodNameOps(" "); this.testCauseMethodNameOps("\t\r\n\t"); this.testCauseMethodNameOps("testMethodName"); } void testCauseMethodNameOps(String name) { String methodName = "testMethodName"; try { Assert.assertFalse(ExceptionUtils.isCauseMethodName(methodName)); ExceptionUtils.addCauseMethodName(methodName); ExceptionUtils.addCauseMethodName(methodName); Assert.assertTrue(ExceptionUtils.isCauseMethodName(methodName)); } finally { ExceptionUtils.removeCauseMethodName(methodName); Assert.assertFalse( "The method name " + methodName + " should not be in the array", ExceptionUtils.isCauseMethodName(methodName)); } } public void testGetCause_Throwable() { assertSame(null, ExceptionUtils.getCause(null)); assertSame(null, ExceptionUtils.getCause(withoutCause)); assertSame(withoutCause, ExceptionUtils.getCause(nested)); assertSame(nested, ExceptionUtils.getCause(withCause)); assertSame(null, ExceptionUtils.getCause(jdkNoCause)); assertSame(selfCause, ExceptionUtils.getCause(selfCause)); assertSame(cyclicCause.getCause(), ExceptionUtils.getCause(cyclicCause)); assertSame(((ExceptionWithCause) cyclicCause.getCause()).getCause(), ExceptionUtils.getCause(cyclicCause.getCause())); assertSame(cyclicCause.getCause(), ExceptionUtils.getCause(((ExceptionWithCause) cyclicCause.getCause()).getCause())); } public void testGetCause_ThrowableArray() { assertSame(null, ExceptionUtils.getCause(null, null)); assertSame(null, ExceptionUtils.getCause(null, new String[0])); // match because known type assertSame(withoutCause, ExceptionUtils.getCause(nested, null)); assertSame(withoutCause, ExceptionUtils.getCause(nested, new String[0])); assertSame(withoutCause, ExceptionUtils.getCause(nested, new String[] {"getCause"})); // not known type, so match on supplied method names assertSame(nested, ExceptionUtils.getCause(withCause, null)); // default names assertSame(null, ExceptionUtils.getCause(withCause, new String[0])); assertSame(null, ExceptionUtils.getCause(withCause, new String[] {null})); assertSame(nested, ExceptionUtils.getCause(withCause, new String[] {"getCause"})); // not known type, so match on supplied method names assertSame(null, ExceptionUtils.getCause(withoutCause, null)); assertSame(null, ExceptionUtils.getCause(withoutCause, new String[0])); assertSame(null, ExceptionUtils.getCause(withoutCause, new String[] {null})); assertSame(null, ExceptionUtils.getCause(withoutCause, new String[] {"getCause"})); assertSame(null, ExceptionUtils.getCause(withoutCause, new String[] {"getTargetException"})); } public void testGetRootCause_Throwable() { assertSame(null, ExceptionUtils.getRootCause(null)); assertSame(null, ExceptionUtils.getRootCause(withoutCause)); assertSame(withoutCause, ExceptionUtils.getRootCause(nested)); assertSame(withoutCause, ExceptionUtils.getRootCause(withCause)); assertSame(null, ExceptionUtils.getRootCause(jdkNoCause)); assertSame(null, ExceptionUtils.getRootCause(selfCause)); assertSame(((ExceptionWithCause) cyclicCause.getCause()).getCause(), ExceptionUtils.getRootCause(cyclicCause)); } public void testSetCause() { Exception cause = new ExceptionWithoutCause(); assertEquals(true, ExceptionUtils.setCause(new ExceptionWithCause(null), cause)); if (SystemUtils.isJavaVersionAtLeast(140)) { assertEquals(true, ExceptionUtils.setCause(new ExceptionWithoutCause(), cause)); } } /** * Tests overriding a cause to null. */ public void testSetCauseToNull() { Exception ex = new ExceptionWithCause(new IOException()); assertEquals(true, ExceptionUtils.setCause(ex, new IllegalStateException())); assertNotNull(ExceptionUtils.getCause(ex)); assertEquals(true, ExceptionUtils.setCause(ex, null)); assertNull(ExceptionUtils.getCause(ex)); } //----------------------------------------------------------------------- public void testIsThrowableNested() { if (SystemUtils.isJavaVersionAtLeast(140)) { assertEquals(true, ExceptionUtils.isThrowableNested()); } else { assertEquals(false, ExceptionUtils.isThrowableNested()); } } public void testIsNestedThrowable_Throwable() { assertEquals(true, ExceptionUtils.isNestedThrowable(new SQLException())); assertEquals(true, ExceptionUtils.isNestedThrowable(new InvocationTargetException(new Exception()))); assertEquals(true, ExceptionUtils.isNestedThrowable(new NestableRuntimeException())); assertEquals(true, ExceptionUtils.isNestedThrowable(withCause)); assertEquals(true, ExceptionUtils.isNestedThrowable(nested)); if (SystemUtils.isJavaVersionAtLeast(140)) { assertEquals(true, ExceptionUtils.isNestedThrowable(withoutCause)); assertEquals(true, ExceptionUtils.isNestedThrowable(new Throwable())); } else { assertEquals(false, ExceptionUtils.isNestedThrowable(withoutCause)); assertEquals(false, ExceptionUtils.isNestedThrowable(new Throwable())); } } //----------------------------------------------------------------------- public void testGetThrowableCount_Throwable() { assertEquals(0, ExceptionUtils.getThrowableCount(null)); assertEquals(1, ExceptionUtils.getThrowableCount(withoutCause)); assertEquals(2, ExceptionUtils.getThrowableCount(nested)); assertEquals(3, ExceptionUtils.getThrowableCount(withCause)); assertEquals(1, ExceptionUtils.getThrowableCount(jdkNoCause)); assertEquals(1, ExceptionUtils.getThrowableCount(selfCause)); assertEquals(3, ExceptionUtils.getThrowableCount(cyclicCause)); } //----------------------------------------------------------------------- public void testGetThrowables_Throwable_null() { assertEquals(0, ExceptionUtils.getThrowables(null).length); } public void testGetThrowables_Throwable_withoutCause() { Throwable[] throwables = ExceptionUtils.getThrowables(withoutCause); assertEquals(1, throwables.length); assertSame(withoutCause, throwables[0]); } public void testGetThrowables_Throwable_nested() { Throwable[] throwables = ExceptionUtils.getThrowables(nested); assertEquals(2, throwables.length); assertSame(nested, throwables[0]); assertSame(withoutCause, throwables[1]); } public void testGetThrowables_Throwable_withCause() { Throwable[] throwables = ExceptionUtils.getThrowables(withCause); assertEquals(3, throwables.length); assertSame(withCause, throwables[0]); assertSame(nested, throwables[1]); assertSame(withoutCause, throwables[2]); } public void testGetThrowables_Throwable_jdkNoCause() { Throwable[] throwables = ExceptionUtils.getThrowables(jdkNoCause); assertEquals(1, throwables.length); assertSame(jdkNoCause, throwables[0]); } public void testGetThrowables_Throwable_selfCause() { Throwable[] throwables = ExceptionUtils.getThrowables(selfCause); assertEquals(1, throwables.length); assertSame(selfCause, throwables[0]); } public void testGetThrowables_Throwable_recursiveCause() { Throwable[] throwables = ExceptionUtils.getThrowables(cyclicCause); assertEquals(3, throwables.length); assertSame(cyclicCause, throwables[0]); assertSame(cyclicCause.getCause(), throwables[1]); assertSame(((ExceptionWithCause) cyclicCause.getCause()).getCause(), throwables[2]); } //----------------------------------------------------------------------- public void testGetThrowableList_Throwable_null() { List throwables = ExceptionUtils.getThrowableList(null); assertEquals(0, throwables.size()); } public void testGetThrowableList_Throwable_withoutCause() { List throwables = ExceptionUtils.getThrowableList(withoutCause); assertEquals(1, throwables.size()); assertSame(withoutCause, throwables.get(0)); } public void testGetThrowableList_Throwable_nested() { List throwables = ExceptionUtils.getThrowableList(nested); assertEquals(2, throwables.size()); assertSame(nested, throwables.get(0)); assertSame(withoutCause, throwables.get(1)); } public void testGetThrowableList_Throwable_withCause() { List throwables = ExceptionUtils.getThrowableList(withCause); assertEquals(3, throwables.size()); assertSame(withCause, throwables.get(0)); assertSame(nested, throwables.get(1)); assertSame(withoutCause, throwables.get(2)); } public void testGetThrowableList_Throwable_jdkNoCause() { List throwables = ExceptionUtils.getThrowableList(jdkNoCause); assertEquals(1, throwables.size()); assertSame(jdkNoCause, throwables.get(0)); } public void testGetThrowableList_Throwable_selfCause() { List throwables = ExceptionUtils.getThrowableList(selfCause); assertEquals(1, throwables.size()); assertSame(selfCause, throwables.get(0)); } public void testGetThrowableList_Throwable_recursiveCause() { List throwables = ExceptionUtils.getThrowableList(cyclicCause); assertEquals(3, throwables.size()); assertSame(cyclicCause, throwables.get(0)); assertSame(cyclicCause.getCause(), throwables.get(1)); assertSame(((ExceptionWithCause) cyclicCause.getCause()).getCause(), throwables.get(2)); } //----------------------------------------------------------------------- public void testIndexOf_ThrowableClass() { assertEquals(-1, ExceptionUtils.indexOfThrowable(null, null)); assertEquals(-1, ExceptionUtils.indexOfThrowable(null, NestableException.class)); assertEquals(-1, ExceptionUtils.indexOfThrowable(withoutCause, null)); assertEquals(-1, ExceptionUtils.indexOfThrowable(withoutCause, ExceptionWithCause.class)); assertEquals(-1, ExceptionUtils.indexOfThrowable(withoutCause, NestableException.class)); assertEquals(0, ExceptionUtils.indexOfThrowable(withoutCause, ExceptionWithoutCause.class)); assertEquals(-1, ExceptionUtils.indexOfThrowable(nested, null)); assertEquals(-1, ExceptionUtils.indexOfThrowable(nested, ExceptionWithCause.class)); assertEquals(0, ExceptionUtils.indexOfThrowable(nested, NestableException.class)); assertEquals(1, ExceptionUtils.indexOfThrowable(nested, ExceptionWithoutCause.class)); assertEquals(-1, ExceptionUtils.indexOfThrowable(withCause, null)); assertEquals(0, ExceptionUtils.indexOfThrowable(withCause, ExceptionWithCause.class)); assertEquals(1, ExceptionUtils.indexOfThrowable(withCause, NestableException.class)); assertEquals(2, ExceptionUtils.indexOfThrowable(withCause, ExceptionWithoutCause.class)); assertEquals(-1, ExceptionUtils.indexOfThrowable(withCause, Exception.class)); } public void testIndexOf_ThrowableClassInt() { assertEquals(-1, ExceptionUtils.indexOfThrowable(null, null, 0)); assertEquals(-1, ExceptionUtils.indexOfThrowable(null, NestableException.class, 0)); assertEquals(-1, ExceptionUtils.indexOfThrowable(withoutCause, null)); assertEquals(-1, ExceptionUtils.indexOfThrowable(withoutCause, ExceptionWithCause.class, 0)); assertEquals(-1, ExceptionUtils.indexOfThrowable(withoutCause, NestableException.class, 0)); assertEquals(0, ExceptionUtils.indexOfThrowable(withoutCause, ExceptionWithoutCause.class, 0)); assertEquals(-1, ExceptionUtils.indexOfThrowable(nested, null, 0)); assertEquals(-1, ExceptionUtils.indexOfThrowable(nested, ExceptionWithCause.class, 0)); assertEquals(0, ExceptionUtils.indexOfThrowable(nested, NestableException.class, 0)); assertEquals(1, ExceptionUtils.indexOfThrowable(nested, ExceptionWithoutCause.class, 0)); assertEquals(-1, ExceptionUtils.indexOfThrowable(withCause, null)); assertEquals(0, ExceptionUtils.indexOfThrowable(withCause, ExceptionWithCause.class, 0)); assertEquals(1, ExceptionUtils.indexOfThrowable(withCause, NestableException.class, 0)); assertEquals(2, ExceptionUtils.indexOfThrowable(withCause, ExceptionWithoutCause.class, 0)); assertEquals(0, ExceptionUtils.indexOfThrowable(withCause, ExceptionWithCause.class, -1)); assertEquals(0, ExceptionUtils.indexOfThrowable(withCause, ExceptionWithCause.class, 0)); assertEquals(-1, ExceptionUtils.indexOfThrowable(withCause, ExceptionWithCause.class, 1)); assertEquals(-1, ExceptionUtils.indexOfThrowable(withCause, ExceptionWithCause.class, 9)); assertEquals(-1, ExceptionUtils.indexOfThrowable(withCause, Exception.class, 0)); } //----------------------------------------------------------------------- public void testIndexOfType_ThrowableClass() { assertEquals(-1, ExceptionUtils.indexOfType(null, null)); assertEquals(-1, ExceptionUtils.indexOfType(null, NestableException.class)); assertEquals(-1, ExceptionUtils.indexOfType(withoutCause, null)); assertEquals(-1, ExceptionUtils.indexOfType(withoutCause, ExceptionWithCause.class)); assertEquals(-1, ExceptionUtils.indexOfType(withoutCause, NestableException.class)); assertEquals(0, ExceptionUtils.indexOfType(withoutCause, ExceptionWithoutCause.class)); assertEquals(-1, ExceptionUtils.indexOfType(nested, null)); assertEquals(-1, ExceptionUtils.indexOfType(nested, ExceptionWithCause.class)); assertEquals(0, ExceptionUtils.indexOfType(nested, NestableException.class)); assertEquals(1, ExceptionUtils.indexOfType(nested, ExceptionWithoutCause.class)); assertEquals(-1, ExceptionUtils.indexOfType(withCause, null)); assertEquals(0, ExceptionUtils.indexOfType(withCause, ExceptionWithCause.class)); assertEquals(1, ExceptionUtils.indexOfType(withCause, NestableException.class)); assertEquals(2, ExceptionUtils.indexOfType(withCause, ExceptionWithoutCause.class)); assertEquals(0, ExceptionUtils.indexOfType(withCause, Exception.class)); } public void testIndexOfType_ThrowableClassInt() { assertEquals(-1, ExceptionUtils.indexOfType(null, null, 0)); assertEquals(-1, ExceptionUtils.indexOfType(null, NestableException.class, 0)); assertEquals(-1, ExceptionUtils.indexOfType(withoutCause, null)); assertEquals(-1, ExceptionUtils.indexOfType(withoutCause, ExceptionWithCause.class, 0)); assertEquals(-1, ExceptionUtils.indexOfType(withoutCause, NestableException.class, 0)); assertEquals(0, ExceptionUtils.indexOfType(withoutCause, ExceptionWithoutCause.class, 0)); assertEquals(-1, ExceptionUtils.indexOfType(nested, null, 0)); assertEquals(-1, ExceptionUtils.indexOfType(nested, ExceptionWithCause.class, 0)); assertEquals(0, ExceptionUtils.indexOfType(nested, NestableException.class, 0)); assertEquals(1, ExceptionUtils.indexOfType(nested, ExceptionWithoutCause.class, 0)); assertEquals(-1, ExceptionUtils.indexOfType(withCause, null)); assertEquals(0, ExceptionUtils.indexOfType(withCause, ExceptionWithCause.class, 0)); assertEquals(1, ExceptionUtils.indexOfType(withCause, NestableException.class, 0)); assertEquals(2, ExceptionUtils.indexOfType(withCause, ExceptionWithoutCause.class, 0)); assertEquals(0, ExceptionUtils.indexOfType(withCause, ExceptionWithCause.class, -1)); assertEquals(0, ExceptionUtils.indexOfType(withCause, ExceptionWithCause.class, 0)); assertEquals(-1, ExceptionUtils.indexOfType(withCause, ExceptionWithCause.class, 1)); assertEquals(-1, ExceptionUtils.indexOfType(withCause, ExceptionWithCause.class, 9)); assertEquals(0, ExceptionUtils.indexOfType(withCause, Exception.class, 0)); } //----------------------------------------------------------------------- public void testPrintRootCauseStackTrace_Throwable() throws Exception { ExceptionUtils.printRootCauseStackTrace(null); // could pipe system.err to a known stream, but not much point as // internally this method calls stram method anyway } public void testPrintRootCauseStackTrace_ThrowableStream() throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(1024); ExceptionUtils.printRootCauseStackTrace(null, (PrintStream) null); ExceptionUtils.printRootCauseStackTrace(null, new PrintStream(out)); assertEquals(0, out.toString().length()); out = new ByteArrayOutputStream(1024); try { ExceptionUtils.printRootCauseStackTrace(withCause, (PrintStream) null); fail(); } catch (IllegalArgumentException ex) { } out = new ByteArrayOutputStream(1024); Throwable withCause = createExceptionWithCause(); ExceptionUtils.printRootCauseStackTrace(withCause, new PrintStream(out)); String stackTrace = out.toString(); assertTrue(stackTrace.indexOf(ExceptionUtils.WRAPPED_MARKER) != -1); out = new ByteArrayOutputStream(1024); ExceptionUtils.printRootCauseStackTrace(withoutCause, new PrintStream(out)); stackTrace = out.toString(); assertTrue(stackTrace.indexOf(ExceptionUtils.WRAPPED_MARKER) == -1); } public void testPrintRootCauseStackTrace_ThrowableWriter() throws Exception { StringWriter writer = new StringWriter(1024); ExceptionUtils.printRootCauseStackTrace(null, (PrintWriter) null); ExceptionUtils.printRootCauseStackTrace(null, new PrintWriter(writer)); assertEquals(0, writer.getBuffer().length()); writer = new StringWriter(1024); try { ExceptionUtils.printRootCauseStackTrace(withCause, (PrintWriter) null); fail(); } catch (IllegalArgumentException ex) { } writer = new StringWriter(1024); Throwable withCause = createExceptionWithCause(); ExceptionUtils.printRootCauseStackTrace(withCause, new PrintWriter(writer)); String stackTrace = writer.toString(); assertTrue(stackTrace.indexOf(ExceptionUtils.WRAPPED_MARKER) != -1); writer = new StringWriter(1024); ExceptionUtils.printRootCauseStackTrace(withoutCause, new PrintWriter(writer)); stackTrace = writer.toString(); assertTrue(stackTrace.indexOf(ExceptionUtils.WRAPPED_MARKER) == -1); } //----------------------------------------------------------------------- public void testGetRootCauseStackTrace_Throwable() throws Exception { assertEquals(0, ExceptionUtils.getRootCauseStackTrace(null).length); Throwable withCause = createExceptionWithCause(); String[] stackTrace = ExceptionUtils.getRootCauseStackTrace(withCause); boolean match = false; for (int i = 0; i < stackTrace.length; i++) { if (stackTrace[i].startsWith(ExceptionUtils.WRAPPED_MARKER)) { match = true; break; } } assertEquals(true, match); stackTrace = ExceptionUtils.getRootCauseStackTrace(withoutCause); match = false; for (int i = 0; i < stackTrace.length; i++) { if (stackTrace[i].startsWith(ExceptionUtils.WRAPPED_MARKER)) { match = true; break; } } assertEquals(false, match); } public void testRemoveCommonFrames_ListList() throws Exception { try { ExceptionUtils.removeCommonFrames(null, null); fail(); } catch (IllegalArgumentException ex) { } } public void test_getMessage_Throwable() { Throwable th = null; assertEquals("", ExceptionUtils.getMessage(th)); th = new IllegalArgumentException("Base"); assertEquals("IllegalArgumentException: Base", ExceptionUtils.getMessage(th)); th = new ExceptionWithCause("Wrapper", th); assertEquals("ExceptionUtilsTest.ExceptionWithCause: Wrapper", ExceptionUtils.getMessage(th)); } public void test_getRootCauseMessage_Throwable() { Throwable th = null; assertEquals("", ExceptionUtils.getRootCauseMessage(th)); th = new IllegalArgumentException("Base"); assertEquals("IllegalArgumentException: Base", ExceptionUtils.getRootCauseMessage(th)); th = new ExceptionWithCause("Wrapper", th); assertEquals("IllegalArgumentException: Base", ExceptionUtils.getRootCauseMessage(th)); } //----------------------------------------------------------------------- /** * Provides a method with a well known chained/nested exception * name which matches the full signature (e.g. has a return value * of Throwable. */ private static class ExceptionWithCause extends Exception { private Throwable cause; public ExceptionWithCause(String str, Throwable cause) { super(str); setCause(cause); } public ExceptionWithCause(Throwable cause) { super(); setCause(cause); } public Throwable getCause() { return cause; } public void setCause(Throwable cause) { this.cause = cause; } } /** * Provides a method with a well known chained/nested exception * name which does not match the full signature (e.g. lacks a * return value of Throwable. */ private static class ExceptionWithoutCause extends Exception { public void getTargetException() { } } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/exception/NestableDelegateTest.java100644 0 0 104512 11513702435 27717 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.exception; import java.io.ByteArrayOutputStream; import java.io.EOFException; import java.io.IOException; import java.io.PrintStream; import java.io.PrintWriter; /** * Tests the org.apache.commons.lang.exception.NestableDelegate class. * * @author Steven Caswell * @author Daniel L. Rall * @version $Id: NestableDelegateTest.java 905628 2010-02-02 13:29:55Z niallp $ */ public class NestableDelegateTest extends junit.framework.TestCase { private static final String CONSTRUCTOR_FAILED_MSG = "The Nestable implementation passed to the NestableDelegate(Nestable) constructor must extend java.lang.Throwable"; private static final String PARTIAL_STACK_TRACE = "ThrowableNestedNestable partial stack trace place-holder"; protected String lineSeparator; /** * Construct a new instance of NestableDelegateTestCase with the specified name */ public NestableDelegateTest(String name) { super(name); } /** * Set up instance variables required by this test case. */ public void setUp() { lineSeparator = System.getProperty("line.separator"); } /** * Tear down instance variables required by this test case. */ public void tearDown() { lineSeparator = null; } /** * Test the implementation */ public void testNestableDelegateConstructor() { String msg = null; boolean constructorFailed = false; try { NestableDelegate nonThrowableCause = new NestableDelegate(new NonThrowableNestable()); } catch(IllegalArgumentException iae) { constructorFailed = true; msg = iae.getMessage(); } assertTrue("nestable delegate constructor with non-throwable cause failed == true", constructorFailed); assertTrue("constructor failed exception msg == " + CONSTRUCTOR_FAILED_MSG, msg.equals(CONSTRUCTOR_FAILED_MSG)); constructorFailed = false; try { NestableDelegate nd1 = new NestableDelegate(new ThrowableNestable()); } catch(IllegalArgumentException iae) { constructorFailed = true; } assertTrue("nestable delegate constructor with throwable cause failed == false", !constructorFailed); } public void testNestableDelegateGetMessage() { Nestable ne1 = new ThrowableNestable(); assertTrue("ThrowableNestable ne1 getMessage() == ThrowableNestable exception", ne1.getMessage().equals("ThrowableNestable exception")); NestableDelegate nd1 = new NestableDelegate(ne1); assertTrue("nd1 getMessage() == " + ne1.getCause().getMessage(), nd1.getMessage("base").equals("base: " + ne1.getCause().getMessage())); Nestable ne2 = new ThrowableNestedNestable(new Exception("nested exception 2")); NestableDelegate nd2 = new NestableDelegate(ne2); assertTrue("nd2 getMessage() == base: " + ne2.getCause().getMessage(), nd2.getMessage("base").equals("base: " + ne2.getCause().getMessage())); } public void testNestableDelegateGetThrowableCount() { Nestable n = null; NestableDelegate d = null; n = new NestableDelegateTester1(); d = new NestableDelegate(n); doNestableDelegateGetThrowableCount(d, 1); n = new NestableDelegateTester1("level 1"); d = new NestableDelegate(n); doNestableDelegateGetThrowableCount(d, 1); n = new NestableDelegateTester1(new Exception()); d = new NestableDelegate(n); doNestableDelegateGetThrowableCount(d, 2); n = new NestableDelegateTester1(new Exception("level 2")); d = new NestableDelegate(n); doNestableDelegateGetThrowableCount(d, 2); n = new NestableDelegateTester1("level 1", new NestableDelegateTester2("level 2", new NestableDelegateTester1( new NestableDelegateTester2("level 4", new Exception("level 5") ) ) ) ); d = new NestableDelegate(n); doNestableDelegateGetThrowableCount(d, 5); } private void doNestableDelegateGetThrowableCount(NestableDelegate d, int len) { // Compare the lengths assertEquals("delegate length", len, d.getThrowableCount()); } public void testNestableDelegateGetMessages() { Nestable n = null; NestableDelegate d = null; String msgs[] = null; msgs = new String[1]; n = new NestableDelegateTester1(); d = new NestableDelegate(n); doNestableDelegateGetMessages(d, msgs); msgs = new String[1]; msgs[0] = "level 1"; n = new NestableDelegateTester1(msgs[0]); d = new NestableDelegate(n); doNestableDelegateGetMessages(d, msgs); msgs = new String[2]; n = new NestableDelegateTester1(new Exception()); d = new NestableDelegate(n); doNestableDelegateGetMessages(d, msgs); msgs = new String[2]; msgs[0] = null; msgs[1] = "level 2"; n = new NestableDelegateTester1(new Exception(msgs[1])); d = new NestableDelegate(n); doNestableDelegateGetMessages(d, msgs); msgs = new String[5]; msgs[0] = "level 1"; msgs[1] = "level 2"; msgs[2] = null; msgs[3] = "level 4"; msgs[4] = "level 5"; n = new NestableDelegateTester1(msgs[0], new NestableDelegateTester2(msgs[1], new NestableDelegateTester1( new NestableDelegateTester2(msgs[3], new Exception(msgs[4]) ) ) ) ); d = new NestableDelegate(n); doNestableDelegateGetMessages(d, msgs); } private void doNestableDelegateGetMessages(NestableDelegate d, String[] nMsgs) { // Compare the messages String[] dMsgs = d.getMessages(); assertEquals("messages length", nMsgs.length, dMsgs.length); for(int i = 0; i < nMsgs.length; i++) { assertEquals("message " + i, nMsgs[i], dMsgs[i]); } } public void testGetMessageString() { NestableDelegateTester1 ndt1 = new NestableDelegateTester1 (new NullPointerException ()); NestableDelegate nd = new NestableDelegate (ndt1); assertNull (nd.getMessage((String)null)); ndt1 = new NestableDelegateTester1 (new NullPointerException ("null pointer")); nd = new NestableDelegate (ndt1); assertNotNull(nd.getMessage((String)null)); ndt1 = new NestableDelegateTester1 (); nd = new NestableDelegate (ndt1); assertNull(nd.getMessage((String)null)); ndt1 = new NestableDelegateTester1 ("root"); nd = new NestableDelegate (ndt1); assertNull(nd.getMessage((String)null)); } public void testNestableDelegateGetMessageN() { Nestable n = null; NestableDelegate d = null; String[] msgs = new String[5]; msgs[0] = "level 1"; msgs[1] = "level 2"; msgs[2] = null; msgs[3] = "level 4"; msgs[4] = "level 5"; n = new NestableDelegateTester1(msgs[0], new NestableDelegateTester2(msgs[1], new NestableDelegateTester1( new NestableDelegateTester2(msgs[3], new Exception(msgs[4]) ) ) ) ); d = new NestableDelegate(n); for(int i = 0; i < msgs.length; i++) { assertEquals("message " + i, msgs[i], d.getMessage(i)); } // Test for index out of bounds try { String msg = d.getMessage(-1); fail("getMessage(-1) should have thrown IndexOutOfBoundsException"); } catch(IndexOutOfBoundsException ioode) { } try { String msg = d.getMessage(msgs.length + 100); fail("getMessage(999) should have thrown IndexOutOfBoundsException"); } catch(IndexOutOfBoundsException ioode) { } } public void testNestableDelegateGetThrowableN() { Nestable n = null; NestableDelegate d = null; String msgs[] = null; Class[] throwables = null; msgs = new String[2]; msgs[0] = null; msgs[1] = "level 2"; throwables = new Class[2]; throwables[0] = NestableDelegateTester1.class; throwables[1] = Exception.class; n = new NestableDelegateTester1(new Exception(msgs[1])); d = new NestableDelegate(n); doNestableDelegateGetThrowableN(d, throwables, msgs); msgs = new String[5]; msgs[0] = "level 1"; msgs[1] = "level 2"; msgs[2] = null; msgs[3] = "level 4"; msgs[4] = "level 5"; throwables = new Class[5]; throwables[0] = NestableDelegateTester1.class; throwables[1] = NestableDelegateTester2.class; throwables[2] = NestableDelegateTester1.class; throwables[3] = NestableDelegateTester2.class; throwables[4] = Exception.class; n = new NestableDelegateTester1(msgs[0], new NestableDelegateTester2(msgs[1], new NestableDelegateTester1( new NestableDelegateTester2(msgs[3], new Exception(msgs[4]) ) ) ) ); d = new NestableDelegate(n); doNestableDelegateGetThrowableN(d, throwables, msgs); } private void doNestableDelegateGetThrowableN(NestableDelegate d, Class[] classes, String[] msgs) { Throwable t = null; String msg = null; for(int i = 0; i < classes.length; i++) { t = d.getThrowable(i); assertEquals("throwable class", classes[i], t.getClass()); if(Nestable.class.isInstance(t)) { msg = ((Nestable) t).getMessage(0); } else { msg = t.getMessage(); } assertEquals("throwable message", msgs[i], msg); } // Test for index out of bounds try { t = d.getThrowable(-1); fail("getThrowable(-1) should have thrown IndexOutOfBoundsException"); } catch(IndexOutOfBoundsException ioobe) { } try { t = d.getThrowable(999); fail("getThrowable(999) should have thrown IndexOutOfBoundsException"); } catch(IndexOutOfBoundsException ioobe) { } } public void testNestableDelegateGetThrowables() { Nestable n = null; NestableDelegate d = null; String msgs[] = null; Class[] throwables = null; msgs = new String[2]; msgs[0] = null; msgs[1] = "level 2"; throwables = new Class[2]; throwables[0] = NestableDelegateTester1.class; throwables[1] = Exception.class; n = new NestableDelegateTester1(new Exception(msgs[1])); d = new NestableDelegate(n); doNestableDelegateGetThrowables(d, throwables, msgs); msgs = new String[5]; msgs[0] = "level 1"; msgs[1] = "level 2"; msgs[2] = null; msgs[3] = "level 4"; msgs[4] = "level 5"; throwables = new Class[5]; throwables[0] = NestableDelegateTester1.class; throwables[1] = NestableDelegateTester2.class; throwables[2] = NestableDelegateTester1.class; throwables[3] = NestableDelegateTester2.class; throwables[4] = Exception.class; n = new NestableDelegateTester1(msgs[0], new NestableDelegateTester2(msgs[1], new NestableDelegateTester1( new NestableDelegateTester2(msgs[3], new Exception(msgs[4]) ) ) ) ); d = new NestableDelegate(n); doNestableDelegateGetThrowables(d, throwables, msgs); } private void doNestableDelegateGetThrowables(NestableDelegate d, Class[] classes, String[] msgs) { Throwable[] throwables = null; String msg = null; throwables = d.getThrowables(); assertEquals("throwables length", classes.length, throwables.length); for(int i = 0; i < classes.length; i++) { assertEquals("throwable class", classes[i], throwables[i].getClass()); Throwable t = throwables[i]; if(Nestable.class.isInstance(t)) { msg = ((Nestable) t).getMessage(0); } else { msg = t.getMessage(); } assertEquals("throwable message", msgs[i], msg); } } public void testIndexOfThrowable() { Nestable n = null; NestableDelegate d = null; String msgs[] = null; Class[] throwables = null; msgs = new String[5]; msgs[0] = "level 1"; msgs[1] = "level 2"; msgs[2] = null; msgs[3] = "level 4"; msgs[4] = "level 5"; throwables = new Class[5]; throwables[0] = NestableDelegateTester1.class; throwables[1] = NestableDelegateTester2.class; throwables[2] = NestableDelegateTester1.class; throwables[3] = NestableDelegateTester2.class; throwables[4] = EOFException.class; int[] indexes = {0, 1, 0, 1, 4}; n = new NestableDelegateTester1(msgs[0], new NestableDelegateTester2(msgs[1], new NestableDelegateTester1( new NestableDelegateTester2(msgs[3], new EOFException(msgs[4]) ) ) ) ); d = new NestableDelegate(n); for(int i = 0; i < throwables.length; i++) { doNestableDelegateIndexOfThrowable(d, throwables[i], 0, indexes[i], msgs[indexes[i]]); } doNestableDelegateIndexOfThrowable(d, NestableDelegateTester2.class, 2, 3, msgs[3]); doNestableDelegateIndexOfThrowable(d, NestableDelegateTester1.class, 1, 2, msgs[2]); doNestableDelegateIndexOfThrowable(d, NestableDelegateTester1.class, 3, -1, null); doNestableDelegateIndexOfThrowable(d, NestableDelegateTester1.class, 4, -1, null); doNestableDelegateIndexOfThrowable(d, EOFException.class, 2, 4, msgs[4]); doNestableDelegateIndexOfThrowable(d, IOException.class, 2, 4, msgs[4]); doNestableDelegateIndexOfThrowable(d, Exception.class, 2, 2, msgs[2]); doNestableDelegateIndexOfThrowable(d, Exception.class, 0, 0, msgs[0]); doNestableDelegateIndexOfThrowable(d, java.util.Date.class, 0, -1, null); doNestableDelegateIndexOfThrowable(d, null, 0, -1, null); // Test for index out of bounds try { int index = d.indexOfThrowable(NestableDelegateTester1.class, -1); fail("method should have thrown IndexOutOfBoundsException"); } catch(IndexOutOfBoundsException iooob) { } try { int index = d.indexOfThrowable(NestableDelegateTester1.class, 5); fail("method should have thrown IndexOutOfBoundsException"); } catch(IndexOutOfBoundsException iooob) { } } private void doNestableDelegateIndexOfThrowable(NestableDelegate d, Class type, int fromIndex, int expectedIndex, String expectedMsg) { Throwable t = null; int index = d.indexOfThrowable(type, fromIndex); assertEquals("index of throwable " + (type == null ? "null" : type.getName()), expectedIndex, index); if(expectedIndex > -1) { t = d.getThrowable(index); if(expectedMsg != null) { String msg = null; if(Nestable.class.isInstance(t)) { msg = ((Nestable) t).getMessage(0); } else { msg = t.getMessage(); } assertEquals("message of indexed throwable", expectedMsg, msg); } } } public void testNestableDelegetePrintStackTrace() { int lineSepLen = lineSeparator.length(); int partialStackTraceLen = PARTIAL_STACK_TRACE.length(); Nestable ne3 = new ThrowableNestedNestable(new Exception("nested exception 3")); NestableDelegate nd3 = new NestableDelegate(ne3); ByteArrayOutputStream baos1 = new ByteArrayOutputStream(); PrintStream ps1 = new PrintStream(baos1); nd3.printStackTrace(ps1); String stack1 = baos1.toString(); assertTrue("stack trace startsWith", stack1.startsWith(PARTIAL_STACK_TRACE)); Nestable n = new NestableDelegateTester1("level 1", new NestableDelegateTester2("level 2", new NestableDelegateTester1( new NestableDelegateTester2("level 4", new Exception("level 5") ) ) ) ); NestableDelegate d = new NestableDelegate(n); // Only testing the flags for jdk1.3 and below if (!ExceptionUtils.isThrowableNested()) { NestableDelegate.topDown = true; NestableDelegate.trimStackFrames = true; checkStackTrace(d, true, true, NestableDelegateTester1.class.getName()+": level 1", 24); NestableDelegate.topDown = true; NestableDelegate.trimStackFrames = false; checkStackTrace(d, true, false, NestableDelegateTester1.class.getName()+": level 1", 80); NestableDelegate.topDown = false; NestableDelegate.trimStackFrames = true; checkStackTrace(d, false, true, "java.lang.Exception: level 5", 24); NestableDelegate.topDown = false; NestableDelegate.trimStackFrames = false; checkStackTrace(d, false, false, "java.lang.Exception: level 5", 80); NestableDelegate.topDown = true; NestableDelegate.trimStackFrames = true; } } private void checkStackTrace(NestableDelegate d, boolean topDown, boolean trimStackFrames, String startsWith, int expCount) { ByteArrayOutputStream baos1 = new ByteArrayOutputStream(); PrintStream ps1 = new PrintStream(baos1); d.printStackTrace(ps1); String stack1 = baos1.toString(); int actCount = countLines(stack1); assertTrue("topDown: "+topDown+", trimStackFrames: "+trimStackFrames+" startsWith", stack1.startsWith(startsWith)); // test is unreliable, as count varies depending on JUnit version/where main method is // assertEquals("topDown: "+topDown+", trimStackFrames: "+trimStackFrames+" lineCount", // expCount, actCount); } private int countLines(String s) { if (s == null) return 0; int i = 0, ndx = -1; while ((ndx = s.indexOf("\n", ndx+1)) != -1) { i++; } return i; } } /** * Nestable and Throwable class which can be passed to the NestableDelegate * constructor. Used for testing various methods which iterate through the * nested causes. */ class NestableDelegateTester1 extends Exception implements Nestable { private Throwable cause = null; public NestableDelegateTester1() { super(); } public NestableDelegateTester1(String reason, Throwable cause) { super(reason); this.cause = cause; } public NestableDelegateTester1(String reason) { super(reason); } public NestableDelegateTester1(Throwable cause) { super(); this.cause = cause; } /** * @see Nestable#getThrowables() * Returns zero-length Throwable array for this test. */ public Throwable[] getThrowables() { return new Throwable[0]; } /** * @see Nestable#getMessages() * Returns zero-length String array for this test. */ public String[] getMessages() { return new String[0]; } /** * @see Nestable#indexOfThrowable(Class) * Returns -1 for this test. */ public int indexOfThrowable(Class type) { return -1; } /** * @see Nestable#getThrowable(int) * Returns null for this test. */ public Throwable getThrowable(int index) { return null; } /** * @see Nestable#getThrowableCount() * Returns 1 for this test. */ public int getThrowableCount() { return 1; } /** * @see Nestable#getCause() */ public Throwable getCause() { return cause; } /** * Empty method to satisfy the implemented interface. Does nothing * in this test. * * @param out The writer to use. */ public void printPartialStackTrace(PrintWriter out) { super.printStackTrace(out); } /** * @see Nestable#getMessage(int) */ public String getMessage(int index) { if(index == 0) { return super.getMessage(); } else { return ""; } } /** * @see Nestable#indexOfThrowable(Class, int) * Returns -1 for this test. */ public int indexOfThrowable(Class type, int fromIndex) { return -1; } } /** * Nestable and Throwable class which can be passed to the NestableDelegate * constructor. Used for testing various methods which iterate through the * nested causes. */ class NestableDelegateTester2 extends Throwable implements Nestable { private Throwable cause = null; public NestableDelegateTester2() { super(); } public NestableDelegateTester2(String reason, Throwable cause) { super(reason); this.cause = cause; } public NestableDelegateTester2(String reason) { super(reason); } public NestableDelegateTester2(Throwable cause) { super(); this.cause = cause; } /** * @see Nestable#getThrowables() * Returns zero-length Throwable array for this test. */ public Throwable[] getThrowables() { return new Throwable[0]; } /** * @see Nestable#getMessages() * Returns zero-length String array for this test. */ public String[] getMessages() { return new String[0]; } /** * @see Nestable#indexOfThrowable(Class) * Returns -1 for this test. */ public int indexOfThrowable(Class type) { return -1; } /** * @see Nestable#getThrowable(int) * Returns null for this test. */ public Throwable getThrowable(int index) { return null; } /** * @see Nestable#getThrowableCount() * Returns 1 for this test. * * @return 1 */ public int getThrowableCount() { return 1; } /** * @see Nestable#getCause() */ public Throwable getCause() { return cause; } /** * Empty method to satisfy the implemented interface. Does nothing * in this test. * * @param out The writer to use. */ public void printPartialStackTrace(PrintWriter out) { super.printStackTrace(out); } /** * @see Nestable#getMessage(int) */ public String getMessage(int index) { if(index == 0) { return super.getMessage(); } else { return ""; } } /** * @see Nestable#indexOfThrowable(Class, int) * Returns -1 for this test. */ public int indexOfThrowable(Class type, int fromIndex) { return -1; } } /** * Used to test that the constructor passes when passed a throwable cause * And, the NestableDelegate.getMessage() returns the message from underlying * nestable (which also has to be a Throwable). */ class ThrowableNestable extends Throwable implements Nestable { private Throwable cause = new Exception("ThrowableNestable cause"); /** * @see Nestable#getThrowableCount() * Returns 1 for this test. */ public int getThrowableCount() { return 1; } /** * @see Nestable#getMessage() * Returns the hard-coded string "ThrowableNestable exception" for this * test. */ public String getMessage() { return "ThrowableNestable exception"; } /** * @see Nestable#getMessage(int) * Returns the hard-coded string "ThrowableNestable exception" for this * test. */ public String getMessage(int index) { return getMessage(); } /** * @see Nestable#getMessages() * Returns single-element string array with "ThrowableNestable exception". */ public String[] getMessages() { String msgs[] = new String[1]; msgs[0] = getMessage(); return msgs; } /** * @see Nestable#getCause() */ public Throwable getCause() { return cause; } /** * @see Nestable#printStackTrace(PrintWriter) * Empty method to satisfy the implemented interface. Does nothing * in this test. */ public void printStackTrace(PrintWriter out) { } /** * @see Nestable#printPartialStackTrace(PrintWriter) * Empty method to satisfy the implemented interface. Does nothing * in this test. */ public void printPartialStackTrace(PrintWriter out) { } /** * @see Nestable#getThrowable(int) */ public Throwable getThrowable(int index) { return cause; } /** * @see Nestable#getThrowables() */ public Throwable[] getThrowables() { Throwable throwables[] = new Throwable[1]; throwables[0] = cause; return throwables; } /** * @see Nestable#indexOfThrowable(Class) */ public int indexOfThrowable(Class type) { if(Exception.class.isInstance(type)) { return 0; } return -1; } /** * @see Nestable#indexOfThrowable(Class,int) */ public int indexOfThrowable(Class type, int fromIndex) { return indexOfThrowable(type); } } /** * Nestable and Throwable class which takes in a 'cause' object. * Returns a message wrapping the 'cause' message * Prints a fixed stack trace and partial stack trace. */ class ThrowableNestedNestable extends Throwable implements Nestable { private Throwable cause = null; public ThrowableNestedNestable(Throwable cause) { this.cause = cause; } /** * @see Nestable#getThrowableCount() * Returns 1 for this test. */ public int getThrowableCount() { return 1; } /** * @see Nestable#getMessage() * For this test, returns "ThrowableNestable exception (" appended to the * message of the cause specified in the constructor. */ public String getMessage() { return "ThrowableNestedNestable exception (" + cause.getMessage() + ")"; } /** * @see Nestable#getMessage(int) * For this test, returns "ThrowableNestable exception (" appended to the * message of the cause specified in the constructor. */ public String getMessage(int index) { return "ThrowableNestedNestable exception (" + cause.getMessage() + ")"; } /** * @see Nestable#getMessages() * For this test, returns a single-element string array containing * "ThrowableNestable exception (" appended to the * message of the cause specified in the constructor. */ public String[] getMessages() { String[] msgs = new String[1]; msgs[0] = "ThrowableNestedNestable exception (" + cause.getMessage() + ")"; return msgs; } /** * @see Nestable#getCause() */ public Throwable getCause() { return cause; } /** * @see Nestable#printStackTrace(PrintWriter) * For this test, writes the string * "ThrowableNestedNestable stack trace place-holder" to the print writer. */ public void printStackTrace(PrintWriter out) { out.println("ThrowableNestedNestable stack trace place-holder"); } /** * @see Nestable#printPartialStackTrace(PrintWriter) * For this test, writes the string * "ThrowableNestedNestable partial stack trace place-holder" to the print * writer. */ public void printPartialStackTrace(PrintWriter out) { out.println("ThrowableNestedNestable partial stack trace place-holder"); } /** * @see Nestable#getThrowable(int) */ public Throwable getThrowable(int index) { return cause; } /** * @see Nestable#getThrowables() */ public Throwable[] getThrowables() { Throwable throwables[] = new Throwable[1]; throwables[0] = cause; return throwables; } /** * @see Nestable#indexOfThrowable(Class) */ public int indexOfThrowable(Class type) { if(Exception.class.isInstance(type)) { return 0; } return -1; } /** * @see Nestable#indexOfThrowable(Class, int) */ public int indexOfThrowable(Class type, int fromIndex) { return indexOfThrowable(type); } } /** * Used to test that the constructor fails when passed a non-throwable cause */ class NonThrowableNestable implements Nestable { /** * @see Nestable#getThrowableCount() * Returns 1 for this test. */ public int getThrowableCount() { return 1; } /** * @see Nestable#getMessage() * Returns the string "non-throwable" for this test. */ public String getMessage() { return "non-throwable"; } /** * @see Nestable#getMessage(int) * Returns the string "non-throwable" for this test. */ public String getMessage(int index) { return "non-throwable"; } /** * @see Nestable#getMessage() * Returns a single-element array containing the string "non-throwable" for * this test. */ public String[] getMessages() { String[] msgs = new String[1]; msgs[0] = "non-throwable"; return msgs; } /** * @see Nestable#getCause() * Returns null for this test. */ public Throwable getCause() { return null; } /** * @see Nestable#printStackTrace(PrintWriter) * Empty method to satisfy the implemented interface. Does nothing * in this test. */ public void printStackTrace(PrintWriter out) { } /** * @see Nestable#printStackTrace(PrintStream) * Empty method to satisfy the implemented interface. Does nothing * in this test. */ public void printStackTrace(PrintStream out) { } /** * @see Nestable#printPartialStackTrace(PrintWriter) * Empty method to satisfy the implemented interface. Does nothing * in this test. */ public void printPartialStackTrace(PrintWriter out) { } /** * @see Nestable#getThrowable(int) * Returns null for this test. */ public Throwable getThrowable(int index) { return null; } /** * @see Nestable#getThrowables() * Returns zero-length Throwable array. */ public Throwable[] getThrowables() { return new Throwable[0]; } /** * @see Nestable#indexOfThrowable(Class) * Returns -1 for this test. */ public int indexOfThrowable(Class type) { return -1; } /** * @see Nestable#indexOfThrowable(Class, int) * Returns -1 for this test. */ public int indexOfThrowable(Class type, int fromIndex) { return -1; } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/exception/NestableErrorTest.java100644 0 0 13410 11513702435 27252 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.exception; import java.io.EOFException; /** * Tests the org.apache.commons.lang.exception.NestableError class. * * @author Steven Caswell * @version $Id: NestableErrorTest.java 905628 2010-02-02 13:29:55Z niallp $ */ public class NestableErrorTest extends AbstractNestableTest { /** * Construct a new instance of * NestableErrorTestCase. * * @param name test case name */ public NestableErrorTest(String name) { super(name); } /** * Sets up instance variables required by this test case. */ public void setUp() { } /** * Tears down instance variables required by this test case. */ public void tearDown() { } /** * @see AbstractNestableTest#getNestable() */ public Nestable getNestable() { return new NestableError(); } /** * @see AbstractNestableTest#getNestable(Nestable) */ public Nestable getNestable(Nestable n) { return new NestableError((Throwable) n); } /** * @see AbstractNestableTest#getNestable(String) */ public Nestable getNestable(String msg) { return new NestableError(msg); } /** * @see AbstractNestableTest#getNestable(Throwable) */ public Nestable getNestable(Throwable t) { return new NestableError(t); } /** * @see AbstractNestableTest#getNestable(String, Throwable) */ public Nestable getNestable(String msg, Throwable t) { return new NestableError(msg, t); } /** * @see AbstractNestableTest#getNestable(String, Nestable) */ public Nestable getNestable(String msg, Nestable n) { return new NestableError(msg, (Throwable) n); } /** * @see AbstractNestableTest#getTester1(Throwable) */ public Nestable getTester1(Throwable t) { return new NestableErrorTester1(t); } /** * @see AbstractNestableTest#getTester1(Nestable) */ public Nestable getTester1(Nestable n) { return new NestableErrorTester1((Throwable) n); } /** * @see AbstractNestableTest#getTester1(String, Throwable) */ public Nestable getTester1(String msg, Throwable t) { return new NestableErrorTester1(msg, t); } /** * @see AbstractNestableTest#getTester1(String, Nestable) */ public Nestable getTester1(String msg, Nestable n) { return new NestableErrorTester1(msg, (Throwable) n); } /** * @see AbstractNestableTest#getTester1Class() */ public Class getTester1Class() { return NestableErrorTester1.class; } /** * @see AbstractNestableTest#getTester2(String, Throwable) */ public Nestable getTester2(String msg, Throwable t) { return new NestableErrorTester2(msg, t); } /** * @see AbstractNestableTest#getTester2(String, Nestable) */ public Nestable getTester2(String msg, Nestable n) { return new NestableErrorTester2(msg, (Throwable) n); } /** * @see AbstractNestableTest#getTester2Class() */ public Class getTester2Class() { return NestableErrorTester2.class; } /** * @see AbstractNestableTest#getThrowable(String) */ public Throwable getThrowable(String msg) { return new EOFException(msg); } /** * @see AbstractNestableTest#getThrowableClass() */ public Class getThrowableClass() { return EOFException.class; } /** * @see AbstractNestableTest#getBaseThrowableClass() */ public Class getBaseThrowableClass() { return Error.class; } } /** * First nestable tester implementation for use in test cases. */ class NestableErrorTester1 extends NestableError { public NestableErrorTester1() { super(); } public NestableErrorTester1(String reason, Throwable cause) { super(reason, cause); } public NestableErrorTester1(String reason) { super(reason); } public NestableErrorTester1(Throwable cause) { super(cause); } } /** * Second nestable tester implementation for use in test cases. */ class NestableErrorTester2 extends NestableError { public NestableErrorTester2() { super(); } public NestableErrorTester2(String reason, Throwable cause) { super(reason, cause); } public NestableErrorTester2(String reason) { super(reason); } public NestableErrorTester2(Throwable cause) { super(cause); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/exception/NestableExceptionTest.java100644 0 0 24045 11513702435 30125 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.exception; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.EOFException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.PrintStream; /** * Tests the org.apache.commons.lang.exception.NestableException class. * * @author Steven Caswell * @version $Id: NestableExceptionTest.java 905628 2010-02-02 13:29:55Z niallp $ */ public class NestableExceptionTest extends AbstractNestableTest { /** * Construct a new instance of * NestableExceptionTestCase. * * @param name test case name */ public NestableExceptionTest(String name) { super(name); } /** * Sets up instance variables required by this test case. */ public void setUp() { } /** * Tears down instance variables required by this test case. */ public void tearDown() { } /** * @see AbstractNestableTest#getNestable() */ public Nestable getNestable() { return new NestableException(); } /** * @see AbstractNestableTest#getNestable(Nestable) */ public Nestable getNestable(Nestable n) { return new NestableException((Throwable) n); } /** * @see AbstractNestableTest#getNestable(String) */ public Nestable getNestable(String msg) { return new NestableException(msg); } /** * @see AbstractNestableTest#getNestable(Throwable) */ public Nestable getNestable(Throwable t) { return new NestableException(t); } /** * @see AbstractNestableTest#getNestable(String, Throwable) */ public Nestable getNestable(String msg, Throwable t) { return new NestableException(msg, t); } /** * @see AbstractNestableTest#getNestable(String, Nestable) */ public Nestable getNestable(String msg, Nestable n) { return new NestableException(msg, (Throwable) n); } /** * @see AbstractNestableTest#getTester1(Throwable) */ public Nestable getTester1(Throwable t) { return new NestableExceptionTester1(t); } /** * @see AbstractNestableTest#getTester1(Nestable) */ public Nestable getTester1(Nestable n) { return new NestableExceptionTester1((Throwable) n); } /** * @see AbstractNestableTest#getTester1(String, Throwable) */ public Nestable getTester1(String msg, Throwable t) { return new NestableExceptionTester1(msg, t); } /** * @see AbstractNestableTest#getTester1(String, Nestable) */ public Nestable getTester1(String msg, Nestable n) { return new NestableExceptionTester1(msg, (Throwable) n); } /** * @see AbstractNestableTest#getTester1Class() */ public Class getTester1Class() { return NestableExceptionTester1.class; } /** * @see AbstractNestableTest#getTester2(String, Throwable) */ public Nestable getTester2(String msg, Throwable t) { return new NestableExceptionTester2(msg, t); } /** * @see AbstractNestableTest#getTester2(String, Nestable) */ public Nestable getTester2(String msg, Nestable n) { return new NestableExceptionTester2(msg, (Throwable) n); } /** * @see AbstractNestableTest#getTester2Class() */ public Class getTester2Class() { return NestableExceptionTester2.class; } /** * @see AbstractNestableTest#getThrowable(String) */ public Throwable getThrowable(String msg) { return new EOFException(msg); } /** * @see AbstractNestableTest#getThrowableClass() */ public Class getThrowableClass() { return EOFException.class; } /** * @see AbstractNestableTest#getBaseThrowableClass() */ public Class getBaseThrowableClass() { return Exception.class; } public void testSpecificPrintStackTrace() { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); NestableException ne = new NestableException("outer", new NestableException("inner", new Exception("another exception"))); for(int i = 0; i < 2; i++) { if(i == 0) { // Test printStackTrac() // Replace System.err with our own PrintStream so that we can // obtain and check the printStrackTrace output PrintStream err = System.err; System.setErr(ps); ne.printStackTrace(); // Restore the System.err System.setErr(err); } else { // Test printStackTrace(PrintStream) ne.printStackTrace(ps); } } String msg = baos.toString(); assertTrue( "printStackTrace() starts with outer message", msg.startsWith("org.apache.commons.lang.exception.NestableException: outer")); assertTrue( "printStackTrace() contains 1st nested message", msg.indexOf("Caused by: org.apache.commons.lang.exception.NestableException: inner") >= 0); assertTrue( "printStackTrace() contains 2nd nested message", msg.indexOf("Caused by: java.lang.Exception: another exception") >= 0); assertTrue( "printStackTrace() inner message after outer message", msg.indexOf("org.apache.commons.lang.exception.NestableException: outer") < msg.indexOf("Caused by: org.apache.commons.lang.exception.NestableException: inner")); assertTrue( "printStackTrace() cause message after inner message", msg.indexOf("Caused by: org.apache.commons.lang.exception.NestableException: inner") < msg.indexOf("Caused by: java.lang.Exception: another exception")); } public void testSerialization() throws java.io.IOException, ClassNotFoundException { RuntimeException nestedEx = new RuntimeException("nested exception message"); NestableExceptionTester1 ex = new NestableExceptionTester1("serialization test", nestedEx); assertTrue( "implements java.io.Serializable", nestedEx instanceof java.io.Serializable); assertTrue( "implements java.io.Serializable", ex instanceof java.io.Serializable); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ByteArrayInputStream bais = null; ObjectOutputStream oos = null; ObjectInputStream ois = null; try { oos = new ObjectOutputStream(baos); oos.writeObject(ex); oos.flush(); bais = new ByteArrayInputStream(baos.toByteArray()); ois = new ObjectInputStream(bais); NestableExceptionTester1 deserializedEx = (NestableExceptionTester1) ois.readObject(); assertEquals( "getThrowableCount() return value", ex.getThrowableCount(), deserializedEx.getThrowableCount()); for (int i = 0; i < ex.getThrowableCount(); i++) { Throwable t = ex.getThrowable(i); Throwable deserializedThrowable = deserializedEx.getThrowable(i); assertEquals( t.getClass(), deserializedThrowable.getClass()); assertEquals( t.getMessage(), deserializedThrowable.getMessage()); } } finally { if (null != oos) { try { oos.close(); } catch (Exception ignored) { // intentionally empty } } } } } /** * First nestable tester implementation for use in test cases. */ class NestableExceptionTester1 extends NestableException { public NestableExceptionTester1() { super(); } public NestableExceptionTester1(String reason, Throwable cause) { super(reason, cause); } public NestableExceptionTester1(String reason) { super(reason); } public NestableExceptionTester1(Throwable cause) { super(cause); } } /** * Second nestable tester implementation for use in test cases. */ class NestableExceptionTester2 extends NestableException { public NestableExceptionTester2() { super(); } public NestableExceptionTester2(String reason, Throwable cause) { super(reason, cause); } public NestableExceptionTester2(String reason) { super(reason); } public NestableExceptionTester2(Throwable cause) { super(cause); } } ././@LongLink100644 0 0 147 11513702661 10257 Lustar 0 0 commons-lang-2.6-src/src/test/java/org/apache/commons/lang/exception/NestableRuntimeExceptionTest.javacommons-lang-2.6-src/src/test/java/org/apache/commons/lang/exception/NestableRuntimeExceptionTest.ja100644 0 0 20444 11513702435 31141 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.exception; import java.io.ByteArrayOutputStream; import java.io.EOFException; import java.io.PrintStream; /** * Tests the org.apache.commons.lang.exception.NestableRuntimeException class. * * @author Steven Caswell * @version $Id: NestableRuntimeExceptionTest.java 905628 2010-02-02 13:29:55Z niallp $ */ public class NestableRuntimeExceptionTest extends AbstractNestableTest { /** * Construct a new instance of * NestableRuntimeExceptionTestCase. * * @param name test case name */ public NestableRuntimeExceptionTest(String name) { super(name); } /** * Sets up instance variables required by this test case. */ public void setUp() { } /** * Tears down instance variables required by this test case. */ public void tearDown() { } /** * @see AbstractNestableTest#getNestable() */ public Nestable getNestable() { return new NestableRuntimeException(); } /** * @see AbstractNestableTest#getNestable(Nestable) */ public Nestable getNestable(Nestable n) { return new NestableRuntimeException((Throwable) n); } /** * @see AbstractNestableTest#getNestable(String) */ public Nestable getNestable(String msg) { return new NestableRuntimeException(msg); } /** * @see AbstractNestableTest#getNestable(Throwable) */ public Nestable getNestable(Throwable t) { return new NestableRuntimeException(t); } /** * @see AbstractNestableTest#getNestable(String, Throwable) */ public Nestable getNestable(String msg, Throwable t) { return new NestableRuntimeException(msg, t); } /** * @see AbstractNestableTest#getNestable(String, Nestable) */ public Nestable getNestable(String msg, Nestable n) { return new NestableRuntimeException(msg, (Throwable) n); } /** * @see AbstractNestableTest#getTester1(Throwable) */ public Nestable getTester1(Throwable t) { return new NestableRuntimeExceptionTester1(t); } /** * @see AbstractNestableTest#getTester1(Nestable) */ public Nestable getTester1(Nestable n) { return new NestableRuntimeExceptionTester1((Throwable) n); } /** * @see AbstractNestableTest#getTester1(String, Throwable) */ public Nestable getTester1(String msg, Throwable t) { return new NestableRuntimeExceptionTester1(msg, t); } /** * @see AbstractNestableTest#getTester1(String, Nestable) */ public Nestable getTester1(String msg, Nestable n) { return new NestableRuntimeExceptionTester1(msg, (Throwable) n); } /** * @see AbstractNestableTest#getTester1Class() */ public Class getTester1Class() { return NestableRuntimeExceptionTester1.class; } /** * @see AbstractNestableTest#getTester2(String, Throwable) */ public Nestable getTester2(String msg, Throwable t) { return new NestableRuntimeExceptionTester2(msg, t); } /** * @see AbstractNestableTest#getTester2(String, Nestable) */ public Nestable getTester2(String msg, Nestable n) { return new NestableRuntimeExceptionTester2(msg, (Throwable) n); } /** * @see AbstractNestableTest#getTester2Class() */ public Class getTester2Class() { return NestableRuntimeExceptionTester2.class; } /** * @see AbstractNestableTest#getThrowable(String) */ public Throwable getThrowable(String msg) { return new EOFException(msg); } /** * @see AbstractNestableTest#getThrowableClass() */ public Class getThrowableClass() { return EOFException.class; } /** * @see AbstractNestableTest#getBaseThrowableClass() */ public Class getBaseThrowableClass() { return RuntimeException.class; } public void testSpecificPrintStackTrace() { // Test printStackTrac() // Replace System.err with our own PrintStream so that we can obtain // and check the printStrackTrace output ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); NestableRuntimeException ne = new NestableRuntimeException("outer", new NestableRuntimeException("inner", new Exception("another exception"))); for(int i = 0; i < 2; i++) { if(i == 0) { // Test printStackTrac() // Replace System.err with our own PrintStream so that we can // obtain and check the printStrackTrace output PrintStream err = System.err; System.setErr(ps); ne.printStackTrace(); // Restore the System.err System.setErr(err); } else { // Test printStackTrace(PrintStream) ne.printStackTrace(ps); } } String msg = baos.toString(); assertTrue( "printStackTrace() starts with outer message", msg.startsWith("org.apache.commons.lang.exception.NestableRuntimeException: outer")); assertTrue( "printStackTrace() contains 1st nested message", msg.indexOf("Caused by: org.apache.commons.lang.exception.NestableRuntimeException: inner") >= 0); assertTrue( "printStackTrace() contains 2nd nested message", msg.indexOf("Caused by: java.lang.Exception: another exception") >= 0); assertTrue( "printStackTrace() inner message after outer message", msg.indexOf("org.apache.commons.lang.exception.NestableRuntimeException: outer") < msg.indexOf("Caused by: org.apache.commons.lang.exception.NestableRuntimeException: inner")); assertTrue( "printStackTrace() cause message after inner message", msg.indexOf("Caused by: org.apache.commons.lang.exception.NestableRuntimeException: inner") < msg.indexOf("Caused by: java.lang.Exception: another exception")); } } /** * First nestable tester implementation for use in test cases. */ class NestableRuntimeExceptionTester1 extends NestableRuntimeException { public NestableRuntimeExceptionTester1() { super(); } public NestableRuntimeExceptionTester1(String reason, Throwable cause) { super(reason, cause); } public NestableRuntimeExceptionTester1(String reason) { super(reason); } public NestableRuntimeExceptionTester1(Throwable cause) { super(cause); } } /** * Second nestable tester implementation. */ class NestableRuntimeExceptionTester2 extends NestableRuntimeException { public NestableRuntimeExceptionTester2() { super(); } public NestableRuntimeExceptionTester2(String reason, Throwable cause) { super(reason, cause); } public NestableRuntimeExceptionTester2(String reason) { super(reason); } public NestableRuntimeExceptionTester2(Throwable cause) { super(cause); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/IllegalClassExceptionTest.java100644 0 0 7124 11513702441 26705 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang; import junit.framework.TestCase; /** * JUnit tests. * * @author Matthew Hawthorne * @version $Id: IllegalClassExceptionTest.java 905628 2010-02-02 13:29:55Z niallp $ * @see IllegalClassException */ public class IllegalClassExceptionTest extends TestCase { public IllegalClassExceptionTest(String testName) { super(testName); } // testConstructor_classArgs public void testConstructor_classArgs_allNullInput() { new IllegalClassException(null, null); } public void testConstructor_classArgs_nullExpected() { new IllegalClassException(null, String.class); } public void testConstructor_classArgs_nullActual() { new IllegalClassException(String.class, null); } // testConstructor_stringArg public void testConstructor_stringArg_nullInput() { new IllegalClassException(null); } // testConstructor_classObjectArgs public void testConstructor_classObjectArgs_allNullInput() { new IllegalClassException(null, (Object) null); } public void testConstructor_classObjectArgs_nullExpected() { new IllegalClassException(null, new Object()); } public void testConstructor_classObjectArgs_nullActual() { new IllegalClassException(String.class, (Object) null); } // testGetMessage public void testGetMessage_classArgs_nullInput() { final Throwable t = new IllegalClassException(null, null); assertEquals("Expected: null, actual: null", t.getMessage()); } public void testGetMessage_classArgs_normalInput() { final Throwable t = new IllegalClassException(String.class, Integer.class); assertEquals( "Expected: java.lang.String, actual: java.lang.Integer", t.getMessage()); } public void testGetMessage_classObjectArgs_nullInput() { final Throwable t = new IllegalClassException(null, (Object) null); assertEquals("Expected: null, actual: null", t.getMessage()); } public void testGetMessage_classObjectArgs_normalInput() { final Throwable t = new IllegalClassException(String.class, new Object()); assertEquals( "Expected: java.lang.String, actual: java.lang.Object", t.getMessage()); } public void testGetMessage_stringArg_nullInput() { final Throwable t = new IllegalClassException(null); assertEquals(null, t.getMessage()); } public void testGetMessage_stringArg_validInput() { final String message = "message"; final Throwable t = new IllegalClassException(message); assertEquals(message, t.getMessage()); } } // IllegalClassExceptionTest commons-lang-2.6-src/src/test/java/org/apache/commons/lang/IncompleteArgumentExceptionTest.java100644 0 0 5517 11513702441 30154 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang; import junit.framework.TestCase; /** * JUnit tests. * * @author Matthew Hawthorne * @version $Id: IncompleteArgumentExceptionTest.java 905628 2010-02-02 13:29:55Z niallp $ * @see IncompleteArgumentException */ public class IncompleteArgumentExceptionTest extends TestCase { public IncompleteArgumentExceptionTest(String testName) { super(testName); } // testConstructor public void test1arg_nullInput() { final Throwable t = new IncompleteArgumentException(null); assertEquals("null is incomplete.", t.getMessage()); } public void test1arg_validInput() { final String name = "argument"; final Throwable t = new IncompleteArgumentException(name); assertEquals(name + " is incomplete.", t.getMessage()); } public void test2arg_allNullInput() { final Throwable t = new IncompleteArgumentException(null, null); assertEquals( "null is missing the following items: null", t.getMessage()); } public void test2arg_nullString() { final Throwable t = new IncompleteArgumentException( null, new String[] { "one", "two" }); assertEquals( "null is missing the following items: [one, two]", t.getMessage()); } public void test2arg_nullArray() { final String name = "one"; final Throwable t = new IncompleteArgumentException(name, null); assertEquals( name + " is missing the following items: null", t.getMessage()); } public void test2arg_validInput() { final String name = "input"; final Throwable t = new IncompleteArgumentException( name, new String[] { "one", "two" }); assertEquals( name + " is missing the following items: [one, two]", t.getMessage()); } } // IncompleteArgumentExceptionTest commons-lang-2.6-src/src/test/java/org/apache/commons/lang/IntHashMapTest.java100644 0 0 10301 11513702440 24471 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang; import junit.framework.TestCase; /** * Tests for the IntHashMap class. * * @author Steven Caswell * @version $Id: IntHashMapTest.java 905628 2010-02-02 13:29:55Z niallp $ */ public class IntHashMapTest extends TestCase { public void testConstructor() { try { new IntHashMap(-1, 0.0f); fail(); } catch (IllegalArgumentException e) { assertEquals("Illegal Capacity: -1", e.getMessage()); } try { new IntHashMap(1, 0.0f); fail(); } catch (IllegalArgumentException e) { assertEquals("Illegal Load: 0.0", e.getMessage()); } new IntHashMap(0, 1.0f); try { new IntHashMap(-1); fail(); } catch (IllegalArgumentException e) { assertEquals("Illegal Capacity: -1", e.getMessage()); } IntHashMap map1 = new IntHashMap(0); assertEquals(0, map1.size()); } public void testClear() { IntHashMap map = new IntHashMap(); assertNull(map.put(1, "hello")); assertNull(map.put(2, "world")); assertEquals(2, map.size()); map.clear(); assertEquals(0, map.size()); } public void testContainsKey() { IntHashMap map = new IntHashMap(); assertNull(map.put(1, "hello")); assertNull(map.put(2, "world")); assertEquals(2, map.size()); assertTrue(map.containsKey(1)); assertTrue(map.containsKey(2)); assertFalse(map.containsKey(3)); } public void testContains() { IntHashMap map = new IntHashMap(); assertNull(map.put(1, "hello")); assertNull(map.put(2, "world")); assertEquals(2, map.size()); assertTrue(map.containsValue("hello")); assertTrue(map.containsValue("world")); assertFalse(map.containsValue("goodbye")); try { map.containsValue(null); fail(); } catch(NullPointerException e) { } } public void testContainsValue() { IntHashMap map = new IntHashMap(); assertNull(map.put(1, "hello")); assertNull(map.put(2, "world")); assertEquals(2, map.size()); assertTrue(map.containsValue("hello")); assertTrue(map.containsValue("world")); assertFalse(map.containsValue("goodbye")); try { map.containsValue(null); fail(); } catch(NullPointerException e) { } } public void testIsEmpty() { IntHashMap map = new IntHashMap(); assertTrue(map.isEmpty()); assertNull(map.put(1, "hello")); assertEquals(1, map.size()); assertFalse(map.isEmpty()); } public void testPut() { IntHashMap map = new IntHashMap(); assertNull(map.put(1, "hello")); assertNull(map.put(2, "world")); assertEquals(2, map.size()); assertEquals("hello", map.put(1, "hellooooo")); } public void testRemove() { IntHashMap map = new IntHashMap(); assertNull(map.put(1, "hello")); assertNull(map.put(2, "world")); assertEquals(2, map.size()); assertEquals("hello", map.remove(1)); assertEquals(1, map.size()); assertNull(map.remove(3)); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/LocaleUtilsTest.java100644 0 0 44454 11513702441 24736 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Set; import junit.framework.TestCase; /** * Unit tests for {@link LocaleUtils}. * * @author Apache Software Foundation * @author Chris Hyzer * @version $Id: LocaleUtilsTest.java 905636 2010-02-02 14:03:32Z niallp $ */ public class LocaleUtilsTest extends TestCase { private static final Locale LOCALE_EN = new Locale("en", ""); private static final Locale LOCALE_EN_US = new Locale("en", "US"); private static final Locale LOCALE_EN_US_ZZZZ = new Locale("en", "US", "ZZZZ"); private static final Locale LOCALE_FR = new Locale("fr", ""); private static final Locale LOCALE_FR_CA = new Locale("fr", "CA"); private static final Locale LOCALE_QQ = new Locale("qq", ""); private static final Locale LOCALE_QQ_ZZ = new Locale("qq", "ZZ"); /** * Constructor. * * @param name */ public LocaleUtilsTest(String name) { super(name); } public void setUp() throws Exception { super.setUp(); // Testing #LANG-304. Must be called before availableLocaleSet is called. LocaleUtils.isAvailableLocale(Locale.getDefault()); } //----------------------------------------------------------------------- /** * Test that constructors are public, and work, etc. */ public void testConstructor() { assertNotNull(new LocaleUtils()); Constructor[] cons = LocaleUtils.class.getDeclaredConstructors(); assertEquals(1, cons.length); assertEquals(true, Modifier.isPublic(cons[0].getModifiers())); assertEquals(true, Modifier.isPublic(LocaleUtils.class.getModifiers())); assertEquals(false, Modifier.isFinal(LocaleUtils.class.getModifiers())); } //----------------------------------------------------------------------- /** * Pass in a valid language, test toLocale. * * @param language the language string */ private void assertValidToLocale(String language) { Locale locale = LocaleUtils.toLocale(language); assertNotNull("valid locale", locale); assertEquals(language, locale.getLanguage()); //country and variant are empty assertTrue(locale.getCountry() == null || locale.getCountry().length() == 0); assertTrue(locale.getVariant() == null || locale.getVariant().length() == 0); } /** * Pass in a valid language, test toLocale. * * @param localeString to pass to toLocale() * @param language of the resulting Locale * @param country of the resulting Locale */ private void assertValidToLocale(String localeString, String language, String country) { Locale locale = LocaleUtils.toLocale(localeString); assertNotNull("valid locale", locale); assertEquals(language, locale.getLanguage()); assertEquals(country, locale.getCountry()); //variant is empty assertTrue(locale.getVariant() == null || locale.getVariant().length() == 0); } /** * Pass in a valid language, test toLocale. * * @param localeString to pass to toLocale() * @param language of the resulting Locale * @param country of the resulting Locale * @param variant of the resulting Locale */ private void assertValidToLocale( String localeString, String language, String country, String variant) { Locale locale = LocaleUtils.toLocale(localeString); assertNotNull("valid locale", locale); assertEquals(language, locale.getLanguage()); assertEquals(country, locale.getCountry()); assertEquals(variant, locale.getVariant()); } /** * Test toLocale() method. */ public void testToLocale_1Part() { assertEquals(null, LocaleUtils.toLocale((String) null)); assertValidToLocale("us"); assertValidToLocale("fr"); assertValidToLocale("de"); assertValidToLocale("zh"); // Valid format but lang doesnt exist, should make instance anyway assertValidToLocale("qq"); try { LocaleUtils.toLocale("Us"); fail("Should fail if not lowercase"); } catch (IllegalArgumentException iae) {} try { LocaleUtils.toLocale("US"); fail("Should fail if not lowercase"); } catch (IllegalArgumentException iae) {} try { LocaleUtils.toLocale("uS"); fail("Should fail if not lowercase"); } catch (IllegalArgumentException iae) {} try { LocaleUtils.toLocale("u#"); fail("Should fail if not lowercase"); } catch (IllegalArgumentException iae) {} try { LocaleUtils.toLocale("u"); fail("Must be 2 chars if less than 5"); } catch (IllegalArgumentException iae) {} try { LocaleUtils.toLocale("uuu"); fail("Must be 2 chars if less than 5"); } catch (IllegalArgumentException iae) {} try { LocaleUtils.toLocale("uu_U"); fail("Must be 2 chars if less than 5"); } catch (IllegalArgumentException iae) {} } /** * Test toLocale() method. */ public void testToLocale_2Part() { assertValidToLocale("us_EN", "us", "EN"); //valid though doesnt exist assertValidToLocale("us_ZH", "us", "ZH"); try { LocaleUtils.toLocale("us-EN"); fail("Should fail as not underscore"); } catch (IllegalArgumentException iae) {} try { LocaleUtils.toLocale("us_En"); fail("Should fail second part not uppercase"); } catch (IllegalArgumentException iae) {} try { LocaleUtils.toLocale("us_en"); fail("Should fail second part not uppercase"); } catch (IllegalArgumentException iae) {} try { LocaleUtils.toLocale("us_eN"); fail("Should fail second part not uppercase"); } catch (IllegalArgumentException iae) {} try { LocaleUtils.toLocale("uS_EN"); fail("Should fail first part not lowercase"); } catch (IllegalArgumentException iae) {} try { LocaleUtils.toLocale("us_E3"); fail("Should fail second part not uppercase"); } catch (IllegalArgumentException iae) {} } /** * Test toLocale() method. */ public void testToLocale_3Part() { assertValidToLocale("us_EN_A", "us", "EN", "A"); // this isn't pretty, but was caused by a jdk bug it seems // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4210525 if (SystemUtils.isJavaVersionAtLeast(1.4f)) { assertValidToLocale("us_EN_a", "us", "EN", "a"); assertValidToLocale("us_EN_SFsafdFDsdfF", "us", "EN", "SFsafdFDsdfF"); } else { assertValidToLocale("us_EN_a", "us", "EN", "A"); assertValidToLocale("us_EN_SFsafdFDsdfF", "us", "EN", "SFSAFDFDSDFF"); } try { LocaleUtils.toLocale("us_EN-a"); fail("Should fail as not underscore"); } catch (IllegalArgumentException iae) {} try { LocaleUtils.toLocale("uu_UU_"); fail("Must be 3, 5 or 7+ in length"); } catch (IllegalArgumentException iae) {} } //----------------------------------------------------------------------- /** * Helper method for local lookups. * * @param locale the input locale * @param defaultLocale the input default locale * @param expected expected results */ private void assertLocaleLookupList(Locale locale, Locale defaultLocale, Locale[] expected) { List localeList = defaultLocale == null ? LocaleUtils.localeLookupList(locale) : LocaleUtils.localeLookupList(locale, defaultLocale); assertEquals(expected.length, localeList.size()); assertEquals(Arrays.asList(expected), localeList); assertUnmodifiableCollection(localeList); } //----------------------------------------------------------------------- /** * Test localeLookupList() method. */ public void testLocaleLookupList_Locale() { assertLocaleLookupList(null, null, new Locale[0]); assertLocaleLookupList(LOCALE_QQ, null, new Locale[]{LOCALE_QQ}); assertLocaleLookupList(LOCALE_EN, null, new Locale[]{LOCALE_EN}); assertLocaleLookupList(LOCALE_EN, null, new Locale[]{LOCALE_EN}); assertLocaleLookupList(LOCALE_EN_US, null, new Locale[] { LOCALE_EN_US, LOCALE_EN}); assertLocaleLookupList(LOCALE_EN_US_ZZZZ, null, new Locale[] { LOCALE_EN_US_ZZZZ, LOCALE_EN_US, LOCALE_EN}); } /** * Test localeLookupList() method. */ public void testLocaleLookupList_LocaleLocale() { assertLocaleLookupList(LOCALE_QQ, LOCALE_QQ, new Locale[]{LOCALE_QQ}); assertLocaleLookupList(LOCALE_EN, LOCALE_EN, new Locale[]{LOCALE_EN}); assertLocaleLookupList(LOCALE_EN_US, LOCALE_EN_US, new Locale[]{ LOCALE_EN_US, LOCALE_EN}); assertLocaleLookupList(LOCALE_EN_US, LOCALE_QQ, new Locale[] { LOCALE_EN_US, LOCALE_EN, LOCALE_QQ}); assertLocaleLookupList(LOCALE_EN_US, LOCALE_QQ_ZZ, new Locale[] { LOCALE_EN_US, LOCALE_EN, LOCALE_QQ_ZZ}); assertLocaleLookupList(LOCALE_EN_US_ZZZZ, null, new Locale[] { LOCALE_EN_US_ZZZZ, LOCALE_EN_US, LOCALE_EN}); assertLocaleLookupList(LOCALE_EN_US_ZZZZ, LOCALE_EN_US_ZZZZ, new Locale[] { LOCALE_EN_US_ZZZZ, LOCALE_EN_US, LOCALE_EN}); assertLocaleLookupList(LOCALE_EN_US_ZZZZ, LOCALE_QQ, new Locale[] { LOCALE_EN_US_ZZZZ, LOCALE_EN_US, LOCALE_EN, LOCALE_QQ}); assertLocaleLookupList(LOCALE_EN_US_ZZZZ, LOCALE_QQ_ZZ, new Locale[] { LOCALE_EN_US_ZZZZ, LOCALE_EN_US, LOCALE_EN, LOCALE_QQ_ZZ}); assertLocaleLookupList(LOCALE_FR_CA, LOCALE_EN, new Locale[] { LOCALE_FR_CA, LOCALE_FR, LOCALE_EN}); } //----------------------------------------------------------------------- /** * Test availableLocaleList() method. */ public void testAvailableLocaleList() { List list = LocaleUtils.availableLocaleList(); List list2 = LocaleUtils.availableLocaleList(); assertNotNull(list); assertSame(list, list2); assertUnmodifiableCollection(list); Locale[] jdkLocaleArray = Locale.getAvailableLocales(); List jdkLocaleList = Arrays.asList(jdkLocaleArray); assertEquals(jdkLocaleList, list); } //----------------------------------------------------------------------- /** * Test availableLocaleSet() method. */ public void testAvailableLocaleSet() { Set set = LocaleUtils.availableLocaleSet(); Set set2 = LocaleUtils.availableLocaleSet(); assertNotNull(set); assertSame(set, set2); assertUnmodifiableCollection(set); Locale[] jdkLocaleArray = Locale.getAvailableLocales(); List jdkLocaleList = Arrays.asList(jdkLocaleArray); Set jdkLocaleSet = new HashSet(jdkLocaleList); assertEquals(jdkLocaleSet, set); } //----------------------------------------------------------------------- /** * Test availableLocaleSet() method. */ public void testIsAvailableLocale() { Set set = LocaleUtils.availableLocaleSet(); assertEquals(set.contains(LOCALE_EN), LocaleUtils.isAvailableLocale(LOCALE_EN)); assertEquals(set.contains(LOCALE_EN_US), LocaleUtils.isAvailableLocale(LOCALE_EN_US)); assertEquals(set.contains(LOCALE_EN_US_ZZZZ), LocaleUtils.isAvailableLocale(LOCALE_EN_US_ZZZZ)); assertEquals(set.contains(LOCALE_FR), LocaleUtils.isAvailableLocale(LOCALE_FR)); assertEquals(set.contains(LOCALE_FR_CA), LocaleUtils.isAvailableLocale(LOCALE_FR_CA)); assertEquals(set.contains(LOCALE_QQ), LocaleUtils.isAvailableLocale(LOCALE_QQ)); assertEquals(set.contains(LOCALE_QQ_ZZ), LocaleUtils.isAvailableLocale(LOCALE_QQ_ZZ)); } //----------------------------------------------------------------------- /** * Make sure the language by country is correct. It checks that * the LocaleUtils.languagesByCountry(country) call contains the * array of languages passed in. It may contain more due to JVM * variations. * * @param country * @param languages array of languages that should be returned */ private void assertLanguageByCountry(String country, String[] languages) { List list = LocaleUtils.languagesByCountry(country); List list2 = LocaleUtils.languagesByCountry(country); assertNotNull(list); assertSame(list, list2); //search through langauges for (int i = 0; i < languages.length; i++) { Iterator iterator = list.iterator(); boolean found = false; // see if it was returned by the set while (iterator.hasNext()) { Locale locale = (Locale) iterator.next(); // should have an en empty variant assertTrue(locale.getVariant() == null || locale.getVariant().length() == 0); assertEquals(country, locale.getCountry()); if (languages[i].equals(locale.getLanguage())) { found = true; break; } } if (!found) { fail("Cound not find language: " + languages[i] + " for country: " + country); } } assertUnmodifiableCollection(list); } /** * Test languagesByCountry() method. */ public void testLanguagesByCountry() { assertLanguageByCountry(null, new String[0]); assertLanguageByCountry("GB", new String[]{"en"}); assertLanguageByCountry("ZZ", new String[0]); assertLanguageByCountry("CH", new String[]{"fr", "de", "it"}); } //----------------------------------------------------------------------- /** * Make sure the country by language is correct. It checks that * the LocaleUtils.countryByLanguage(language) call contains the * array of countries passed in. It may contain more due to JVM * variations. * * * @param language * @param countries array of countries that should be returned */ private void assertCountriesByLanguage(String language, String[] countries) { List list = LocaleUtils.countriesByLanguage(language); List list2 = LocaleUtils.countriesByLanguage(language); assertNotNull(list); assertSame(list, list2); //search through langauges for (int i = 0; i < countries.length; i++) { Iterator iterator = list.iterator(); boolean found = false; // see if it was returned by the set while (iterator.hasNext()) { Locale locale = (Locale) iterator.next(); // should have an en empty variant assertTrue(locale.getVariant() == null || locale.getVariant().length() == 0); assertEquals(language, locale.getLanguage()); if (countries[i].equals(locale.getCountry())) { found = true; break; } } if (!found) { fail("Cound not find language: " + countries[i] + " for country: " + language); } } assertUnmodifiableCollection(list); } /** * Test countriesByLanguage() method. */ public void testCountriesByLanguage() { assertCountriesByLanguage(null, new String[0]); assertCountriesByLanguage("de", new String[]{"DE", "CH", "AT", "LU"}); assertCountriesByLanguage("zz", new String[0]); assertCountriesByLanguage("it", new String[]{"IT", "CH"}); } /** * @param coll the collection to check */ private static void assertUnmodifiableCollection(Collection coll) { try { coll.add("Unmodifiable"); fail(); } catch (UnsupportedOperationException ex) {} } /** * Tests #LANG-328 - only language+variant */ public void testLang328() { assertValidToLocale("fr__POSIX", "fr", "", "POSIX"); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/math/AbstractRangeTest.java100644 0 0 41016 11513702434 26160 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "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 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.commons.lang.math; import junit.framework.TestCase; /** * Test cases for the {@link Range} classes. * * @author Apache Software Foundation * @version $Id: AbstractRangeTest.java 905636 2010-02-02 14:03:32Z niallp $ */ public abstract class AbstractRangeTest extends TestCase { protected Range tenToTwenty; protected Range otherRange; protected Integer five; protected Integer ten; protected Integer twelve; protected Integer fifteen; protected Integer twenty; protected Integer twentyFive; protected Long long8; protected Long long10; protected Long long12; protected Long long20; protected Long long21; protected Double double8; protected Double double10; protected Double double12; protected Double double20; protected Double double21; protected Float float8; protected Float float10; protected Float float12; protected Float float20; protected Float float21; private static class InnerNumber extends Number { public double doubleValue() { return 12d; } public float floatValue() { return 12f; } public int intValue() { return 12; } public long longValue() { return 12L; } } protected InnerNumber nonComparableNumber = new InnerNumber(); public AbstractRangeTest(String name) { super(name); } public void setUp() { five = new Integer(5); ten = new Integer(10); twelve = new Integer(12); fifteen = new Integer(15); twenty = new Integer(20); twentyFive = new Integer(25); long8 = new Long(8); long10 = new Long(10); long12 = new Long(12); long20 = new Long(20); long21 = new Long(21); double8 = new Double(8); double10 = new Double(10); double12 = new Double(12); double20 = new Double(20); double21 = new Double(21); float8 = new Float(8); float10 = new Float(10); float12 = new Float(12); float20 = new Float(20); float21 = new Float(21); } // -------------------------------------------------------------------------- public void testGetMinimum() { assertEquals(10L, tenToTwenty.getMinimumLong()); assertEquals(10, tenToTwenty.getMinimumInteger()); assertEquals(10d, tenToTwenty.getMinimumDouble(), 0.00001d); assertEquals(10f, tenToTwenty.getMinimumFloat(), 0.00001f); } public void testGetMaximum() { assertEquals(20L, tenToTwenty.getMaximumLong()); assertEquals(20, tenToTwenty.getMaximumInteger()); assertEquals(20d, tenToTwenty.getMaximumDouble(), 0.00001d); assertEquals(20f, tenToTwenty.getMaximumFloat(), 0.00001f); } //-------------------------------------------------------------------------- public void testContainsLong() { assertEquals(false, tenToTwenty.containsLong(null)); assertEquals(true, tenToTwenty.containsLong(nonComparableNumber)); assertEquals(false, tenToTwenty.containsLong(five)); assertEquals(true, tenToTwenty.containsLong(ten)); assertEquals(true, tenToTwenty.containsLong(fifteen)); assertEquals(true, tenToTwenty.containsLong(twenty)); assertEquals(false, tenToTwenty.containsLong(twentyFive)); assertEquals(false, tenToTwenty.containsLong(long8)); assertEquals(true, tenToTwenty.containsLong(long10)); assertEquals(true, tenToTwenty.containsLong(long12)); assertEquals(true, tenToTwenty.containsLong(long20)); assertEquals(false, tenToTwenty.containsLong(long21)); assertEquals(false, tenToTwenty.containsLong(double8)); assertEquals(true, tenToTwenty.containsLong(double10)); assertEquals(true, tenToTwenty.containsLong(double12)); assertEquals(true, tenToTwenty.containsLong(double20)); assertEquals(false, tenToTwenty.containsLong(double21)); assertEquals(false, tenToTwenty.containsLong(float8)); assertEquals(true, tenToTwenty.containsLong(float10)); assertEquals(true, tenToTwenty.containsLong(float12)); assertEquals(true, tenToTwenty.containsLong(float20)); assertEquals(false, tenToTwenty.containsLong(float21)); assertEquals(false, tenToTwenty.containsLong(9L)); assertEquals(true, tenToTwenty.containsLong(10L)); assertEquals(true, tenToTwenty.containsLong(15L)); assertEquals(true, tenToTwenty.containsLong(20L)); assertEquals(false, tenToTwenty.containsLong(21L)); } public void testContainsInteger() { assertEquals(false, tenToTwenty.containsInteger(null)); assertEquals(true, tenToTwenty.containsInteger(nonComparableNumber)); assertEquals(false, tenToTwenty.containsInteger(five)); assertEquals(true, tenToTwenty.containsInteger(ten)); assertEquals(true, tenToTwenty.containsInteger(fifteen)); assertEquals(true, tenToTwenty.containsInteger(twenty)); assertEquals(false, tenToTwenty.containsInteger(twentyFive)); assertEquals(false, tenToTwenty.containsInteger(long8)); assertEquals(true, tenToTwenty.containsInteger(long10)); assertEquals(true, tenToTwenty.containsInteger(long12)); assertEquals(true, tenToTwenty.containsInteger(long20)); assertEquals(false, tenToTwenty.containsInteger(long21)); assertEquals(false, tenToTwenty.containsInteger(double8)); assertEquals(true, tenToTwenty.containsInteger(double10)); assertEquals(true, tenToTwenty.containsInteger(double12)); assertEquals(true, tenToTwenty.containsInteger(double20)); assertEquals(false, tenToTwenty.containsInteger(double21)); assertEquals(false, tenToTwenty.containsInteger(float8)); assertEquals(true, tenToTwenty.containsInteger(float10)); assertEquals(true, tenToTwenty.containsInteger(float12)); assertEquals(true, tenToTwenty.containsInteger(float20)); assertEquals(false, tenToTwenty.containsInteger(float21)); assertEquals(false, tenToTwenty.containsInteger(9)); assertEquals(true, tenToTwenty.containsInteger(10)); assertEquals(true, tenToTwenty.containsInteger(15)); assertEquals(true, tenToTwenty.containsInteger(20)); assertEquals(false, tenToTwenty.containsInteger(21)); } public void testContainsDouble() { assertEquals(false, tenToTwenty.containsDouble(null)); assertEquals(true, tenToTwenty.containsDouble(nonComparableNumber)); assertEquals(false, tenToTwenty.containsDouble(five)); assertEquals(true, tenToTwenty.containsDouble(ten)); assertEquals(true, tenToTwenty.containsDouble(fifteen)); assertEquals(true, tenToTwenty.containsDouble(twenty)); assertEquals(false, tenToTwenty.containsDouble(twentyFive)); assertEquals(false, tenToTwenty.containsDouble(long8)); assertEquals(true, tenToTwenty.containsDouble(long10)); assertEquals(true, tenToTwenty.containsDouble(long12)); assertEquals(true, tenToTwenty.containsDouble(long20)); assertEquals(false, tenToTwenty.containsDouble(long21)); assertEquals(false, tenToTwenty.containsDouble(double8)); assertEquals(true, tenToTwenty.containsDouble(double10)); assertEquals(true, tenToTwenty.containsDouble(double12)); assertEquals(true, tenToTwenty.containsDouble(double20)); assertEquals(false, tenToTwenty.containsDouble(double21)); assertEquals(false, tenToTwenty.containsDouble(float8)); assertEquals(true, tenToTwenty.containsDouble(float10)); assertEquals(true, tenToTwenty.containsDouble(float12)); assertEquals(true, tenToTwenty.containsDouble(float20)); assertEquals(false, tenToTwenty.containsDouble(float21)); assertEquals(false, tenToTwenty.containsDouble(9d)); assertEquals(true, tenToTwenty.containsDouble(10d)); assertEquals(true, tenToTwenty.containsDouble(15d)); assertEquals(true, tenToTwenty.containsDouble(20d)); assertEquals(false, tenToTwenty.containsDouble(21d)); } public void testContainsFloat() { assertEquals(false, tenToTwenty.containsFloat(null)); assertEquals(true, tenToTwenty.containsFloat(nonComparableNumber)); assertEquals(false, tenToTwenty.containsFloat(five)); assertEquals(true, tenToTwenty.containsFloat(ten)); assertEquals(true, tenToTwenty.containsFloat(fifteen)); assertEquals(true, tenToTwenty.containsFloat(twenty)); assertEquals(false, tenToTwenty.containsFloat(twentyFive)); assertEquals(false, tenToTwenty.containsFloat(long8)); assertEquals(true, tenToTwenty.containsFloat(long10)); assertEquals(true, tenToTwenty.containsFloat(long12)); assertEquals(true, tenToTwenty.containsFloat(long20)); assertEquals(false, tenToTwenty.containsFloat(long21)); assertEquals(false, tenToTwenty.containsFloat(double8)); assertEquals(true, tenToTwenty.containsFloat(double10)); assertEquals(true, tenToTwenty.containsFloat(double12)); assertEquals(true, tenToTwenty.containsFloat(double20)); assertEquals(false, tenToTwenty.containsFloat(double21)); assertEquals(false, tenToTwenty.containsFloat(float8)); assertEquals(true, tenToTwenty.containsFloat(float10)); assertEquals(true, tenToTwenty.containsFloat(float12)); assertEquals(true, tenToTwenty.containsFloat(float20)); assertEquals(false, tenToTwenty.containsFloat(float21)); assertEquals(false, tenToTwenty.containsFloat(9f)); assertEquals(true, tenToTwenty.containsFloat(10f)); assertEquals(true, tenToTwenty.containsFloat(15f)); assertEquals(true, tenToTwenty.containsFloat(20f)); assertEquals(false, tenToTwenty.containsFloat(21f)); } //-------------------------------------------------------------------------- public void testContainsRange() { assertEquals(false, tenToTwenty.containsRange(null)); assertEquals(false, tenToTwenty.containsRange(createRange(five, five))); assertEquals(false, tenToTwenty.containsRange(createRange(five, ten))); assertEquals(false, tenToTwenty.containsRange(createRange(five, twelve))); assertEquals(false, tenToTwenty.containsRange(createRange(five, fifteen))); assertEquals(false, tenToTwenty.containsRange(createRange(five, twenty))); assertEquals(false, tenToTwenty.containsRange(createRange(five, twentyFive))); assertEquals(true, tenToTwenty.containsRange(createRange(ten, ten))); assertEquals(true, tenToTwenty.containsRange(createRange(ten, twelve))); assertEquals(true, tenToTwenty.containsRange(createRange(ten, fifteen))); assertEquals(true, tenToTwenty.containsRange(createRange(ten, twenty))); assertEquals(false, tenToTwenty.containsRange(createRange(ten, twentyFive))); assertEquals(true, tenToTwenty.containsRange(createRange(twelve, twelve))); assertEquals(true, tenToTwenty.containsRange(createRange(twelve, fifteen))); assertEquals(true, tenToTwenty.containsRange(createRange(twelve, twenty))); assertEquals(false, tenToTwenty.containsRange(createRange(twelve, twentyFive))); assertEquals(true, tenToTwenty.containsRange(createRange(fifteen, fifteen))); assertEquals(true, tenToTwenty.containsRange(createRange(fifteen, twenty))); assertEquals(false, tenToTwenty.containsRange(createRange(fifteen, twentyFive))); assertEquals(true, tenToTwenty.containsRange(createRange(twenty, twenty))); assertEquals(false, tenToTwenty.containsRange(createRange(twenty, twentyFive))); assertEquals(false, tenToTwenty.containsRange(createRange(twentyFive, twentyFive))); } public void testOverlapsRange() { assertEquals(false, tenToTwenty.overlapsRange(null)); assertEquals(false, tenToTwenty.overlapsRange(createRange(five, five))); assertEquals(true, tenToTwenty.overlapsRange(createRange(five, ten))); assertEquals(true, tenToTwenty.overlapsRange(createRange(five, twelve))); assertEquals(true, tenToTwenty.overlapsRange(createRange(five, fifteen))); assertEquals(true, tenToTwenty.overlapsRange(createRange(five, twenty))); assertEquals(true, tenToTwenty.overlapsRange(createRange(five, twentyFive))); assertEquals(true, tenToTwenty.overlapsRange(createRange(ten, ten))); assertEquals(true, tenToTwenty.overlapsRange(createRange(ten, twelve))); assertEquals(true, tenToTwenty.overlapsRange(createRange(ten, fifteen))); assertEquals(true, tenToTwenty.overlapsRange(createRange(ten, twenty))); assertEquals(true, tenToTwenty.overlapsRange(createRange(ten, twentyFive))); assertEquals(true, tenToTwenty.overlapsRange(createRange(twelve, twelve))); assertEquals(true, tenToTwenty.overlapsRange(createRange(twelve, fifteen))); assertEquals(true, tenToTwenty.overlapsRange(createRange(twelve, twenty))); assertEquals(true, tenToTwenty.overlapsRange(createRange(twelve, twentyFive))); assertEquals(true, tenToTwenty.overlapsRange(createRange(fifteen, fifteen))); assertEquals(true, tenToTwenty.overlapsRange(createRange(fifteen, twenty))); assertEquals(true, tenToTwenty.overlapsRange(createRange(fifteen, twentyFive))); assertEquals(true, tenToTwenty.overlapsRange(createRange(twenty, twenty))); assertEquals(true, tenToTwenty.overlapsRange(createRange(twenty, twentyFive))); assertEquals(false, tenToTwenty.overlapsRange(createRange(twentyFive, twentyFive))); } //-------------------------------------------------------------------------- public void testEquals() { assertEquals(false, tenToTwenty.equals(createRange(ten, fifteen))); assertEquals(false, tenToTwenty.equals(createRange(ten, twentyFive))); assertEquals(false, tenToTwenty.equals(createRange(fifteen, twenty))); assertEquals(false, tenToTwenty.equals(createRange(five, twenty))); assertEquals(false, tenToTwenty.equals(createRange(five, ten))); assertEquals(false, tenToTwenty.equals(createRange(ten))); assertEquals(true, tenToTwenty.equals(tenToTwenty)); assertEquals(true, tenToTwenty.equals(createRange(ten, twenty))); assertEquals(true, tenToTwenty.equals(createRange(twenty, ten))); assertEquals(false, tenToTwenty.equals(null)); assertEquals(false, tenToTwenty.equals(new Object())); assertEquals(false, tenToTwenty.equals(otherRange)); } public void testHashCode() { assertEquals(tenToTwenty.hashCode(), tenToTwenty.hashCode()); assertTrue(tenToTwenty.hashCode() != 0); } public void testToString() { String str = tenToTwenty.toString(); assertEquals("Range[10,20]", str); assertSame(str, tenToTwenty.toString()); assertEquals("Range[-20,-10]", createRange(new Integer(-20), new Integer(-10)).toString()); } protected abstract Range createRange(Integer integer); protected abstract Range createRange(Integer integer1, Integer integer2); } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/math/DoubleRangeTest.java100644 0 0 14150 11513702435 25627 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "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 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.commons.lang.math; /** * Test cases for the {@link DoubleRange} class. * * @author Apache Software Foundation * @version $Id: DoubleRangeTest.java 905636 2010-02-02 14:03:32Z niallp $ */ public final class DoubleRangeTest extends AbstractRangeTest { public DoubleRangeTest(String name) { super(name); } public void setUp() { super.setUp(); tenToTwenty = new DoubleRange(double10, double20); otherRange = new NumberRange(ten, twenty); } protected Range createRange(Integer integer1, Integer integer2) { return new DoubleRange(integer1, integer2); } protected Range createRange(Integer integer) { return new NumberRange(integer); } //-------------------------------------------------------------------------- public void testConstructor1a() { DoubleRange nr = new DoubleRange(8d); assertEquals(double8, nr.getMinimumNumber()); assertEquals(double8, nr.getMaximumNumber()); try { new DoubleRange(Double.NaN); fail(); } catch (IllegalArgumentException ex) {} } public void testConstructor1b() { DoubleRange nr = new DoubleRange(double8); assertSame(double8, nr.getMinimumNumber()); assertSame(double8, nr.getMaximumNumber()); Range r = new DoubleRange(nonComparableNumber); try { new DoubleRange(null); fail(); } catch (IllegalArgumentException ex) {} try { new DoubleRange(new Double(Double.NaN)); fail(); } catch (IllegalArgumentException ex) {} } public void testConstructor2a() { DoubleRange nr = new DoubleRange(8d, 10d); assertEquals(double8, nr.getMinimumNumber()); assertEquals(double10, nr.getMaximumNumber()); nr = new DoubleRange(10d, 8d); assertEquals(double8, nr.getMinimumNumber()); assertEquals(double10, nr.getMaximumNumber()); try { new DoubleRange(Double.NaN, 8d); fail(); } catch (IllegalArgumentException ex) {} } public void testConstructor2b() { DoubleRange nr = new DoubleRange(double8, double10); assertSame(double8, nr.getMinimumNumber()); assertSame(double10, nr.getMaximumNumber()); nr = new DoubleRange(double10, double8); assertSame(double8, nr.getMinimumNumber()); assertSame(double10, nr.getMaximumNumber()); nr = new DoubleRange(double8, double10); assertSame(double8, nr.getMinimumNumber()); assertEquals(double10, nr.getMaximumNumber()); // not null try { new DoubleRange(double8, null); fail(); } catch (IllegalArgumentException ex) {} try { new DoubleRange(null, double8); fail(); } catch (IllegalArgumentException ex) {} try { new DoubleRange(null, null); fail(); } catch (IllegalArgumentException ex) {} try { new DoubleRange(new Double(Double.NaN), double10); fail(); } catch (IllegalArgumentException ex) {} } //-------------------------------------------------------------------------- public void testContainsNumber() { assertEquals(false, tenToTwenty.containsNumber(null)); assertEquals(true, tenToTwenty.containsNumber(nonComparableNumber)); assertEquals(false, tenToTwenty.containsNumber(five)); assertEquals(true, tenToTwenty.containsNumber(ten)); assertEquals(true, tenToTwenty.containsNumber(fifteen)); assertEquals(true, tenToTwenty.containsNumber(twenty)); assertEquals(false, tenToTwenty.containsNumber(twentyFive)); assertEquals(false, tenToTwenty.containsNumber(long8)); assertEquals(true, tenToTwenty.containsNumber(long10)); assertEquals(true, tenToTwenty.containsNumber(long12)); assertEquals(true, tenToTwenty.containsNumber(long20)); assertEquals(false, tenToTwenty.containsNumber(long21)); assertEquals(false, tenToTwenty.containsNumber(double8)); assertEquals(true, tenToTwenty.containsNumber(double10)); assertEquals(true, tenToTwenty.containsNumber(double12)); assertEquals(true, tenToTwenty.containsNumber(double20)); assertEquals(false, tenToTwenty.containsNumber(double21)); assertEquals(false, tenToTwenty.containsNumber(float8)); assertEquals(true, tenToTwenty.containsNumber(float10)); assertEquals(true, tenToTwenty.containsNumber(float12)); assertEquals(true, tenToTwenty.containsNumber(float20)); assertEquals(false, tenToTwenty.containsNumber(float21)); } public void testToString() { String str = tenToTwenty.toString(); assertEquals("Range[10.0,20.0]", str); assertSame(str, tenToTwenty.toString()); assertEquals("Range[-20.0,-10.0]", createRange(new Integer(-20), new Integer(-10)).toString()); } //-------------------------------------------------------------------------- } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/math/FloatRangeTest.java100644 0 0 14062 11513702435 25464 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "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 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.commons.lang.math; /** * Test cases for the {@link FloatRange} class. * * @author Apache Software Foundation * @version $Id: FloatRangeTest.java 905636 2010-02-02 14:03:32Z niallp $ */ public final class FloatRangeTest extends AbstractRangeTest { public FloatRangeTest(String name) { super(name); } public void setUp() { super.setUp(); tenToTwenty = new FloatRange(float10, float20); otherRange = new NumberRange(ten, twenty); } protected Range createRange(Integer integer1, Integer integer2) { return new FloatRange(integer1, integer2); } protected Range createRange(Integer integer) { return new NumberRange(integer); } //-------------------------------------------------------------------------- public void testConstructor1a() { FloatRange nr = new FloatRange(8f); assertEquals(float8, nr.getMinimumNumber()); assertEquals(float8, nr.getMaximumNumber()); try { new FloatRange(Float.NaN); fail(); } catch (IllegalArgumentException ex) {} } public void testConstructor1b() { FloatRange nr = new FloatRange(float8); assertSame(float8, nr.getMinimumNumber()); assertSame(float8, nr.getMaximumNumber()); Range r = new FloatRange(nonComparableNumber); try { new FloatRange(null); fail(); } catch (IllegalArgumentException ex) {} try { new FloatRange(new Double(Double.NaN)); fail(); } catch (IllegalArgumentException ex) {} } public void testConstructor2a() { FloatRange nr = new FloatRange(8f, 10f); assertEquals(float8, nr.getMinimumNumber()); assertEquals(float10, nr.getMaximumNumber()); nr = new FloatRange(10f, 8f); assertEquals(float8, nr.getMinimumNumber()); assertEquals(float10, nr.getMaximumNumber()); try { new FloatRange(Float.NaN, 8f); fail(); } catch (IllegalArgumentException ex) {} } public void testConstructor2b() { FloatRange nr = new FloatRange(float8, float10); assertSame(float8, nr.getMinimumNumber()); assertSame(float10, nr.getMaximumNumber()); nr = new FloatRange(float10, float8); assertSame(float8, nr.getMinimumNumber()); assertSame(float10, nr.getMaximumNumber()); nr = new FloatRange(float8, float10); assertSame(float8, nr.getMinimumNumber()); assertEquals(float10, nr.getMaximumNumber()); // not null try { new FloatRange(float8, null); fail(); } catch (IllegalArgumentException ex) {} try { new FloatRange(null, float8); fail(); } catch (IllegalArgumentException ex) {} try { new FloatRange(null, null); fail(); } catch (IllegalArgumentException ex) {} try { new FloatRange(new Double(Double.NaN), float10); fail(); } catch (IllegalArgumentException ex) {} } //-------------------------------------------------------------------------- public void testContainsNumber() { assertEquals(false, tenToTwenty.containsNumber(null)); assertEquals(true, tenToTwenty.containsNumber(nonComparableNumber)); assertEquals(false, tenToTwenty.containsNumber(five)); assertEquals(true, tenToTwenty.containsNumber(ten)); assertEquals(true, tenToTwenty.containsNumber(fifteen)); assertEquals(true, tenToTwenty.containsNumber(twenty)); assertEquals(false, tenToTwenty.containsNumber(twentyFive)); assertEquals(false, tenToTwenty.containsNumber(long8)); assertEquals(true, tenToTwenty.containsNumber(long10)); assertEquals(true, tenToTwenty.containsNumber(long12)); assertEquals(true, tenToTwenty.containsNumber(long20)); assertEquals(false, tenToTwenty.containsNumber(long21)); assertEquals(false, tenToTwenty.containsNumber(double8)); assertEquals(true, tenToTwenty.containsNumber(double10)); assertEquals(true, tenToTwenty.containsNumber(double12)); assertEquals(true, tenToTwenty.containsNumber(double20)); assertEquals(false, tenToTwenty.containsNumber(double21)); assertEquals(false, tenToTwenty.containsNumber(float8)); assertEquals(true, tenToTwenty.containsNumber(float10)); assertEquals(true, tenToTwenty.containsNumber(float12)); assertEquals(true, tenToTwenty.containsNumber(float20)); assertEquals(false, tenToTwenty.containsNumber(float21)); } public void testToString() { String str = tenToTwenty.toString(); assertEquals("Range[10.0,20.0]", str); assertSame(str, tenToTwenty.toString()); assertEquals("Range[-20.0,-10.0]", createRange(new Integer(-20), new Integer(-10)).toString()); } //-------------------------------------------------------------------------- } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/math/FractionTest.java100644 0 0 134307 11513702435 25234 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "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 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.commons.lang.math; import junit.framework.TestCase; /** * Test cases for the {@link Fraction} class * * @author Apache Software Foundation * @author C. Scott Ananian * @version $Id: FractionTest.java 905636 2010-02-02 14:03:32Z niallp $ */ public class FractionTest extends TestCase { private static final int SKIP = 500; //53 public FractionTest(String name) { super(name); } //-------------------------------------------------------------------------- public void testConstants() { assertEquals(0, Fraction.ZERO.getNumerator()); assertEquals(1, Fraction.ZERO.getDenominator()); assertEquals(1, Fraction.ONE.getNumerator()); assertEquals(1, Fraction.ONE.getDenominator()); assertEquals(1, Fraction.ONE_HALF.getNumerator()); assertEquals(2, Fraction.ONE_HALF.getDenominator()); assertEquals(1, Fraction.ONE_THIRD.getNumerator()); assertEquals(3, Fraction.ONE_THIRD.getDenominator()); assertEquals(2, Fraction.TWO_THIRDS.getNumerator()); assertEquals(3, Fraction.TWO_THIRDS.getDenominator()); assertEquals(1, Fraction.ONE_QUARTER.getNumerator()); assertEquals(4, Fraction.ONE_QUARTER.getDenominator()); assertEquals(2, Fraction.TWO_QUARTERS.getNumerator()); assertEquals(4, Fraction.TWO_QUARTERS.getDenominator()); assertEquals(3, Fraction.THREE_QUARTERS.getNumerator()); assertEquals(4, Fraction.THREE_QUARTERS.getDenominator()); assertEquals(1, Fraction.ONE_FIFTH.getNumerator()); assertEquals(5, Fraction.ONE_FIFTH.getDenominator()); assertEquals(2, Fraction.TWO_FIFTHS.getNumerator()); assertEquals(5, Fraction.TWO_FIFTHS.getDenominator()); assertEquals(3, Fraction.THREE_FIFTHS.getNumerator()); assertEquals(5, Fraction.THREE_FIFTHS.getDenominator()); assertEquals(4, Fraction.FOUR_FIFTHS.getNumerator()); assertEquals(5, Fraction.FOUR_FIFTHS.getDenominator()); } public void testFactory_int_int() { Fraction f = null; // zero f = Fraction.getFraction(0, 1); assertEquals(0, f.getNumerator()); assertEquals(1, f.getDenominator()); f = Fraction.getFraction(0, 2); assertEquals(0, f.getNumerator()); assertEquals(2, f.getDenominator()); // normal f = Fraction.getFraction(1, 1); assertEquals(1, f.getNumerator()); assertEquals(1, f.getDenominator()); f = Fraction.getFraction(2, 1); assertEquals(2, f.getNumerator()); assertEquals(1, f.getDenominator()); f = Fraction.getFraction(23, 345); assertEquals(23, f.getNumerator()); assertEquals(345, f.getDenominator()); // improper f = Fraction.getFraction(22, 7); assertEquals(22, f.getNumerator()); assertEquals(7, f.getDenominator()); // negatives f = Fraction.getFraction(-6, 10); assertEquals(-6, f.getNumerator()); assertEquals(10, f.getDenominator()); f = Fraction.getFraction(6, -10); assertEquals(-6, f.getNumerator()); assertEquals(10, f.getDenominator()); f = Fraction.getFraction(-6, -10); assertEquals(6, f.getNumerator()); assertEquals(10, f.getDenominator()); // zero denominator try { f = Fraction.getFraction(1, 0); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f = Fraction.getFraction(2, 0); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f = Fraction.getFraction(-3, 0); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} // very large: can't represent as unsimplified fraction, although try { f = Fraction.getFraction(4, Integer.MIN_VALUE); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f = Fraction.getFraction(1, Integer.MIN_VALUE); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} } public void testFactory_int_int_int() { Fraction f = null; // zero f = Fraction.getFraction(0, 0, 2); assertEquals(0, f.getNumerator()); assertEquals(2, f.getDenominator()); f = Fraction.getFraction(2, 0, 2); assertEquals(4, f.getNumerator()); assertEquals(2, f.getDenominator()); f = Fraction.getFraction(0, 1, 2); assertEquals(1, f.getNumerator()); assertEquals(2, f.getDenominator()); // normal f = Fraction.getFraction(1, 1, 2); assertEquals(3, f.getNumerator()); assertEquals(2, f.getDenominator()); // negatives try { f = Fraction.getFraction(1, -6, -10); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f = Fraction.getFraction(1, -6, -10); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f = Fraction.getFraction(1, -6, -10); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} // negative whole f = Fraction.getFraction(-1, 6, 10); assertEquals(-16, f.getNumerator()); assertEquals(10, f.getDenominator()); try { f = Fraction.getFraction(-1, -6, 10); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f = Fraction.getFraction(-1, 6, -10); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f = Fraction.getFraction(-1, -6, -10); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} // zero denominator try { f = Fraction.getFraction(0, 1, 0); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f = Fraction.getFraction(1, 2, 0); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f = Fraction.getFraction(-1, -3, 0); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f = Fraction.getFraction(Integer.MAX_VALUE, 1, 2); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f = Fraction.getFraction(-Integer.MAX_VALUE, 1, 2); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} // very large f = Fraction.getFraction(-1, 0, Integer.MAX_VALUE); assertEquals(-Integer.MAX_VALUE, f.getNumerator()); assertEquals(Integer.MAX_VALUE, f.getDenominator()); try { // negative denominators not allowed in this constructor. f = Fraction.getFraction(0, 4, Integer.MIN_VALUE); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f = Fraction.getFraction(1, 1, Integer.MAX_VALUE); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f = Fraction.getFraction(-1, 2, Integer.MAX_VALUE); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} } public void testReducedFactory_int_int() { Fraction f = null; // zero f = Fraction.getReducedFraction(0, 1); assertEquals(0, f.getNumerator()); assertEquals(1, f.getDenominator()); // normal f = Fraction.getReducedFraction(1, 1); assertEquals(1, f.getNumerator()); assertEquals(1, f.getDenominator()); f = Fraction.getReducedFraction(2, 1); assertEquals(2, f.getNumerator()); assertEquals(1, f.getDenominator()); // improper f = Fraction.getReducedFraction(22, 7); assertEquals(22, f.getNumerator()); assertEquals(7, f.getDenominator()); // negatives f = Fraction.getReducedFraction(-6, 10); assertEquals(-3, f.getNumerator()); assertEquals(5, f.getDenominator()); f = Fraction.getReducedFraction(6, -10); assertEquals(-3, f.getNumerator()); assertEquals(5, f.getDenominator()); f = Fraction.getReducedFraction(-6, -10); assertEquals(3, f.getNumerator()); assertEquals(5, f.getDenominator()); // zero denominator try { f = Fraction.getReducedFraction(1, 0); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f = Fraction.getReducedFraction(2, 0); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f = Fraction.getReducedFraction(-3, 0); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} // reduced f = Fraction.getReducedFraction(0, 2); assertEquals(0, f.getNumerator()); assertEquals(1, f.getDenominator()); f = Fraction.getReducedFraction(2, 2); assertEquals(1, f.getNumerator()); assertEquals(1, f.getDenominator()); f = Fraction.getReducedFraction(2, 4); assertEquals(1, f.getNumerator()); assertEquals(2, f.getDenominator()); f = Fraction.getReducedFraction(15, 10); assertEquals(3, f.getNumerator()); assertEquals(2, f.getDenominator()); f = Fraction.getReducedFraction(121, 22); assertEquals(11, f.getNumerator()); assertEquals(2, f.getDenominator()); // Extreme values // OK, can reduce before negating f = Fraction.getReducedFraction(-2, Integer.MIN_VALUE); assertEquals(1, f.getNumerator()); assertEquals(-(Integer.MIN_VALUE / 2), f.getDenominator()); // Can't reduce, negation will throw try { f = Fraction.getReducedFraction(-7, Integer.MIN_VALUE); fail("Expecting ArithmeticException"); } catch (ArithmeticException ex) {} } public void testFactory_double() { Fraction f = null; try { f = Fraction.getFraction(Double.NaN); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f = Fraction.getFraction(Double.POSITIVE_INFINITY); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f = Fraction.getFraction(Double.NEGATIVE_INFINITY); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f = Fraction.getFraction((double) Integer.MAX_VALUE + 1); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} // zero f = Fraction.getFraction(0.0d); assertEquals(0, f.getNumerator()); assertEquals(1, f.getDenominator()); // one f = Fraction.getFraction(1.0d); assertEquals(1, f.getNumerator()); assertEquals(1, f.getDenominator()); // one half f = Fraction.getFraction(0.5d); assertEquals(1, f.getNumerator()); assertEquals(2, f.getDenominator()); // negative f = Fraction.getFraction(-0.875d); assertEquals(-7, f.getNumerator()); assertEquals(8, f.getDenominator()); // over 1 f = Fraction.getFraction(1.25d); assertEquals(5, f.getNumerator()); assertEquals(4, f.getDenominator()); // two thirds f = Fraction.getFraction(0.66666d); assertEquals(2, f.getNumerator()); assertEquals(3, f.getDenominator()); // small f = Fraction.getFraction(1.0d/10001d); assertEquals(0, f.getNumerator()); assertEquals(1, f.getDenominator()); // normal Fraction f2 = null; for (int i = 1; i <= 100; i++) { // denominator for (int j = 1; j <= i; j++) { // numerator try { f = Fraction.getFraction((double) j / (double) i); } catch (ArithmeticException ex) { System.err.println(j + " " + i); throw ex; } f2 = Fraction.getReducedFraction(j, i); assertEquals(f2.getNumerator(), f.getNumerator()); assertEquals(f2.getDenominator(), f.getDenominator()); } } // save time by skipping some tests! ( for (int i = 1001; i <= 10000; i+=SKIP) { // denominator for (int j = 1; j <= i; j++) { // numerator try { f = Fraction.getFraction((double) j / (double) i); } catch (ArithmeticException ex) { System.err.println(j + " " + i); throw ex; } f2 = Fraction.getReducedFraction(j, i); assertEquals(f2.getNumerator(), f.getNumerator()); assertEquals(f2.getDenominator(), f.getDenominator()); } } } public void testFactory_String() { try { Fraction.getFraction(null); fail("expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) {} } public void testFactory_String_double() { Fraction f = null; f = Fraction.getFraction("0.0"); assertEquals(0, f.getNumerator()); assertEquals(1, f.getDenominator()); f = Fraction.getFraction("0.2"); assertEquals(1, f.getNumerator()); assertEquals(5, f.getDenominator()); f = Fraction.getFraction("0.5"); assertEquals(1, f.getNumerator()); assertEquals(2, f.getDenominator()); f = Fraction.getFraction("0.66666"); assertEquals(2, f.getNumerator()); assertEquals(3, f.getDenominator()); try { f = Fraction.getFraction("2.3R"); fail("Expecting NumberFormatException"); } catch (NumberFormatException ex) {} try { f = Fraction.getFraction("2147483648"); // too big fail("Expecting NumberFormatException"); } catch (NumberFormatException ex) {} try { f = Fraction.getFraction("."); fail("Expecting NumberFormatException"); } catch (NumberFormatException ex) {} } public void testFactory_String_proper() { Fraction f = null; f = Fraction.getFraction("0 0/1"); assertEquals(0, f.getNumerator()); assertEquals(1, f.getDenominator()); f = Fraction.getFraction("1 1/5"); assertEquals(6, f.getNumerator()); assertEquals(5, f.getDenominator()); f = Fraction.getFraction("7 1/2"); assertEquals(15, f.getNumerator()); assertEquals(2, f.getDenominator()); f = Fraction.getFraction("1 2/4"); assertEquals(6, f.getNumerator()); assertEquals(4, f.getDenominator()); f = Fraction.getFraction("-7 1/2"); assertEquals(-15, f.getNumerator()); assertEquals(2, f.getDenominator()); f = Fraction.getFraction("-1 2/4"); assertEquals(-6, f.getNumerator()); assertEquals(4, f.getDenominator()); try { f = Fraction.getFraction("2 3"); fail("expecting NumberFormatException"); } catch (NumberFormatException ex) {} try { f = Fraction.getFraction("a 3"); fail("expecting NumberFormatException"); } catch (NumberFormatException ex) {} try { f = Fraction.getFraction("2 b/4"); fail("expecting NumberFormatException"); } catch (NumberFormatException ex) {} try { f = Fraction.getFraction("2 "); fail("expecting NumberFormatException"); } catch (NumberFormatException ex) {} try { f = Fraction.getFraction(" 3"); fail("expecting NumberFormatException"); } catch (NumberFormatException ex) {} try { f = Fraction.getFraction(" "); fail("expecting NumberFormatException"); } catch (NumberFormatException ex) {} } public void testFactory_String_improper() { Fraction f = null; f = Fraction.getFraction("0/1"); assertEquals(0, f.getNumerator()); assertEquals(1, f.getDenominator()); f = Fraction.getFraction("1/5"); assertEquals(1, f.getNumerator()); assertEquals(5, f.getDenominator()); f = Fraction.getFraction("1/2"); assertEquals(1, f.getNumerator()); assertEquals(2, f.getDenominator()); f = Fraction.getFraction("2/3"); assertEquals(2, f.getNumerator()); assertEquals(3, f.getDenominator()); f = Fraction.getFraction("7/3"); assertEquals(7, f.getNumerator()); assertEquals(3, f.getDenominator()); f = Fraction.getFraction("2/4"); assertEquals(2, f.getNumerator()); assertEquals(4, f.getDenominator()); try { f = Fraction.getFraction("2/d"); fail("expecting NumberFormatException"); } catch (NumberFormatException ex) {} try { f = Fraction.getFraction("2e/3"); fail("expecting NumberFormatException"); } catch (NumberFormatException ex) {} try { f = Fraction.getFraction("2/"); fail("expecting NumberFormatException"); } catch (NumberFormatException ex) {} try { f = Fraction.getFraction("/"); fail("expecting NumberFormatException"); } catch (NumberFormatException ex) {} } public void testGets() { Fraction f = null; f = Fraction.getFraction(3, 5, 6); assertEquals(23, f.getNumerator()); assertEquals(3, f.getProperWhole()); assertEquals(5, f.getProperNumerator()); assertEquals(6, f.getDenominator()); f = Fraction.getFraction(-3, 5, 6); assertEquals(-23, f.getNumerator()); assertEquals(-3, f.getProperWhole()); assertEquals(5, f.getProperNumerator()); assertEquals(6, f.getDenominator()); f = Fraction.getFraction(Integer.MIN_VALUE, 0, 1); assertEquals(Integer.MIN_VALUE, f.getNumerator()); assertEquals(Integer.MIN_VALUE, f.getProperWhole()); assertEquals(0, f.getProperNumerator()); assertEquals(1, f.getDenominator()); } public void testConversions() { Fraction f = null; f = Fraction.getFraction(3, 7, 8); assertEquals(3, f.intValue()); assertEquals(3L, f.longValue()); assertEquals(3.875f, f.floatValue(), 0.00001f); assertEquals(3.875d, f.doubleValue(), 0.00001d); } public void testReduce() { Fraction f = null; f = Fraction.getFraction(50, 75); Fraction result = f.reduce(); assertEquals(2, result.getNumerator()); assertEquals(3, result.getDenominator()); f = Fraction.getFraction(-2, -3); result = f.reduce(); assertEquals(2, result.getNumerator()); assertEquals(3, result.getDenominator()); f = Fraction.getFraction(2, -3); result = f.reduce(); assertEquals(-2, result.getNumerator()); assertEquals(3, result.getDenominator()); f = Fraction.getFraction(-2, 3); result = f.reduce(); assertEquals(-2, result.getNumerator()); assertEquals(3, result.getDenominator()); assertSame(f, result); f = Fraction.getFraction(2, 3); result = f.reduce(); assertEquals(2, result.getNumerator()); assertEquals(3, result.getDenominator()); assertSame(f, result); f = Fraction.getFraction(0, 1); result = f.reduce(); assertEquals(0, result.getNumerator()); assertEquals(1, result.getDenominator()); assertSame(f, result); f = Fraction.getFraction(0, 100); result = f.reduce(); assertEquals(0, result.getNumerator()); assertEquals(1, result.getDenominator()); assertSame(result, Fraction.ZERO); } public void testInvert() { Fraction f = null; f = Fraction.getFraction(50, 75); f = f.invert(); assertEquals(75, f.getNumerator()); assertEquals(50, f.getDenominator()); f = Fraction.getFraction(4, 3); f = f.invert(); assertEquals(3, f.getNumerator()); assertEquals(4, f.getDenominator()); f = Fraction.getFraction(-15, 47); f = f.invert(); assertEquals(-47, f.getNumerator()); assertEquals(15, f.getDenominator()); f = Fraction.getFraction(0, 3); try { f = f.invert(); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} // large values f = Fraction.getFraction(Integer.MIN_VALUE, 1); try { f = f.invert(); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} f = Fraction.getFraction(Integer.MAX_VALUE, 1); f = f.invert(); assertEquals(1, f.getNumerator()); assertEquals(Integer.MAX_VALUE, f.getDenominator()); } public void testNegate() { Fraction f = null; f = Fraction.getFraction(50, 75); f = f.negate(); assertEquals(-50, f.getNumerator()); assertEquals(75, f.getDenominator()); f = Fraction.getFraction(-50, 75); f = f.negate(); assertEquals(50, f.getNumerator()); assertEquals(75, f.getDenominator()); // large values f = Fraction.getFraction(Integer.MAX_VALUE-1, Integer.MAX_VALUE); f = f.negate(); assertEquals(Integer.MIN_VALUE+2, f.getNumerator()); assertEquals(Integer.MAX_VALUE, f.getDenominator()); f = Fraction.getFraction(Integer.MIN_VALUE, 1); try { f = f.negate(); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} } public void testAbs() { Fraction f = null; f = Fraction.getFraction(50, 75); f = f.abs(); assertEquals(50, f.getNumerator()); assertEquals(75, f.getDenominator()); f = Fraction.getFraction(-50, 75); f = f.abs(); assertEquals(50, f.getNumerator()); assertEquals(75, f.getDenominator()); f = Fraction.getFraction(Integer.MAX_VALUE, 1); f = f.abs(); assertEquals(Integer.MAX_VALUE, f.getNumerator()); assertEquals(1, f.getDenominator()); f = Fraction.getFraction(Integer.MAX_VALUE, -1); f = f.abs(); assertEquals(Integer.MAX_VALUE, f.getNumerator()); assertEquals(1, f.getDenominator()); f = Fraction.getFraction(Integer.MIN_VALUE, 1); try { f = f.abs(); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} } public void testPow() { Fraction f = null; f = Fraction.getFraction(3, 5); assertEquals(Fraction.ONE, f.pow(0)); f = Fraction.getFraction(3, 5); assertSame(f, f.pow(1)); assertEquals(f, f.pow(1)); f = Fraction.getFraction(3, 5); f = f.pow(2); assertEquals(9, f.getNumerator()); assertEquals(25, f.getDenominator()); f = Fraction.getFraction(3, 5); f = f.pow(3); assertEquals(27, f.getNumerator()); assertEquals(125, f.getDenominator()); f = Fraction.getFraction(3, 5); f = f.pow(-1); assertEquals(5, f.getNumerator()); assertEquals(3, f.getDenominator()); f = Fraction.getFraction(3, 5); f = f.pow(-2); assertEquals(25, f.getNumerator()); assertEquals(9, f.getDenominator()); // check unreduced fractions stay that way. f = Fraction.getFraction(6, 10); assertEquals(Fraction.ONE, f.pow(0)); f = Fraction.getFraction(6, 10); assertEquals(f, f.pow(1)); assertFalse(f.pow(1).equals(Fraction.getFraction(3,5))); f = Fraction.getFraction(6, 10); f = f.pow(2); assertEquals(9, f.getNumerator()); assertEquals(25, f.getDenominator()); f = Fraction.getFraction(6, 10); f = f.pow(3); assertEquals(27, f.getNumerator()); assertEquals(125, f.getDenominator()); f = Fraction.getFraction(6, 10); f = f.pow(-1); assertEquals(10, f.getNumerator()); assertEquals(6, f.getDenominator()); f = Fraction.getFraction(6, 10); f = f.pow(-2); assertEquals(25, f.getNumerator()); assertEquals(9, f.getDenominator()); // zero to any positive power is still zero. f = Fraction.getFraction(0, 1231); f = f.pow(1); assertTrue(0==f.compareTo(Fraction.ZERO)); assertEquals(0, f.getNumerator()); assertEquals(1231, f.getDenominator()); f = f.pow(2); assertTrue(0==f.compareTo(Fraction.ZERO)); assertEquals(0, f.getNumerator()); assertEquals(1, f.getDenominator()); // zero to negative powers should throw an exception try { f = f.pow(-1); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f = f.pow(Integer.MIN_VALUE); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} // one to any power is still one. f = Fraction.getFraction(1, 1); f = f.pow(0); assertEquals(f, Fraction.ONE); f = f.pow(1); assertEquals(f, Fraction.ONE); f = f.pow(-1); assertEquals(f, Fraction.ONE); f = f.pow(Integer.MAX_VALUE); assertEquals(f, Fraction.ONE); f = f.pow(Integer.MIN_VALUE); assertEquals(f, Fraction.ONE); f = Fraction.getFraction(Integer.MAX_VALUE, 1); try { f = f.pow(2); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} // Numerator growing too negative during the pow operation. f = Fraction.getFraction(Integer.MIN_VALUE, 1); try { f = f.pow(3); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} f = Fraction.getFraction(65536, 1); try { f = f.pow(2); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} } public void testAdd() { Fraction f = null; Fraction f1 = null; Fraction f2 = null; f1 = Fraction.getFraction(3, 5); f2 = Fraction.getFraction(1, 5); f = f1.add(f2); assertEquals(4, f.getNumerator()); assertEquals(5, f.getDenominator()); f1 = Fraction.getFraction(3, 5); f2 = Fraction.getFraction(2, 5); f = f1.add(f2); assertEquals(1, f.getNumerator()); assertEquals(1, f.getDenominator()); f1 = Fraction.getFraction(3, 5); f2 = Fraction.getFraction(3, 5); f = f1.add(f2); assertEquals(6, f.getNumerator()); assertEquals(5, f.getDenominator()); f1 = Fraction.getFraction(3, 5); f2 = Fraction.getFraction(-4, 5); f = f1.add(f2); assertEquals(-1, f.getNumerator()); assertEquals(5, f.getDenominator()); f1 = Fraction.getFraction(Integer.MAX_VALUE - 1, 1); f2 = Fraction.ONE; f = f1.add(f2); assertEquals(Integer.MAX_VALUE, f.getNumerator()); assertEquals(1, f.getDenominator()); f1 = Fraction.getFraction(3, 5); f2 = Fraction.getFraction(1, 2); f = f1.add(f2); assertEquals(11, f.getNumerator()); assertEquals(10, f.getDenominator()); f1 = Fraction.getFraction(3, 8); f2 = Fraction.getFraction(1, 6); f = f1.add(f2); assertEquals(13, f.getNumerator()); assertEquals(24, f.getDenominator()); f1 = Fraction.getFraction(0, 5); f2 = Fraction.getFraction(1, 5); f = f1.add(f2); assertSame(f2, f); f = f2.add(f1); assertSame(f2, f); f1 = Fraction.getFraction(-1, 13*13*2*2); f2 = Fraction.getFraction(-2, 13*17*2); f = f1.add(f2); assertEquals(13*13*17*2*2, f.getDenominator()); assertEquals(-17 - 2*13*2, f.getNumerator()); try { f.add(null); fail("expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) {} // if this fraction is added naively, it will overflow. // check that it doesn't. f1 = Fraction.getFraction(1,32768*3); f2 = Fraction.getFraction(1,59049); f = f1.add(f2); assertEquals(52451, f.getNumerator()); assertEquals(1934917632, f.getDenominator()); f1 = Fraction.getFraction(Integer.MIN_VALUE, 3); f2 = Fraction.ONE_THIRD; f = f1.add(f2); assertEquals(Integer.MIN_VALUE+1, f.getNumerator()); assertEquals(3, f.getDenominator()); f1 = Fraction.getFraction(Integer.MAX_VALUE - 1, 1); f2 = Fraction.ONE; f = f1.add(f2); assertEquals(Integer.MAX_VALUE, f.getNumerator()); assertEquals(1, f.getDenominator()); try { f = f.add(Fraction.ONE); // should overflow fail("expecting ArithmeticException but got: " + f.toString()); } catch (ArithmeticException ex) {} // denominator should not be a multiple of 2 or 3 to trigger overflow f1 = Fraction.getFraction(Integer.MIN_VALUE, 5); f2 = Fraction.getFraction(-1,5); try { f = f1.add(f2); // should overflow fail("expecting ArithmeticException but got: " + f.toString()); } catch (ArithmeticException ex) {} try { f= Fraction.getFraction(-Integer.MAX_VALUE, 1); f = f.add(f); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f= Fraction.getFraction(-Integer.MAX_VALUE, 1); f = f.add(f); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} f1 = Fraction.getFraction(3,327680); f2 = Fraction.getFraction(2,59049); try { f = f1.add(f2); // should overflow fail("expecting ArithmeticException but got: " + f.toString()); } catch (ArithmeticException ex) {} } public void testSubtract() { Fraction f = null; Fraction f1 = null; Fraction f2 = null; f1 = Fraction.getFraction(3, 5); f2 = Fraction.getFraction(1, 5); f = f1.subtract(f2); assertEquals(2, f.getNumerator()); assertEquals(5, f.getDenominator()); f1 = Fraction.getFraction(7, 5); f2 = Fraction.getFraction(2, 5); f = f1.subtract(f2); assertEquals(1, f.getNumerator()); assertEquals(1, f.getDenominator()); f1 = Fraction.getFraction(3, 5); f2 = Fraction.getFraction(3, 5); f = f1.subtract(f2); assertEquals(0, f.getNumerator()); assertEquals(1, f.getDenominator()); f1 = Fraction.getFraction(3, 5); f2 = Fraction.getFraction(-4, 5); f = f1.subtract(f2); assertEquals(7, f.getNumerator()); assertEquals(5, f.getDenominator()); f1 = Fraction.getFraction(0, 5); f2 = Fraction.getFraction(4, 5); f = f1.subtract(f2); assertEquals(-4, f.getNumerator()); assertEquals(5, f.getDenominator()); f1 = Fraction.getFraction(0, 5); f2 = Fraction.getFraction(-4, 5); f = f1.subtract(f2); assertEquals(4, f.getNumerator()); assertEquals(5, f.getDenominator()); f1 = Fraction.getFraction(3, 5); f2 = Fraction.getFraction(1, 2); f = f1.subtract(f2); assertEquals(1, f.getNumerator()); assertEquals(10, f.getDenominator()); f1 = Fraction.getFraction(0, 5); f2 = Fraction.getFraction(1, 5); f = f2.subtract(f1); assertSame(f2, f); try { f.subtract(null); fail("expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) {} // if this fraction is subtracted naively, it will overflow. // check that it doesn't. f1 = Fraction.getFraction(1,32768*3); f2 = Fraction.getFraction(1,59049); f = f1.subtract(f2); assertEquals(-13085, f.getNumerator()); assertEquals(1934917632, f.getDenominator()); f1 = Fraction.getFraction(Integer.MIN_VALUE, 3); f2 = Fraction.ONE_THIRD.negate(); f = f1.subtract(f2); assertEquals(Integer.MIN_VALUE+1, f.getNumerator()); assertEquals(3, f.getDenominator()); f1 = Fraction.getFraction(Integer.MAX_VALUE, 1); f2 = Fraction.ONE; f = f1.subtract(f2); assertEquals(Integer.MAX_VALUE-1, f.getNumerator()); assertEquals(1, f.getDenominator()); try { f1 = Fraction.getFraction(1, Integer.MAX_VALUE); f2 = Fraction.getFraction(1, Integer.MAX_VALUE - 1); f = f1.subtract(f2); fail("expecting ArithmeticException"); //should overflow } catch (ArithmeticException ex) {} // denominator should not be a multiple of 2 or 3 to trigger overflow f1 = Fraction.getFraction(Integer.MIN_VALUE, 5); f2 = Fraction.getFraction(1,5); try { f = f1.subtract(f2); // should overflow fail("expecting ArithmeticException but got: " + f.toString()); } catch (ArithmeticException ex) {} try { f= Fraction.getFraction(Integer.MIN_VALUE, 1); f = f.subtract(Fraction.ONE); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f= Fraction.getFraction(Integer.MAX_VALUE, 1); f = f.subtract(Fraction.ONE.negate()); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} f1 = Fraction.getFraction(3,327680); f2 = Fraction.getFraction(2,59049); try { f = f1.subtract(f2); // should overflow fail("expecting ArithmeticException but got: " + f.toString()); } catch (ArithmeticException ex) {} } public void testMultiply() { Fraction f = null; Fraction f1 = null; Fraction f2 = null; f1 = Fraction.getFraction(3, 5); f2 = Fraction.getFraction(2, 5); f = f1.multiplyBy(f2); assertEquals(6, f.getNumerator()); assertEquals(25, f.getDenominator()); f1 = Fraction.getFraction(6, 10); f2 = Fraction.getFraction(6, 10); f = f1.multiplyBy(f2); assertEquals(9, f.getNumerator()); assertEquals(25, f.getDenominator()); f = f.multiplyBy(f2); assertEquals(27, f.getNumerator()); assertEquals(125, f.getDenominator()); f1 = Fraction.getFraction(3, 5); f2 = Fraction.getFraction(-2, 5); f = f1.multiplyBy(f2); assertEquals(-6, f.getNumerator()); assertEquals(25, f.getDenominator()); f1 = Fraction.getFraction(-3, 5); f2 = Fraction.getFraction(-2, 5); f = f1.multiplyBy(f2); assertEquals(6, f.getNumerator()); assertEquals(25, f.getDenominator()); f1 = Fraction.getFraction(0, 5); f2 = Fraction.getFraction(2, 7); f = f1.multiplyBy(f2); assertSame(Fraction.ZERO, f); f1 = Fraction.getFraction(2, 7); f2 = Fraction.ONE; f = f1.multiplyBy(f2); assertEquals(2, f.getNumerator()); assertEquals(7, f.getDenominator()); f1 = Fraction.getFraction(Integer.MAX_VALUE, 1); f2 = Fraction.getFraction(Integer.MIN_VALUE, Integer.MAX_VALUE); f = f1.multiplyBy(f2); assertEquals(Integer.MIN_VALUE, f.getNumerator()); assertEquals(1, f.getDenominator()); try { f.multiplyBy(null); fail("expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) {} try { f1 = Fraction.getFraction(1, Integer.MAX_VALUE); f = f1.multiplyBy(f1); // should overflow fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f1 = Fraction.getFraction(1, -Integer.MAX_VALUE); f = f1.multiplyBy(f1); // should overflow fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} } public void testDivide() { Fraction f = null; Fraction f1 = null; Fraction f2 = null; f1 = Fraction.getFraction(3, 5); f2 = Fraction.getFraction(2, 5); f = f1.divideBy(f2); assertEquals(3, f.getNumerator()); assertEquals(2, f.getDenominator()); f1 = Fraction.getFraction(3, 5); f2 = Fraction.ZERO; try { f = f1.divideBy(f2); fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} f1 = Fraction.getFraction(0, 5); f2 = Fraction.getFraction(2, 7); f = f1.divideBy(f2); assertSame(Fraction.ZERO, f); f1 = Fraction.getFraction(2, 7); f2 = Fraction.ONE; f = f1.divideBy(f2); assertEquals(2, f.getNumerator()); assertEquals(7, f.getDenominator()); f1 = Fraction.getFraction(1, Integer.MAX_VALUE); f = f1.divideBy(f1); assertEquals(1, f.getNumerator()); assertEquals(1, f.getDenominator()); f1 = Fraction.getFraction(Integer.MIN_VALUE, Integer.MAX_VALUE); f2 = Fraction.getFraction(1, Integer.MAX_VALUE); f = f1.divideBy(f2); assertEquals(Integer.MIN_VALUE, f.getNumerator()); assertEquals(1, f.getDenominator()); try { f.divideBy(null); fail("IllegalArgumentException"); } catch (IllegalArgumentException ex) {} try { f1 = Fraction.getFraction(1, Integer.MAX_VALUE); f = f1.divideBy(f1.invert()); // should overflow fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} try { f1 = Fraction.getFraction(1, -Integer.MAX_VALUE); f = f1.divideBy(f1.invert()); // should overflow fail("expecting ArithmeticException"); } catch (ArithmeticException ex) {} } public void testEquals() { Fraction f1 = null; Fraction f2 = null; f1 = Fraction.getFraction(3, 5); assertEquals(false, f1.equals(null)); assertEquals(false, f1.equals(new Object())); assertEquals(false, f1.equals(new Integer(6))); f1 = Fraction.getFraction(3, 5); f2 = Fraction.getFraction(2, 5); assertEquals(false, f1.equals(f2)); assertEquals(true, f1.equals(f1)); assertEquals(true, f2.equals(f2)); f2 = Fraction.getFraction(3, 5); assertEquals(true, f1.equals(f2)); f2 = Fraction.getFraction(6, 10); assertEquals(false, f1.equals(f2)); } public void testHashCode() { Fraction f1 = Fraction.getFraction(3, 5); Fraction f2 = Fraction.getFraction(3, 5); assertTrue(f1.hashCode() == f2.hashCode()); f2 = Fraction.getFraction(2, 5); assertTrue(f1.hashCode() != f2.hashCode()); f2 = Fraction.getFraction(6, 10); assertTrue(f1.hashCode() != f2.hashCode()); } public void testCompareTo() { Fraction f1 = null; Fraction f2 = null; f1 = Fraction.getFraction(3, 5); assertTrue(f1.compareTo(f1) == 0); try { f1.compareTo(null); fail("expecting NullPointerException"); } catch (NullPointerException ex) {} try { f1.compareTo(new Object()); fail("expecting ClassCastException"); } catch (ClassCastException ex) {} f2 = Fraction.getFraction(2, 5); assertTrue(f1.compareTo(f2) > 0); assertTrue(f2.compareTo(f2) == 0); f2 = Fraction.getFraction(4, 5); assertTrue(f1.compareTo(f2) < 0); assertTrue(f2.compareTo(f2) == 0); f2 = Fraction.getFraction(3, 5); assertTrue(f1.compareTo(f2) == 0); assertTrue(f2.compareTo(f2) == 0); f2 = Fraction.getFraction(6, 10); assertTrue(f1.compareTo(f2) == 0); assertTrue(f2.compareTo(f2) == 0); f2 = Fraction.getFraction(-1, 1, Integer.MAX_VALUE); assertTrue(f1.compareTo(f2) > 0); assertTrue(f2.compareTo(f2) == 0); } public void testToString() { Fraction f = null; f = Fraction.getFraction(3, 5); String str = f.toString(); assertEquals("3/5", str); assertSame(str, f.toString()); f = Fraction.getFraction(7, 5); assertEquals("7/5", f.toString()); f = Fraction.getFraction(4, 2); assertEquals("4/2", f.toString()); f = Fraction.getFraction(0, 2); assertEquals("0/2", f.toString()); f = Fraction.getFraction(2, 2); assertEquals("2/2", f.toString()); f = Fraction.getFraction(Integer.MIN_VALUE, 0, 1); assertEquals("-2147483648/1", f.toString()); f = Fraction.getFraction(-1, 1, Integer.MAX_VALUE); assertEquals("-2147483648/2147483647", f.toString()); } public void testToProperString() { Fraction f = null; f = Fraction.getFraction(3, 5); String str = f.toProperString(); assertEquals("3/5", str); assertSame(str, f.toProperString()); f = Fraction.getFraction(7, 5); assertEquals("1 2/5", f.toProperString()); f = Fraction.getFraction(14, 10); assertEquals("1 4/10", f.toProperString()); f = Fraction.getFraction(4, 2); assertEquals("2", f.toProperString()); f = Fraction.getFraction(0, 2); assertEquals("0", f.toProperString()); f = Fraction.getFraction(2, 2); assertEquals("1", f.toProperString()); f = Fraction.getFraction(-7, 5); assertEquals("-1 2/5", f.toProperString()); f = Fraction.getFraction(Integer.MIN_VALUE, 0, 1); assertEquals("-2147483648", f.toProperString()); f = Fraction.getFraction(-1, 1, Integer.MAX_VALUE); assertEquals("-1 1/2147483647", f.toProperString()); assertEquals("-1", Fraction.getFraction(-1).toProperString()); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/math/IEEE754rUtilsTest.java100644 0 0 10202 11513702435 25604 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.math; import junit.framework.TestCase; /** * Unit tests {@link org.apache.commons.lang.math.IEEE754rUtils}. * * @version $Id: IEEE754rUtilsTest.java 905246 2010-02-01 10:55:38Z niallp $ */ public class IEEE754rUtilsTest extends TestCase { public void testLang381() { assertEquals(1.2, IEEE754rUtils.min(1.2, 2.5, Double.NaN), 0.01); assertEquals(2.5, IEEE754rUtils.max(1.2, 2.5, Double.NaN), 0.01); assertTrue(Double.isNaN(IEEE754rUtils.max(Double.NaN, Double.NaN, Double.NaN))); assertEquals(1.2f, IEEE754rUtils.min(1.2f, 2.5f, Float.NaN), 0.01); assertEquals(2.5f, IEEE754rUtils.max(1.2f, 2.5f, Float.NaN), 0.01); assertTrue(Float.isNaN(IEEE754rUtils.max(Float.NaN, Float.NaN, Float.NaN))); double[] a = new double[] { 1.2, Double.NaN, 3.7, 27.0, 42.0, Double.NaN }; assertEquals(42.0, IEEE754rUtils.max(a), 0.01); assertEquals(1.2, IEEE754rUtils.min(a), 0.01); double[] b = new double[] { Double.NaN, 1.2, Double.NaN, 3.7, 27.0, 42.0, Double.NaN }; assertEquals(42.0, IEEE754rUtils.max(b), 0.01); assertEquals(1.2, IEEE754rUtils.min(b), 0.01); float[] aF = new float[] { 1.2f, Float.NaN, 3.7f, 27.0f, 42.0f, Float.NaN }; assertEquals(1.2f, IEEE754rUtils.min(aF), 0.01); assertEquals(42.0f, IEEE754rUtils.max(aF), 0.01); float[] bF = new float[] { Float.NaN, 1.2f, Float.NaN, 3.7f, 27.0f, 42.0f, Float.NaN }; assertEquals(1.2f, IEEE754rUtils.min(bF), 0.01); assertEquals(42.0f, IEEE754rUtils.max(bF), 0.01); } public void testEnforceExceptions() { try { IEEE754rUtils.min( (float[]) null); fail("IllegalArgumentException expected for null input"); } catch(IllegalArgumentException iae) { /* expected */ } try { IEEE754rUtils.min(new float[0]); fail("IllegalArgumentException expected for empty input"); } catch(IllegalArgumentException iae) { /* expected */ } try { IEEE754rUtils.max( (float[]) null); fail("IllegalArgumentException expected for null input"); } catch(IllegalArgumentException iae) { /* expected */ } try { IEEE754rUtils.max(new float[0]); fail("IllegalArgumentException expected for empty input"); } catch(IllegalArgumentException iae) { /* expected */ } try { IEEE754rUtils.min( (double[]) null); fail("IllegalArgumentException expected for null input"); } catch(IllegalArgumentException iae) { /* expected */ } try { IEEE754rUtils.min(new double[0]); fail("IllegalArgumentException expected for empty input"); } catch(IllegalArgumentException iae) { /* expected */ } try { IEEE754rUtils.max( (double[]) null); fail("IllegalArgumentException expected for null input"); } catch(IllegalArgumentException iae) { /* expected */ } try { IEEE754rUtils.max(new double[0]); fail("IllegalArgumentException expected for empty input"); } catch(IllegalArgumentException iae) { /* expected */ } } public void testConstructorExists() { new IEEE754rUtils(); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/math/IntRangeTest.java100644 0 0 14172 11513702435 25153 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "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 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.commons.lang.math; import java.util.Arrays; /** * Test cases for the {@link IntRange} class. * * @author Apache Software Foundation * @author Janek Bogucki * @author Phil Steitz * @version $Id: IntRangeTest.java 905636 2010-02-02 14:03:32Z niallp $ */ public final class IntRangeTest extends AbstractRangeTest { public IntRangeTest(String name) { super(name); } public void setUp() { super.setUp(); tenToTwenty = new IntRange(ten, twenty); otherRange = new NumberRange(ten, twenty); } protected Range createRange(Integer integer1, Integer integer2) { return new IntRange(integer1, integer2); } protected Range createRange(Integer integer) { return new NumberRange(integer); } //-------------------------------------------------------------------------- public void testConstructor1a() { IntRange nr = new IntRange(5); assertEquals(five, nr.getMinimumNumber()); assertEquals(five, nr.getMaximumNumber()); } public void testConstructor1b() { IntRange nr = new IntRange(five); assertSame(five, nr.getMinimumNumber()); assertSame(five, nr.getMaximumNumber()); Range r = new IntRange(nonComparableNumber); try { new IntRange(null); fail(); } catch (IllegalArgumentException ex) {} } public void testConstructor2a() { IntRange nr = new IntRange(5, 10); assertEquals(five, nr.getMinimumNumber()); assertEquals(ten, nr.getMaximumNumber()); nr = new IntRange(5, 10); assertEquals(five, nr.getMinimumNumber()); assertEquals(ten, nr.getMaximumNumber()); } public void testConstructor2b() { IntRange nr = new IntRange(five, ten); assertSame(five, nr.getMinimumNumber()); assertSame(ten, nr.getMaximumNumber()); nr = new IntRange(ten, five); assertSame(five, nr.getMinimumNumber()); assertSame(ten, nr.getMaximumNumber()); nr = new IntRange(five, long10); assertSame(five, nr.getMinimumNumber()); assertEquals(ten, nr.getMaximumNumber()); // test non Integer, for full coverage Long fiveL = new Long(5L); Long tenL = new Long(10L); nr = new IntRange(fiveL, tenL); assertEquals(five, nr.getMinimumNumber()); assertEquals(ten, nr.getMaximumNumber()); nr = new IntRange(tenL, fiveL); assertEquals(five, nr.getMinimumNumber()); assertEquals(ten, nr.getMaximumNumber()); // not null try { new IntRange(five, null); fail(); } catch (IllegalArgumentException ex) {} try { new IntRange(null, five); fail(); } catch (IllegalArgumentException ex) {} try { new IntRange(null, null); fail(); } catch (IllegalArgumentException ex) {} } //-------------------------------------------------------------------------- public void testContainsNumber() { assertEquals(false, tenToTwenty.containsNumber(null)); assertEquals(true, tenToTwenty.containsNumber(nonComparableNumber)); assertEquals(false, tenToTwenty.containsNumber(five)); assertEquals(true, tenToTwenty.containsNumber(ten)); assertEquals(true, tenToTwenty.containsNumber(fifteen)); assertEquals(true, tenToTwenty.containsNumber(twenty)); assertEquals(false, tenToTwenty.containsNumber(twentyFive)); assertEquals(false, tenToTwenty.containsNumber(long8)); assertEquals(true, tenToTwenty.containsNumber(long10)); assertEquals(true, tenToTwenty.containsNumber(long12)); assertEquals(true, tenToTwenty.containsNumber(long20)); assertEquals(false, tenToTwenty.containsNumber(long21)); assertEquals(false, tenToTwenty.containsNumber(double8)); assertEquals(true, tenToTwenty.containsNumber(double10)); assertEquals(true, tenToTwenty.containsNumber(double12)); assertEquals(true, tenToTwenty.containsNumber(double20)); assertEquals(false, tenToTwenty.containsNumber(double21)); assertEquals(false, tenToTwenty.containsNumber(float8)); assertEquals(true, tenToTwenty.containsNumber(float10)); assertEquals(true, tenToTwenty.containsNumber(float12)); assertEquals(true, tenToTwenty.containsNumber(float20)); assertEquals(false, tenToTwenty.containsNumber(float21)); } public void testContainsIntegerBig() { IntRange big = new IntRange(Integer.MAX_VALUE, Integer.MAX_VALUE- 2); assertEquals(true, big.containsInteger(Integer.MAX_VALUE - 1)); assertEquals(false, big.containsInteger(Integer.MAX_VALUE - 3)); } public void testToArray() { int[] threeItems = new IntRange(3, 5).toArray(); assertTrue(Arrays.equals(new int[]{3, 4, 5}, threeItems)); int[] oneItem = new IntRange(4).toArray(); assertTrue(Arrays.equals(new int[]{4}, oneItem)); } //-------------------------------------------------------------------------- } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/math/LongRangeTest.java100644 0 0 13333 11513702435 25316 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "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 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.commons.lang.math; import java.util.Arrays; /** * Test cases for the {@link LongRange} class. * * @author Apache Software Foundation * @version $Id: LongRangeTest.java 905636 2010-02-02 14:03:32Z niallp $ */ public final class LongRangeTest extends AbstractRangeTest { public LongRangeTest(String name) { super(name); } public void setUp() { super.setUp(); tenToTwenty = new LongRange(long10, long20); otherRange = new NumberRange(ten, twenty); } protected Range createRange(Integer integer1, Integer integer2) { return new LongRange(integer1, integer2); } protected Range createRange(Integer integer) { return new NumberRange(integer); } //-------------------------------------------------------------------------- public void testConstructor1a() { LongRange nr = new LongRange(8L); assertEquals(long8, nr.getMinimumNumber()); assertEquals(long8, nr.getMaximumNumber()); } public void testConstructor1b() { LongRange nr = new LongRange(long8); assertSame(long8, nr.getMinimumNumber()); assertSame(long8, nr.getMaximumNumber()); Range r = new LongRange(nonComparableNumber); try { new LongRange(null); fail(); } catch (IllegalArgumentException ex) {} } public void testConstructor2a() { LongRange nr = new LongRange(8L, 10L); assertEquals(long8, nr.getMinimumNumber()); assertEquals(long10, nr.getMaximumNumber()); nr = new LongRange(10L, 8L); assertEquals(long8, nr.getMinimumNumber()); assertEquals(long10, nr.getMaximumNumber()); } public void testConstructor2b() { LongRange nr = new LongRange(long8, long10); assertSame(long8, nr.getMinimumNumber()); assertSame(long10, nr.getMaximumNumber()); nr = new LongRange(long10, long8); assertSame(long8, nr.getMinimumNumber()); assertSame(long10, nr.getMaximumNumber()); nr = new LongRange(long8, long10); assertSame(long8, nr.getMinimumNumber()); assertEquals(long10, nr.getMaximumNumber()); // not null try { new LongRange(long8, null); fail(); } catch (IllegalArgumentException ex) {} try { new LongRange(null, long8); fail(); } catch (IllegalArgumentException ex) {} try { new LongRange(null, null); fail(); } catch (IllegalArgumentException ex) {} } //-------------------------------------------------------------------------- public void testContainsNumber() { assertEquals(false, tenToTwenty.containsNumber(null)); assertEquals(true, tenToTwenty.containsNumber(nonComparableNumber)); assertEquals(false, tenToTwenty.containsNumber(five)); assertEquals(true, tenToTwenty.containsNumber(ten)); assertEquals(true, tenToTwenty.containsNumber(fifteen)); assertEquals(true, tenToTwenty.containsNumber(twenty)); assertEquals(false, tenToTwenty.containsNumber(twentyFive)); assertEquals(false, tenToTwenty.containsNumber(long8)); assertEquals(true, tenToTwenty.containsNumber(long10)); assertEquals(true, tenToTwenty.containsNumber(long12)); assertEquals(true, tenToTwenty.containsNumber(long20)); assertEquals(false, tenToTwenty.containsNumber(long21)); assertEquals(false, tenToTwenty.containsNumber(double8)); assertEquals(true, tenToTwenty.containsNumber(double10)); assertEquals(true, tenToTwenty.containsNumber(double12)); assertEquals(true, tenToTwenty.containsNumber(double20)); assertEquals(false, tenToTwenty.containsNumber(double21)); assertEquals(false, tenToTwenty.containsNumber(float8)); assertEquals(true, tenToTwenty.containsNumber(float10)); assertEquals(true, tenToTwenty.containsNumber(float12)); assertEquals(true, tenToTwenty.containsNumber(float20)); assertEquals(false, tenToTwenty.containsNumber(float21)); } public void testContainsLongBig() { LongRange big = new LongRange(Long.MAX_VALUE, Long.MAX_VALUE- 2); assertEquals(true, big.containsLong(Long.MAX_VALUE - 1)); assertEquals(false, big.containsLong(Long.MAX_VALUE - 3)); } public void testToArray() { long[] threeItems = new LongRange(3, 5).toArray(); assertTrue(Arrays.equals(new long[]{3, 4, 5}, threeItems)); long[] oneItem = new LongRange(4).toArray(); assertTrue(Arrays.equals(new long[]{4}, oneItem)); } //-------------------------------------------------------------------------- } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/math/NumberRangeTest.java100644 0 0 14101 11513702435 25641 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "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 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.commons.lang.math; /** * Test cases for the {@link NumberRange} class. * * @author Apache Software Foundation * @author Christopher Elkins * @author Ringo De Smet * @version $Id: NumberRangeTest.java 905636 2010-02-02 14:03:32Z niallp $ */ public final class NumberRangeTest extends AbstractRangeTest { public NumberRangeTest(String name) { super(name); } void checkConstructorException(Number num) { try { new NumberRange(num); fail("Expected an IllegalArgumentException"); } catch (IllegalArgumentException e) { // Expected. } } void checkConstructorException(Number num1, Number num2) { try { new NumberRange(num1, num2); fail("Expected an IllegalArgumentException"); } catch (IllegalArgumentException e) { // Expected. } } protected Range createRange(Integer integer) { return new NumberRange(integer); } // -------------------------------------------------------------------------- protected Range createRange(Integer integer1, Integer integer2) { return new NumberRange(integer1, integer2); } public void setUp() { super.setUp(); tenToTwenty = new NumberRange(ten, twenty); otherRange = new IntRange(ten, twenty); } /** * Tests non-exceptional conditions for the one argument constructor. */ public void testConstructor1() { NumberRange nr = new NumberRange(five); assertSame(five, nr.getMinimumNumber()); assertSame(five, nr.getMaximumNumber()); } /** * Tests exceptional conditions for the one argument constructor. */ public void testConstructor1Exceptions() { this.checkConstructorException(null); this.checkConstructorException(nonComparableNumber); this.checkConstructorException(new Float(Float.NaN)); this.checkConstructorException(new Double(Double.NaN)); } /** * Tests non-exceptional conditions for the two argument constructor. */ public void testConstructor2() { NumberRange nr = new NumberRange(five, ten); assertSame(five, nr.getMinimumNumber()); assertSame(ten, nr.getMaximumNumber()); nr = new NumberRange(ten, five); assertSame(five, nr.getMinimumNumber()); assertSame(ten, nr.getMaximumNumber()); } /** * Tests exceptional conditions for the two argument constructor. */ public void testConstructor2Exceptions() { this.checkConstructorException(null, null); this.checkConstructorException(new Float(12.2f), new Double(12.2)); this.checkConstructorException(new Float(Float.NaN), new Double(12.2)); this.checkConstructorException(new Double(Double.NaN), new Double(12.2)); this.checkConstructorException(new Double(12.2), new Double(Double.NaN)); this.checkConstructorException(new Double(Double.NaN), new Double(Double.NaN)); this.checkConstructorException(null, new Double(12.2)); this.checkConstructorException(new Double(12.2), null); this.checkConstructorException(new Double(12.2f), new Float(12.2)); this.checkConstructorException(new Double(Double.NaN), new Float(12.2)); this.checkConstructorException(new Float(Float.NaN), new Float(12.2)); this.checkConstructorException(new Float(12.2), new Float(Float.NaN)); this.checkConstructorException(new Float(Float.NaN), new Float(Float.NaN)); this.checkConstructorException(null, new Float(12.2)); this.checkConstructorException(new Float(12.2), null); this.checkConstructorException(nonComparableNumber, nonComparableNumber); this.checkConstructorException(null, nonComparableNumber); this.checkConstructorException(nonComparableNumber, null); this.checkConstructorException(new Float(12.2), nonComparableNumber); this.checkConstructorException(nonComparableNumber, new Float(12.2)); } // -------------------------------------------------------------------------- public void testContainsLongBig() { // original NumberRange class failed this test NumberRange big = new NumberRange(new Long(Long.MAX_VALUE), new Long(Long.MAX_VALUE - 2)); assertEquals(true, big.containsLong(Long.MAX_VALUE - 1)); assertEquals(false, big.containsLong(Long.MAX_VALUE - 3)); } public void testContainsNumber() { assertEquals(false, tenToTwenty.containsNumber(null)); assertEquals(false, tenToTwenty.containsNumber(five)); assertEquals(true, tenToTwenty.containsNumber(ten)); assertEquals(true, tenToTwenty.containsNumber(fifteen)); assertEquals(true, tenToTwenty.containsNumber(twenty)); assertEquals(false, tenToTwenty.containsNumber(twentyFive)); try { tenToTwenty.containsNumber(long21); fail(); } catch (IllegalArgumentException ex) { } } // -------------------------------------------------------------------------- } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/math/NumberUtilsTest.java100644 0 0 170465 11513702435 25745 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.math; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.math.BigDecimal; import java.math.BigInteger; import junit.framework.TestCase; import org.apache.commons.lang.SystemUtils; /** * Unit tests {@link org.apache.commons.lang.math.NumberUtils}. * * @author Apache Software Foundation * @author Rand McNeely * @author Ringo De Smet * @author Eric Pugh * @author Phil Steitz * @author Matthew Hawthorne * @author Gary Gregory * @version $Id: NumberUtilsTest.java 1056853 2011-01-09 01:07:04Z niallp $ */ public class NumberUtilsTest extends TestCase { public NumberUtilsTest(String name) { super(name); } //----------------------------------------------------------------------- public void testConstructor() { assertNotNull(new NumberUtils()); Constructor[] cons = NumberUtils.class.getDeclaredConstructors(); assertEquals(1, cons.length); assertEquals(true, Modifier.isPublic(cons[0].getModifiers())); assertEquals(true, Modifier.isPublic(NumberUtils.class.getModifiers())); assertEquals(false, Modifier.isFinal(NumberUtils.class.getModifiers())); } //--------------------------------------------------------------------- /** * Test for {@link NumberUtils#stringToInt(String)}. */ public void testDeprecatedStringToIntString() { assertTrue("stringToInt(String) 1 failed", NumberUtils.stringToInt("12345") == 12345); assertTrue("stringToInt(String) 2 failed", NumberUtils.stringToInt("abc") == 0); assertTrue("stringToInt(empty) failed", NumberUtils.stringToInt("") == 0); assertTrue("stringToInt(null) failed", NumberUtils.stringToInt(null) == 0); } /** * Test for {@link NumberUtils#toInt(String)}. */ public void testToIntString() { assertTrue("toInt(String) 1 failed", NumberUtils.toInt("12345") == 12345); assertTrue("toInt(String) 2 failed", NumberUtils.toInt("abc") == 0); assertTrue("toInt(empty) failed", NumberUtils.toInt("") == 0); assertTrue("toInt(null) failed", NumberUtils.toInt(null) == 0); } /** * Test for {@link NumberUtils#stringToInt(String, int)}. */ public void testDeprecatedStringToIntStringI() { assertTrue("stringToInt(String,int) 1 failed", NumberUtils.stringToInt("12345", 5) == 12345); assertTrue("stringToInt(String,int) 2 failed", NumberUtils.stringToInt("1234.5", 5) == 5); } /** * Test for {@link NumberUtils#toInt(String, int)}. */ public void testToIntStringI() { assertTrue("toInt(String,int) 1 failed", NumberUtils.toInt("12345", 5) == 12345); assertTrue("toInt(String,int) 2 failed", NumberUtils.toInt("1234.5", 5) == 5); } /** * Test for {@link NumberUtils#toLong(String)}. */ public void testToLongString() { assertTrue("toLong(String) 1 failed", NumberUtils.toLong("12345") == 12345l); assertTrue("toLong(String) 2 failed", NumberUtils.toLong("abc") == 0l); assertTrue("toLong(String) 3 failed", NumberUtils.toLong("1L") == 0l); assertTrue("toLong(String) 4 failed", NumberUtils.toLong("1l") == 0l); assertTrue("toLong(Long.MAX_VALUE) failed", NumberUtils.toLong(Long.MAX_VALUE+"") == Long.MAX_VALUE); assertTrue("toLong(Long.MIN_VALUE) failed", NumberUtils.toLong(Long.MIN_VALUE+"") == Long.MIN_VALUE); assertTrue("toLong(empty) failed", NumberUtils.toLong("") == 0l); assertTrue("toLong(null) failed", NumberUtils.toLong(null) == 0l); } /** * Test for {@link NumberUtils#toLong(String, long)}. */ public void testToLongStringL() { assertTrue("toLong(String,long) 1 failed", NumberUtils.toLong("12345", 5l) == 12345l); assertTrue("toLong(String,long) 2 failed", NumberUtils.toLong("1234.5", 5l) == 5l); } /** * Test for {@link NumberUtils#toFloat(String)}. */ public void testToFloatString() { assertTrue("toFloat(String) 1 failed", NumberUtils.toFloat("-1.2345") == -1.2345f); assertTrue("toFloat(String) 2 failed", NumberUtils.toFloat("1.2345") == 1.2345f); assertTrue("toFloat(String) 3 failed", NumberUtils.toFloat("abc") == 0.0f); assertTrue("toFloat(Float.MAX_VALUE) failed", NumberUtils.toFloat(Float.MAX_VALUE+"") == Float.MAX_VALUE); assertTrue("toFloat(Float.MIN_VALUE) failed", NumberUtils.toFloat(Float.MIN_VALUE+"") == Float.MIN_VALUE); assertTrue("toFloat(empty) failed", NumberUtils.toFloat("") == 0.0f); assertTrue("toFloat(null) failed", NumberUtils.toFloat(null) == 0.0f); } /** * Test for {@link NumberUtils#toFloat(String, float)}. */ public void testToFloatStringF() { assertTrue("toFloat(String,int) 1 failed", NumberUtils.toFloat("1.2345", 5.1f) == 1.2345f); assertTrue("toFloat(String,int) 2 failed", NumberUtils.toFloat("a", 5.0f) == 5.0f); } /** * Test for {@link NumberUtils#toDouble(String)}. */ public void testStringToDoubleString() { assertTrue("toDouble(String) 1 failed", NumberUtils.toDouble("-1.2345") == -1.2345d); assertTrue("toDouble(String) 2 failed", NumberUtils.toDouble("1.2345") == 1.2345d); assertTrue("toDouble(String) 3 failed", NumberUtils.toDouble("abc") == 0.0d); assertTrue("toDouble(Double.MAX_VALUE) failed", NumberUtils.toDouble(Double.MAX_VALUE+"") == Double.MAX_VALUE); assertTrue("toDouble(Double.MIN_VALUE) failed", NumberUtils.toDouble(Double.MIN_VALUE+"") == Double.MIN_VALUE); assertTrue("toDouble(empty) failed", NumberUtils.toDouble("") == 0.0d); assertTrue("toDouble(null) failed", NumberUtils.toDouble(null) == 0.0d); } /** * Test for {@link NumberUtils#toDouble(String, double)}. */ public void testStringToDoubleStringD() { assertTrue("toDouble(String,int) 1 failed", NumberUtils.toDouble("1.2345", 5.1d) == 1.2345d); assertTrue("toDouble(String,int) 2 failed", NumberUtils.toDouble("a", 5.0d) == 5.0d); } /** * Test for {@link NumberUtils#toByte(String)}. */ public void testToByteString() { assertTrue("toByte(String) 1 failed", NumberUtils.toByte("123") == 123); assertTrue("toByte(String) 2 failed", NumberUtils.toByte("abc") == 0); assertTrue("toByte(empty) failed", NumberUtils.toByte("") == 0); assertTrue("toByte(null) failed", NumberUtils.toByte(null) == 0); } /** * Test for {@link NumberUtils#toByte(String, byte)}. */ public void testToByteStringI() { assertTrue("toByte(String,byte) 1 failed", NumberUtils.toByte("123", (byte) 5) == 123); assertTrue("toByte(String,byte) 2 failed", NumberUtils.toByte("12.3", (byte) 5) == 5); } /** * Test for {@link NumberUtils#toShort(String)}. */ public void testToShortString() { assertTrue("toShort(String) 1 failed", NumberUtils.toShort("12345") == 12345); assertTrue("toShort(String) 2 failed", NumberUtils.toShort("abc") == 0); assertTrue("toShort(empty) failed", NumberUtils.toShort("") == 0); assertTrue("toShort(null) failed", NumberUtils.toShort(null) == 0); } /** * Test for {@link NumberUtils#toShort(String, short)}. */ public void testToShortStringI() { assertTrue("toShort(String,short) 1 failed", NumberUtils.toShort("12345", (short) 5) == 12345); assertTrue("toShort(String,short) 2 failed", NumberUtils.toShort("1234.5", (short) 5) == 5); } public void testCreateNumber() { // a lot of things can go wrong assertEquals("createNumber(String) 1 failed", new Float("1234.5"), NumberUtils.createNumber("1234.5")); assertEquals("createNumber(String) 2 failed", new Integer("12345"), NumberUtils.createNumber("12345")); assertEquals("createNumber(String) 3 failed", new Double("1234.5"), NumberUtils.createNumber("1234.5D")); assertEquals("createNumber(String) 3 failed", new Double("1234.5"), NumberUtils.createNumber("1234.5d")); assertEquals("createNumber(String) 4 failed", new Float("1234.5"), NumberUtils.createNumber("1234.5F")); assertEquals("createNumber(String) 4 failed", new Float("1234.5"), NumberUtils.createNumber("1234.5f")); assertEquals("createNumber(String) 5 failed", new Long(Integer.MAX_VALUE + 1L), NumberUtils.createNumber("" + (Integer.MAX_VALUE + 1L))); assertEquals("createNumber(String) 6 failed", new Long(12345), NumberUtils.createNumber("12345L")); assertEquals("createNumber(String) 6 failed", new Long(12345), NumberUtils.createNumber("12345l")); assertEquals("createNumber(String) 7 failed", new Float("-1234.5"), NumberUtils.createNumber("-1234.5")); assertEquals("createNumber(String) 8 failed", new Integer("-12345"), NumberUtils.createNumber("-12345")); assertTrue("createNumber(String) 9 failed", 0xFADE == NumberUtils.createNumber("0xFADE").intValue()); assertTrue("createNumber(String) 10 failed", -0xFADE == NumberUtils.createNumber("-0xFADE").intValue()); assertEquals("createNumber(String) 11 failed", new Double("1.1E200"), NumberUtils.createNumber("1.1E200")); assertEquals("createNumber(String) 12 failed", new Float("1.1E20"), NumberUtils.createNumber("1.1E20")); assertEquals("createNumber(String) 13 failed", new Double("-1.1E200"), NumberUtils.createNumber("-1.1E200")); assertEquals("createNumber(String) 14 failed", new Double("1.1E-200"), NumberUtils.createNumber("1.1E-200")); assertEquals("createNumber(null) failed", null, NumberUtils.createNumber(null)); assertEquals("createNumber(String) failed", new BigInteger("12345678901234567890"), NumberUtils .createNumber("12345678901234567890L")); // jdk 1.2 doesn't support this. unsure about jdk 1.2.2 if (SystemUtils.isJavaVersionAtLeast(1.3f)) { assertEquals("createNumber(String) 15 failed", new BigDecimal("1.1E-700"), NumberUtils .createNumber("1.1E-700F")); } assertEquals("createNumber(String) 16 failed", new Long("10" + Integer.MAX_VALUE), NumberUtils .createNumber("10" + Integer.MAX_VALUE + "L")); assertEquals("createNumber(String) 17 failed", new Long("10" + Integer.MAX_VALUE), NumberUtils .createNumber("10" + Integer.MAX_VALUE)); assertEquals("createNumber(String) 18 failed", new BigInteger("10" + Long.MAX_VALUE), NumberUtils .createNumber("10" + Long.MAX_VALUE)); // LANG-521 assertEquals("createNumber(String) LANG-521 failed", new Float("2."), NumberUtils.createNumber("2.")); // LANG-638 assertFalse("createNumber(String) succeeded", checkCreateNumber("1eE")); } public void testCreateFloat() { assertEquals("createFloat(String) failed", new Float("1234.5"), NumberUtils.createFloat("1234.5")); assertEquals("createFloat(null) failed", null, NumberUtils.createFloat(null)); this.testCreateFloatFailure(""); this.testCreateFloatFailure(" "); this.testCreateFloatFailure("\b\t\n\f\r"); // Funky whitespaces this.testCreateFloatFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F"); } protected void testCreateFloatFailure(String str) { try { Float value = NumberUtils.createFloat(str); fail("createFloat(blank) failed: " + value); } catch (NumberFormatException ex) { // empty } } public void testCreateDouble() { assertEquals("createDouble(String) failed", new Double("1234.5"), NumberUtils.createDouble("1234.5")); assertEquals("createDouble(null) failed", null, NumberUtils.createDouble(null)); this.testCreateDoubleFailure(""); this.testCreateDoubleFailure(" "); this.testCreateDoubleFailure("\b\t\n\f\r"); // Funky whitespaces this.testCreateDoubleFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F"); } protected void testCreateDoubleFailure(String str) { try { Double value = NumberUtils.createDouble(str); fail("createDouble(blank) failed: " + value); } catch (NumberFormatException ex) { // empty } } public void testCreateInteger() { assertEquals("createInteger(String) failed", new Integer("12345"), NumberUtils.createInteger("12345")); assertEquals("createInteger(null) failed", null, NumberUtils.createInteger(null)); this.testCreateIntegerFailure(""); this.testCreateIntegerFailure(" "); this.testCreateIntegerFailure("\b\t\n\f\r"); // Funky whitespaces this.testCreateIntegerFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F"); } protected void testCreateIntegerFailure(String str) { try { Integer value = NumberUtils.createInteger(str); fail("createInteger(blank) failed: " + value); } catch (NumberFormatException ex) { // empty } } public void testCreateLong() { assertEquals("createLong(String) failed", new Long("12345"), NumberUtils.createLong("12345")); assertEquals("createLong(null) failed", null, NumberUtils.createLong(null)); this.testCreateLongFailure(""); this.testCreateLongFailure(" "); this.testCreateLongFailure("\b\t\n\f\r"); // Funky whitespaces this.testCreateLongFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F"); } protected void testCreateLongFailure(String str) { try { Long value = NumberUtils.createLong(str); fail("createLong(blank) failed: " + value); } catch (NumberFormatException ex) { // empty } } public void testCreateBigInteger() { assertEquals("createBigInteger(String) failed", new BigInteger("12345"), NumberUtils.createBigInteger("12345")); assertEquals("createBigInteger(null) failed", null, NumberUtils.createBigInteger(null)); this.testCreateBigIntegerFailure(""); this.testCreateBigIntegerFailure(" "); this.testCreateBigIntegerFailure("\b\t\n\f\r"); // Funky whitespaces this.testCreateBigIntegerFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F"); } protected void testCreateBigIntegerFailure(String str) { try { BigInteger value = NumberUtils.createBigInteger(str); fail("createBigInteger(blank) failed: " + value); } catch (NumberFormatException ex) { // empty } } public void testCreateBigDecimal() { assertEquals("createBigDecimal(String) failed", new BigDecimal("1234.5"), NumberUtils.createBigDecimal("1234.5")); assertEquals("createBigDecimal(null) failed", null, NumberUtils.createBigDecimal(null)); this.testCreateBigDecimalFailure(""); this.testCreateBigDecimalFailure(" "); this.testCreateBigDecimalFailure("\b\t\n\f\r"); // Funky whitespaces this.testCreateBigDecimalFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F"); } protected void testCreateBigDecimalFailure(String str) { try { BigDecimal value = NumberUtils.createBigDecimal(str); fail("createBigDecimal(blank) failed: " + value); } catch (NumberFormatException ex) { // empty } } // min/max tests // ---------------------------------------------------------------------- public void testMinLong() { final long[] l = null; try { NumberUtils.min(l); fail("No exception was thrown for null input."); } catch (IllegalArgumentException ex) {} try { NumberUtils.min(new long[0]); fail("No exception was thrown for empty input."); } catch (IllegalArgumentException ex) {} assertEquals( "min(long[]) failed for array length 1", 5, NumberUtils.min(new long[] { 5 })); assertEquals( "min(long[]) failed for array length 2", 6, NumberUtils.min(new long[] { 6, 9 })); assertEquals(-10, NumberUtils.min(new long[] { -10, -5, 0, 5, 10 })); assertEquals(-10, NumberUtils.min(new long[] { -5, 0, -10, 5, 10 })); } public void testMinInt() { final int[] i = null; try { NumberUtils.min(i); fail("No exception was thrown for null input."); } catch (IllegalArgumentException ex) {} try { NumberUtils.min(new int[0]); fail("No exception was thrown for empty input."); } catch (IllegalArgumentException ex) {} assertEquals( "min(int[]) failed for array length 1", 5, NumberUtils.min(new int[] { 5 })); assertEquals( "min(int[]) failed for array length 2", 6, NumberUtils.min(new int[] { 6, 9 })); assertEquals(-10, NumberUtils.min(new int[] { -10, -5, 0, 5, 10 })); assertEquals(-10, NumberUtils.min(new int[] { -5, 0, -10, 5, 10 })); } public void testMinShort() { final short[] s = null; try { NumberUtils.min(s); fail("No exception was thrown for null input."); } catch (IllegalArgumentException ex) {} try { NumberUtils.min(new short[0]); fail("No exception was thrown for empty input."); } catch (IllegalArgumentException ex) {} assertEquals( "min(short[]) failed for array length 1", 5, NumberUtils.min(new short[] { 5 })); assertEquals( "min(short[]) failed for array length 2", 6, NumberUtils.min(new short[] { 6, 9 })); assertEquals(-10, NumberUtils.min(new short[] { -10, -5, 0, 5, 10 })); assertEquals(-10, NumberUtils.min(new short[] { -5, 0, -10, 5, 10 })); } public void testMinByte() { final byte[] b = null; try { NumberUtils.min(b); fail("No exception was thrown for null input."); } catch (IllegalArgumentException ex) {} try { NumberUtils.min(new byte[0]); fail("No exception was thrown for empty input."); } catch (IllegalArgumentException ex) {} assertEquals( "min(byte[]) failed for array length 1", 5, NumberUtils.min(new byte[] { 5 })); assertEquals( "min(byte[]) failed for array length 2", 6, NumberUtils.min(new byte[] { 6, 9 })); assertEquals(-10, NumberUtils.min(new byte[] { -10, -5, 0, 5, 10 })); assertEquals(-10, NumberUtils.min(new byte[] { -5, 0, -10, 5, 10 })); } public void testMinDouble() { final double[] d = null; try { NumberUtils.min(d); fail("No exception was thrown for null input."); } catch (IllegalArgumentException ex) {} try { NumberUtils.min(new double[0]); fail("No exception was thrown for empty input."); } catch (IllegalArgumentException ex) {} assertEquals( "min(double[]) failed for array length 1", 5.12, NumberUtils.min(new double[] { 5.12 }), 0); assertEquals( "min(double[]) failed for array length 2", 6.23, NumberUtils.min(new double[] { 6.23, 9.34 }), 0); assertEquals( "min(double[]) failed for array length 5", -10.45, NumberUtils.min(new double[] { -10.45, -5.56, 0, 5.67, 10.78 }), 0); assertEquals(-10, NumberUtils.min(new double[] { -10, -5, 0, 5, 10 }), 0.0001); assertEquals(-10, NumberUtils.min(new double[] { -5, 0, -10, 5, 10 }), 0.0001); } public void testMinFloat() { final float[] f = null; try { NumberUtils.min(f); fail("No exception was thrown for null input."); } catch (IllegalArgumentException ex) {} try { NumberUtils.min(new float[0]); fail("No exception was thrown for empty input."); } catch (IllegalArgumentException ex) {} assertEquals( "min(float[]) failed for array length 1", 5.9f, NumberUtils.min(new float[] { 5.9f }), 0); assertEquals( "min(float[]) failed for array length 2", 6.8f, NumberUtils.min(new float[] { 6.8f, 9.7f }), 0); assertEquals( "min(float[]) failed for array length 5", -10.6f, NumberUtils.min(new float[] { -10.6f, -5.5f, 0, 5.4f, 10.3f }), 0); assertEquals(-10, NumberUtils.min(new float[] { -10, -5, 0, 5, 10 }), 0.0001f); assertEquals(-10, NumberUtils.min(new float[] { -5, 0, -10, 5, 10 }), 0.0001f); } public void testMaxLong() { final long[] l = null; try { NumberUtils.max(l); fail("No exception was thrown for null input."); } catch (IllegalArgumentException ex) {} try { NumberUtils.max(new long[0]); fail("No exception was thrown for empty input."); } catch (IllegalArgumentException ex) {} assertEquals( "max(long[]) failed for array length 1", 5, NumberUtils.max(new long[] { 5 })); assertEquals( "max(long[]) failed for array length 2", 9, NumberUtils.max(new long[] { 6, 9 })); assertEquals( "max(long[]) failed for array length 5", 10, NumberUtils.max(new long[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new long[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new long[] { -5, 0, 10, 5, -10 })); } public void testMaxInt() { final int[] i = null; try { NumberUtils.max(i); fail("No exception was thrown for null input."); } catch (IllegalArgumentException ex) {} try { NumberUtils.max(new int[0]); fail("No exception was thrown for empty input."); } catch (IllegalArgumentException ex) {} assertEquals( "max(int[]) failed for array length 1", 5, NumberUtils.max(new int[] { 5 })); assertEquals( "max(int[]) failed for array length 2", 9, NumberUtils.max(new int[] { 6, 9 })); assertEquals( "max(int[]) failed for array length 5", 10, NumberUtils.max(new int[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new int[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new int[] { -5, 0, 10, 5, -10 })); } public void testMaxShort() { final short[] s = null; try { NumberUtils.max(s); fail("No exception was thrown for null input."); } catch (IllegalArgumentException ex) {} try { NumberUtils.max(new short[0]); fail("No exception was thrown for empty input."); } catch (IllegalArgumentException ex) {} assertEquals( "max(short[]) failed for array length 1", 5, NumberUtils.max(new short[] { 5 })); assertEquals( "max(short[]) failed for array length 2", 9, NumberUtils.max(new short[] { 6, 9 })); assertEquals( "max(short[]) failed for array length 5", 10, NumberUtils.max(new short[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new short[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new short[] { -5, 0, 10, 5, -10 })); } public void testMaxByte() { final byte[] b = null; try { NumberUtils.max(b); fail("No exception was thrown for null input."); } catch (IllegalArgumentException ex) {} try { NumberUtils.max(new byte[0]); fail("No exception was thrown for empty input."); } catch (IllegalArgumentException ex) {} assertEquals( "max(byte[]) failed for array length 1", 5, NumberUtils.max(new byte[] { 5 })); assertEquals( "max(byte[]) failed for array length 2", 9, NumberUtils.max(new byte[] { 6, 9 })); assertEquals( "max(byte[]) failed for array length 5", 10, NumberUtils.max(new byte[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new byte[] { -10, -5, 0, 5, 10 })); assertEquals(10, NumberUtils.max(new byte[] { -5, 0, 10, 5, -10 })); } public void testMaxDouble() { final double[] d = null; try { NumberUtils.max(d); fail("No exception was thrown for null input."); } catch (IllegalArgumentException ex) {} try { NumberUtils.max(new double[0]); fail("No exception was thrown for empty input."); } catch (IllegalArgumentException ex) {} assertEquals( "max(double[]) failed for array length 1", 5.1f, NumberUtils.max(new double[] { 5.1f }), 0); assertEquals( "max(double[]) failed for array length 2", 9.2f, NumberUtils.max(new double[] { 6.3f, 9.2f }), 0); assertEquals( "max(double[]) failed for float length 5", 10.4f, NumberUtils.max(new double[] { -10.5f, -5.6f, 0, 5.7f, 10.4f }), 0); assertEquals(10, NumberUtils.max(new double[] { -10, -5, 0, 5, 10 }), 0.0001); assertEquals(10, NumberUtils.max(new double[] { -5, 0, 10, 5, -10 }), 0.0001); } public void testMaxFloat() { final float[] f = null; try { NumberUtils.max(f); fail("No exception was thrown for null input."); } catch (IllegalArgumentException ex) {} try { NumberUtils.max(new float[0]); fail("No exception was thrown for empty input."); } catch (IllegalArgumentException ex) {} assertEquals( "max(float[]) failed for array length 1", 5.1f, NumberUtils.max(new float[] { 5.1f }), 0); assertEquals( "max(float[]) failed for array length 2", 9.2f, NumberUtils.max(new float[] { 6.3f, 9.2f }), 0); assertEquals( "max(float[]) failed for float length 5", 10.4f, NumberUtils.max(new float[] { -10.5f, -5.6f, 0, 5.7f, 10.4f }), 0); assertEquals(10, NumberUtils.max(new float[] { -10, -5, 0, 5, 10 }), 0.0001f); assertEquals(10, NumberUtils.max(new float[] { -5, 0, 10, 5, -10 }), 0.0001f); } public void testMinimumLong() { assertEquals("minimum(long,long,long) 1 failed", 12345L, NumberUtils.min(12345L, 12345L + 1L, 12345L + 2L)); assertEquals("minimum(long,long,long) 2 failed", 12345L, NumberUtils.min(12345L + 1L, 12345L, 12345 + 2L)); assertEquals("minimum(long,long,long) 3 failed", 12345L, NumberUtils.min(12345L + 1L, 12345L + 2L, 12345L)); assertEquals("minimum(long,long,long) 4 failed", 12345L, NumberUtils.min(12345L + 1L, 12345L, 12345L)); assertEquals("minimum(long,long,long) 5 failed", 12345L, NumberUtils.min(12345L, 12345L, 12345L)); } public void testMinimumInt() { assertEquals("minimum(int,int,int) 1 failed", 12345, NumberUtils.min(12345, 12345 + 1, 12345 + 2)); assertEquals("minimum(int,int,int) 2 failed", 12345, NumberUtils.min(12345 + 1, 12345, 12345 + 2)); assertEquals("minimum(int,int,int) 3 failed", 12345, NumberUtils.min(12345 + 1, 12345 + 2, 12345)); assertEquals("minimum(int,int,int) 4 failed", 12345, NumberUtils.min(12345 + 1, 12345, 12345)); assertEquals("minimum(int,int,int) 5 failed", 12345, NumberUtils.min(12345, 12345, 12345)); } public void testMinimumShort() { short low = 1234; short mid = 1234 + 1; short high = 1234 + 2; assertEquals("minimum(short,short,short) 1 failed", low, NumberUtils.min(low, mid, high)); assertEquals("minimum(short,short,short) 1 failed", low, NumberUtils.min(mid, low, high)); assertEquals("minimum(short,short,short) 1 failed", low, NumberUtils.min(mid, high, low)); assertEquals("minimum(short,short,short) 1 failed", low, NumberUtils.min(low, mid, low)); } public void testMinimumByte() { byte low = 123; byte mid = 123 + 1; byte high = 123 + 2; assertEquals("minimum(byte,byte,byte) 1 failed", low, NumberUtils.min(low, mid, high)); assertEquals("minimum(byte,byte,byte) 1 failed", low, NumberUtils.min(mid, low, high)); assertEquals("minimum(byte,byte,byte) 1 failed", low, NumberUtils.min(mid, high, low)); assertEquals("minimum(byte,byte,byte) 1 failed", low, NumberUtils.min(low, mid, low)); } public void testMinimumDouble() { double low = 12.3; double mid = 12.3 + 1; double high = 12.3 + 2; assertEquals(low, NumberUtils.min(low, mid, high), 0.0001); assertEquals(low, NumberUtils.min(mid, low, high), 0.0001); assertEquals(low, NumberUtils.min(mid, high, low), 0.0001); assertEquals(low, NumberUtils.min(low, mid, low), 0.0001); assertEquals(mid, NumberUtils.min(high, mid, high), 0.0001); } public void testMinimumFloat() { float low = 12.3f; float mid = 12.3f + 1; float high = 12.3f + 2; assertEquals(low, NumberUtils.min(low, mid, high), 0.0001f); assertEquals(low, NumberUtils.min(mid, low, high), 0.0001f); assertEquals(low, NumberUtils.min(mid, high, low), 0.0001f); assertEquals(low, NumberUtils.min(low, mid, low), 0.0001f); assertEquals(mid, NumberUtils.min(high, mid, high), 0.0001f); } public void testMaximumLong() { assertEquals("maximum(long,long,long) 1 failed", 12345L, NumberUtils.max(12345L, 12345L - 1L, 12345L - 2L)); assertEquals("maximum(long,long,long) 2 failed", 12345L, NumberUtils.max(12345L - 1L, 12345L, 12345L - 2L)); assertEquals("maximum(long,long,long) 3 failed", 12345L, NumberUtils.max(12345L - 1L, 12345L - 2L, 12345L)); assertEquals("maximum(long,long,long) 4 failed", 12345L, NumberUtils.max(12345L - 1L, 12345L, 12345L)); assertEquals("maximum(long,long,long) 5 failed", 12345L, NumberUtils.max(12345L, 12345L, 12345L)); } public void testMaximumInt() { assertEquals("maximum(int,int,int) 1 failed", 12345, NumberUtils.max(12345, 12345 - 1, 12345 - 2)); assertEquals("maximum(int,int,int) 2 failed", 12345, NumberUtils.max(12345 - 1, 12345, 12345 - 2)); assertEquals("maximum(int,int,int) 3 failed", 12345, NumberUtils.max(12345 - 1, 12345 - 2, 12345)); assertEquals("maximum(int,int,int) 4 failed", 12345, NumberUtils.max(12345 - 1, 12345, 12345)); assertEquals("maximum(int,int,int) 5 failed", 12345, NumberUtils.max(12345, 12345, 12345)); } public void testMaximumShort() { short low = 1234; short mid = 1234 + 1; short high = 1234 + 2; assertEquals("maximum(short,short,short) 1 failed", high, NumberUtils.max(low, mid, high)); assertEquals("maximum(short,short,short) 1 failed", high, NumberUtils.max(mid, low, high)); assertEquals("maximum(short,short,short) 1 failed", high, NumberUtils.max(mid, high, low)); assertEquals("maximum(short,short,short) 1 failed", high, NumberUtils.max(high, mid, high)); } public void testMaximumByte() { byte low = 123; byte mid = 123 + 1; byte high = 123 + 2; assertEquals("maximum(byte,byte,byte) 1 failed", high, NumberUtils.max(low, mid, high)); assertEquals("maximum(byte,byte,byte) 1 failed", high, NumberUtils.max(mid, low, high)); assertEquals("maximum(byte,byte,byte) 1 failed", high, NumberUtils.max(mid, high, low)); assertEquals("maximum(byte,byte,byte) 1 failed", high, NumberUtils.max(high, mid, high)); } public void testMaximumDouble() { double low = 12.3; double mid = 12.3 + 1; double high = 12.3 + 2; assertEquals(high, NumberUtils.max(low, mid, high), 0.0001); assertEquals(high, NumberUtils.max(mid, low, high), 0.0001); assertEquals(high, NumberUtils.max(mid, high, low), 0.0001); assertEquals(mid, NumberUtils.max(low, mid, low), 0.0001); assertEquals(high, NumberUtils.max(high, mid, high), 0.0001); } public void testMaximumFloat() { float low = 12.3f; float mid = 12.3f + 1; float high = 12.3f + 2; assertEquals(high, NumberUtils.max(low, mid, high), 0.0001f); assertEquals(high, NumberUtils.max(mid, low, high), 0.0001f); assertEquals(high, NumberUtils.max(mid, high, low), 0.0001f); assertEquals(mid, NumberUtils.max(low, mid, low), 0.0001f); assertEquals(high, NumberUtils.max(high, mid, high), 0.0001f); } public void testCompareDouble() { assertTrue(NumberUtils.compare(Double.NaN, Double.NaN) == 0); assertTrue(NumberUtils.compare(Double.NaN, Double.POSITIVE_INFINITY) == +1); assertTrue(NumberUtils.compare(Double.NaN, Double.MAX_VALUE) == +1); assertTrue(NumberUtils.compare(Double.NaN, 1.2d) == +1); assertTrue(NumberUtils.compare(Double.NaN, 0.0d) == +1); assertTrue(NumberUtils.compare(Double.NaN, -0.0d) == +1); assertTrue(NumberUtils.compare(Double.NaN, -1.2d) == +1); assertTrue(NumberUtils.compare(Double.NaN, -Double.MAX_VALUE) == +1); assertTrue(NumberUtils.compare(Double.NaN, Double.NEGATIVE_INFINITY) == +1); assertTrue(NumberUtils.compare(Double.POSITIVE_INFINITY, Double.NaN) == -1); assertTrue(NumberUtils.compare(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY) == 0); assertTrue(NumberUtils.compare(Double.POSITIVE_INFINITY, Double.MAX_VALUE) == +1); assertTrue(NumberUtils.compare(Double.POSITIVE_INFINITY, 1.2d) == +1); assertTrue(NumberUtils.compare(Double.POSITIVE_INFINITY, 0.0d) == +1); assertTrue(NumberUtils.compare(Double.POSITIVE_INFINITY, -0.0d) == +1); assertTrue(NumberUtils.compare(Double.POSITIVE_INFINITY, -1.2d) == +1); assertTrue(NumberUtils.compare(Double.POSITIVE_INFINITY, -Double.MAX_VALUE) == +1); assertTrue(NumberUtils.compare(Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY) == +1); assertTrue(NumberUtils.compare(Double.MAX_VALUE, Double.NaN) == -1); assertTrue(NumberUtils.compare(Double.MAX_VALUE, Double.POSITIVE_INFINITY) == -1); assertTrue(NumberUtils.compare(Double.MAX_VALUE, Double.MAX_VALUE) == 0); assertTrue(NumberUtils.compare(Double.MAX_VALUE, 1.2d) == +1); assertTrue(NumberUtils.compare(Double.MAX_VALUE, 0.0d) == +1); assertTrue(NumberUtils.compare(Double.MAX_VALUE, -0.0d) == +1); assertTrue(NumberUtils.compare(Double.MAX_VALUE, -1.2d) == +1); assertTrue(NumberUtils.compare(Double.MAX_VALUE, -Double.MAX_VALUE) == +1); assertTrue(NumberUtils.compare(Double.MAX_VALUE, Double.NEGATIVE_INFINITY) == +1); assertTrue(NumberUtils.compare(1.2d, Double.NaN) == -1); assertTrue(NumberUtils.compare(1.2d, Double.POSITIVE_INFINITY) == -1); assertTrue(NumberUtils.compare(1.2d, Double.MAX_VALUE) == -1); assertTrue(NumberUtils.compare(1.2d, 1.2d) == 0); assertTrue(NumberUtils.compare(1.2d, 0.0d) == +1); assertTrue(NumberUtils.compare(1.2d, -0.0d) == +1); assertTrue(NumberUtils.compare(1.2d, -1.2d) == +1); assertTrue(NumberUtils.compare(1.2d, -Double.MAX_VALUE) == +1); assertTrue(NumberUtils.compare(1.2d, Double.NEGATIVE_INFINITY) == +1); assertTrue(NumberUtils.compare(0.0d, Double.NaN) == -1); assertTrue(NumberUtils.compare(0.0d, Double.POSITIVE_INFINITY) == -1); assertTrue(NumberUtils.compare(0.0d, Double.MAX_VALUE) == -1); assertTrue(NumberUtils.compare(0.0d, 1.2d) == -1); assertTrue(NumberUtils.compare(0.0d, 0.0d) == 0); assertTrue(NumberUtils.compare(0.0d, -0.0d) == +1); assertTrue(NumberUtils.compare(0.0d, -1.2d) == +1); assertTrue(NumberUtils.compare(0.0d, -Double.MAX_VALUE) == +1); assertTrue(NumberUtils.compare(0.0d, Double.NEGATIVE_INFINITY) == +1); assertTrue(NumberUtils.compare(-0.0d, Double.NaN) == -1); assertTrue(NumberUtils.compare(-0.0d, Double.POSITIVE_INFINITY) == -1); assertTrue(NumberUtils.compare(-0.0d, Double.MAX_VALUE) == -1); assertTrue(NumberUtils.compare(-0.0d, 1.2d) == -1); assertTrue(NumberUtils.compare(-0.0d, 0.0d) == -1); assertTrue(NumberUtils.compare(-0.0d, -0.0d) == 0); assertTrue(NumberUtils.compare(-0.0d, -1.2d) == +1); assertTrue(NumberUtils.compare(-0.0d, -Double.MAX_VALUE) == +1); assertTrue(NumberUtils.compare(-0.0d, Double.NEGATIVE_INFINITY) == +1); assertTrue(NumberUtils.compare(-1.2d, Double.NaN) == -1); assertTrue(NumberUtils.compare(-1.2d, Double.POSITIVE_INFINITY) == -1); assertTrue(NumberUtils.compare(-1.2d, Double.MAX_VALUE) == -1); assertTrue(NumberUtils.compare(-1.2d, 1.2d) == -1); assertTrue(NumberUtils.compare(-1.2d, 0.0d) == -1); assertTrue(NumberUtils.compare(-1.2d, -0.0d) == -1); assertTrue(NumberUtils.compare(-1.2d, -1.2d) == 0); assertTrue(NumberUtils.compare(-1.2d, -Double.MAX_VALUE) == +1); assertTrue(NumberUtils.compare(-1.2d, Double.NEGATIVE_INFINITY) == +1); assertTrue(NumberUtils.compare(-Double.MAX_VALUE, Double.NaN) == -1); assertTrue(NumberUtils.compare(-Double.MAX_VALUE, Double.POSITIVE_INFINITY) == -1); assertTrue(NumberUtils.compare(-Double.MAX_VALUE, Double.MAX_VALUE) == -1); assertTrue(NumberUtils.compare(-Double.MAX_VALUE, 1.2d) == -1); assertTrue(NumberUtils.compare(-Double.MAX_VALUE, 0.0d) == -1); assertTrue(NumberUtils.compare(-Double.MAX_VALUE, -0.0d) == -1); assertTrue(NumberUtils.compare(-Double.MAX_VALUE, -1.2d) == -1); assertTrue(NumberUtils.compare(-Double.MAX_VALUE, -Double.MAX_VALUE) == 0); assertTrue(NumberUtils.compare(-Double.MAX_VALUE, Double.NEGATIVE_INFINITY) == +1); assertTrue(NumberUtils.compare(Double.NEGATIVE_INFINITY, Double.NaN) == -1); assertTrue(NumberUtils.compare(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY) == -1); assertTrue(NumberUtils.compare(Double.NEGATIVE_INFINITY, Double.MAX_VALUE) == -1); assertTrue(NumberUtils.compare(Double.NEGATIVE_INFINITY, 1.2d) == -1); assertTrue(NumberUtils.compare(Double.NEGATIVE_INFINITY, 0.0d) == -1); assertTrue(NumberUtils.compare(Double.NEGATIVE_INFINITY, -0.0d) == -1); assertTrue(NumberUtils.compare(Double.NEGATIVE_INFINITY, -1.2d) == -1); assertTrue(NumberUtils.compare(Double.NEGATIVE_INFINITY, -Double.MAX_VALUE) == -1); assertTrue(NumberUtils.compare(Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY) == 0); } public void testCompareFloat() { assertTrue(NumberUtils.compare(Float.NaN, Float.NaN) == 0); assertTrue(NumberUtils.compare(Float.NaN, Float.POSITIVE_INFINITY) == +1); assertTrue(NumberUtils.compare(Float.NaN, Float.MAX_VALUE) == +1); assertTrue(NumberUtils.compare(Float.NaN, 1.2f) == +1); assertTrue(NumberUtils.compare(Float.NaN, 0.0f) == +1); assertTrue(NumberUtils.compare(Float.NaN, -0.0f) == +1); assertTrue(NumberUtils.compare(Float.NaN, -1.2f) == +1); assertTrue(NumberUtils.compare(Float.NaN, -Float.MAX_VALUE) == +1); assertTrue(NumberUtils.compare(Float.NaN, Float.NEGATIVE_INFINITY) == +1); assertTrue(NumberUtils.compare(Float.POSITIVE_INFINITY, Float.NaN) == -1); assertTrue(NumberUtils.compare(Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY) == 0); assertTrue(NumberUtils.compare(Float.POSITIVE_INFINITY, Float.MAX_VALUE) == +1); assertTrue(NumberUtils.compare(Float.POSITIVE_INFINITY, 1.2f) == +1); assertTrue(NumberUtils.compare(Float.POSITIVE_INFINITY, 0.0f) == +1); assertTrue(NumberUtils.compare(Float.POSITIVE_INFINITY, -0.0f) == +1); assertTrue(NumberUtils.compare(Float.POSITIVE_INFINITY, -1.2f) == +1); assertTrue(NumberUtils.compare(Float.POSITIVE_INFINITY, -Float.MAX_VALUE) == +1); assertTrue(NumberUtils.compare(Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY) == +1); assertTrue(NumberUtils.compare(Float.MAX_VALUE, Float.NaN) == -1); assertTrue(NumberUtils.compare(Float.MAX_VALUE, Float.POSITIVE_INFINITY) == -1); assertTrue(NumberUtils.compare(Float.MAX_VALUE, Float.MAX_VALUE) == 0); assertTrue(NumberUtils.compare(Float.MAX_VALUE, 1.2f) == +1); assertTrue(NumberUtils.compare(Float.MAX_VALUE, 0.0f) == +1); assertTrue(NumberUtils.compare(Float.MAX_VALUE, -0.0f) == +1); assertTrue(NumberUtils.compare(Float.MAX_VALUE, -1.2f) == +1); assertTrue(NumberUtils.compare(Float.MAX_VALUE, -Float.MAX_VALUE) == +1); assertTrue(NumberUtils.compare(Float.MAX_VALUE, Float.NEGATIVE_INFINITY) == +1); assertTrue(NumberUtils.compare(1.2f, Float.NaN) == -1); assertTrue(NumberUtils.compare(1.2f, Float.POSITIVE_INFINITY) == -1); assertTrue(NumberUtils.compare(1.2f, Float.MAX_VALUE) == -1); assertTrue(NumberUtils.compare(1.2f, 1.2f) == 0); assertTrue(NumberUtils.compare(1.2f, 0.0f) == +1); assertTrue(NumberUtils.compare(1.2f, -0.0f) == +1); assertTrue(NumberUtils.compare(1.2f, -1.2f) == +1); assertTrue(NumberUtils.compare(1.2f, -Float.MAX_VALUE) == +1); assertTrue(NumberUtils.compare(1.2f, Float.NEGATIVE_INFINITY) == +1); assertTrue(NumberUtils.compare(0.0f, Float.NaN) == -1); assertTrue(NumberUtils.compare(0.0f, Float.POSITIVE_INFINITY) == -1); assertTrue(NumberUtils.compare(0.0f, Float.MAX_VALUE) == -1); assertTrue(NumberUtils.compare(0.0f, 1.2f) == -1); assertTrue(NumberUtils.compare(0.0f, 0.0f) == 0); assertTrue(NumberUtils.compare(0.0f, -0.0f) == +1); assertTrue(NumberUtils.compare(0.0f, -1.2f) == +1); assertTrue(NumberUtils.compare(0.0f, -Float.MAX_VALUE) == +1); assertTrue(NumberUtils.compare(0.0f, Float.NEGATIVE_INFINITY) == +1); assertTrue(NumberUtils.compare(-0.0f, Float.NaN) == -1); assertTrue(NumberUtils.compare(-0.0f, Float.POSITIVE_INFINITY) == -1); assertTrue(NumberUtils.compare(-0.0f, Float.MAX_VALUE) == -1); assertTrue(NumberUtils.compare(-0.0f, 1.2f) == -1); assertTrue(NumberUtils.compare(-0.0f, 0.0f) == -1); assertTrue(NumberUtils.compare(-0.0f, -0.0f) == 0); assertTrue(NumberUtils.compare(-0.0f, -1.2f) == +1); assertTrue(NumberUtils.compare(-0.0f, -Float.MAX_VALUE) == +1); assertTrue(NumberUtils.compare(-0.0f, Float.NEGATIVE_INFINITY) == +1); assertTrue(NumberUtils.compare(-1.2f, Float.NaN) == -1); assertTrue(NumberUtils.compare(-1.2f, Float.POSITIVE_INFINITY) == -1); assertTrue(NumberUtils.compare(-1.2f, Float.MAX_VALUE) == -1); assertTrue(NumberUtils.compare(-1.2f, 1.2f) == -1); assertTrue(NumberUtils.compare(-1.2f, 0.0f) == -1); assertTrue(NumberUtils.compare(-1.2f, -0.0f) == -1); assertTrue(NumberUtils.compare(-1.2f, -1.2f) == 0); assertTrue(NumberUtils.compare(-1.2f, -Float.MAX_VALUE) == +1); assertTrue(NumberUtils.compare(-1.2f, Float.NEGATIVE_INFINITY) == +1); assertTrue(NumberUtils.compare(-Float.MAX_VALUE, Float.NaN) == -1); assertTrue(NumberUtils.compare(-Float.MAX_VALUE, Float.POSITIVE_INFINITY) == -1); assertTrue(NumberUtils.compare(-Float.MAX_VALUE, Float.MAX_VALUE) == -1); assertTrue(NumberUtils.compare(-Float.MAX_VALUE, 1.2f) == -1); assertTrue(NumberUtils.compare(-Float.MAX_VALUE, 0.0f) == -1); assertTrue(NumberUtils.compare(-Float.MAX_VALUE, -0.0f) == -1); assertTrue(NumberUtils.compare(-Float.MAX_VALUE, -1.2f) == -1); assertTrue(NumberUtils.compare(-Float.MAX_VALUE, -Float.MAX_VALUE) == 0); assertTrue(NumberUtils.compare(-Float.MAX_VALUE, Float.NEGATIVE_INFINITY) == +1); assertTrue(NumberUtils.compare(Float.NEGATIVE_INFINITY, Float.NaN) == -1); assertTrue(NumberUtils.compare(Float.NEGATIVE_INFINITY, Float.POSITIVE_INFINITY) == -1); assertTrue(NumberUtils.compare(Float.NEGATIVE_INFINITY, Float.MAX_VALUE) == -1); assertTrue(NumberUtils.compare(Float.NEGATIVE_INFINITY, 1.2f) == -1); assertTrue(NumberUtils.compare(Float.NEGATIVE_INFINITY, 0.0f) == -1); assertTrue(NumberUtils.compare(Float.NEGATIVE_INFINITY, -0.0f) == -1); assertTrue(NumberUtils.compare(Float.NEGATIVE_INFINITY, -1.2f) == -1); assertTrue(NumberUtils.compare(Float.NEGATIVE_INFINITY, -Float.MAX_VALUE) == -1); assertTrue(NumberUtils.compare(Float.NEGATIVE_INFINITY, Float.NEGATIVE_INFINITY) == 0); } public void testIsDigits() { assertEquals("isDigits(null) failed", false, NumberUtils.isDigits(null)); assertEquals("isDigits('') failed", false, NumberUtils.isDigits("")); assertEquals("isDigits(String) failed", true, NumberUtils.isDigits("12345")); assertEquals("isDigits(String) neg 1 failed", false, NumberUtils.isDigits("1234.5")); assertEquals("isDigits(String) neg 3 failed", false, NumberUtils.isDigits("1ab")); assertEquals("isDigits(String) neg 4 failed", false, NumberUtils.isDigits("abc")); } /** * Tests isNumber(String) and tests that createNumber(String) returns * a valid number iff isNumber(String) returns false. */ public void testIsNumber() { String val = "12345"; assertTrue("isNumber(String) 1 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 1 failed", checkCreateNumber(val)); val = "1234.5"; assertTrue("isNumber(String) 2 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 2 failed", checkCreateNumber(val)); val = ".12345"; assertTrue("isNumber(String) 3 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 3 failed", checkCreateNumber(val)); val = "1234E5"; assertTrue("isNumber(String) 4 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 4 failed", checkCreateNumber(val)); val = "1234E+5"; assertTrue("isNumber(String) 5 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 5 failed", checkCreateNumber(val)); val = "1234E-5"; assertTrue("isNumber(String) 6 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 6 failed", checkCreateNumber(val)); val = "123.4E5"; assertTrue("isNumber(String) 7 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 7 failed", checkCreateNumber(val)); val = "-1234"; assertTrue("isNumber(String) 8 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 8 failed", checkCreateNumber(val)); val = "-1234.5"; assertTrue("isNumber(String) 9 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 9 failed", checkCreateNumber(val)); val = "-.12345"; assertTrue("isNumber(String) 10 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 10 failed", checkCreateNumber(val)); val = "-1234E5"; assertTrue("isNumber(String) 11 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 11 failed", checkCreateNumber(val)); val = "0"; assertTrue("isNumber(String) 12 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 12 failed", checkCreateNumber(val)); val = "-0"; assertTrue("isNumber(String) 13 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 13 failed", checkCreateNumber(val)); val = "01234"; assertTrue("isNumber(String) 14 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 14 failed", checkCreateNumber(val)); val = "-01234"; assertTrue("isNumber(String) 15 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 15 failed", checkCreateNumber(val)); val = "0xABC123"; assertTrue("isNumber(String) 16 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 16 failed", checkCreateNumber(val)); val = "0x0"; assertTrue("isNumber(String) 17 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 17 failed", checkCreateNumber(val)); val = "123.4E21D"; assertTrue("isNumber(String) 19 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 19 failed", checkCreateNumber(val)); val = "-221.23F"; assertTrue("isNumber(String) 20 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 20 failed", checkCreateNumber(val)); val = "22338L"; assertTrue("isNumber(String) 21 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 21 failed", checkCreateNumber(val)); val = null; assertTrue("isNumber(String) 1 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 1 Neg failed", !checkCreateNumber(val)); val = ""; assertTrue("isNumber(String) 2 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 2 Neg failed", !checkCreateNumber(val)); val = "--2.3"; assertTrue("isNumber(String) 3 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 3 Neg failed", !checkCreateNumber(val)); val = ".12.3"; assertTrue("isNumber(String) 4 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 4 Neg failed", !checkCreateNumber(val)); val = "-123E"; assertTrue("isNumber(String) 5 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 5 Neg failed", !checkCreateNumber(val)); val = "-123E+-212"; assertTrue("isNumber(String) 6 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 6 Neg failed", !checkCreateNumber(val)); val = "-123E2.12"; assertTrue("isNumber(String) 7 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 7 Neg failed", !checkCreateNumber(val)); val = "0xGF"; assertTrue("isNumber(String) 8 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 8 Neg failed", !checkCreateNumber(val)); val = "0xFAE-1"; assertTrue("isNumber(String) 9 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 9 Neg failed", !checkCreateNumber(val)); val = "."; assertTrue("isNumber(String) 10 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 10 Neg failed", !checkCreateNumber(val)); val = "-0ABC123"; assertTrue("isNumber(String) 11 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 11 Neg failed", !checkCreateNumber(val)); val = "123.4E-D"; assertTrue("isNumber(String) 12 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 12 Neg failed", !checkCreateNumber(val)); val = "123.4ED"; assertTrue("isNumber(String) 13 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 13 Neg failed", !checkCreateNumber(val)); val = "1234E5l"; assertTrue("isNumber(String) 14 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 14 Neg failed", !checkCreateNumber(val)); val = "11a"; assertTrue("isNumber(String) 15 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 15 Neg failed", !checkCreateNumber(val)); val = "1a"; assertTrue("isNumber(String) 16 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 16 Neg failed", !checkCreateNumber(val)); val = "a"; assertTrue("isNumber(String) 17 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 17 Neg failed", !checkCreateNumber(val)); val = "11g"; assertTrue("isNumber(String) 18 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 18 Neg failed", !checkCreateNumber(val)); val = "11z"; assertTrue("isNumber(String) 19 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 19 Neg failed", !checkCreateNumber(val)); val = "11def"; assertTrue("isNumber(String) 20 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 20 Neg failed", !checkCreateNumber(val)); val = "11d11"; assertTrue("isNumber(String) 21 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 21 Neg failed", !checkCreateNumber(val)); val = "11 11"; assertTrue("isNumber(String) 22 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 22 Neg failed", !checkCreateNumber(val)); val = " 1111"; assertTrue("isNumber(String) 23 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 23 Neg failed", !checkCreateNumber(val)); val = "1111 "; assertTrue("isNumber(String) 24 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 24 Neg failed", !checkCreateNumber(val)); // LANG-521 val = "2."; assertTrue("isNumber(String) LANG-521 failed", NumberUtils.isNumber(val)); } private boolean checkCreateNumber(String val) { try { Object obj = NumberUtils.createNumber(val); if (obj == null) { return false; } return true; } catch (NumberFormatException e) { return false; } } public void testConstants() { assertTrue(NumberUtils.LONG_ZERO instanceof Long); assertTrue(NumberUtils.LONG_ONE instanceof Long); assertTrue(NumberUtils.LONG_MINUS_ONE instanceof Long); assertTrue(NumberUtils.INTEGER_ZERO instanceof Integer); assertTrue(NumberUtils.INTEGER_ONE instanceof Integer); assertTrue(NumberUtils.INTEGER_MINUS_ONE instanceof Integer); assertTrue(NumberUtils.SHORT_ZERO instanceof Short); assertTrue(NumberUtils.SHORT_ONE instanceof Short); assertTrue(NumberUtils.SHORT_MINUS_ONE instanceof Short); assertTrue(NumberUtils.BYTE_ZERO instanceof Byte); assertTrue(NumberUtils.BYTE_ONE instanceof Byte); assertTrue(NumberUtils.BYTE_MINUS_ONE instanceof Byte); assertTrue(NumberUtils.DOUBLE_ZERO instanceof Double); assertTrue(NumberUtils.DOUBLE_ONE instanceof Double); assertTrue(NumberUtils.DOUBLE_MINUS_ONE instanceof Double); assertTrue(NumberUtils.FLOAT_ZERO instanceof Float); assertTrue(NumberUtils.FLOAT_ONE instanceof Float); assertTrue(NumberUtils.FLOAT_MINUS_ONE instanceof Float); assertTrue(NumberUtils.LONG_ZERO.longValue() == 0); assertTrue(NumberUtils.LONG_ONE.longValue() == 1); assertTrue(NumberUtils.LONG_MINUS_ONE.longValue() == -1); assertTrue(NumberUtils.INTEGER_ZERO.intValue() == 0); assertTrue(NumberUtils.INTEGER_ONE.intValue() == 1); assertTrue(NumberUtils.INTEGER_MINUS_ONE.intValue() == -1); assertTrue(NumberUtils.SHORT_ZERO.shortValue() == 0); assertTrue(NumberUtils.SHORT_ONE.shortValue() == 1); assertTrue(NumberUtils.SHORT_MINUS_ONE.shortValue() == -1); assertTrue(NumberUtils.BYTE_ZERO.byteValue() == 0); assertTrue(NumberUtils.BYTE_ONE.byteValue() == 1); assertTrue(NumberUtils.BYTE_MINUS_ONE.byteValue() == -1); assertTrue(NumberUtils.DOUBLE_ZERO.doubleValue() == 0.0d); assertTrue(NumberUtils.DOUBLE_ONE.doubleValue() == 1.0d); assertTrue(NumberUtils.DOUBLE_MINUS_ONE.doubleValue() == -1.0d); assertTrue(NumberUtils.FLOAT_ZERO.floatValue() == 0.0f); assertTrue(NumberUtils.FLOAT_ONE.floatValue() == 1.0f); assertTrue(NumberUtils.FLOAT_MINUS_ONE.floatValue() == -1.0f); } public void testLang300() { NumberUtils.createNumber("-1l"); NumberUtils.createNumber("01l"); NumberUtils.createNumber("1l"); } public void testLang381() { assertTrue(Double.isNaN(NumberUtils.min(1.2, 2.5, Double.NaN))); assertTrue(Double.isNaN(NumberUtils.max(1.2, 2.5, Double.NaN))); assertTrue(Float.isNaN(NumberUtils.min(1.2f, 2.5f, Float.NaN))); assertTrue(Float.isNaN(NumberUtils.max(1.2f, 2.5f, Float.NaN))); double[] a = new double[] { 1.2, Double.NaN, 3.7, 27.0, 42.0, Double.NaN }; assertTrue(Double.isNaN(NumberUtils.max(a))); assertTrue(Double.isNaN(NumberUtils.min(a))); double[] b = new double[] { Double.NaN, 1.2, Double.NaN, 3.7, 27.0, 42.0, Double.NaN }; assertTrue(Double.isNaN(NumberUtils.max(b))); assertTrue(Double.isNaN(NumberUtils.min(b))); float[] aF = new float[] { 1.2f, Float.NaN, 3.7f, 27.0f, 42.0f, Float.NaN }; assertTrue(Float.isNaN(NumberUtils.max(aF))); float[] bF = new float[] { Float.NaN, 1.2f, Float.NaN, 3.7f, 27.0f, 42.0f, Float.NaN }; assertTrue(Float.isNaN(NumberUtils.max(bF))); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/math/RandomUtilsFreqTest.java100644 0 0 14032 11513702434 26515 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.math; import java.util.Random; import junit.framework.TestCase; /** * Test cases for the {@link RandomUtils} class. * * @author Phil Steitz * @version $Revision: 912374 $ $Date: 2010-02-21 17:20:57 +0000 (Sun, 21 Feb 2010) $ */ public final class RandomUtilsFreqTest extends TestCase { public RandomUtilsFreqTest(String name) { super(name); } public void testNextIntBound(){ tstNextInt(10); tstNextInt(1<<8); tstNextInt((1<<8)+1); tstNextInt((1<<8)-1); tstNextInt(1<<30); tstNextInt((1<<30)-1); tstNextInt((1<<30)+1); Random rnd = new Random(); for(int i=0;i<10;i++){ tstNextInt(rnd.nextInt(Integer.MAX_VALUE)); } } public void testNextLongBound(){ tstNextLong(Integer.MAX_VALUE-1); tstNextLong(Integer.MAX_VALUE); tstNextLong((long)Integer.MAX_VALUE+1); tstNextLong(Long.MAX_VALUE/1024); tstNextLong(Long.MAX_VALUE/920); tstNextLong(Long.MAX_VALUE/1000); tstNextLong(Long.MAX_VALUE/512); tstNextLong(Long.MAX_VALUE/64); tstNextLong(Long.MAX_VALUE-1); tstNextLong(Long.MAX_VALUE); Random rnd = new Random(); for(int i=0;i<10;i++){ tstNextLong(rnd.nextInt(Integer.MAX_VALUE)); } for(int i=0;i<10;i++){ tstNextLong(rnd.nextLong() & 0x7fffffffffffffffL); } } /** * Generate 1000 values for nextInt(bound) and compare * the observed frequency counts to expected counts using * a chi-square test. * @param bound upper bound to use */ private void tstNextInt(int bound) { assertTrue(bound+" Must be non-negative",bound>=0); int result = 0; Random rnd = new Random(); // test uniformity -- use Chi-Square test at .01 level int[] expected = new int[] {500,500}; int[] observed = new int[] {0,0}; int[] observed2 = new int[] {0,0}; for (int i = 0; i < 1000; i ++) { result = rnd.nextInt(bound); assertTrue(result+" Must be non-negative",result>=0); assertTrue(result+" Must be less than bound: "+bound,result=0); assertTrue(result+" Must be less than bound: "+bound,resultPhil Steitz * @version $Revision: 912374 $ $Date: 2010-02-21 17:20:57 +0000 (Sun, 21 Feb 2010) $ */ public final class RandomUtilsTest extends TestCase { public RandomUtilsTest(String name) { super(name); } /** test distribution of nextInt() */ public void testNextInt() { tstNextInt(null); assertTrue (RandomUtils.nextInt() >= 0); } /** test distribution of nextInt(Random) */ public void testNextInt2() { Random rnd = new Random(); rnd.setSeed(System.currentTimeMillis()); tstNextInt(rnd); } /** test distribution of JVMRandom.nextInt() */ public void testJvmRandomNextInt() { tstNextInt(RandomUtils.JVM_RANDOM); } /** * Generate 1000 values for nextInt(bound) and compare * the observed frequency counts to expected counts using * a chi-square test. * @param rnd Random to use if not null */ private void tstNextInt(Random rnd) { int bound = 0; int result = 0; // test boundary condition: n = Integer.MAX_VALUE; bound = Integer.MAX_VALUE; if (rnd == null) { result = RandomUtils.nextInt(bound); } else { result = RandomUtils.nextInt(rnd,bound); } assertTrue("result less than bound",result < bound); assertTrue("result non-negative",result >= 0); // test uniformity -- use Chi-Square test at .01 level bound = 4; int[] expected = new int[] {250,250,250,250}; int[] observed = new int[] {0,0,0,0}; for (int i = 0; i < 1000; i ++) { if (rnd == null) { result = RandomUtils.nextInt(bound); } else { result = RandomUtils.nextInt(rnd,bound); } assertTrue(result < bound); assertTrue(result >= 0); observed[result]++; } /* Use ChiSquare dist with df = 4-1 = 3, alpha = .001 * Change to 11.34 for alpha = .01 */ assertTrue( "chi-square test -- will fail about 1 in 1000 times", chiSquare(expected,observed) < 16.27); } /** test distribution of nextLong() */ public void testNextLong() { tstNextLong(null); } /** test distribution of nextLong(Random) BROKEN * contract of nextLong(Random) is different from * nextLong() */ public void testNextLong2() { Random rnd = new Random(); rnd.setSeed(System.currentTimeMillis()); tstNextLong(rnd); } /** * Generate 1000 values for nextLong() and check that * p(value < long.MAXVALUE/2) ~ 0.5. Use chi-square test * with df = 2-1 = 1 * @param rnd Random to use if not null */ private void tstNextLong(Random rnd) { // Distribution int[] expected = new int[] {500,500}; int[] observed = new int[] {0,0}; // Even/Odd int[] expected2 = new int[] {500,500}; int[] observed2 = new int[] {0,0}; long result = 0; long midPoint = Long.MAX_VALUE/2; for (int i = 0; i < 1000; i ++) { if (rnd == null) { result = Math.abs(RandomUtils.nextLong()); } else { result = Math.abs(RandomUtils.nextLong(rnd)); } if (result < midPoint) { observed[0]++; } else { observed[1]++; } if (result % 2 == 0) { observed2[0]++; } else { observed2[1]++; } } /* Use ChiSquare dist with df = 2-1 = 1, alpha = .001 * Change to 6.64 for alpha = .01 */ assertTrue( "mid point chi-square test -- will fail about 1 in 1000 times", chiSquare(expected,observed) < 10.83); assertTrue( "odd/even chi-square test -- will fail about 1 in 1000 times", chiSquare(expected2,observed2) < 10.83); } /** test distribution of nextBoolean() */ public void testNextBoolean() { tstNextBoolean(null); } /** test distribution of nextBoolean(Random) */ public void testNextBoolean2() { Random rnd = new Random(); rnd.setSeed(System.currentTimeMillis()); tstNextBoolean(rnd); } /** * Generate 1000 values for nextBoolean and check that * p(value = false) ~ 0.5. Use chi-square test * with df = 2-1 = 1 * @param rnd Random to use if not null */ private void tstNextBoolean(Random rnd) { int[] expected = new int[] {500,500}; int[] observed = new int[] {0,0}; boolean result = false; for (int i = 0; i < 1000; i ++) { if (rnd == null) { result = RandomUtils.nextBoolean(); } else { result = RandomUtils.nextBoolean(rnd); } if (result) { observed[0]++; } else { observed[1]++; } } /* Use ChiSquare dist with df = 2-1 = 1, alpha = .001 * Change to 6.64 for alpha = .01 */ assertTrue( "chi-square test -- will fail about 1 in 1000 times", chiSquare(expected,observed) < 10.83 ); } /** test distribution of nextFloat() */ public void testNextFloat() { tstNextFloat(null); } /** test distribution of nextFloat(Random) */ public void testNextFloat2() { Random rnd = new Random(); rnd.setSeed(System.currentTimeMillis()); tstNextFloat(rnd); } /** * Generate 1000 values for nextFloat and check that * p(value < 0.5) ~ 0.5. Use chi-square test * with df = 2-1 = 1 * @param rnd Random to use if not null */ private void tstNextFloat(Random rnd) { int[] expected = new int[] {500,500}; int[] observed = new int[] {0,0}; float result = 0; for (int i = 0; i < 1000; i ++) { if (rnd == null) { result = RandomUtils.nextFloat(); } else { result = RandomUtils.nextFloat(rnd); } if (result < 0.5) { observed[0]++; } else { observed[1]++; } } /* Use ChiSquare dist with df = 2-1 = 1, alpha = .001 * Change to 6.64 for alpha = .01 */ assertTrue( "chi-square test -- will fail about 1 in 1000 times", chiSquare(expected,observed) < 10.83); } /** test distribution of nextDouble() */ public void testNextDouble() { tstNextDouble(null); } /** test distribution of nextDouble(Random) */ public void testNextDouble2() { Random rnd = new Random(); rnd.setSeed(System.currentTimeMillis()); tstNextDouble(rnd); } /** * Generate 1000 values for nextFloat and check that * p(value < 0.5) ~ 0.5. Use chi-square test * with df = 2-1 = 1 * @param rnd Random to use if not null */ private void tstNextDouble(Random rnd) { int[] expected = new int[] {500,500}; int[] observed = new int[] {0,0}; double result = 0; for (int i = 0; i < 1000; i ++) { if (rnd == null) { result = RandomUtils.nextDouble(); } else { result = RandomUtils.nextDouble(rnd); } if (result < 0.5) { observed[0]++; } else { observed[1]++; } } /* Use ChiSquare dist with df = 2-1 = 1, alpha = .001 * Change to 6.64 for alpha = .01 */ assertTrue( "chi-square test -- will fail about 1 in 1000 times", chiSquare(expected,observed) < 10.83); } /** make sure that unimplemented methods fail */ public void testUnimplementedMethods() { try { RandomUtils.JVM_RANDOM.setSeed(1000); fail("expecting UnsupportedOperationException"); } catch (UnsupportedOperationException ex) { // empty } try { RandomUtils.JVM_RANDOM.nextGaussian(); fail("expecting UnsupportedOperationException"); } catch (UnsupportedOperationException ex) { // empty } try { RandomUtils.JVM_RANDOM.nextBytes(null); fail("expecting UnsupportedOperationException"); } catch (UnsupportedOperationException ex) { // empty } } /** make sure that illegal arguments fail */ public void testIllegalArguments() { try { RandomUtils.JVM_RANDOM.nextInt(-1); fail("expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // empty } try { JVMRandom.nextLong( -1L ); fail("expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // empty } } /** * Computes Chi-Square statistic given observed and expected counts * @param observed array of observed frequency counts * @param expected array of expected frequency counts */ private double chiSquare(int[] expected, int[] observed) { double sumSq = 0.0d; double dev = 0.0d; for (int i = 0; i< observed.length; i++) { dev = (double)(observed[i] - expected[i]); sumSq += dev*dev/(double)expected[i]; } return sumSq; } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/math/RangeTest.java100644 0 0 7313 11513702435 24457 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.math; import junit.framework.TestCase; /** *

    * Tests the base methods in the {@link org.apache.commons.lang.math.Range} class. *

    * * @author Nathan Beyer * @version $Id: RangeTest.java 905628 2010-02-02 13:29:55Z niallp $ */ public class RangeTest extends TestCase { private static class RangeTestFixture extends Range { private byte max; private byte min; RangeTestFixture(byte min, byte max) { super(); this.min = min; this.max = max; } public boolean containsNumber(Number number) { if (number.byteValue() >= min && number.byteValue() <= max) { return true; } return false; } public Number getMaximumNumber() { return new Byte(max); } public Number getMinimumNumber() { return new Byte(min); } } public RangeTest(String name) { super(name); } protected void setUp() throws Exception { super.setUp(); } protected void tearDown() throws Exception { super.tearDown(); } /** * Test method for 'org.apache.commons.lang.math.Range.equals(Object)' */ public void testEqualsObject() { RangeTestFixture r1 = new RangeTestFixture((byte) 0, (byte) 5); RangeTestFixture r2 = new RangeTestFixture((byte) 0, (byte) 5); RangeTestFixture r3 = new RangeTestFixture((byte) 0, (byte) 10); assertEquals(r1, r1); assertEquals(r1, r2); assertEquals(r2, r2); assertTrue(r1.equals(r1)); assertTrue(r2.equals(r2)); assertTrue(r3.equals(r3)); assertFalse(r2.equals(r3)); assertFalse(r2.equals(null)); assertFalse(r2.equals("Ni!")); } /** * Test method for 'org.apache.commons.lang.math.Range.hashCode()' */ public void testHashCode() { RangeTestFixture r1 = new RangeTestFixture((byte) 0, (byte) 5); RangeTestFixture r2 = new RangeTestFixture((byte) 0, (byte) 5); RangeTestFixture r3 = new RangeTestFixture((byte) 0, (byte) 10); assertEquals(r1.hashCode(), r2.hashCode()); assertFalse(r1.hashCode() == r3.hashCode()); } /** * Test method for 'org.apache.commons.lang.math.Range.toString()' */ public void testToString() { RangeTestFixture r1 = new RangeTestFixture((byte) 0, (byte) 5); assertNotNull(r1.toString()); assertNotNull(r1.toString()); RangeTestFixture r2 = new RangeTestFixture((byte) 0, (byte) 5); assertNotNull(r2.toString()); assertNotNull(r2.toString()); RangeTestFixture r3 = new RangeTestFixture((byte) 0, (byte) 10); assertNotNull(r3.toString()); assertNotNull(r3.toString()); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/mutable/MutableBooleanTest.java100644 0 0 12567 11513702437 27045 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.mutable; import junit.framework.TestCase; /** * JUnit tests. * * @since 2.2 * @see MutableBoolean * @author Apache Software Foundation * @version $Id: MutableBooleanTest.java 905628 2010-02-02 13:29:55Z niallp $ */ public class MutableBooleanTest extends TestCase { public MutableBooleanTest(String testName) { super(testName); } public void testCompareTo() { final MutableBoolean mutBool = new MutableBoolean(false); assertEquals(0, mutBool.compareTo(new MutableBoolean(false))); assertEquals(-1, mutBool.compareTo(new MutableBoolean(true))); mutBool.setValue(true); assertEquals(+1, mutBool.compareTo(new MutableBoolean(false))); assertEquals(0, mutBool.compareTo(new MutableBoolean(true))); try { mutBool.compareTo(null); fail(); } catch (NullPointerException ex) { } try { mutBool.compareTo(Boolean.FALSE); fail(); } catch (ClassCastException ex) { } try { mutBool.compareTo("false"); fail(); } catch (ClassCastException ex) { } } // ---------------------------------------------------------------- public void testConstructors() { assertEquals(false, new MutableBoolean().booleanValue()); assertEquals(true, new MutableBoolean(true).booleanValue()); assertEquals(false, new MutableBoolean(false).booleanValue()); assertEquals(true, new MutableBoolean(Boolean.TRUE).booleanValue()); assertEquals(false, new MutableBoolean(Boolean.FALSE).booleanValue()); try { new MutableBoolean(null); fail(); } catch (NullPointerException ex) { } } public void testEquals() { final MutableBoolean mutBoolA = new MutableBoolean(false); final MutableBoolean mutBoolB = new MutableBoolean(false); final MutableBoolean mutBoolC = new MutableBoolean(true); assertEquals(true, mutBoolA.equals(mutBoolA)); assertEquals(true, mutBoolA.equals(mutBoolB)); assertEquals(true, mutBoolB.equals(mutBoolA)); assertEquals(true, mutBoolB.equals(mutBoolB)); assertEquals(false, mutBoolA.equals(mutBoolC)); assertEquals(false, mutBoolB.equals(mutBoolC)); assertEquals(true, mutBoolC.equals(mutBoolC)); assertEquals(false, mutBoolA.equals(null)); assertEquals(false, mutBoolA.equals(Boolean.FALSE)); assertEquals(false, mutBoolA.equals("false")); } public void testGetSet() { assertEquals(false, new MutableBoolean().booleanValue()); assertEquals(Boolean.FALSE, new MutableBoolean().getValue()); final MutableBoolean mutBool = new MutableBoolean(false); assertEquals(Boolean.FALSE, mutBool.toBoolean()); assertEquals(false, mutBool.booleanValue()); assertEquals(true, mutBool.isFalse()); assertEquals(false, mutBool.isTrue()); mutBool.setValue(Boolean.TRUE); assertEquals(Boolean.TRUE, mutBool.toBoolean()); assertEquals(true, mutBool.booleanValue()); assertEquals(false, mutBool.isFalse()); assertEquals(true, mutBool.isTrue()); mutBool.setValue(false); assertEquals(false, mutBool.booleanValue()); mutBool.setValue(true); assertEquals(true, mutBool.booleanValue()); try { mutBool.setValue(null); fail(); } catch (NullPointerException ex) { } try { mutBool.setValue("false"); fail(); } catch (ClassCastException ex) { } } public void testHashCode() { final MutableBoolean mutBoolA = new MutableBoolean(false); final MutableBoolean mutBoolB = new MutableBoolean(false); final MutableBoolean mutBoolC = new MutableBoolean(true); assertEquals(true, mutBoolA.hashCode() == mutBoolA.hashCode()); assertEquals(true, mutBoolA.hashCode() == mutBoolB.hashCode()); assertEquals(false, mutBoolA.hashCode() == mutBoolC.hashCode()); assertEquals(true, mutBoolA.hashCode() == Boolean.FALSE.hashCode()); assertEquals(true, mutBoolC.hashCode() == Boolean.TRUE.hashCode()); } public void testToString() { assertEquals(Boolean.FALSE.toString(), new MutableBoolean(false).toString()); assertEquals(Boolean.TRUE.toString(), new MutableBoolean(true).toString()); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/mutable/MutableByteTest.java100644 0 0 15545 11513702437 26370 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.mutable; import junit.framework.TestCase; /** * JUnit tests. * * @version $Id: MutableByteTest.java 905628 2010-02-02 13:29:55Z niallp $ * @see MutableByte */ public class MutableByteTest extends TestCase { public MutableByteTest(String testName) { super(testName); } // ---------------------------------------------------------------- public void testConstructors() { assertEquals((byte) 0, new MutableByte().byteValue()); assertEquals((byte) 1, new MutableByte((byte) 1).byteValue()); assertEquals((byte) 2, new MutableByte(new Byte((byte) 2)).byteValue()); assertEquals((byte) 3, new MutableByte(new MutableByte((byte) 3)).byteValue()); assertEquals((byte) 2, new MutableByte("2").byteValue()); try { new MutableByte((Number)null); fail(); } catch (NullPointerException ex) {} } public void testGetSet() { final MutableByte mutNum = new MutableByte((byte) 0); assertEquals((byte) 0, new MutableByte().byteValue()); assertEquals(new Byte((byte) 0), new MutableByte().getValue()); mutNum.setValue((byte) 1); assertEquals((byte) 1, mutNum.byteValue()); assertEquals(new Byte((byte) 1), mutNum.getValue()); mutNum.setValue(new Byte((byte) 2)); assertEquals((byte) 2, mutNum.byteValue()); assertEquals(new Byte((byte) 2), mutNum.getValue()); mutNum.setValue(new MutableByte((byte) 3)); assertEquals((byte) 3, mutNum.byteValue()); assertEquals(new Byte((byte) 3), mutNum.getValue()); try { mutNum.setValue(null); fail(); } catch (NullPointerException ex) {} try { mutNum.setValue("0"); fail(); } catch (ClassCastException ex) {} } public void testEquals() { final MutableByte mutNumA = new MutableByte((byte) 0); final MutableByte mutNumB = new MutableByte((byte) 0); final MutableByte mutNumC = new MutableByte((byte) 1); assertEquals(true, mutNumA.equals(mutNumA)); assertEquals(true, mutNumA.equals(mutNumB)); assertEquals(true, mutNumB.equals(mutNumA)); assertEquals(true, mutNumB.equals(mutNumB)); assertEquals(false, mutNumA.equals(mutNumC)); assertEquals(false, mutNumB.equals(mutNumC)); assertEquals(true, mutNumC.equals(mutNumC)); assertEquals(false, mutNumA.equals(null)); assertEquals(false, mutNumA.equals(new Byte((byte) 0))); assertEquals(false, mutNumA.equals("0")); } public void testHashCode() { final MutableByte mutNumA = new MutableByte((byte) 0); final MutableByte mutNumB = new MutableByte((byte) 0); final MutableByte mutNumC = new MutableByte((byte) 1); assertEquals(true, mutNumA.hashCode() == mutNumA.hashCode()); assertEquals(true, mutNumA.hashCode() == mutNumB.hashCode()); assertEquals(false, mutNumA.hashCode() == mutNumC.hashCode()); assertEquals(true, mutNumA.hashCode() == new Byte((byte) 0).hashCode()); } public void testCompareTo() { final MutableByte mutNum = new MutableByte((byte) 0); assertEquals((byte) 0, mutNum.compareTo(new MutableByte((byte) 0))); assertEquals((byte) +1, mutNum.compareTo(new MutableByte((byte) -1))); assertEquals((byte) -1, mutNum.compareTo(new MutableByte((byte) 1))); try { mutNum.compareTo(null); fail(); } catch (NullPointerException ex) {} try { mutNum.compareTo(new Byte((byte) 0)); fail(); } catch (ClassCastException ex) {} try { mutNum.compareTo("0"); fail(); } catch (ClassCastException ex) {} } public void testPrimitiveValues() { MutableByte mutNum = new MutableByte( (byte) 1 ); assertEquals( 1.0F, mutNum.floatValue(), 0 ); assertEquals( 1.0, mutNum.doubleValue(), 0 ); assertEquals( (byte) 1, mutNum.byteValue() ); assertEquals( (short) 1, mutNum.shortValue() ); assertEquals( 1, mutNum.intValue() ); assertEquals( 1L, mutNum.longValue() ); } public void testToByte() { assertEquals(new Byte((byte) 0), new MutableByte((byte) 0).toByte()); assertEquals(new Byte((byte) 123), new MutableByte((byte) 123).toByte()); } public void testIncrement() { MutableByte mutNum = new MutableByte((byte) 1); mutNum.increment(); assertEquals(2, mutNum.intValue()); assertEquals(2L, mutNum.longValue()); } public void testDecrement() { MutableByte mutNum = new MutableByte((byte) 1); mutNum.decrement(); assertEquals(0, mutNum.intValue()); assertEquals(0L, mutNum.longValue()); } public void testAddValuePrimitive() { MutableByte mutNum = new MutableByte((byte) 1); mutNum.add((byte)1); assertEquals((byte) 2, mutNum.byteValue()); } public void testAddValueObject() { MutableByte mutNum = new MutableByte((byte) 1); mutNum.add(new Integer(1)); assertEquals((byte) 2, mutNum.byteValue()); } public void testSubtractValuePrimitive() { MutableByte mutNum = new MutableByte((byte) 1); mutNum.subtract((byte) 1); assertEquals((byte) 0, mutNum.byteValue()); } public void testSubtractValueObject() { MutableByte mutNum = new MutableByte((byte) 1); mutNum.subtract(new Integer(1)); assertEquals((byte) 0, mutNum.byteValue()); } public void testToString() { assertEquals("0", new MutableByte((byte) 0).toString()); assertEquals("10", new MutableByte((byte) 10).toString()); assertEquals("-123", new MutableByte((byte) -123).toString()); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/mutable/MutableDoubleTest.java100644 0 0 16307 11513702437 26674 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.mutable; import junit.framework.TestCase; /** * JUnit tests. * * @version $Id: MutableDoubleTest.java 905628 2010-02-02 13:29:55Z niallp $ * @see MutableDouble */ public class MutableDoubleTest extends TestCase { public MutableDoubleTest(String testName) { super(testName); } // ---------------------------------------------------------------- public void testConstructors() { assertEquals(0d, new MutableDouble().doubleValue(), 0.0001d); assertEquals(1d, new MutableDouble(1d).doubleValue(), 0.0001d); assertEquals(2d, new MutableDouble(new Double(2d)).doubleValue(), 0.0001d); assertEquals(3d, new MutableDouble(new MutableDouble(3d)).doubleValue(), 0.0001d); assertEquals(2d, new MutableDouble("2.0").doubleValue(), 0.0001d); try { new MutableDouble((Number)null); fail(); } catch (NullPointerException ex) {} } public void testGetSet() { final MutableDouble mutNum = new MutableDouble(0d); assertEquals(0d, new MutableDouble().doubleValue(), 0.0001d); assertEquals(new Double(0), new MutableDouble().getValue()); mutNum.setValue(1); assertEquals(1d, mutNum.doubleValue(), 0.0001d); assertEquals(new Double(1d), mutNum.getValue()); mutNum.setValue(new Double(2d)); assertEquals(2d, mutNum.doubleValue(), 0.0001d); assertEquals(new Double(2d), mutNum.getValue()); mutNum.setValue(new MutableDouble(3d)); assertEquals(3d, mutNum.doubleValue(), 0.0001d); assertEquals(new Double(3d), mutNum.getValue()); try { mutNum.setValue(null); fail(); } catch (NullPointerException ex) {} try { mutNum.setValue("0"); fail(); } catch (ClassCastException ex) {} } public void testNanInfinite() { MutableDouble mutNum = new MutableDouble(Double.NaN); assertEquals(true, mutNum.isNaN()); mutNum = new MutableDouble(Double.POSITIVE_INFINITY); assertEquals(true, mutNum.isInfinite()); mutNum = new MutableDouble(Double.NEGATIVE_INFINITY); assertEquals(true, mutNum.isInfinite()); } public void testEquals() { final MutableDouble mutNumA = new MutableDouble(0d); final MutableDouble mutNumB = new MutableDouble(0d); final MutableDouble mutNumC = new MutableDouble(1d); assertEquals(true, mutNumA.equals(mutNumA)); assertEquals(true, mutNumA.equals(mutNumB)); assertEquals(true, mutNumB.equals(mutNumA)); assertEquals(true, mutNumB.equals(mutNumB)); assertEquals(false, mutNumA.equals(mutNumC)); assertEquals(false, mutNumB.equals(mutNumC)); assertEquals(true, mutNumC.equals(mutNumC)); assertEquals(false, mutNumA.equals(null)); assertEquals(false, mutNumA.equals(new Double(0d))); assertEquals(false, mutNumA.equals("0")); } public void testHashCode() { final MutableDouble mutNumA = new MutableDouble(0d); final MutableDouble mutNumB = new MutableDouble(0d); final MutableDouble mutNumC = new MutableDouble(1d); assertEquals(true, mutNumA.hashCode() == mutNumA.hashCode()); assertEquals(true, mutNumA.hashCode() == mutNumB.hashCode()); assertEquals(false, mutNumA.hashCode() == mutNumC.hashCode()); assertEquals(true, mutNumA.hashCode() == new Double(0d).hashCode()); } public void testCompareTo() { final MutableDouble mutNum = new MutableDouble(0d); assertEquals(0, mutNum.compareTo(new MutableDouble(0d))); assertEquals(+1, mutNum.compareTo(new MutableDouble(-1d))); assertEquals(-1, mutNum.compareTo(new MutableDouble(1d))); try { mutNum.compareTo(null); fail(); } catch (NullPointerException ex) {} try { mutNum.compareTo(new Double(0d)); fail(); } catch (ClassCastException ex) {} try { mutNum.compareTo("0"); fail(); } catch (ClassCastException ex) {} } public void testPrimitiveValues() { MutableDouble mutNum = new MutableDouble(1.7); assertEquals( 1.7F, mutNum.floatValue(), 0 ); assertEquals( 1.7, mutNum.doubleValue(), 0 ); assertEquals( (byte) 1, mutNum.byteValue() ); assertEquals( (short) 1, mutNum.shortValue() ); assertEquals( 1, mutNum.intValue() ); assertEquals( 1L, mutNum.longValue() ); } public void testToDouble() { assertEquals(new Double(0d), new MutableDouble(0d).toDouble()); assertEquals(new Double(12.3d), new MutableDouble(12.3d).toDouble()); } public void testIncrement() { MutableDouble mutNum = new MutableDouble(1); mutNum.increment(); assertEquals(2, mutNum.intValue()); assertEquals(2L, mutNum.longValue()); } public void testDecrement() { MutableDouble mutNum = new MutableDouble(1); mutNum.decrement(); assertEquals(0, mutNum.intValue()); assertEquals(0L, mutNum.longValue()); } public void testAddValuePrimitive() { MutableDouble mutNum = new MutableDouble(1); mutNum.add(1.1d); assertEquals(2.1d, mutNum.doubleValue(), 0.01d); } public void testAddValueObject() { MutableDouble mutNum = new MutableDouble(1); mutNum.add(new Double(1.1d)); assertEquals(2.1d, mutNum.doubleValue(), 0.01d); } public void testSubtractValuePrimitive() { MutableDouble mutNum = new MutableDouble(1); mutNum.subtract(0.9d); assertEquals(0.1d, mutNum.doubleValue(), 0.01d); } public void testSubtractValueObject() { MutableDouble mutNum = new MutableDouble(1); mutNum.subtract(new Double(0.9d)); assertEquals(0.1d, mutNum.doubleValue(), 0.01d); } public void testToString() { assertEquals("0.0", new MutableDouble(0d).toString()); assertEquals("10.0", new MutableDouble(10d).toString()); assertEquals("-123.0", new MutableDouble(-123d).toString()); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/mutable/MutableFloatTest.java100644 0 0 16147 11513702437 26531 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.mutable; import junit.framework.TestCase; /** * JUnit tests. * * @version $Id: MutableFloatTest.java 1057020 2011-01-09 20:13:35Z niallp $ * @see MutableFloat */ public class MutableFloatTest extends TestCase { public MutableFloatTest(String testName) { super(testName); } // ---------------------------------------------------------------- public void testConstructors() { assertEquals(0f, new MutableFloat().floatValue(), 0.0001f); assertEquals(1f, new MutableFloat(1f).floatValue(), 0.0001f); assertEquals(2f, new MutableFloat(new Float(2f)).floatValue(), 0.0001f); assertEquals(3f, new MutableFloat(new MutableFloat(3f)).floatValue(), 0.0001f); assertEquals(2f, new MutableFloat("2.0").floatValue(), 0.0001f); try { new MutableFloat((Number)null); fail(); } catch (NullPointerException ex) {} } public void testGetSet() { final MutableFloat mutNum = new MutableFloat(0f); assertEquals(0f, new MutableFloat().floatValue(), 0.0001f); assertEquals(new Float(0), new MutableFloat().getValue()); mutNum.setValue(1); assertEquals(1f, mutNum.floatValue(), 0.0001f); assertEquals(new Float(1f), mutNum.getValue()); mutNum.setValue(new Float(2f)); assertEquals(2f, mutNum.floatValue(), 0.0001f); assertEquals(new Float(2f), mutNum.getValue()); mutNum.setValue(new MutableFloat(3f)); assertEquals(3f, mutNum.floatValue(), 0.0001f); assertEquals(new Float(3f), mutNum.getValue()); try { mutNum.setValue(null); fail(); } catch (NullPointerException ex) {} try { mutNum.setValue("0"); fail(); } catch (ClassCastException ex) {} } public void testNanInfinite() { MutableFloat mutNum = new MutableFloat(Float.NaN); assertEquals(true, mutNum.isNaN()); mutNum = new MutableFloat(Float.POSITIVE_INFINITY); assertEquals(true, mutNum.isInfinite()); mutNum = new MutableFloat(Float.NEGATIVE_INFINITY); assertEquals(true, mutNum.isInfinite()); } public void testEquals() { final MutableFloat mutNumA = new MutableFloat(0f); final MutableFloat mutNumB = new MutableFloat(0f); final MutableFloat mutNumC = new MutableFloat(1f); assertEquals(true, mutNumA.equals(mutNumA)); assertEquals(true, mutNumA.equals(mutNumB)); assertEquals(true, mutNumB.equals(mutNumA)); assertEquals(true, mutNumB.equals(mutNumB)); assertEquals(false, mutNumA.equals(mutNumC)); assertEquals(false, mutNumB.equals(mutNumC)); assertEquals(true, mutNumC.equals(mutNumC)); assertEquals(false, mutNumA.equals(null)); assertEquals(false, mutNumA.equals(new Float(0f))); assertEquals(false, mutNumA.equals("0")); } public void testHashCode() { final MutableFloat mutNumA = new MutableFloat(0f); final MutableFloat mutNumB = new MutableFloat(0f); final MutableFloat mutNumC = new MutableFloat(1f); assertEquals(true, mutNumA.hashCode() == mutNumA.hashCode()); assertEquals(true, mutNumA.hashCode() == mutNumB.hashCode()); assertEquals(false, mutNumA.hashCode() == mutNumC.hashCode()); assertEquals(true, mutNumA.hashCode() == new Float(0f).hashCode()); } public void testCompareTo() { final MutableFloat mutNum = new MutableFloat(0f); assertEquals(0, mutNum.compareTo(new MutableFloat(0f))); assertEquals(+1, mutNum.compareTo(new MutableFloat(-1f))); assertEquals(-1, mutNum.compareTo(new MutableFloat(1f))); try { mutNum.compareTo(null); fail(); } catch (NullPointerException ex) {} try { mutNum.compareTo(new Float(0f)); fail(); } catch (ClassCastException ex) {} try { mutNum.compareTo("0"); fail(); } catch (ClassCastException ex) {} } public void testPrimitiveValues() { MutableFloat mutNum = new MutableFloat(1.7F); assertEquals( 1, mutNum.intValue() ); assertEquals( 1.7, mutNum.doubleValue(), 0.00001 ); assertEquals( (byte) 1, mutNum.byteValue() ); assertEquals( (short) 1, mutNum.shortValue() ); assertEquals( 1, mutNum.intValue() ); assertEquals( 1L, mutNum.longValue() ); } public void testToFloat() { assertEquals(new Float(0f), new MutableFloat(0f).toFloat()); assertEquals(new Float(12.3f), new MutableFloat(12.3f).toFloat()); } public void testIncrement() { MutableFloat mutNum = new MutableFloat(1); mutNum.increment(); assertEquals(2, mutNum.intValue()); assertEquals(2L, mutNum.longValue()); } public void testDecrement() { MutableFloat mutNum = new MutableFloat(1); mutNum.decrement(); assertEquals(0, mutNum.intValue()); assertEquals(0L, mutNum.longValue()); } public void testAddValuePrimitive() { MutableFloat mutNum = new MutableFloat(1); mutNum.add(1.1f); assertEquals(2.1f, mutNum.floatValue(), 0.01f); } public void testAddValueObject() { MutableFloat mutNum = new MutableFloat(1); mutNum.add(new Float(1.1f)); assertEquals(2.1f, mutNum.floatValue(), 0.01f); } public void testSubtractValuePrimitive() { MutableFloat mutNum = new MutableFloat(1); mutNum.subtract(0.9f); assertEquals(0.1f, mutNum.floatValue(), 0.01f); } public void testSubtractValueObject() { MutableFloat mutNum = new MutableFloat(1); mutNum.subtract(new Float(0.9f)); assertEquals(0.1f, mutNum.floatValue(), 0.01f); } public void testToString() { assertEquals("0.0", new MutableFloat(0f).toString()); assertEquals("10.0", new MutableFloat(10f).toString()); assertEquals("-123.0", new MutableFloat(-123f).toString()); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/mutable/MutableIntTest.java100644 0 0 15555 11513702437 26220 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.mutable; import junit.framework.TestCase; /** * JUnit tests. * * @version $Id: MutableIntTest.java 905628 2010-02-02 13:29:55Z niallp $ * @see MutableInt */ public class MutableIntTest extends TestCase { public MutableIntTest(String testName) { super(testName); } // ---------------------------------------------------------------- public void testConstructors() { assertEquals(0, new MutableInt().intValue()); assertEquals(1, new MutableInt(1).intValue()); assertEquals(2, new MutableInt(new Integer(2)).intValue()); assertEquals(3, new MutableInt(new MutableLong(3)).intValue()); assertEquals(2, new MutableInt("2").intValue()); try { new MutableInt((Number)null); fail(); } catch (NullPointerException ex) {} } public void testGetSet() { final MutableInt mutNum = new MutableInt(0); assertEquals(0, new MutableInt().intValue()); assertEquals(new Integer(0), new MutableInt().getValue()); mutNum.setValue(1); assertEquals(1, mutNum.intValue()); assertEquals(new Integer(1), mutNum.getValue()); mutNum.setValue(new Integer(2)); assertEquals(2, mutNum.intValue()); assertEquals(new Integer(2), mutNum.getValue()); mutNum.setValue(new MutableLong(3)); assertEquals(3, mutNum.intValue()); assertEquals(new Integer(3), mutNum.getValue()); try { mutNum.setValue(null); fail(); } catch (NullPointerException ex) {} try { mutNum.setValue("0"); fail(); } catch (ClassCastException ex) {} } public void testEquals() { this.testEquals(new MutableInt(0), new MutableInt(0), new MutableInt(1)); // Should Numbers be supported? GaryG July-21-2005. //this.testEquals(mutNumA, new Integer(0), mutNumC); } /** * @param numA must not be a 0 Integer; must not equal numC. * @param numB must equal numA; must not equal numC. * @param numC must not equal numA; must not equal numC. */ void testEquals(final Number numA, final Number numB, final Number numC) { assertEquals(true, numA.equals(numA)); assertEquals(true, numA.equals(numB)); assertEquals(true, numB.equals(numA)); assertEquals(true, numB.equals(numB)); assertEquals(false, numA.equals(numC)); assertEquals(false, numB.equals(numC)); assertEquals(true, numC.equals(numC)); assertEquals(false, numA.equals(null)); assertEquals(false, numA.equals(new Integer(0))); assertEquals(false, numA.equals("0")); } public void testHashCode() { final MutableInt mutNumA = new MutableInt(0); final MutableInt mutNumB = new MutableInt(0); final MutableInt mutNumC = new MutableInt(1); assertEquals(true, mutNumA.hashCode() == mutNumA.hashCode()); assertEquals(true, mutNumA.hashCode() == mutNumB.hashCode()); assertEquals(false, mutNumA.hashCode() == mutNumC.hashCode()); assertEquals(true, mutNumA.hashCode() == new Integer(0).hashCode()); } public void testCompareTo() { final MutableInt mutNum = new MutableInt(0); assertEquals(0, mutNum.compareTo(new MutableInt(0))); assertEquals(+1, mutNum.compareTo(new MutableInt(-1))); assertEquals(-1, mutNum.compareTo(new MutableInt(1))); try { mutNum.compareTo(null); fail(); } catch (NullPointerException ex) {} try { mutNum.compareTo(new Integer(0)); fail(); } catch (ClassCastException ex) {} try { mutNum.compareTo("0"); fail(); } catch (ClassCastException ex) {} } public void testPrimitiveValues() { MutableInt mutNum = new MutableInt(1); assertEquals( (byte) 1, mutNum.byteValue() ); assertEquals( (short) 1, mutNum.shortValue() ); assertEquals( 1.0F, mutNum.floatValue(), 0 ); assertEquals( 1.0, mutNum.doubleValue(), 0 ); assertEquals( 1L, mutNum.longValue() ); } public void testToInteger() { assertEquals(new Integer(0), new MutableInt(0).toInteger()); assertEquals(new Integer(123), new MutableInt(123).toInteger()); } public void testIncrement() { MutableInt mutNum = new MutableInt(1); mutNum.increment(); assertEquals(2, mutNum.intValue()); assertEquals(2L, mutNum.longValue()); } public void testDecrement() { MutableInt mutNum = new MutableInt(1); mutNum.decrement(); assertEquals(0, mutNum.intValue()); assertEquals(0L, mutNum.longValue()); } public void testAddValuePrimitive() { MutableInt mutNum = new MutableInt(1); mutNum.add(1); assertEquals(2, mutNum.intValue()); assertEquals(2L, mutNum.longValue()); } public void testAddValueObject() { MutableInt mutNum = new MutableInt(1); mutNum.add(new Integer(1)); assertEquals(2, mutNum.intValue()); assertEquals(2L, mutNum.longValue()); } public void testSubtractValuePrimitive() { MutableInt mutNum = new MutableInt(1); mutNum.subtract(1); assertEquals(0, mutNum.intValue()); assertEquals(0L, mutNum.longValue()); } public void testSubtractValueObject() { MutableInt mutNum = new MutableInt(1); mutNum.subtract(new Integer(1)); assertEquals(0, mutNum.intValue()); assertEquals(0L, mutNum.longValue()); } public void testToString() { assertEquals("0", new MutableInt(0).toString()); assertEquals("10", new MutableInt(10).toString()); assertEquals("-123", new MutableInt(-123).toString()); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/mutable/MutableLongTest.java100644 0 0 15213 11513702437 26354 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.mutable; import junit.framework.TestCase; /** * JUnit tests. * * @version $Id: MutableLongTest.java 905628 2010-02-02 13:29:55Z niallp $ * @see MutableLong */ public class MutableLongTest extends TestCase { public MutableLongTest(String testName) { super(testName); } // ---------------------------------------------------------------- public void testConstructors() { assertEquals(0, new MutableLong().longValue()); assertEquals(1, new MutableLong(1).longValue()); assertEquals(2, new MutableLong(new Long(2)).longValue()); assertEquals(3, new MutableLong(new MutableLong(3)).longValue()); assertEquals(2, new MutableLong("2").longValue()); try { new MutableLong((Number)null); fail(); } catch (NullPointerException ex) {} } public void testGetSet() { final MutableLong mutNum = new MutableLong(0); assertEquals(0, new MutableLong().longValue()); assertEquals(new Long(0), new MutableLong().getValue()); mutNum.setValue(1); assertEquals(1, mutNum.longValue()); assertEquals(new Long(1), mutNum.getValue()); mutNum.setValue(new Long(2)); assertEquals(2, mutNum.longValue()); assertEquals(new Long(2), mutNum.getValue()); mutNum.setValue(new MutableLong(3)); assertEquals(3, mutNum.longValue()); assertEquals(new Long(3), mutNum.getValue()); try { mutNum.setValue(null); fail(); } catch (NullPointerException ex) {} try { mutNum.setValue("0"); fail(); } catch (ClassCastException ex) {} } public void testEquals() { final MutableLong mutNumA = new MutableLong(0); final MutableLong mutNumB = new MutableLong(0); final MutableLong mutNumC = new MutableLong(1); assertEquals(true, mutNumA.equals(mutNumA)); assertEquals(true, mutNumA.equals(mutNumB)); assertEquals(true, mutNumB.equals(mutNumA)); assertEquals(true, mutNumB.equals(mutNumB)); assertEquals(false, mutNumA.equals(mutNumC)); assertEquals(false, mutNumB.equals(mutNumC)); assertEquals(true, mutNumC.equals(mutNumC)); assertEquals(false, mutNumA.equals(null)); assertEquals(false, mutNumA.equals(new Long(0))); assertEquals(false, mutNumA.equals("0")); } public void testHashCode() { final MutableLong mutNumA = new MutableLong(0); final MutableLong mutNumB = new MutableLong(0); final MutableLong mutNumC = new MutableLong(1); assertEquals(true, mutNumA.hashCode() == mutNumA.hashCode()); assertEquals(true, mutNumA.hashCode() == mutNumB.hashCode()); assertEquals(false, mutNumA.hashCode() == mutNumC.hashCode()); assertEquals(true, mutNumA.hashCode() == new Long(0).hashCode()); } public void testCompareTo() { final MutableLong mutNum = new MutableLong(0); assertEquals(0, mutNum.compareTo(new MutableLong(0))); assertEquals(+1, mutNum.compareTo(new MutableLong(-1))); assertEquals(-1, mutNum.compareTo(new MutableLong(1))); try { mutNum.compareTo(null); fail(); } catch (NullPointerException ex) {} try { mutNum.compareTo(new Long(0)); fail(); } catch (ClassCastException ex) {} try { mutNum.compareTo("0"); fail(); } catch (ClassCastException ex) {} } public void testPrimitiveValues() { MutableLong mutNum = new MutableLong(1L); assertEquals( 1.0F, mutNum.floatValue(), 0 ); assertEquals( 1.0, mutNum.doubleValue(), 0 ); assertEquals( (byte) 1, mutNum.byteValue() ); assertEquals( (short) 1, mutNum.shortValue() ); assertEquals( 1, mutNum.intValue() ); assertEquals( 1L, mutNum.longValue() ); } public void testToLong() { assertEquals(new Long(0L), new MutableLong(0L).toLong()); assertEquals(new Long(123L), new MutableLong(123L).toLong()); } public void testIncrement() { MutableLong mutNum = new MutableLong(1); mutNum.increment(); assertEquals(2, mutNum.intValue()); assertEquals(2L, mutNum.longValue()); } public void testDecrement() { MutableLong mutNum = new MutableLong(1); mutNum.decrement(); assertEquals(0, mutNum.intValue()); assertEquals(0L, mutNum.longValue()); } public void testAddValuePrimitive() { MutableLong mutNum = new MutableLong(1); mutNum.add(1); assertEquals(2, mutNum.intValue()); assertEquals(2L, mutNum.longValue()); } public void testAddValueObject() { MutableLong mutNum = new MutableLong(1); mutNum.add(new Long(1)); assertEquals(2, mutNum.intValue()); assertEquals(2L, mutNum.longValue()); } public void testSubtractValuePrimitive() { MutableLong mutNum = new MutableLong(1); mutNum.subtract(1); assertEquals(0, mutNum.intValue()); assertEquals(0L, mutNum.longValue()); } public void testSubtractValueObject() { MutableLong mutNum = new MutableLong(1); mutNum.subtract(new Long(1)); assertEquals(0, mutNum.intValue()); assertEquals(0L, mutNum.longValue()); } public void testToString() { assertEquals("0", new MutableLong(0).toString()); assertEquals("10", new MutableLong(10).toString()); assertEquals("-123", new MutableLong(-123).toString()); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/mutable/MutableObjectTest.java100644 0 0 7424 11513702437 26650 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.mutable; import junit.framework.TestCase; /** * JUnit tests. * * @version $Id: MutableObjectTest.java 905628 2010-02-02 13:29:55Z niallp $ * @see MutableShort */ public class MutableObjectTest extends TestCase { public MutableObjectTest(String testName) { super(testName); } // ---------------------------------------------------------------- public void testConstructors() { assertEquals(null, new MutableObject().getValue()); Integer i = new Integer(6); assertSame(i, new MutableObject(i).getValue()); assertSame("HI", new MutableObject("HI").getValue()); assertSame(null, new MutableObject(null).getValue()); } public void testGetSet() { final MutableObject mutNum = new MutableObject(); assertEquals(null, new MutableObject().getValue()); mutNum.setValue("HELLO"); assertSame("HELLO", mutNum.getValue()); mutNum.setValue(null); assertSame(null, mutNum.getValue()); } public void testEquals() { final MutableObject mutNumA = new MutableObject("ALPHA"); final MutableObject mutNumB = new MutableObject("ALPHA"); final MutableObject mutNumC = new MutableObject("BETA"); final MutableObject mutNumD = new MutableObject(null); assertEquals(true, mutNumA.equals(mutNumA)); assertEquals(true, mutNumA.equals(mutNumB)); assertEquals(true, mutNumB.equals(mutNumA)); assertEquals(true, mutNumB.equals(mutNumB)); assertEquals(false, mutNumA.equals(mutNumC)); assertEquals(false, mutNumB.equals(mutNumC)); assertEquals(true, mutNumC.equals(mutNumC)); assertEquals(false, mutNumA.equals(mutNumD)); assertEquals(true, mutNumD.equals(mutNumD)); assertEquals(false, mutNumA.equals(null)); assertEquals(false, mutNumA.equals(new Object())); assertEquals(false, mutNumA.equals("0")); } public void testHashCode() { final MutableObject mutNumA = new MutableObject("ALPHA"); final MutableObject mutNumB = new MutableObject("ALPHA"); final MutableObject mutNumC = new MutableObject("BETA"); final MutableObject mutNumD = new MutableObject(null); assertEquals(true, mutNumA.hashCode() == mutNumA.hashCode()); assertEquals(true, mutNumA.hashCode() == mutNumB.hashCode()); assertEquals(false, mutNumA.hashCode() == mutNumC.hashCode()); assertEquals(false, mutNumA.hashCode() == mutNumD.hashCode()); assertEquals(true, mutNumA.hashCode() == "ALPHA".hashCode()); assertEquals(0, mutNumD.hashCode()); } public void testToString() { assertEquals("HI", new MutableObject("HI").toString()); assertEquals("10.0", new MutableObject(new Double(10)).toString()); assertEquals("null", new MutableObject(null).toString()); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/mutable/MutableShortTest.java100644 0 0 15771 11513702437 26565 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.mutable; import junit.framework.TestCase; /** * JUnit tests. * * @version $Id: MutableShortTest.java 905628 2010-02-02 13:29:55Z niallp $ * @see MutableShort */ public class MutableShortTest extends TestCase { public MutableShortTest(String testName) { super(testName); } // ---------------------------------------------------------------- public void testConstructors() { assertEquals((short) 0, new MutableShort().shortValue()); assertEquals((short) 1, new MutableShort((short) 1).shortValue()); assertEquals((short) 2, new MutableShort(new Short((short) 2)).shortValue()); assertEquals((short) 3, new MutableShort(new MutableShort((short) 3)).shortValue()); assertEquals((short) 2, new MutableShort("2").shortValue()); try { new MutableShort((Number)null); fail(); } catch (NullPointerException ex) {} } public void testGetSet() { final MutableShort mutNum = new MutableShort((short) 0); assertEquals((short) 0, new MutableShort().shortValue()); assertEquals(new Short((short) 0), new MutableShort().getValue()); mutNum.setValue((short) 1); assertEquals((short) 1, mutNum.shortValue()); assertEquals(new Short((short) 1), mutNum.getValue()); mutNum.setValue(new Short((short) 2)); assertEquals((short) 2, mutNum.shortValue()); assertEquals(new Short((short) 2), mutNum.getValue()); mutNum.setValue(new MutableShort((short) 3)); assertEquals((short) 3, mutNum.shortValue()); assertEquals(new Short((short) 3), mutNum.getValue()); try { mutNum.setValue(null); fail(); } catch (NullPointerException ex) {} try { mutNum.setValue("0"); fail(); } catch (ClassCastException ex) {} } public void testEquals() { final MutableShort mutNumA = new MutableShort((short) 0); final MutableShort mutNumB = new MutableShort((short) 0); final MutableShort mutNumC = new MutableShort((short) 1); assertEquals(true, mutNumA.equals(mutNumA)); assertEquals(true, mutNumA.equals(mutNumB)); assertEquals(true, mutNumB.equals(mutNumA)); assertEquals(true, mutNumB.equals(mutNumB)); assertEquals(false, mutNumA.equals(mutNumC)); assertEquals(false, mutNumB.equals(mutNumC)); assertEquals(true, mutNumC.equals(mutNumC)); assertEquals(false, mutNumA.equals(null)); assertEquals(false, mutNumA.equals(new Short((short) 0))); assertEquals(false, mutNumA.equals("0")); } public void testHashCode() { final MutableShort mutNumA = new MutableShort((short) 0); final MutableShort mutNumB = new MutableShort((short) 0); final MutableShort mutNumC = new MutableShort((short) 1); assertEquals(true, mutNumA.hashCode() == mutNumA.hashCode()); assertEquals(true, mutNumA.hashCode() == mutNumB.hashCode()); assertEquals(false, mutNumA.hashCode() == mutNumC.hashCode()); assertEquals(true, mutNumA.hashCode() == new Short((short) 0).hashCode()); } public void testCompareTo() { final MutableShort mutNum = new MutableShort((short) 0); assertEquals((short) 0, mutNum.compareTo(new MutableShort((short) 0))); assertEquals((short) +1, mutNum.compareTo(new MutableShort((short) -1))); assertEquals((short) -1, mutNum.compareTo(new MutableShort((short) 1))); try { mutNum.compareTo(null); fail(); } catch (NullPointerException ex) {} try { mutNum.compareTo(new Short((short) 0)); fail(); } catch (ClassCastException ex) {} try { mutNum.compareTo("0"); fail(); } catch (ClassCastException ex) {} } public void testPrimitiveValues() { MutableShort mutNum = new MutableShort( (short) 1 ); assertEquals( 1.0F, mutNum.floatValue(), 0 ); assertEquals( 1.0, mutNum.doubleValue(), 0 ); assertEquals( (byte) 1, mutNum.byteValue() ); assertEquals( (short) 1, mutNum.shortValue() ); assertEquals( 1, mutNum.intValue() ); assertEquals( 1L, mutNum.longValue() ); } public void testToShort() { assertEquals(new Short((short) 0), new MutableShort((short) 0).toShort()); assertEquals(new Short((short) 123), new MutableShort((short) 123).toShort()); } public void testIncrement() { MutableShort mutNum = new MutableShort((short) 1); mutNum.increment(); assertEquals(2, mutNum.intValue()); assertEquals(2L, mutNum.longValue()); } public void testDecrement() { MutableShort mutNum = new MutableShort((short) 1); mutNum.decrement(); assertEquals(0, mutNum.intValue()); assertEquals(0L, mutNum.longValue()); } public void testAddValuePrimitive() { MutableShort mutNum = new MutableShort((short) 1); mutNum.add((short) 1); assertEquals((short) 2, mutNum.shortValue()); } public void testAddValueObject() { MutableShort mutNum = new MutableShort((short) 1); mutNum.add(new Short((short) 1)); assertEquals((short) 2, mutNum.shortValue()); } public void testSubtractValuePrimitive() { MutableShort mutNum = new MutableShort((short) 1); mutNum.subtract((short) 1); assertEquals((short) 0, mutNum.shortValue()); } public void testSubtractValueObject() { MutableShort mutNum = new MutableShort((short) 1); mutNum.subtract(new Short((short) 1)); assertEquals((short) 0, mutNum.shortValue()); } public void testToString() { assertEquals("0", new MutableShort((short) 0).toString()); assertEquals("10", new MutableShort((short) 10).toString()); assertEquals("-123", new MutableShort((short) -123).toString()); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/NotImplementedExceptionTest.java100644 0 0 21535 11513702440 27313 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.reflect.Constructor; import junit.framework.TestCase; import org.apache.commons.lang.exception.NestableException; /** * JUnit tests. * * @author Matthew Hawthorne * @version $Id: NotImplementedExceptionTest.java 905628 2010-02-02 13:29:55Z niallp $ * @see NotImplementedException */ public class NotImplementedExceptionTest extends TestCase { public NotImplementedExceptionTest(String testName) { super(testName); } //----------------------------------------------------------------------- public void testConstructor_() { NotImplementedException ex = new NotImplementedException(); assertEquals("Code is not implemented", ex.getMessage()); assertEquals(null, ex.getCause()); assertEquals("Code is not implemented", ex.getMessage()); } public void testConstructor_String1() { NotImplementedException ex = new NotImplementedException((String) null); assertEquals("Code is not implemented", ex.getMessage()); assertEquals(null, ex.getCause()); assertEquals("Code is not implemented", ex.getMessage()); } public void testConstructor_String2() { NotImplementedException ex = new NotImplementedException("msg"); assertEquals("msg", ex.getMessage()); assertEquals(null, ex.getCause()); assertEquals("msg", ex.getMessage()); } public void testConstructor_Throwable1() { NotImplementedException ex = new NotImplementedException((Throwable) null); assertEquals("Code is not implemented", ex.getMessage()); assertEquals(null, ex.getCause()); assertEquals("Code is not implemented", ex.getMessage()); } public void testConstructor_Throwable2() { Exception npe = new NullPointerException(); NotImplementedException ex = new NotImplementedException(npe); assertEquals("Code is not implemented", ex.getMessage()); assertSame(npe, ex.getCause()); assertEquals("Code is not implemented", ex.getMessage()); } public void testConstructor_StringThrowable1() { NotImplementedException ex = new NotImplementedException((String) null, (Throwable) null); assertEquals("Code is not implemented", ex.getMessage()); assertEquals(null, ex.getCause()); assertEquals("Code is not implemented", ex.getMessage()); } public void testConstructor_StringThrowable2() { Exception npe = new NullPointerException(); NotImplementedException ex = new NotImplementedException("msg", npe); assertEquals("msg", ex.getMessage()); assertSame(npe, ex.getCause()); assertEquals("msg", ex.getMessage()); } public void testConstructor_Class1() { NotImplementedException ex = new NotImplementedException((Class) null); assertEquals("Code is not implemented", ex.getMessage()); assertEquals(null, ex.getCause()); assertEquals("Code is not implemented", ex.getMessage()); } public void testConstructor_Class2() { NotImplementedException ex = new NotImplementedException(String.class); assertEquals("Code is not implemented in class java.lang.String", ex.getMessage()); assertEquals(null, ex.getCause()); assertEquals("Code is not implemented in class java.lang.String", ex.getMessage()); } public void testGetMessage_Indexed() throws Exception { if (SystemUtils.isJavaVersionAtLeast(1.4f)) { Exception ex1 = new Exception("nested 2"); Constructor con = Exception.class.getConstructor(new Class[] {String.class, Throwable.class}); Exception ex2 = (Exception) con.newInstance(new Object[] {"nested 1", ex1}); NotImplementedException ex = new NotImplementedException(ex2); assertEquals("Code is not implemented", ex.getMessage()); assertEquals("Code is not implemented", ex.getMessage(0)); assertEquals("nested 1", ex.getMessage(1)); assertEquals("nested 2", ex.getMessage(2)); String[] messages = ex.getMessages(); assertEquals(3, messages.length); assertEquals("Code is not implemented", messages[0]); assertEquals("nested 1", messages[1]); assertEquals("nested 2", messages[2]); } } public void testGetThrowable() { NotImplementedException ex = new NotImplementedException(new NestableException("nested 1", new NestableException("nested 2"))); assertEquals(3, ex.getThrowableCount()); assertEquals(NotImplementedException.class, ex.getThrowable(0).getClass()); assertEquals("Code is not implemented", ex.getThrowable(0).getMessage()); assertEquals(NestableException.class, ex.getThrowable(1).getClass()); assertEquals("nested 1", ex.getThrowable(1).getMessage()); assertEquals(NestableException.class, ex.getThrowable(2).getClass()); assertEquals("nested 2", ex.getThrowable(2).getMessage()); assertEquals(3, ex.getThrowables().length); assertEquals(NotImplementedException.class, ex.getThrowables()[0].getClass()); assertEquals("Code is not implemented", ex.getThrowables()[0].getMessage()); assertEquals(NestableException.class, ex.getThrowables()[1].getClass()); assertEquals("nested 1", ex.getThrowables()[1].getMessage()); assertEquals(NestableException.class, ex.getThrowables()[2].getClass()); assertEquals("nested 2", ex.getThrowables()[2].getMessage()); } public void testIndexOfThrowable() { NotImplementedException ex = new NotImplementedException(new NestableException("nested 1", new NestableException("nested 2"))); assertEquals(0, ex.indexOfThrowable(NotImplementedException.class)); assertEquals(1, ex.indexOfThrowable(NestableException.class)); } public void testIndexOfThrowable_Index() { NotImplementedException ex = new NotImplementedException(new NestableException("nested 1", new NestableException("nested 2"))); assertEquals(1, ex.indexOfThrowable(NestableException.class, 1)); } public void testPrintStackTrace() { NotImplementedException ex = new NotImplementedException(new NestableException("nested 1", new NestableException("nested 2"))); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); PrintStream errStream = System.err; System.setErr(ps); ex.printStackTrace(); System.setErr(errStream); assertTrue(baos.toString().length() > 0); } public void testPrintStackTrace_Stream() { NotImplementedException ex = new NotImplementedException(new NestableException("nested 1", new NestableException("nested 2"))); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); ex.printStackTrace(ps); assertTrue(baos.toString().length() > 0); } public void testPrintStackTrace_Writer() { NotImplementedException ex = new NotImplementedException(new NestableException("nested 1", new NestableException("nested 2"))); StringWriter stringWriter = new StringWriter(); PrintWriter writer = new PrintWriter(stringWriter); ex.printStackTrace(writer); assertTrue(stringWriter.toString().length() > 0); } public void testPrintPartialStackTrace_Writer() { NotImplementedException ex = new NotImplementedException(new NestableException("nested 1", new NestableException("nested 2"))); StringWriter stringWriter = new StringWriter(); PrintWriter writer = new PrintWriter(stringWriter); ex.printPartialStackTrace(writer); assertTrue(stringWriter.toString().length() > 0); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/NullArgumentExceptionTest.java100644 0 0 3537 11513702440 26766 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang; import junit.framework.TestCase; /** * JUnit tests. * * @author Apache Software Foundation * @author Matthew Hawthorne * @version $Id: NullArgumentExceptionTest.java 905636 2010-02-02 14:03:32Z niallp $ * @see NullArgumentException */ public class NullArgumentExceptionTest extends TestCase { public NullArgumentExceptionTest(String testName) { super(testName); } // testConstructor public void testConstructor_nullInput() { new NullArgumentException(null); } // testGetMessage public void testGetMessage_nullConstructorInput() { final Throwable t = new NullArgumentException(null); assertEquals("Argument must not be null.", t.getMessage()); } public void testGetMessage_validConstructorInput() { final String argName = "name"; final Throwable t = new NullArgumentException(argName); assertEquals(argName + " must not be null.", t.getMessage()); } } // NullArgumentExceptionTest commons-lang-2.6-src/src/test/java/org/apache/commons/lang/NumberRangeTest.java100644 0 0 21045 11513702440 24711 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang; import junit.framework.TestCase; /** * Test cases for the {@link NumberRange} class. * * @author Christopher Elkins * @author Ringo De Smet * @author Tim O'Brien * @version $Revision: 905628 $ $Date: 2010-02-02 13:29:55 +0000 (Tue, 02 Feb 2010) $ */ public final class NumberRangeTest extends TestCase { private NumberRange tenToTwenty; private NumberRange fifteenToTwentyFive; private NumberRange fiveToNine; private Number five; private Number nine; private Number ten; private Number fifteen; private Number twenty; private Number twentyFive; public NumberRangeTest(String name) { super(name); } public void setUp() { five = new Integer(5); nine = new Double(9.0); ten = new Integer(10); fifteen = new Integer(15); twenty = new Integer(20); twentyFive = new Integer(25); tenToTwenty = new NumberRange(ten, twenty); fifteenToTwentyFive = new NumberRange( fifteen, twentyFive); fiveToNine = new NumberRange( five, nine ); } public void testMaxMin() { boolean expected = true; boolean result = tenToTwenty.getMaximum().equals(twenty); assertEquals(expected, result); expected = true; result = tenToTwenty.getMinimum().equals(ten); assertEquals(expected, result); } public void testEquals() { boolean expected = false; boolean result = tenToTwenty.equals(new NumberRange(five, ten)); assertEquals(expected, result); expected = true; result = tenToTwenty.equals(new NumberRange(ten, twenty)); assertEquals(expected, result); expected = false; result = tenToTwenty.equals(new NumberRange(ten, fifteen)); assertEquals(expected, result); expected = false; result = tenToTwenty.equals(new NumberRange(fifteen, twenty)); assertEquals(expected, result); } public void testEqualsWithOtherObject() { assertEquals( "A NumberRange should not equals a String object", false, fiveToNine.equals("TEST")); } public void testEqualsWithSameReference() { assertEquals( "A NumberRange should equal itself", true, fiveToNine.equals(fiveToNine)); } public void testEqualsNull() { assertEquals( "A NumberRange should not equal null", false, fiveToNine.equals(null)); } public void testHashCode() { NumberRange nr = new NumberRange( new Integer(5), new Double(9.0)); assertEquals( "The hashCode of 5-9 should equals the hashcode of another NumberRange of the same min/max", fiveToNine.hashCode(), nr.hashCode()); assertTrue( "The hashCode of 10-20 should not equal the hashCode of 5-9", fiveToNine.hashCode() != tenToTwenty.hashCode()); } public void testIncludesNumber() { boolean expected = false; boolean result = tenToTwenty.includesNumber(five); assertEquals(expected, result); expected = true; result = tenToTwenty.includesNumber(ten); assertEquals(expected, result); expected = true; result = tenToTwenty.includesNumber(fifteen); assertEquals(expected, result); expected = true; result = tenToTwenty.includesNumber(twenty); assertEquals(expected, result); expected = false; result = tenToTwenty.includesNumber(twentyFive); assertEquals(expected, result); } public void testIncludesNumberNull() { boolean result = tenToTwenty.includesNumber(null); assertEquals("Includes number should return false for null values", false, result); } public void testIncludesRange() { boolean expected = false; boolean result = tenToTwenty.includesRange(new NumberRange(five, ten)); assertEquals(expected, result); expected = false; result = tenToTwenty.includesRange(new NumberRange(five, fifteen)); assertEquals(expected, result); expected = true; result = tenToTwenty.includesRange(new NumberRange(ten, fifteen)); assertEquals(expected, result); expected = true; result = tenToTwenty.includesRange(new NumberRange(ten, twenty)); assertEquals(expected, result); expected = true; result = tenToTwenty.includesRange(new NumberRange(fifteen, twenty)); assertEquals(expected, result); expected = false; result = tenToTwenty.includesRange(new NumberRange(fifteen, twentyFive)); assertEquals(expected, result); expected = false; result = tenToTwenty.includesRange(new NumberRange(twenty, twentyFive)); assertEquals(expected, result); } public void testIncludesRangeNull() { boolean result = tenToTwenty.includesRange(null); assertEquals("Includes range should return false for null values", false, result); } public void testConstructor() { NumberRange nr = new NumberRange( new Double(2.0)); assertEquals("Unexpected min on NumberRange", 2.0, nr.getMinimum().doubleValue(), Double.MIN_VALUE); assertEquals("Unexpected max on NumberRange", 2.0, nr.getMaximum().doubleValue(), Double.MIN_VALUE); } public void testConstructorNullParameters() { try { NumberRange nr = new NumberRange(null); fail("NumberRange(null) did not throw an exception."); } catch (Exception e) { assertTrue( "NumberRange(null)", e instanceof NullPointerException); } try { NumberRange nr = new NumberRange(five, null); fail("NumberRange(five, null) did not throw an exception."); } catch (Exception e) { assertTrue("NumberRange(five, null)", e instanceof NullPointerException); } try { NumberRange nr = new NumberRange(null, five); fail("NumberRange(null, five) did not throw an exception."); } catch (Exception e) { assertTrue("NumberRange(null, five)", e instanceof NullPointerException); } } public void testConstructorWithMaxLessThanMin() { NumberRange nr = new NumberRange( new Double(2.0), new Double(1.0)); assertEquals("Unexpected min on NumberRange", 2.0, nr.getMinimum().doubleValue(), Double.MIN_VALUE); assertEquals("Unexpected max on NumberRange", 2.0, nr.getMaximum().doubleValue(), Double.MIN_VALUE); } public void testOverlap() { assertEquals( "5-9 should not overlap 10-20", false, fiveToNine.overlaps( tenToTwenty )); assertEquals( "10-20 should overlap 15-25", true, tenToTwenty.overlaps( fifteenToTwentyFive )); } public void testOverlapNull() { assertEquals( "5-9 should not overlap null", false, fiveToNine.overlaps( null )); } public void testToString() { String expected = "10-20"; String result = tenToTwenty.toString(); assertEquals(expected, result); } public void testToStringWithNegatives() { String expected = "(-20)-(-10)"; NumberRange nr = new NumberRange( new Integer(-20), new Integer(-10)); String result = nr.toString(); assertEquals(expected, result); expected = "(-20)-10"; nr = new NumberRange( new Integer(-20), new Integer(10)); result = nr.toString(); assertEquals(expected, result); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/NumberUtilsTest.java100644 0 0 75774 11513702441 25000 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang; import java.math.BigDecimal; import java.math.BigInteger; import junit.framework.TestCase; /** * Unit tests {@link org.apache.commons.lang.NumberUtils}. * * @author Apache Software Foundation * @author Rand McNeely * @author Ringo De Smet * @author Eric Pugh * @author Phil Steitz * @version $Id: NumberUtilsTest.java 905636 2010-02-02 14:03:32Z niallp $ */ public class NumberUtilsTest extends TestCase { public NumberUtilsTest(String name) { super(name); } //--------------------------------------------------------------------- /** * Test for int stringToInt(String) */ public void testStringToIntString() { assertTrue("stringToInt(String) 1 failed", NumberUtils.stringToInt("12345") == 12345); assertTrue("stringToInt(String) 2 failed", NumberUtils.stringToInt("abc") == 0); } /** * Test for int stringToInt(String, int) */ public void testStringToIntStringI() { assertTrue("stringToInt(String,int) 1 failed", NumberUtils.stringToInt("12345", 5) == 12345); assertTrue("stringToInt(String,int) 2 failed", NumberUtils.stringToInt("1234.5", 5) == 5); } public void testCreateNumber() { //a lot of things can go wrong assertEquals("createNumber(String) 1 failed", new Float("1234.5"), NumberUtils.createNumber("1234.5")); assertEquals("createNumber(String) 2 failed", new Integer("12345"), NumberUtils.createNumber("12345")); assertEquals("createNumber(String) 3 failed", new Double("1234.5"), NumberUtils.createNumber("1234.5D")); assertEquals("createNumber(String) 4 failed", new Float("1234.5"), NumberUtils.createNumber("1234.5F")); assertEquals("createNumber(String) 5 failed", new Long(Integer.MAX_VALUE + 1L), NumberUtils.createNumber("" + (Integer.MAX_VALUE + 1L))); assertEquals("createNumber(String) 6 failed", new BigInteger(Long.MAX_VALUE + "0"), NumberUtils.createNumber(Long.MAX_VALUE + "0L")); assertEquals("createNumber(String) 7 failed", new Long(12345), NumberUtils.createNumber("12345L")); assertEquals("createNumber(String) 8 failed", new Float("-1234.5"), NumberUtils.createNumber("-1234.5")); assertEquals("createNumber(String) 9 failed", new Integer("-12345"), NumberUtils.createNumber("-12345")); assertTrue("createNumber(String) 10 failed", 0xFADE == NumberUtils.createNumber("0xFADE").intValue()); assertTrue("createNumber(String) 11 failed", -0xFADE == NumberUtils.createNumber("-0xFADE").intValue()); assertEquals("createNumber(String) 12 failed", new Double("1.1E200"), NumberUtils.createNumber("1.1E200")); assertEquals("createNumber(String) 13 failed", new Float("1.1E20"), NumberUtils.createNumber("1.1E20")); assertEquals("createNumber(String) 14 failed", new Double("-1.1E200"), NumberUtils.createNumber("-1.1E200")); assertEquals("createNumber(String) 15 failed", new Double("1.1E-200"), NumberUtils.createNumber("1.1E-200")); assertEquals("createNumber(String) 16 failed", new Double("1.1E-200"), NumberUtils.createNumber("1.1E-200")); // jdk 1.2 doesn't support this. unsure about jdk 1.2.2 if(SystemUtils.isJavaVersionAtLeast(1.3f)) { assertEquals("createNumber(String) 15 failed", new BigDecimal("1.1E-700"), NumberUtils.createNumber("1.1E-700F")); } assertEquals( "createNumber(String) 16 failed", new Long("10" + Integer.MAX_VALUE), NumberUtils.createNumber("10" + Integer.MAX_VALUE + "L")); assertEquals( "createNumber(String) 17 failed", new Long("10" + Integer.MAX_VALUE), NumberUtils.createNumber("10" + Integer.MAX_VALUE)); assertEquals( "createNumber(String) 18 failed", new BigInteger("10" + Long.MAX_VALUE), NumberUtils.createNumber("10" + Long.MAX_VALUE)); } public void testCreateFloat() { assertEquals("createFloat(String) failed", new Float("1234.5"), NumberUtils.createFloat("1234.5")); } public void testCreateDouble() { assertEquals("createDouble(String) failed", new Double("1234.5"), NumberUtils.createDouble("1234.5")); } public void testCreateInteger() { assertEquals("createInteger(String) failed", new Integer("12345"), NumberUtils.createInteger("12345")); } public void testCreateLong() { assertEquals("createInteger(String) failed", new Long("12345"), NumberUtils.createLong("12345")); } public void testCreateBigInteger() { assertEquals("createBigInteger(String) failed", new BigInteger("12345"), NumberUtils.createBigInteger("12345")); } public void testCreateBigDecimal() { assertEquals("createBigDecimal(String) failed", new BigDecimal("1234.5"), NumberUtils.createBigDecimal("1234.5")); } public void testMinimumLong() { assertEquals("minimum(long,long,long) 1 failed", 12345L, NumberUtils.minimum(12345L, 12345L + 1L, 12345L + 2L)); assertEquals("minimum(long,long,long) 2 failed", 12345L, NumberUtils.minimum(12345L + 1L, 12345L, 12345 + 2L)); assertEquals("minimum(long,long,long) 3 failed", 12345L, NumberUtils.minimum(12345L + 1L, 12345L + 2L, 12345L)); assertEquals("minimum(long,long,long) 4 failed", 12345L, NumberUtils.minimum(12345L + 1L, 12345L, 12345L)); assertEquals("minimum(long,long,long) 5 failed", 12345L, NumberUtils.minimum(12345L, 12345L, 12345L)); } public void testMinimumInt() { assertEquals("minimum(int,int,int) 1 failed", 12345, NumberUtils.minimum(12345, 12345 + 1, 12345 + 2)); assertEquals("minimum(int,int,int) 2 failed", 12345, NumberUtils.minimum(12345 + 1, 12345, 12345 + 2)); assertEquals("minimum(int,int,int) 3 failed", 12345, NumberUtils.minimum(12345 + 1, 12345 + 2, 12345)); assertEquals("minimum(int,int,int) 4 failed", 12345, NumberUtils.minimum(12345 + 1, 12345, 12345)); assertEquals("minimum(int,int,int) 5 failed", 12345, NumberUtils.minimum(12345, 12345, 12345)); } public void testMaximumLong() { assertEquals("maximum(long,long,long) 1 failed", 12345L, NumberUtils.maximum(12345L, 12345L - 1L, 12345L - 2L)); assertEquals("maximum(long,long,long) 2 failed", 12345L, NumberUtils.maximum(12345L - 1L, 12345L, 12345L - 2L)); assertEquals("maximum(long,long,long) 3 failed", 12345L, NumberUtils.maximum(12345L - 1L, 12345L - 2L, 12345L)); assertEquals("maximum(long,long,long) 4 failed", 12345L, NumberUtils.maximum(12345L - 1L, 12345L, 12345L)); assertEquals("maximum(long,long,long) 5 failed", 12345L, NumberUtils.maximum(12345L, 12345L, 12345L)); } public void testMaximumInt() { assertEquals("maximum(int,int,int) 1 failed", 12345, NumberUtils.maximum(12345, 12345 - 1, 12345 - 2)); assertEquals("maximum(int,int,int) 2 failed", 12345, NumberUtils.maximum(12345 - 1, 12345, 12345 - 2)); assertEquals("maximum(int,int,int) 3 failed", 12345, NumberUtils.maximum(12345 - 1, 12345 - 2, 12345)); assertEquals("maximum(int,int,int) 4 failed", 12345, NumberUtils.maximum(12345 - 1, 12345, 12345)); assertEquals("maximum(int,int,int) 5 failed", 12345, NumberUtils.maximum(12345, 12345, 12345)); } public void testCompareDouble() { assertTrue(NumberUtils.compare(Double.NaN, Double.NaN) == 0); assertTrue(NumberUtils.compare(Double.NaN, Double.POSITIVE_INFINITY) == +1); assertTrue(NumberUtils.compare(Double.NaN, Double.MAX_VALUE) == +1); assertTrue(NumberUtils.compare(Double.NaN, 1.2d) == +1); assertTrue(NumberUtils.compare(Double.NaN, 0.0d) == +1); assertTrue(NumberUtils.compare(Double.NaN, -0.0d) == +1); assertTrue(NumberUtils.compare(Double.NaN, -1.2d) == +1); assertTrue(NumberUtils.compare(Double.NaN, -Double.MAX_VALUE) == +1); assertTrue(NumberUtils.compare(Double.NaN, Double.NEGATIVE_INFINITY) == +1); assertTrue(NumberUtils.compare(Double.POSITIVE_INFINITY, Double.NaN) == -1); assertTrue(NumberUtils.compare(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY) == 0); assertTrue(NumberUtils.compare(Double.POSITIVE_INFINITY, Double.MAX_VALUE) == +1); assertTrue(NumberUtils.compare(Double.POSITIVE_INFINITY, 1.2d) == +1); assertTrue(NumberUtils.compare(Double.POSITIVE_INFINITY, 0.0d) == +1); assertTrue(NumberUtils.compare(Double.POSITIVE_INFINITY, -0.0d) == +1); assertTrue(NumberUtils.compare(Double.POSITIVE_INFINITY, -1.2d) == +1); assertTrue(NumberUtils.compare(Double.POSITIVE_INFINITY, -Double.MAX_VALUE) == +1); assertTrue(NumberUtils.compare(Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY) == +1); assertTrue(NumberUtils.compare(Double.MAX_VALUE, Double.NaN) == -1); assertTrue(NumberUtils.compare(Double.MAX_VALUE, Double.POSITIVE_INFINITY) == -1); assertTrue(NumberUtils.compare(Double.MAX_VALUE, Double.MAX_VALUE) == 0); assertTrue(NumberUtils.compare(Double.MAX_VALUE, 1.2d) == +1); assertTrue(NumberUtils.compare(Double.MAX_VALUE, 0.0d) == +1); assertTrue(NumberUtils.compare(Double.MAX_VALUE, -0.0d) == +1); assertTrue(NumberUtils.compare(Double.MAX_VALUE, -1.2d) == +1); assertTrue(NumberUtils.compare(Double.MAX_VALUE, -Double.MAX_VALUE) == +1); assertTrue(NumberUtils.compare(Double.MAX_VALUE, Double.NEGATIVE_INFINITY) == +1); assertTrue(NumberUtils.compare(1.2d, Double.NaN) == -1); assertTrue(NumberUtils.compare(1.2d, Double.POSITIVE_INFINITY) == -1); assertTrue(NumberUtils.compare(1.2d, Double.MAX_VALUE) == -1); assertTrue(NumberUtils.compare(1.2d, 1.2d) == 0); assertTrue(NumberUtils.compare(1.2d, 0.0d) == +1); assertTrue(NumberUtils.compare(1.2d, -0.0d) == +1); assertTrue(NumberUtils.compare(1.2d, -1.2d) == +1); assertTrue(NumberUtils.compare(1.2d, -Double.MAX_VALUE) == +1); assertTrue(NumberUtils.compare(1.2d, Double.NEGATIVE_INFINITY) == +1); assertTrue(NumberUtils.compare(0.0d, Double.NaN) == -1); assertTrue(NumberUtils.compare(0.0d, Double.POSITIVE_INFINITY) == -1); assertTrue(NumberUtils.compare(0.0d, Double.MAX_VALUE) == -1); assertTrue(NumberUtils.compare(0.0d, 1.2d) == -1); assertTrue(NumberUtils.compare(0.0d, 0.0d) == 0); assertTrue(NumberUtils.compare(0.0d, -0.0d) == +1); assertTrue(NumberUtils.compare(0.0d, -1.2d) == +1); assertTrue(NumberUtils.compare(0.0d, -Double.MAX_VALUE) == +1); assertTrue(NumberUtils.compare(0.0d, Double.NEGATIVE_INFINITY) == +1); assertTrue(NumberUtils.compare(-0.0d, Double.NaN) == -1); assertTrue(NumberUtils.compare(-0.0d, Double.POSITIVE_INFINITY) == -1); assertTrue(NumberUtils.compare(-0.0d, Double.MAX_VALUE) == -1); assertTrue(NumberUtils.compare(-0.0d, 1.2d) == -1); assertTrue(NumberUtils.compare(-0.0d, 0.0d) == -1); assertTrue(NumberUtils.compare(-0.0d, -0.0d) == 0); assertTrue(NumberUtils.compare(-0.0d, -1.2d) == +1); assertTrue(NumberUtils.compare(-0.0d, -Double.MAX_VALUE) == +1); assertTrue(NumberUtils.compare(-0.0d, Double.NEGATIVE_INFINITY) == +1); assertTrue(NumberUtils.compare(-1.2d, Double.NaN) == -1); assertTrue(NumberUtils.compare(-1.2d, Double.POSITIVE_INFINITY) == -1); assertTrue(NumberUtils.compare(-1.2d, Double.MAX_VALUE) == -1); assertTrue(NumberUtils.compare(-1.2d, 1.2d) == -1); assertTrue(NumberUtils.compare(-1.2d, 0.0d) == -1); assertTrue(NumberUtils.compare(-1.2d, -0.0d) == -1); assertTrue(NumberUtils.compare(-1.2d, -1.2d) == 0); assertTrue(NumberUtils.compare(-1.2d, -Double.MAX_VALUE) == +1); assertTrue(NumberUtils.compare(-1.2d, Double.NEGATIVE_INFINITY) == +1); assertTrue(NumberUtils.compare(-Double.MAX_VALUE, Double.NaN) == -1); assertTrue(NumberUtils.compare(-Double.MAX_VALUE, Double.POSITIVE_INFINITY) == -1); assertTrue(NumberUtils.compare(-Double.MAX_VALUE, Double.MAX_VALUE) == -1); assertTrue(NumberUtils.compare(-Double.MAX_VALUE, 1.2d) == -1); assertTrue(NumberUtils.compare(-Double.MAX_VALUE, 0.0d) == -1); assertTrue(NumberUtils.compare(-Double.MAX_VALUE, -0.0d) == -1); assertTrue(NumberUtils.compare(-Double.MAX_VALUE, -1.2d) == -1); assertTrue(NumberUtils.compare(-Double.MAX_VALUE, -Double.MAX_VALUE) == 0); assertTrue(NumberUtils.compare(-Double.MAX_VALUE, Double.NEGATIVE_INFINITY) == +1); assertTrue(NumberUtils.compare(Double.NEGATIVE_INFINITY, Double.NaN) == -1); assertTrue(NumberUtils.compare(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY) == -1); assertTrue(NumberUtils.compare(Double.NEGATIVE_INFINITY, Double.MAX_VALUE) == -1); assertTrue(NumberUtils.compare(Double.NEGATIVE_INFINITY, 1.2d) == -1); assertTrue(NumberUtils.compare(Double.NEGATIVE_INFINITY, 0.0d) == -1); assertTrue(NumberUtils.compare(Double.NEGATIVE_INFINITY, -0.0d) == -1); assertTrue(NumberUtils.compare(Double.NEGATIVE_INFINITY, -1.2d) == -1); assertTrue(NumberUtils.compare(Double.NEGATIVE_INFINITY, -Double.MAX_VALUE) == -1); assertTrue(NumberUtils.compare(Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY) == 0); } public void testCompareFloat() { assertTrue(NumberUtils.compare(Float.NaN, Float.NaN) == 0); assertTrue(NumberUtils.compare(Float.NaN, Float.POSITIVE_INFINITY) == +1); assertTrue(NumberUtils.compare(Float.NaN, Float.MAX_VALUE) == +1); assertTrue(NumberUtils.compare(Float.NaN, 1.2f) == +1); assertTrue(NumberUtils.compare(Float.NaN, 0.0f) == +1); assertTrue(NumberUtils.compare(Float.NaN, -0.0f) == +1); assertTrue(NumberUtils.compare(Float.NaN, -1.2f) == +1); assertTrue(NumberUtils.compare(Float.NaN, -Float.MAX_VALUE) == +1); assertTrue(NumberUtils.compare(Float.NaN, Float.NEGATIVE_INFINITY) == +1); assertTrue(NumberUtils.compare(Float.POSITIVE_INFINITY, Float.NaN) == -1); assertTrue(NumberUtils.compare(Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY) == 0); assertTrue(NumberUtils.compare(Float.POSITIVE_INFINITY, Float.MAX_VALUE) == +1); assertTrue(NumberUtils.compare(Float.POSITIVE_INFINITY, 1.2f) == +1); assertTrue(NumberUtils.compare(Float.POSITIVE_INFINITY, 0.0f) == +1); assertTrue(NumberUtils.compare(Float.POSITIVE_INFINITY, -0.0f) == +1); assertTrue(NumberUtils.compare(Float.POSITIVE_INFINITY, -1.2f) == +1); assertTrue(NumberUtils.compare(Float.POSITIVE_INFINITY, -Float.MAX_VALUE) == +1); assertTrue(NumberUtils.compare(Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY) == +1); assertTrue(NumberUtils.compare(Float.MAX_VALUE, Float.NaN) == -1); assertTrue(NumberUtils.compare(Float.MAX_VALUE, Float.POSITIVE_INFINITY) == -1); assertTrue(NumberUtils.compare(Float.MAX_VALUE, Float.MAX_VALUE) == 0); assertTrue(NumberUtils.compare(Float.MAX_VALUE, 1.2f) == +1); assertTrue(NumberUtils.compare(Float.MAX_VALUE, 0.0f) == +1); assertTrue(NumberUtils.compare(Float.MAX_VALUE, -0.0f) == +1); assertTrue(NumberUtils.compare(Float.MAX_VALUE, -1.2f) == +1); assertTrue(NumberUtils.compare(Float.MAX_VALUE, -Float.MAX_VALUE) == +1); assertTrue(NumberUtils.compare(Float.MAX_VALUE, Float.NEGATIVE_INFINITY) == +1); assertTrue(NumberUtils.compare(1.2f, Float.NaN) == -1); assertTrue(NumberUtils.compare(1.2f, Float.POSITIVE_INFINITY) == -1); assertTrue(NumberUtils.compare(1.2f, Float.MAX_VALUE) == -1); assertTrue(NumberUtils.compare(1.2f, 1.2f) == 0); assertTrue(NumberUtils.compare(1.2f, 0.0f) == +1); assertTrue(NumberUtils.compare(1.2f, -0.0f) == +1); assertTrue(NumberUtils.compare(1.2f, -1.2f) == +1); assertTrue(NumberUtils.compare(1.2f, -Float.MAX_VALUE) == +1); assertTrue(NumberUtils.compare(1.2f, Float.NEGATIVE_INFINITY) == +1); assertTrue(NumberUtils.compare(0.0f, Float.NaN) == -1); assertTrue(NumberUtils.compare(0.0f, Float.POSITIVE_INFINITY) == -1); assertTrue(NumberUtils.compare(0.0f, Float.MAX_VALUE) == -1); assertTrue(NumberUtils.compare(0.0f, 1.2f) == -1); assertTrue(NumberUtils.compare(0.0f, 0.0f) == 0); assertTrue(NumberUtils.compare(0.0f, -0.0f) == +1); assertTrue(NumberUtils.compare(0.0f, -1.2f) == +1); assertTrue(NumberUtils.compare(0.0f, -Float.MAX_VALUE) == +1); assertTrue(NumberUtils.compare(0.0f, Float.NEGATIVE_INFINITY) == +1); assertTrue(NumberUtils.compare(-0.0f, Float.NaN) == -1); assertTrue(NumberUtils.compare(-0.0f, Float.POSITIVE_INFINITY) == -1); assertTrue(NumberUtils.compare(-0.0f, Float.MAX_VALUE) == -1); assertTrue(NumberUtils.compare(-0.0f, 1.2f) == -1); assertTrue(NumberUtils.compare(-0.0f, 0.0f) == -1); assertTrue(NumberUtils.compare(-0.0f, -0.0f) == 0); assertTrue(NumberUtils.compare(-0.0f, -1.2f) == +1); assertTrue(NumberUtils.compare(-0.0f, -Float.MAX_VALUE) == +1); assertTrue(NumberUtils.compare(-0.0f, Float.NEGATIVE_INFINITY) == +1); assertTrue(NumberUtils.compare(-1.2f, Float.NaN) == -1); assertTrue(NumberUtils.compare(-1.2f, Float.POSITIVE_INFINITY) == -1); assertTrue(NumberUtils.compare(-1.2f, Float.MAX_VALUE) == -1); assertTrue(NumberUtils.compare(-1.2f, 1.2f) == -1); assertTrue(NumberUtils.compare(-1.2f, 0.0f) == -1); assertTrue(NumberUtils.compare(-1.2f, -0.0f) == -1); assertTrue(NumberUtils.compare(-1.2f, -1.2f) == 0); assertTrue(NumberUtils.compare(-1.2f, -Float.MAX_VALUE) == +1); assertTrue(NumberUtils.compare(-1.2f, Float.NEGATIVE_INFINITY) == +1); assertTrue(NumberUtils.compare(-Float.MAX_VALUE, Float.NaN) == -1); assertTrue(NumberUtils.compare(-Float.MAX_VALUE, Float.POSITIVE_INFINITY) == -1); assertTrue(NumberUtils.compare(-Float.MAX_VALUE, Float.MAX_VALUE) == -1); assertTrue(NumberUtils.compare(-Float.MAX_VALUE, 1.2f) == -1); assertTrue(NumberUtils.compare(-Float.MAX_VALUE, 0.0f) == -1); assertTrue(NumberUtils.compare(-Float.MAX_VALUE, -0.0f) == -1); assertTrue(NumberUtils.compare(-Float.MAX_VALUE, -1.2f) == -1); assertTrue(NumberUtils.compare(-Float.MAX_VALUE, -Float.MAX_VALUE) == 0); assertTrue(NumberUtils.compare(-Float.MAX_VALUE, Float.NEGATIVE_INFINITY) == +1); assertTrue(NumberUtils.compare(Float.NEGATIVE_INFINITY, Float.NaN) == -1); assertTrue(NumberUtils.compare(Float.NEGATIVE_INFINITY, Float.POSITIVE_INFINITY) == -1); assertTrue(NumberUtils.compare(Float.NEGATIVE_INFINITY, Float.MAX_VALUE) == -1); assertTrue(NumberUtils.compare(Float.NEGATIVE_INFINITY, 1.2f) == -1); assertTrue(NumberUtils.compare(Float.NEGATIVE_INFINITY, 0.0f) == -1); assertTrue(NumberUtils.compare(Float.NEGATIVE_INFINITY, -0.0f) == -1); assertTrue(NumberUtils.compare(Float.NEGATIVE_INFINITY, -1.2f) == -1); assertTrue(NumberUtils.compare(Float.NEGATIVE_INFINITY, -Float.MAX_VALUE) == -1); assertTrue(NumberUtils.compare(Float.NEGATIVE_INFINITY, Float.NEGATIVE_INFINITY) == 0); } public void testIsDigits() { assertEquals("isDigits(null) failed", false, NumberUtils.isDigits(null)); assertEquals("isDigits('') failed", false, NumberUtils.isDigits("")); assertEquals("isDigits(String) failed", true, NumberUtils.isDigits("12345")); assertEquals("isDigits(String) neg 1 failed", false, NumberUtils.isDigits("1234.5")); assertEquals("isDigits(String) neg 3 failed", false, NumberUtils.isDigits("1ab")); assertEquals("isDigits(String) neg 4 failed", false, NumberUtils.isDigits("abc")); } /** * Tests isNumber(String) and tests that createNumber(String) returns * a valid number iff isNumber(String) returns false. */ public void testIsNumber() { String val = "12345"; assertTrue("isNumber(String) 1 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 1 failed", checkCreateNumber(val)); val = "1234.5"; assertTrue("isNumber(String) 2 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 2 failed", checkCreateNumber(val)); val = ".12345"; assertTrue("isNumber(String) 3 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 3 failed", checkCreateNumber(val)); val = "1234E5"; assertTrue("isNumber(String) 4 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 4 failed", checkCreateNumber(val)); val = "1234E+5"; assertTrue("isNumber(String) 5 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 5 failed", checkCreateNumber(val)); val = "1234E-5"; assertTrue("isNumber(String) 6 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 6 failed", checkCreateNumber(val)); val = "123.4E5"; assertTrue("isNumber(String) 7 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 7 failed", checkCreateNumber(val)); val = "-1234"; assertTrue("isNumber(String) 8 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 8 failed", checkCreateNumber(val)); val = "-1234.5"; assertTrue("isNumber(String) 9 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 9 failed", checkCreateNumber(val)); val = "-.12345"; assertTrue("isNumber(String) 10 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 10 failed", checkCreateNumber(val)); val = "-1234E5"; assertTrue("isNumber(String) 11 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 11 failed", checkCreateNumber(val)); val = "0"; assertTrue("isNumber(String) 12 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 12 failed", checkCreateNumber(val)); val = "-0"; assertTrue("isNumber(String) 13 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 13 failed", checkCreateNumber(val)); val = "01234"; assertTrue("isNumber(String) 14 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 14 failed", checkCreateNumber(val)); val = "-01234"; assertTrue("isNumber(String) 15 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 15 failed", checkCreateNumber(val)); val = "0xABC123"; assertTrue("isNumber(String) 16 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 16 failed", checkCreateNumber(val)); val = "0x0"; assertTrue("isNumber(String) 17 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 17 failed", checkCreateNumber(val)); val = "123.4E21D"; assertTrue("isNumber(String) 19 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 19 failed", checkCreateNumber(val)); val = "-221.23F"; assertTrue("isNumber(String) 20 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 20 failed", checkCreateNumber(val)); val = "22338L"; assertTrue("isNumber(String) 21 failed", NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 21 failed", checkCreateNumber(val)); val = null; assertTrue("isNumber(String) 1 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 1 Neg failed", !checkCreateNumber(val)); val = ""; assertTrue("isNumber(String) 2 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 2 Neg failed", !checkCreateNumber(val)); val = "--2.3"; assertTrue("isNumber(String) 3 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 3 Neg failed", !checkCreateNumber(val)); val = ".12.3"; assertTrue("isNumber(String) 4 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 4 Neg failed", !checkCreateNumber(val)); val = "-123E"; assertTrue("isNumber(String) 5 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 5 Neg failed", !checkCreateNumber(val)); val = "-123E+-212"; assertTrue("isNumber(String) 6 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 6 Neg failed", !checkCreateNumber(val)); val = "-123E2.12"; assertTrue("isNumber(String) 7 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 7 Neg failed", !checkCreateNumber(val)); val = "0xGF"; assertTrue("isNumber(String) 8 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 8 Neg failed", !checkCreateNumber(val)); val = "0xFAE-1"; assertTrue("isNumber(String) 9 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 9 Neg failed", !checkCreateNumber(val)); val = "."; assertTrue("isNumber(String) 10 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 10 Neg failed", !checkCreateNumber(val)); val = "-0ABC123"; assertTrue("isNumber(String) 11 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 11 Neg failed", !checkCreateNumber(val)); val = "123.4E-D"; assertTrue("isNumber(String) 12 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 12 Neg failed", !checkCreateNumber(val)); val = "123.4ED"; assertTrue("isNumber(String) 13 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 13 Neg failed", !checkCreateNumber(val)); val = "1234E5l"; assertTrue("isNumber(String) 14 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 14 Neg failed", !checkCreateNumber(val)); val = "11a"; assertTrue("isNumber(String) 15 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 15 Neg failed", !checkCreateNumber(val)); val = "1a"; assertTrue("isNumber(String) 16 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 16 Neg failed", !checkCreateNumber(val)); val = "a"; assertTrue("isNumber(String) 17 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 17 Neg failed", !checkCreateNumber(val)); val = "11g"; assertTrue("isNumber(String) 18 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 18 Neg failed", !checkCreateNumber(val)); val = "11z"; assertTrue("isNumber(String) 19 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 19 Neg failed", !checkCreateNumber(val)); val = "11def"; assertTrue("isNumber(String) 20 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 20 Neg failed", !checkCreateNumber(val)); val = "11d11"; assertTrue("isNumber(String) 21 Neg failed", !NumberUtils.isNumber(val)); assertTrue("isNumber(String)/createNumber(String) 21 Neg failed", !checkCreateNumber(val)); } public void testIsNumberInvalidInput() { String val = "0x"; assertEquals("isNumber() with 0x wasn't false", false, NumberUtils.isNumber(val)); val = "0x3x3"; assertEquals("isNumber() with 0x3x3 wasn't false", false, NumberUtils.isNumber(val)); val = "20EE-3"; assertEquals("isNumber() with 20EE-3 wasn't false", false, NumberUtils.isNumber(val)); val = "2435q"; assertEquals("isNumber() with 2435q wasn't false", false, NumberUtils.isNumber(val)); val = "."; assertEquals("isNumber() with . wasn't false", false, NumberUtils.isNumber(val)); } private boolean checkCreateNumber(String val) { try { Object obj = NumberUtils.createNumber(val); if (obj == null) { return false; } return true; } catch (NumberFormatException e) { return false; } catch (NullPointerException e) { return false; } } public void testPublicNoArgConstructor() { try { NumberUtils nu = new NumberUtils(); } catch( Exception e ) { fail( "Error calling public no-arg constructor" ); } } public void testLang457() { String[] badInputs = new String[] { "l", "L", "f", "F", "junk", "bobL"}; for(int i=0; iJohn McNally * @author Ringo De Smet * @author Gary Gregory * @version $Id: ObjectUtilsTest.java 1057423 2011-01-11 00:20:38Z niallp $ */ public class ObjectUtilsTest extends TestCase { private static final String FOO = "foo"; private static final String BAR = "bar"; public ObjectUtilsTest(String name) { super(name); } //----------------------------------------------------------------------- public void testConstructor() { assertNotNull(new ObjectUtils()); Constructor[] cons = ObjectUtils.class.getDeclaredConstructors(); assertEquals(1, cons.length); assertEquals(true, Modifier.isPublic(cons[0].getModifiers())); assertEquals(true, Modifier.isPublic(ObjectUtils.class.getModifiers())); assertEquals(false, Modifier.isFinal(ObjectUtils.class.getModifiers())); } //----------------------------------------------------------------------- public void testIsNull() { Object o = FOO; Object dflt = BAR; assertSame("dflt was not returned when o was null", dflt, ObjectUtils.defaultIfNull(null, dflt)); assertSame("dflt was returned when o was not null", o, ObjectUtils.defaultIfNull(o, dflt)); } public void testEquals() { assertTrue("ObjectUtils.equals(null, null) returned false", ObjectUtils.equals(null, null)); assertTrue("ObjectUtils.equals(\"foo\", null) returned true", !ObjectUtils.equals(FOO, null)); assertTrue("ObjectUtils.equals(null, \"bar\") returned true", !ObjectUtils.equals(null, BAR)); assertTrue("ObjectUtils.equals(\"foo\", \"bar\") returned true", !ObjectUtils.equals(FOO, BAR)); assertTrue("ObjectUtils.equals(\"foo\", \"foo\") returned false", ObjectUtils.equals(FOO, FOO)); } public void testNotEqual() { assertFalse("ObjectUtils.notEqual(null, null) returned false", ObjectUtils.notEqual(null, null)); assertTrue("ObjectUtils.notEqual(\"foo\", null) returned true", ObjectUtils.notEqual(FOO, null)); assertTrue("ObjectUtils.notEqual(null, \"bar\") returned true", ObjectUtils.notEqual(null, BAR)); assertTrue("ObjectUtils.notEqual(\"foo\", \"bar\") returned true", ObjectUtils.notEqual(FOO, BAR)); assertFalse("ObjectUtils.notEqual(\"foo\", \"foo\") returned false", ObjectUtils.notEqual(FOO, FOO)); } public void testHashCode() { assertEquals(0, ObjectUtils.hashCode(null)); assertEquals("a".hashCode(), ObjectUtils.hashCode("a")); } // /** // * Show that java.util.Date and java.sql.Timestamp are apples and oranges. // * Prompted by an email discussion. // * // * The behavior is different b/w Sun Java 1.3.1_10 and 1.4.2_03. // */ // public void testDateEqualsJava() { // long now = 1076957313284L; // Feb 16, 2004 10:49... PST // java.util.Date date = new java.util.Date(now); // java.sql.Timestamp realTimestamp = new java.sql.Timestamp(now); // java.util.Date timestamp = realTimestamp; // // sanity check 1: // assertEquals(284000000, realTimestamp.getNanos()); // assertEquals(1076957313284L, date.getTime()); // // // // On Sun 1.3.1_10: // //junit.framework.AssertionFailedError: expected:<1076957313284> but was:<1076957313000> // // // //assertEquals(1076957313284L, timestamp.getTime()); // // // //junit.framework.AssertionFailedError: expected:<1076957313284> but was:<1076957313000> // // // //assertEquals(1076957313284L, realTimestamp.getTime()); // // sanity check 2: // assertEquals(date.getDay(), realTimestamp.getDay()); // assertEquals(date.getHours(), realTimestamp.getHours()); // assertEquals(date.getMinutes(), realTimestamp.getMinutes()); // assertEquals(date.getMonth(), realTimestamp.getMonth()); // assertEquals(date.getSeconds(), realTimestamp.getSeconds()); // assertEquals(date.getTimezoneOffset(), realTimestamp.getTimezoneOffset()); // assertEquals(date.getYear(), realTimestamp.getYear()); // // // // Time values are == and equals() on Sun 1.4.2_03 but NOT on Sun 1.3.1_10: // // // //assertFalse("Sanity check failed: date.getTime() == timestamp.getTime()", date.getTime() == timestamp.getTime()); // //assertFalse("Sanity check failed: timestamp.equals(date)", timestamp.equals(date)); // //assertFalse("Sanity check failed: date.equals(timestamp)", date.equals(timestamp)); // // real test: // //assertFalse("java.util.Date and java.sql.Timestamp should be equal", ObjectUtils.equals(date, timestamp)); // } public void testIdentityToString() { assertEquals(null, ObjectUtils.identityToString(null)); assertEquals( "java.lang.String@" + Integer.toHexString(System.identityHashCode(FOO)), ObjectUtils.identityToString(FOO)); Integer i = new Integer(90); String expected = "java.lang.Integer@" + Integer.toHexString(System.identityHashCode(i)); assertEquals(expected, ObjectUtils.identityToString(i)); StringBuffer buffer = new StringBuffer(); ObjectUtils.identityToString(buffer, i); assertEquals(expected, buffer.toString()); try { ObjectUtils.identityToString(null, "tmp"); fail("NullPointerException expected"); } catch(NullPointerException npe) { } try { ObjectUtils.identityToString(new StringBuffer(), null); fail("NullPointerException expected"); } catch(NullPointerException npe) { } } public void testAppendIdentityToString() { assertEquals(null, ObjectUtils.appendIdentityToString(null, null)); assertEquals(null, ObjectUtils.appendIdentityToString(new StringBuffer(), null)); assertEquals( "java.lang.String@" + Integer.toHexString(System.identityHashCode(FOO)), ObjectUtils.appendIdentityToString(null, FOO).toString()); assertEquals( "java.lang.String@" + Integer.toHexString(System.identityHashCode(FOO)), ObjectUtils.appendIdentityToString(new StringBuffer(), FOO).toString()); Integer val = new Integer(90); assertEquals( "java.lang.Integer@" + Integer.toHexString(System.identityHashCode(val)), ObjectUtils.appendIdentityToString(null, val).toString()); assertEquals( "java.lang.Integer@" + Integer.toHexString(System.identityHashCode(val)), ObjectUtils.appendIdentityToString(new StringBuffer(), val).toString()); } public void testToString_Object() { assertEquals("", ObjectUtils.toString((Object) null) ); assertEquals(Boolean.TRUE.toString(), ObjectUtils.toString(Boolean.TRUE) ); } public void testToString_ObjectString() { assertEquals(BAR, ObjectUtils.toString((Object) null, BAR) ); assertEquals(Boolean.TRUE.toString(), ObjectUtils.toString(Boolean.TRUE, BAR) ); } public void testNull() { assertTrue(ObjectUtils.NULL != null); assertTrue(ObjectUtils.NULL instanceof ObjectUtils.Null); assertSame(ObjectUtils.NULL, SerializationUtils.clone(ObjectUtils.NULL)); } public void testMax() { Calendar calendar = Calendar.getInstance(); Comparable nonNullComparable1 = calendar.getTime(); Comparable nonNullComparable2 = calendar.getTime(); calendar.set( Calendar.YEAR, calendar.get( Calendar.YEAR ) -1 ); Comparable minComparable = calendar.getTime(); assertNotSame( nonNullComparable1, nonNullComparable2 ); assertSame( nonNullComparable1, ObjectUtils.max( null, nonNullComparable1 ) ); assertSame( nonNullComparable1, ObjectUtils.max( nonNullComparable1, null ) ); assertSame( nonNullComparable1, ObjectUtils.max( nonNullComparable1, nonNullComparable2 ) ); assertSame( nonNullComparable1, ObjectUtils.max( nonNullComparable1, minComparable ) ); assertSame( nonNullComparable1, ObjectUtils.max( minComparable, nonNullComparable1 ) ); } public void testMin() { Calendar calendar = Calendar.getInstance(); Comparable nonNullComparable1 = calendar.getTime(); Comparable nonNullComparable2 = calendar.getTime(); calendar.set( Calendar.YEAR, calendar.get( Calendar.YEAR ) -1 ); Comparable minComparable = calendar.getTime(); assertNotSame( nonNullComparable1, nonNullComparable2 ); assertSame( nonNullComparable1, ObjectUtils.min( null, nonNullComparable1 ) ); assertSame( nonNullComparable1, ObjectUtils.min( nonNullComparable1, null ) ); assertSame( nonNullComparable1, ObjectUtils.min( nonNullComparable1, nonNullComparable2 ) ); assertSame( minComparable, ObjectUtils.min( nonNullComparable1, minComparable ) ); assertSame( minComparable, ObjectUtils.min( minComparable, nonNullComparable1 ) ); } /** * Tests {@link ObjectUtils#compare(Comparable, Comparable, boolean)}. */ public void testCompare() { Integer one = new Integer(1); Integer two = new Integer(2); Integer nullValue = null; assertEquals("Null Null false", 0, ObjectUtils.compare(nullValue, nullValue)); assertEquals("Null Null true", 0, ObjectUtils.compare(nullValue, nullValue, true)); assertEquals("Null one false", -1, ObjectUtils.compare(nullValue, one)); assertEquals("Null one true", 1, ObjectUtils.compare(nullValue, one, true)); assertEquals("one Null false", 1, ObjectUtils.compare(one, nullValue)); assertEquals("one Null true", -1, ObjectUtils.compare(one, nullValue, true)); assertEquals("one two false", -1, ObjectUtils.compare(one, two)); assertEquals("one two true", -1, ObjectUtils.compare(one, two, true)); } /** * Tests {@link ObjectUtils#clone(Object)} with a cloneable object. */ public void testCloneOfCloneable() { final CloneableString string = new CloneableString("apache"); final CloneableString stringClone = (CloneableString)ObjectUtils.clone(string); assertEquals("apache", stringClone.getValue()); } /** * Tests {@link ObjectUtils#clone(Object)} with a not cloneable object. */ public void testCloneOfNotCloneable() { final String string = new String("apache"); assertNull(ObjectUtils.clone(string)); } /** * Tests {@link ObjectUtils#clone(Object)} with an uncloneable object. */ public void testCloneOfUncloneable() { final UncloneableString string = new UncloneableString("apache"); try { ObjectUtils.clone(string); fail("Thrown " + CloneFailedException.class.getName() + " expected"); } catch (final CloneFailedException e) { //expected result } } /** * Tests {@link ObjectUtils#clone(Object)} with an object array. */ public void testCloneOfStringArray() { assertTrue(Arrays.equals( new String[]{"string"}, (String[])ObjectUtils.clone(new String[]{"string"}))); } /** * Tests {@link ObjectUtils#clone(Object)} with an array of primitives. */ public void testCloneOfPrimitiveArray() { assertTrue(Arrays.equals(new int[]{1}, (int[])ObjectUtils.clone(new int[]{1}))); } /** * Tests {@link ObjectUtils#cloneIfPossible(Object)} with a cloneable object. */ public void testPossibleCloneOfCloneable() { final CloneableString string = new CloneableString("apache"); final CloneableString stringClone = (CloneableString)ObjectUtils.cloneIfPossible(string); assertEquals("apache", stringClone.getValue()); } /** * Tests {@link ObjectUtils#cloneIfPossible(Object)} with a not cloneable object. */ public void testPossibleCloneOfNotCloneable() { final String string = new String("apache"); assertSame(string, ObjectUtils.cloneIfPossible(string)); } /** * Tests {@link ObjectUtils#cloneIfPossible(Object)} with an uncloneable object. */ public void testPossibleCloneOfUncloneable() { final UncloneableString string = new UncloneableString("apache"); try { ObjectUtils.cloneIfPossible(string); fail("Thrown " + CloneFailedException.class.getName() + " expected"); } catch (final CloneFailedException e) { //expected result } } /** * String that is cloneable. */ static final class CloneableString extends MutableObject implements Cloneable { private static final long serialVersionUID = 1L; CloneableString(final String s) { super(s); } public Object clone() throws CloneNotSupportedException { return (CloneableString)super.clone(); } } /** * String that is not cloneable. */ static final class UncloneableString extends MutableObject implements Cloneable { private static final long serialVersionUID = 1L; UncloneableString(final String s) { super(s); } } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/RandomStringUtilsTest.java100644 0 0 32312 11513702440 26133 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.util.Random; /** * Unit tests {@link org.apache.commons.lang.RandomStringUtils}. * * @author Steven Caswell * @author Ringo De Smet * @author Phil Steitz * @version $Id: RandomStringUtilsTest.java 905628 2010-02-02 13:29:55Z niallp $ */ public class RandomStringUtilsTest extends junit.framework.TestCase { /** * Construct a new instance of RandomStringUtilsTest with the specified name */ public RandomStringUtilsTest(String name) { super(name); } //----------------------------------------------------------------------- public void testConstructor() { assertNotNull(new RandomStringUtils()); Constructor[] cons = RandomStringUtils.class.getDeclaredConstructors(); assertEquals(1, cons.length); assertEquals(true, Modifier.isPublic(cons[0].getModifiers())); assertEquals(true, Modifier.isPublic(RandomStringUtils.class.getModifiers())); assertEquals(false, Modifier.isFinal(RandomStringUtils.class.getModifiers())); } //----------------------------------------------------------------------- /** * Test the implementation */ public void testRandomStringUtils() { String r1 = RandomStringUtils.random(50); assertEquals("random(50) length", 50, r1.length()); String r2 = RandomStringUtils.random(50); assertEquals("random(50) length", 50, r2.length()); assertTrue("!r1.equals(r2)", !r1.equals(r2)); r1 = RandomStringUtils.randomAscii(50); assertEquals("randomAscii(50) length", 50, r1.length()); for(int i = 0; i < r1.length(); i++) { assertTrue("char between 32 and 127", r1.charAt(i) >= 32 && r1.charAt(i) <= 127); } r2 = RandomStringUtils.randomAscii(50); assertTrue("!r1.equals(r2)", !r1.equals(r2)); r1 = RandomStringUtils.randomAlphabetic(50); assertEquals("randomAlphabetic(50)", 50, r1.length()); for(int i = 0; i < r1.length(); i++) { assertEquals("r1 contains alphabetic", true, Character.isLetter(r1.charAt(i)) && !Character.isDigit(r1.charAt(i))); } r2 = RandomStringUtils.randomAlphabetic(50); assertTrue("!r1.equals(r2)", !r1.equals(r2)); r1 = RandomStringUtils.randomAlphanumeric(50); assertEquals("randomAlphanumeric(50)", 50, r1.length()); for(int i = 0; i < r1.length(); i++) { assertEquals("r1 contains alphanumeric", true, Character.isLetterOrDigit(r1.charAt(i))); } r2 = RandomStringUtils.randomAlphabetic(50); assertTrue("!r1.equals(r2)", !r1.equals(r2)); r1 = RandomStringUtils.randomNumeric(50); assertEquals("randomNumeric(50)", 50, r1.length()); for(int i = 0; i < r1.length(); i++) { assertEquals("r1 contains numeric", true, Character.isDigit(r1.charAt(i)) && !Character.isLetter(r1.charAt(i))); } r2 = RandomStringUtils.randomNumeric(50); assertTrue("!r1.equals(r2)", !r1.equals(r2)); String set = "abcdefg"; r1 = RandomStringUtils.random(50, set); assertEquals("random(50, \"abcdefg\")", 50, r1.length()); for(int i = 0; i < r1.length(); i++) { assertTrue("random char in set", set.indexOf(r1.charAt(i)) > -1); } r2 = RandomStringUtils.random(50, set); assertTrue("!r1.equals(r2)", !r1.equals(r2)); r1 = RandomStringUtils.random(50, (String) null); assertEquals("random(50) length", 50, r1.length()); r2 = RandomStringUtils.random(50, (String) null); assertEquals("random(50) length", 50, r2.length()); assertTrue("!r1.equals(r2)", !r1.equals(r2)); set = "stuvwxyz"; r1 = RandomStringUtils.random(50, set.toCharArray()); assertEquals("random(50, \"stuvwxyz\")", 50, r1.length()); for(int i = 0; i < r1.length(); i++) { assertTrue("random char in set", set.indexOf(r1.charAt(i)) > -1); } r2 = RandomStringUtils.random(50, set); assertTrue("!r1.equals(r2)", !r1.equals(r2)); r1 = RandomStringUtils.random(50, (char[]) null); assertEquals("random(50) length", 50, r1.length()); r2 = RandomStringUtils.random(50, (char[]) null); assertEquals("random(50) length", 50, r2.length()); assertTrue("!r1.equals(r2)", !r1.equals(r2)); long seed = System.currentTimeMillis(); r1 = RandomStringUtils.random(50,0,0,true,true,null,new Random(seed)); r2 = RandomStringUtils.random(50,0,0,true,true,null,new Random(seed)); assertEquals("r1.equals(r2)", r1, r2); r1 = RandomStringUtils.random(0); assertEquals("random(0).equals(\"\")", "", r1); } public void testExceptions() { try { RandomStringUtils.random(-1); fail(); } catch (IllegalArgumentException ex) {} try { RandomStringUtils.random(-1, true, true); fail(); } catch (IllegalArgumentException ex) {} try { RandomStringUtils.random(-1, new char[0]); fail(); } catch (IllegalArgumentException ex) {} try { RandomStringUtils.random(-1, ""); fail(); } catch (IllegalArgumentException ex) {} try { RandomStringUtils.random(-1, 'a', 'z', false, false); fail(); } catch (IllegalArgumentException ex) {} try { RandomStringUtils.random(-1, 'a', 'z', false, false, new char[0]); fail(); } catch (IllegalArgumentException ex) {} try { RandomStringUtils.random(-1, 'a', 'z', false, false, new char[0], new Random()); fail(); } catch (IllegalArgumentException ex) {} } /** * Make sure boundary alphanumeric characters are generated by randomAlphaNumeric * This test will fail randomly with probability = 6 * (61/62)**1000 ~ 5.2E-7 */ public void testRandomAlphaNumeric() { char[] testChars = {'a', 'z', 'A', 'Z', '0', '9'}; boolean[] found = {false, false, false, false, false, false}; for (int i = 0; i < 100; i++) { String randString = RandomStringUtils.randomAlphanumeric(10); for (int j = 0; j < testChars.length; j++) { if (randString.indexOf(testChars[j]) > 0) { found[j] = true; } } } for (int i = 0; i < testChars.length; i++) { if (!found[i]) { fail("alphanumeric character not generated in 1000 attempts: " + testChars[i] +" -- repeated failures indicate a problem "); } } } /** * Make sure '0' and '9' are generated by randomNumeric * This test will fail randomly with probability = 2 * (9/10)**1000 ~ 3.5E-46 */ public void testRandomNumeric() { char[] testChars = {'0','9'}; boolean[] found = {false, false}; for (int i = 0; i < 100; i++) { String randString = RandomStringUtils.randomNumeric(10); for (int j = 0; j < testChars.length; j++) { if (randString.indexOf(testChars[j]) > 0) { found[j] = true; } } } for (int i = 0; i < testChars.length; i++) { if (!found[i]) { fail("digit not generated in 1000 attempts: " + testChars[i] +" -- repeated failures indicate a problem "); } } } /** * Make sure boundary alpha characters are generated by randomAlphabetic * This test will fail randomly with probability = 4 * (51/52)**1000 ~ 1.58E-8 */ public void testRandomAlphabetic() { char[] testChars = {'a', 'z', 'A', 'Z'}; boolean[] found = {false, false, false, false}; for (int i = 0; i < 100; i++) { String randString = RandomStringUtils.randomAlphabetic(10); for (int j = 0; j < testChars.length; j++) { if (randString.indexOf(testChars[j]) > 0) { found[j] = true; } } } for (int i = 0; i < testChars.length; i++) { if (!found[i]) { fail("alphanumeric character not generated in 1000 attempts: " + testChars[i] +" -- repeated failures indicate a problem "); } } } /** * Make sure 32 and 127 are generated by randomNumeric * This test will fail randomly with probability = 2*(95/96)**1000 ~ 5.7E-5 */ public void testRandomAscii() { char[] testChars = {(char) 32, (char) 126}; boolean[] found = {false, false}; for (int i = 0; i < 100; i++) { String randString = RandomStringUtils.randomAscii(10); for (int j = 0; j < testChars.length; j++) { if (randString.indexOf(testChars[j]) > 0) { found[j] = true; } } } for (int i = 0; i < testChars.length; i++) { if (!found[i]) { fail("ascii character not generated in 1000 attempts: " + (int) testChars[i] + " -- repeated failures indicate a problem"); } } } /** * Test homogeneity of random strings generated -- * i.e., test that characters show up with expected frequencies * in generated strings. Will fail randomly about 1 in 1000 times. * Repeated failures indicate a problem. */ public void testRandomStringUtilsHomog() { String set = "abc"; char[] chars = set.toCharArray(); String gen = ""; int[] counts = {0,0,0}; int[] expected = {200,200,200}; for (int i = 0; i< 100; i++) { gen = RandomStringUtils.random(6,chars); for (int j = 0; j < 6; j++) { switch (gen.charAt(j)) { case 'a': {counts[0]++; break;} case 'b': {counts[1]++; break;} case 'c': {counts[2]++; break;} default: {fail("generated character not in set");} } } } // Perform chi-square test with df = 3-1 = 2, testing at .001 level assertTrue("test homogeneity -- will fail about 1 in 1000 times", chiSquare(expected,counts) < 13.82); } /** * Computes Chi-Square statistic given observed and expected counts * @param observed array of observed frequency counts * @param expected array of expected frequency counts */ private double chiSquare(int[] expected, int[] observed) { double sumSq = 0.0d; double dev = 0.0d; for (int i = 0; i < observed.length; i++) { dev = (double) (observed[i] - expected[i]); sumSq += dev * dev / (double) expected[i]; } return sumSq; } /** * Checks if the string got by {@link RandomStringUtils#random(int)} * can be converted to UTF-8 and back without loss. * * @see LANG-100 * * @throws Exception */ public void testLang100() throws Exception { int size = 5000; String encoding = "UTF-8"; String orig = RandomStringUtils.random(size); byte[] bytes = orig.getBytes(encoding); String copy = new String(bytes, encoding); // for a verbose compare: for (int i=0; i < orig.length() && i < copy.length(); i++) { char o = orig.charAt(i); char c = copy.charAt(i); assertEquals("differs at " + i + "(" + Integer.toHexString((new Character(o)).hashCode()) + "," + Integer.toHexString((new Character(c)).hashCode()) + ")", o, c); } // compare length also assertEquals(orig.length(), copy.length()); // just to be complete assertEquals(orig, copy); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/reflect/ConstructorUtilsTest.java100644 0 0 23170 11513702436 27504 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.reflect; import java.lang.reflect.Constructor; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import junit.framework.TestCase; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.math.NumberUtils; /** * Unit tests ConstructorUtils * @author mbenson * @version $Id: ConstructorUtilsTest.java 905628 2010-02-02 13:29:55Z niallp $ */ public class ConstructorUtilsTest extends TestCase { public static class TestBean { private String toString; public TestBean() { toString = "()"; } public TestBean(int i) { toString = "(int)"; } public TestBean(Integer i) { toString = "(Integer)"; } public TestBean(double d) { toString = "(double)"; } public TestBean(String s) { toString = "(String)"; } public TestBean(Object o) { toString = "(Object)"; } public String toString() { return toString; } } private static class PrivateClass { public PrivateClass() { } } private Map classCache; public ConstructorUtilsTest(String name) { super(name); classCache = new HashMap(); } protected void setUp() throws Exception { super.setUp(); classCache.clear(); } public void testConstructor() throws Exception { assertNotNull(MethodUtils.class.newInstance()); } public void testInvokeConstructor() throws Exception { assertEquals("()", ConstructorUtils.invokeConstructor(TestBean.class, ArrayUtils.EMPTY_CLASS_ARRAY).toString()); assertEquals("()", ConstructorUtils.invokeConstructor(TestBean.class, (Class[]) null).toString()); assertEquals("(String)", ConstructorUtils.invokeConstructor( TestBean.class, "").toString()); assertEquals("(Object)", ConstructorUtils.invokeConstructor( TestBean.class, new Object()).toString()); assertEquals("(Object)", ConstructorUtils.invokeConstructor( TestBean.class, Boolean.TRUE).toString()); assertEquals("(Integer)", ConstructorUtils.invokeConstructor( TestBean.class, NumberUtils.INTEGER_ONE).toString()); assertEquals("(int)", ConstructorUtils.invokeConstructor( TestBean.class, NumberUtils.BYTE_ONE).toString()); assertEquals("(double)", ConstructorUtils.invokeConstructor( TestBean.class, NumberUtils.LONG_ONE).toString()); assertEquals("(double)", ConstructorUtils.invokeConstructor( TestBean.class, NumberUtils.DOUBLE_ONE).toString()); } public void testInvokeExactConstructor() throws Exception { assertEquals("()", ConstructorUtils.invokeExactConstructor( TestBean.class, ArrayUtils.EMPTY_CLASS_ARRAY).toString()); assertEquals("()", ConstructorUtils.invokeExactConstructor( TestBean.class, (Class[]) null).toString()); assertEquals("(String)", ConstructorUtils.invokeExactConstructor( TestBean.class, "").toString()); assertEquals("(Object)", ConstructorUtils.invokeExactConstructor( TestBean.class, new Object()).toString()); assertEquals("(Integer)", ConstructorUtils.invokeExactConstructor( TestBean.class, NumberUtils.INTEGER_ONE).toString()); assertEquals("(double)", ConstructorUtils.invokeExactConstructor( TestBean.class, new Object[] { NumberUtils.DOUBLE_ONE }, new Class[] { Double.TYPE }).toString()); try { ConstructorUtils.invokeExactConstructor(TestBean.class, NumberUtils.BYTE_ONE); fail("should throw NoSuchMethodException"); } catch (NoSuchMethodException e) { } try { ConstructorUtils.invokeExactConstructor(TestBean.class, NumberUtils.LONG_ONE); fail("should throw NoSuchMethodException"); } catch (NoSuchMethodException e) { } try { ConstructorUtils.invokeExactConstructor(TestBean.class, Boolean.TRUE); fail("should throw NoSuchMethodException"); } catch (NoSuchMethodException e) { } } public void testGetAccessibleConstructor() throws Exception { assertNotNull(ConstructorUtils.getAccessibleConstructor(Object.class .getConstructor(ArrayUtils.EMPTY_CLASS_ARRAY))); assertNull(ConstructorUtils.getAccessibleConstructor(PrivateClass.class .getConstructor(ArrayUtils.EMPTY_CLASS_ARRAY))); } public void testGetAccessibleConstructorFromDescription() throws Exception { assertNotNull(ConstructorUtils.getAccessibleConstructor(Object.class, ArrayUtils.EMPTY_CLASS_ARRAY)); assertNull(ConstructorUtils.getAccessibleConstructor( PrivateClass.class, ArrayUtils.EMPTY_CLASS_ARRAY)); } public void testGetMatchingAccessibleMethod() throws Exception { expectMatchingAccessibleConstructorParameterTypes(TestBean.class, ArrayUtils.EMPTY_CLASS_ARRAY, ArrayUtils.EMPTY_CLASS_ARRAY); expectMatchingAccessibleConstructorParameterTypes(TestBean.class, null, ArrayUtils.EMPTY_CLASS_ARRAY); expectMatchingAccessibleConstructorParameterTypes(TestBean.class, singletonArray(String.class), singletonArray(String.class)); expectMatchingAccessibleConstructorParameterTypes(TestBean.class, singletonArray(Object.class), singletonArray(Object.class)); expectMatchingAccessibleConstructorParameterTypes(TestBean.class, singletonArray(Boolean.class), singletonArray(Object.class)); expectMatchingAccessibleConstructorParameterTypes(TestBean.class, singletonArray(Byte.class), singletonArray(Integer.TYPE)); expectMatchingAccessibleConstructorParameterTypes(TestBean.class, singletonArray(Byte.TYPE), singletonArray(Integer.TYPE)); expectMatchingAccessibleConstructorParameterTypes(TestBean.class, singletonArray(Short.class), singletonArray(Integer.TYPE)); expectMatchingAccessibleConstructorParameterTypes(TestBean.class, singletonArray(Short.TYPE), singletonArray(Integer.TYPE)); expectMatchingAccessibleConstructorParameterTypes(TestBean.class, singletonArray(Character.class), singletonArray(Integer.TYPE)); expectMatchingAccessibleConstructorParameterTypes(TestBean.class, singletonArray(Character.TYPE), singletonArray(Integer.TYPE)); expectMatchingAccessibleConstructorParameterTypes(TestBean.class, singletonArray(Integer.class), singletonArray(Integer.class)); expectMatchingAccessibleConstructorParameterTypes(TestBean.class, singletonArray(Integer.TYPE), singletonArray(Integer.TYPE)); expectMatchingAccessibleConstructorParameterTypes(TestBean.class, singletonArray(Long.class), singletonArray(Double.TYPE)); expectMatchingAccessibleConstructorParameterTypes(TestBean.class, singletonArray(Long.TYPE), singletonArray(Double.TYPE)); expectMatchingAccessibleConstructorParameterTypes(TestBean.class, singletonArray(Float.class), singletonArray(Double.TYPE)); expectMatchingAccessibleConstructorParameterTypes(TestBean.class, singletonArray(Float.TYPE), singletonArray(Double.TYPE)); expectMatchingAccessibleConstructorParameterTypes(TestBean.class, singletonArray(Double.class), singletonArray(Double.TYPE)); expectMatchingAccessibleConstructorParameterTypes(TestBean.class, singletonArray(Double.TYPE), singletonArray(Double.TYPE)); } private void expectMatchingAccessibleConstructorParameterTypes(Class cls, Class[] requestTypes, Class[] actualTypes) { Constructor c = ConstructorUtils.getMatchingAccessibleConstructor(cls, requestTypes); assertTrue(toString(c.getParameterTypes()) + " not equals " + toString(actualTypes), Arrays.equals(actualTypes, c .getParameterTypes())); } private String toString(Class[] c) { return Arrays.asList(c).toString(); } private Class[] singletonArray(Class c) { Class[] result = (Class[]) classCache.get(c); if (result == null) { result = new Class[] { c }; classCache.put(c, result); } return result; } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/reflect/FieldUtilsTest.java100644 0 0 132014 11513702436 26220 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.reflect; import java.lang.reflect.Field; import org.apache.commons.lang.reflect.testbed.Ambig; import org.apache.commons.lang.reflect.testbed.Foo; import org.apache.commons.lang.reflect.testbed.PrivatelyShadowedChild; import org.apache.commons.lang.reflect.testbed.PublicChild; import org.apache.commons.lang.reflect.testbed.PubliclyShadowedChild; import org.apache.commons.lang.reflect.testbed.StaticContainer; import org.apache.commons.lang.reflect.testbed.StaticContainerChild; import junit.framework.TestCase; /** * Unit tests FieldUtils * @author mbenson * @version $Id: FieldUtilsTest.java 905628 2010-02-02 13:29:55Z niallp $ */ public class FieldUtilsTest extends TestCase { static final String S = "s"; static final String SS = "ss"; static final Integer I0 = new Integer(0); static final Integer I1 = new Integer(1); static final Double D0 = new Double(0.0); static final Double D1 = new Double(1.0); private PublicChild publicChild; private PubliclyShadowedChild publiclyShadowedChild; private PrivatelyShadowedChild privatelyShadowedChild; private Class parentClass = PublicChild.class.getSuperclass(); protected void setUp() throws Exception { super.setUp(); StaticContainer.reset(); publicChild = new PublicChild(); publiclyShadowedChild = new PubliclyShadowedChild(); privatelyShadowedChild = new PrivatelyShadowedChild(); } public void testGetField() { assertEquals(Foo.class, FieldUtils.getField(PublicChild.class, "VALUE").getDeclaringClass()); assertEquals(parentClass, FieldUtils.getField(PublicChild.class, "s").getDeclaringClass()); assertNull(FieldUtils.getField(PublicChild.class, "b")); assertNull(FieldUtils.getField(PublicChild.class, "i")); assertNull(FieldUtils.getField(PublicChild.class, "d")); assertEquals(Foo.class, FieldUtils.getField(PubliclyShadowedChild.class, "VALUE").getDeclaringClass()); assertEquals(PubliclyShadowedChild.class, FieldUtils.getField(PubliclyShadowedChild.class, "s") .getDeclaringClass()); assertEquals(PubliclyShadowedChild.class, FieldUtils.getField(PubliclyShadowedChild.class, "b") .getDeclaringClass()); assertEquals(PubliclyShadowedChild.class, FieldUtils.getField(PubliclyShadowedChild.class, "i") .getDeclaringClass()); assertEquals(PubliclyShadowedChild.class, FieldUtils.getField(PubliclyShadowedChild.class, "d") .getDeclaringClass()); assertEquals(Foo.class, FieldUtils.getField(PrivatelyShadowedChild.class, "VALUE").getDeclaringClass()); assertEquals(parentClass, FieldUtils.getField(PrivatelyShadowedChild.class, "s").getDeclaringClass()); assertNull(FieldUtils.getField(PrivatelyShadowedChild.class, "b")); assertNull(FieldUtils.getField(PrivatelyShadowedChild.class, "i")); assertNull(FieldUtils.getField(PrivatelyShadowedChild.class, "d")); } public void testGetFieldForceAccess() { assertEquals(PublicChild.class, FieldUtils.getField(PublicChild.class, "VALUE", true).getDeclaringClass()); assertEquals(parentClass, FieldUtils.getField(PublicChild.class, "s", true).getDeclaringClass()); assertEquals(parentClass, FieldUtils.getField(PublicChild.class, "b", true).getDeclaringClass()); assertEquals(parentClass, FieldUtils.getField(PublicChild.class, "i", true).getDeclaringClass()); assertEquals(parentClass, FieldUtils.getField(PublicChild.class, "d", true).getDeclaringClass()); assertEquals(Foo.class, FieldUtils.getField(PubliclyShadowedChild.class, "VALUE", true).getDeclaringClass()); assertEquals(PubliclyShadowedChild.class, FieldUtils.getField(PubliclyShadowedChild.class, "s", true) .getDeclaringClass()); assertEquals(PubliclyShadowedChild.class, FieldUtils.getField(PubliclyShadowedChild.class, "b", true) .getDeclaringClass()); assertEquals(PubliclyShadowedChild.class, FieldUtils.getField(PubliclyShadowedChild.class, "i", true) .getDeclaringClass()); assertEquals(PubliclyShadowedChild.class, FieldUtils.getField(PubliclyShadowedChild.class, "d", true) .getDeclaringClass()); assertEquals(Foo.class, FieldUtils.getField(PrivatelyShadowedChild.class, "VALUE", true).getDeclaringClass()); assertEquals(PrivatelyShadowedChild.class, FieldUtils.getField(PrivatelyShadowedChild.class, "s", true) .getDeclaringClass()); assertEquals(PrivatelyShadowedChild.class, FieldUtils.getField(PrivatelyShadowedChild.class, "b", true) .getDeclaringClass()); assertEquals(PrivatelyShadowedChild.class, FieldUtils.getField(PrivatelyShadowedChild.class, "i", true) .getDeclaringClass()); assertEquals(PrivatelyShadowedChild.class, FieldUtils.getField(PrivatelyShadowedChild.class, "d", true) .getDeclaringClass()); } public void testGetDeclaredField() { assertNull(FieldUtils.getDeclaredField(PublicChild.class, "VALUE")); assertNull(FieldUtils.getDeclaredField(PublicChild.class, "s")); assertNull(FieldUtils.getDeclaredField(PublicChild.class, "b")); assertNull(FieldUtils.getDeclaredField(PublicChild.class, "i")); assertNull(FieldUtils.getDeclaredField(PublicChild.class, "d")); assertNull(FieldUtils.getDeclaredField(PubliclyShadowedChild.class, "VALUE")); assertEquals(PubliclyShadowedChild.class, FieldUtils.getDeclaredField(PubliclyShadowedChild.class, "s") .getDeclaringClass()); assertEquals(PubliclyShadowedChild.class, FieldUtils.getDeclaredField(PubliclyShadowedChild.class, "b") .getDeclaringClass()); assertEquals(PubliclyShadowedChild.class, FieldUtils.getDeclaredField(PubliclyShadowedChild.class, "i") .getDeclaringClass()); assertEquals(PubliclyShadowedChild.class, FieldUtils.getDeclaredField(PubliclyShadowedChild.class, "d") .getDeclaringClass()); assertNull(FieldUtils.getDeclaredField(PrivatelyShadowedChild.class, "VALUE")); assertNull(FieldUtils.getDeclaredField(PrivatelyShadowedChild.class, "s")); assertNull(FieldUtils.getDeclaredField(PrivatelyShadowedChild.class, "b")); assertNull(FieldUtils.getDeclaredField(PrivatelyShadowedChild.class, "i")); assertNull(FieldUtils.getDeclaredField(PrivatelyShadowedChild.class, "d")); } public void testGetDeclaredFieldForceAccess() { assertEquals(PublicChild.class, FieldUtils.getDeclaredField(PublicChild.class, "VALUE", true) .getDeclaringClass()); assertNull(FieldUtils.getDeclaredField(PublicChild.class, "s", true)); assertNull(FieldUtils.getDeclaredField(PublicChild.class, "b", true)); assertNull(FieldUtils.getDeclaredField(PublicChild.class, "i", true)); assertNull(FieldUtils.getDeclaredField(PublicChild.class, "d", true)); assertNull(FieldUtils.getDeclaredField(PubliclyShadowedChild.class, "VALUE", true)); assertEquals(PubliclyShadowedChild.class, FieldUtils.getDeclaredField(PubliclyShadowedChild.class, "s", true) .getDeclaringClass()); assertEquals(PubliclyShadowedChild.class, FieldUtils.getDeclaredField(PubliclyShadowedChild.class, "b", true) .getDeclaringClass()); assertEquals(PubliclyShadowedChild.class, FieldUtils.getDeclaredField(PubliclyShadowedChild.class, "i", true) .getDeclaringClass()); assertEquals(PubliclyShadowedChild.class, FieldUtils.getDeclaredField(PubliclyShadowedChild.class, "d", true) .getDeclaringClass()); assertNull(FieldUtils.getDeclaredField(PrivatelyShadowedChild.class, "VALUE", true)); assertEquals(PrivatelyShadowedChild.class, FieldUtils.getDeclaredField(PrivatelyShadowedChild.class, "s", true) .getDeclaringClass()); assertEquals(PrivatelyShadowedChild.class, FieldUtils.getDeclaredField(PrivatelyShadowedChild.class, "b", true) .getDeclaringClass()); assertEquals(PrivatelyShadowedChild.class, FieldUtils.getDeclaredField(PrivatelyShadowedChild.class, "i", true) .getDeclaringClass()); assertEquals(PrivatelyShadowedChild.class, FieldUtils.getDeclaredField(PrivatelyShadowedChild.class, "d", true) .getDeclaringClass()); } public void testReadStaticField() throws Exception { assertEquals(Foo.VALUE, FieldUtils.readStaticField(FieldUtils.getField(Foo.class, "VALUE"))); } public void testReadStaticFieldForceAccess() throws Exception { assertEquals(Foo.VALUE, FieldUtils.readStaticField(FieldUtils.getField(Foo.class, "VALUE"))); assertEquals(Foo.VALUE, FieldUtils.readStaticField(FieldUtils.getField(PublicChild.class, "VALUE"))); } public void testReadNamedStaticField() throws Exception { assertEquals(Foo.VALUE, FieldUtils.readStaticField(Foo.class, "VALUE")); assertEquals(Foo.VALUE, FieldUtils.readStaticField(PubliclyShadowedChild.class, "VALUE")); assertEquals(Foo.VALUE, FieldUtils.readStaticField(PrivatelyShadowedChild.class, "VALUE")); assertEquals(Foo.VALUE, FieldUtils.readStaticField(PublicChild.class, "VALUE")); } public void testReadNamedStaticFieldForceAccess() throws Exception { assertEquals(Foo.VALUE, FieldUtils.readStaticField(Foo.class, "VALUE", true)); assertEquals(Foo.VALUE, FieldUtils.readStaticField(PubliclyShadowedChild.class, "VALUE", true)); assertEquals(Foo.VALUE, FieldUtils.readStaticField(PrivatelyShadowedChild.class, "VALUE", true)); assertEquals("child", FieldUtils.readStaticField(PublicChild.class, "VALUE", true)); } public void testReadDeclaredNamedStaticField() throws Exception { assertEquals(Foo.VALUE, FieldUtils.readDeclaredStaticField(Foo.class, "VALUE")); try { assertEquals("child", FieldUtils.readDeclaredStaticField(PublicChild.class, "VALUE")); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // pass } try { assertEquals(Foo.VALUE, FieldUtils.readDeclaredStaticField(PubliclyShadowedChild.class, "VALUE")); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // pass } try { assertEquals(Foo.VALUE, FieldUtils.readDeclaredStaticField(PrivatelyShadowedChild.class, "VALUE")); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // pass } } public void testReadDeclaredNamedStaticFieldForceAccess() throws Exception { assertEquals(Foo.VALUE, FieldUtils.readDeclaredStaticField(Foo.class, "VALUE", true)); assertEquals("child", FieldUtils.readDeclaredStaticField(PublicChild.class, "VALUE", true)); try { assertEquals(Foo.VALUE, FieldUtils.readDeclaredStaticField(PubliclyShadowedChild.class, "VALUE", true)); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // pass } try { assertEquals(Foo.VALUE, FieldUtils.readDeclaredStaticField(PrivatelyShadowedChild.class, "VALUE", true)); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // pass } } public void testReadField() throws Exception { Field parentS = FieldUtils.getDeclaredField(parentClass, "s"); assertEquals("s", FieldUtils.readField(parentS, publicChild)); assertEquals("s", FieldUtils.readField(parentS, publiclyShadowedChild)); assertEquals("s", FieldUtils.readField(parentS, privatelyShadowedChild)); Field parentB = FieldUtils.getDeclaredField(parentClass, "b", true); assertEquals(Boolean.FALSE, FieldUtils.readField(parentB, publicChild)); assertEquals(Boolean.FALSE, FieldUtils.readField(parentB, publiclyShadowedChild)); assertEquals(Boolean.FALSE, FieldUtils.readField(parentB, privatelyShadowedChild)); Field parentI = FieldUtils.getDeclaredField(parentClass, "i", true); assertEquals(I0, FieldUtils.readField(parentI, publicChild)); assertEquals(I0, FieldUtils.readField(parentI, publiclyShadowedChild)); assertEquals(I0, FieldUtils.readField(parentI, privatelyShadowedChild)); Field parentD = FieldUtils.getDeclaredField(parentClass, "d", true); assertEquals(D0, FieldUtils.readField(parentD, publicChild)); assertEquals(D0, FieldUtils.readField(parentD, publiclyShadowedChild)); assertEquals(D0, FieldUtils.readField(parentD, privatelyShadowedChild)); } public void testReadFieldForceAccess() throws Exception { Field parentS = FieldUtils.getDeclaredField(parentClass, "s"); parentS.setAccessible(false); assertEquals("s", FieldUtils.readField(parentS, publicChild, true)); assertEquals("s", FieldUtils.readField(parentS, publiclyShadowedChild, true)); assertEquals("s", FieldUtils.readField(parentS, privatelyShadowedChild, true)); Field parentB = FieldUtils.getDeclaredField(parentClass, "b", true); parentB.setAccessible(false); assertEquals(Boolean.FALSE, FieldUtils.readField(parentB, publicChild, true)); assertEquals(Boolean.FALSE, FieldUtils.readField(parentB, publiclyShadowedChild, true)); assertEquals(Boolean.FALSE, FieldUtils.readField(parentB, privatelyShadowedChild, true)); Field parentI = FieldUtils.getDeclaredField(parentClass, "i", true); parentI.setAccessible(false); assertEquals(I0, FieldUtils.readField(parentI, publicChild, true)); assertEquals(I0, FieldUtils.readField(parentI, publiclyShadowedChild, true)); assertEquals(I0, FieldUtils.readField(parentI, privatelyShadowedChild, true)); Field parentD = FieldUtils.getDeclaredField(parentClass, "d", true); parentD.setAccessible(false); assertEquals(D0, FieldUtils.readField(parentD, publicChild, true)); assertEquals(D0, FieldUtils.readField(parentD, publiclyShadowedChild, true)); assertEquals(D0, FieldUtils.readField(parentD, privatelyShadowedChild, true)); } public void testReadNamedField() throws Exception { assertEquals("s", FieldUtils.readField(publicChild, "s")); assertEquals("ss", FieldUtils.readField(publiclyShadowedChild, "s")); assertEquals("s", FieldUtils.readField(privatelyShadowedChild, "s")); try { assertEquals(Boolean.FALSE, FieldUtils.readField(publicChild, "b")); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // pass } assertEquals(Boolean.TRUE, FieldUtils.readField(publiclyShadowedChild, "b")); try { assertEquals(Boolean.FALSE, FieldUtils.readField(privatelyShadowedChild, "b")); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // pass } try { assertEquals(I0, FieldUtils.readField(publicChild, "i")); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // pass } assertEquals(I1, FieldUtils.readField(publiclyShadowedChild, "i")); try { assertEquals(I0, FieldUtils.readField(privatelyShadowedChild, "i")); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // pass } try { assertEquals(D0, FieldUtils.readField(publicChild, "d")); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // pass } assertEquals(D1, FieldUtils.readField(publiclyShadowedChild, "d")); try { assertEquals(D0, FieldUtils.readField(privatelyShadowedChild, "d")); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // pass } } public void testReadNamedFieldForceAccess() throws Exception { assertEquals("s", FieldUtils.readField(publicChild, "s", true)); assertEquals("ss", FieldUtils.readField(publiclyShadowedChild, "s", true)); assertEquals("ss", FieldUtils.readField(privatelyShadowedChild, "s", true)); assertEquals(Boolean.FALSE, FieldUtils.readField(publicChild, "b", true)); assertEquals(Boolean.TRUE, FieldUtils.readField(publiclyShadowedChild, "b", true)); assertEquals(Boolean.TRUE, FieldUtils.readField(privatelyShadowedChild, "b", true)); assertEquals(I0, FieldUtils.readField(publicChild, "i", true)); assertEquals(I1, FieldUtils.readField(publiclyShadowedChild, "i", true)); assertEquals(I1, FieldUtils.readField(privatelyShadowedChild, "i", true)); assertEquals(D0, FieldUtils.readField(publicChild, "d", true)); assertEquals(D1, FieldUtils.readField(publiclyShadowedChild, "d", true)); assertEquals(D1, FieldUtils.readField(privatelyShadowedChild, "d", true)); } public void testReadDeclaredNamedField() throws Exception { try { assertEquals("s", FieldUtils.readDeclaredField(publicChild, "s")); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // pass } assertEquals("ss", FieldUtils.readDeclaredField(publiclyShadowedChild, "s")); try { assertEquals("s", FieldUtils.readDeclaredField(privatelyShadowedChild, "s")); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // pass } try { assertEquals(Boolean.FALSE, FieldUtils.readDeclaredField(publicChild, "b")); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // pass } assertEquals(Boolean.TRUE, FieldUtils.readDeclaredField(publiclyShadowedChild, "b")); try { assertEquals(Boolean.FALSE, FieldUtils.readDeclaredField(privatelyShadowedChild, "b")); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // pass } try { assertEquals(I0, FieldUtils.readDeclaredField(publicChild, "i")); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // pass } assertEquals(I1, FieldUtils.readDeclaredField(publiclyShadowedChild, "i")); try { assertEquals(I0, FieldUtils.readDeclaredField(privatelyShadowedChild, "i")); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // pass } try { assertEquals(D0, FieldUtils.readDeclaredField(publicChild, "d")); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // pass } assertEquals(D1, FieldUtils.readDeclaredField(publiclyShadowedChild, "d")); try { assertEquals(D0, FieldUtils.readDeclaredField(privatelyShadowedChild, "d")); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // pass } } public void testReadDeclaredNamedFieldForceAccess() throws Exception { try { assertEquals("s", FieldUtils.readDeclaredField(publicChild, "s", true)); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // pass } assertEquals("ss", FieldUtils.readDeclaredField(publiclyShadowedChild, "s", true)); assertEquals("ss", FieldUtils.readDeclaredField(privatelyShadowedChild, "s", true)); try { assertEquals(Boolean.FALSE, FieldUtils.readDeclaredField(publicChild, "b", true)); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // pass } assertEquals(Boolean.TRUE, FieldUtils.readDeclaredField(publiclyShadowedChild, "b", true)); assertEquals(Boolean.TRUE, FieldUtils.readDeclaredField(privatelyShadowedChild, "b", true)); try { assertEquals(I0, FieldUtils.readDeclaredField(publicChild, "i", true)); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // pass } assertEquals(I1, FieldUtils.readDeclaredField(publiclyShadowedChild, "i", true)); assertEquals(I1, FieldUtils.readDeclaredField(privatelyShadowedChild, "i", true)); try { assertEquals(D0, FieldUtils.readDeclaredField(publicChild, "d", true)); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // pass } assertEquals(D1, FieldUtils.readDeclaredField(publiclyShadowedChild, "d", true)); assertEquals(D1, FieldUtils.readDeclaredField(privatelyShadowedChild, "d", true)); } public void testWriteStaticField() throws Exception { Field field = StaticContainer.class.getDeclaredField("mutablePublic"); FieldUtils.writeStaticField(field, "new"); assertEquals("new", StaticContainer.mutablePublic); field = StaticContainer.class.getDeclaredField("mutableProtected"); try { FieldUtils.writeStaticField(field, "new"); fail("Expected IllegalAccessException"); } catch (IllegalAccessException e) { // pass } field = StaticContainer.class.getDeclaredField("mutablePackage"); try { FieldUtils.writeStaticField(field, "new"); fail("Expected IllegalAccessException"); } catch (IllegalAccessException e) { // pass } field = StaticContainer.class.getDeclaredField("mutablePrivate"); try { FieldUtils.writeStaticField(field, "new"); fail("Expected IllegalAccessException"); } catch (IllegalAccessException e) { // pass } field = StaticContainer.class.getDeclaredField("IMMUTABLE_PUBLIC"); try { FieldUtils.writeStaticField(field, "new"); fail("Expected IllegalAccessException"); } catch (IllegalAccessException e) { // pass } field = StaticContainer.class.getDeclaredField("IMMUTABLE_PROTECTED"); try { FieldUtils.writeStaticField(field, "new"); fail("Expected IllegalAccessException"); } catch (IllegalAccessException e) { // pass } field = StaticContainer.class.getDeclaredField("IMMUTABLE_PACKAGE"); try { FieldUtils.writeStaticField(field, "new"); fail("Expected IllegalAccessException"); } catch (IllegalAccessException e) { // pass } field = StaticContainer.class.getDeclaredField("IMMUTABLE_PRIVATE"); try { FieldUtils.writeStaticField(field, "new"); fail("Expected IllegalAccessException"); } catch (IllegalAccessException e) { // pass } } public void testWriteStaticFieldForceAccess() throws Exception { Field field = StaticContainer.class.getDeclaredField("mutablePublic"); FieldUtils.writeStaticField(field, "new", true); assertEquals("new", StaticContainer.mutablePublic); field = StaticContainer.class.getDeclaredField("mutableProtected"); FieldUtils.writeStaticField(field, "new", true); assertEquals("new", StaticContainer.getMutableProtected()); field = StaticContainer.class.getDeclaredField("mutablePackage"); FieldUtils.writeStaticField(field, "new", true); assertEquals("new", StaticContainer.getMutablePackage()); field = StaticContainer.class.getDeclaredField("mutablePrivate"); FieldUtils.writeStaticField(field, "new", true); assertEquals("new", StaticContainer.getMutablePrivate()); field = StaticContainer.class.getDeclaredField("IMMUTABLE_PUBLIC"); try { FieldUtils.writeStaticField(field, "new", true); fail("Expected IllegalAccessException"); } catch (IllegalAccessException e) { // pass } field = StaticContainer.class.getDeclaredField("IMMUTABLE_PROTECTED"); try { FieldUtils.writeStaticField(field, "new", true); fail("Expected IllegalAccessException"); } catch (IllegalAccessException e) { // pass } field = StaticContainer.class.getDeclaredField("IMMUTABLE_PACKAGE"); try { FieldUtils.writeStaticField(field, "new", true); fail("Expected IllegalAccessException"); } catch (IllegalAccessException e) { // pass } field = StaticContainer.class.getDeclaredField("IMMUTABLE_PRIVATE"); try { FieldUtils.writeStaticField(field, "new", true); fail("Expected IllegalAccessException"); } catch (IllegalAccessException e) { // pass } } public void testWriteNamedStaticField() throws Exception { FieldUtils.writeStaticField(StaticContainerChild.class, "mutablePublic", "new"); assertEquals("new", StaticContainer.mutablePublic); try { FieldUtils.writeStaticField(StaticContainerChild.class, "mutableProtected", "new"); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // pass } try { FieldUtils.writeStaticField(StaticContainerChild.class, "mutablePackage", "new"); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // pass } try { FieldUtils.writeStaticField(StaticContainerChild.class, "mutablePrivate", "new"); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // pass } try { FieldUtils.writeStaticField(StaticContainerChild.class, "IMMUTABLE_PUBLIC", "new"); fail("Expected IllegalAccessException"); } catch (IllegalAccessException e) { // pass } try { FieldUtils.writeStaticField(StaticContainerChild.class, "IMMUTABLE_PROTECTED", "new"); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // pass } try { FieldUtils.writeStaticField(StaticContainerChild.class, "IMMUTABLE_PACKAGE", "new"); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // pass } try { FieldUtils.writeStaticField(StaticContainerChild.class, "IMMUTABLE_PRIVATE", "new"); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // pass } } public void testWriteNamedStaticFieldForceAccess() throws Exception { FieldUtils.writeStaticField(StaticContainerChild.class, "mutablePublic", "new", true); assertEquals("new", StaticContainer.mutablePublic); FieldUtils.writeStaticField(StaticContainerChild.class, "mutableProtected", "new", true); assertEquals("new", StaticContainer.getMutableProtected()); FieldUtils.writeStaticField(StaticContainerChild.class, "mutablePackage", "new", true); assertEquals("new", StaticContainer.getMutablePackage()); FieldUtils.writeStaticField(StaticContainerChild.class, "mutablePrivate", "new", true); assertEquals("new", StaticContainer.getMutablePrivate()); try { FieldUtils.writeStaticField(StaticContainerChild.class, "IMMUTABLE_PUBLIC", "new", true); fail("Expected IllegalAccessException"); } catch (IllegalAccessException e) { // pass } try { FieldUtils.writeStaticField(StaticContainerChild.class, "IMMUTABLE_PROTECTED", "new", true); fail("Expected IllegalAccessException"); } catch (IllegalAccessException e) { // pass } try { FieldUtils.writeStaticField(StaticContainerChild.class, "IMMUTABLE_PACKAGE", "new", true); fail("Expected IllegalAccessException"); } catch (IllegalAccessException e) { // pass } try { FieldUtils.writeStaticField(StaticContainerChild.class, "IMMUTABLE_PRIVATE", "new", true); fail("Expected IllegalAccessException"); } catch (IllegalAccessException e) { // pass } } public void testWriteDeclaredNamedStaticField() throws Exception { FieldUtils.writeStaticField(StaticContainer.class, "mutablePublic", "new"); assertEquals("new", StaticContainer.mutablePublic); try { FieldUtils.writeDeclaredStaticField(StaticContainer.class, "mutableProtected", "new"); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // pass } try { FieldUtils.writeDeclaredStaticField(StaticContainer.class, "mutablePackage", "new"); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // pass } try { FieldUtils.writeDeclaredStaticField(StaticContainer.class, "mutablePrivate", "new"); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // pass } try { FieldUtils.writeDeclaredStaticField(StaticContainer.class, "IMMUTABLE_PUBLIC", "new"); fail("Expected IllegalAccessException"); } catch (IllegalAccessException e) { // pass } try { FieldUtils.writeDeclaredStaticField(StaticContainer.class, "IMMUTABLE_PROTECTED", "new"); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // pass } try { FieldUtils.writeDeclaredStaticField(StaticContainer.class, "IMMUTABLE_PACKAGE", "new"); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // pass } try { FieldUtils.writeDeclaredStaticField(StaticContainer.class, "IMMUTABLE_PRIVATE", "new"); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // pass } } public void testWriteDeclaredNamedStaticFieldForceAccess() throws Exception { FieldUtils.writeDeclaredStaticField(StaticContainer.class, "mutablePublic", "new", true); assertEquals("new", StaticContainer.mutablePublic); FieldUtils.writeDeclaredStaticField(StaticContainer.class, "mutableProtected", "new", true); assertEquals("new", StaticContainer.getMutableProtected()); FieldUtils.writeDeclaredStaticField(StaticContainer.class, "mutablePackage", "new", true); assertEquals("new", StaticContainer.getMutablePackage()); FieldUtils.writeDeclaredStaticField(StaticContainer.class, "mutablePrivate", "new", true); assertEquals("new", StaticContainer.getMutablePrivate()); try { FieldUtils.writeDeclaredStaticField(StaticContainer.class, "IMMUTABLE_PUBLIC", "new", true); fail("Expected IllegalAccessException"); } catch (IllegalAccessException e) { // pass } try { FieldUtils.writeDeclaredStaticField(StaticContainer.class, "IMMUTABLE_PROTECTED", "new", true); fail("Expected IllegalAccessException"); } catch (IllegalAccessException e) { // pass } try { FieldUtils.writeDeclaredStaticField(StaticContainer.class, "IMMUTABLE_PACKAGE", "new", true); fail("Expected IllegalAccessException"); } catch (IllegalAccessException e) { // pass } try { FieldUtils.writeDeclaredStaticField(StaticContainer.class, "IMMUTABLE_PRIVATE", "new", true); fail("Expected IllegalAccessException"); } catch (IllegalAccessException e) { // pass } } public void testWriteField() throws Exception { Field field = parentClass.getDeclaredField("s"); FieldUtils.writeField(field, publicChild, "S"); assertEquals("S", field.get(publicChild)); field = parentClass.getDeclaredField("b"); try { FieldUtils.writeField(field, publicChild, Boolean.TRUE); fail("Expected IllegalAccessException"); } catch (IllegalAccessException e) { // pass } field = parentClass.getDeclaredField("i"); try { FieldUtils.writeField(field, publicChild, new Integer(Integer.MAX_VALUE)); } catch (IllegalAccessException e) { // pass } field = parentClass.getDeclaredField("d"); try { FieldUtils.writeField(field, publicChild, new Double(Double.MAX_VALUE)); } catch (IllegalAccessException e) { // pass } } public void testWriteFieldForceAccess() throws Exception { Field field = parentClass.getDeclaredField("s"); FieldUtils.writeField(field, publicChild, "S", true); assertEquals("S", field.get(publicChild)); field = parentClass.getDeclaredField("b"); FieldUtils.writeField(field, publicChild, Boolean.TRUE, true); assertEquals(Boolean.TRUE, field.get(publicChild)); field = parentClass.getDeclaredField("i"); FieldUtils.writeField(field, publicChild, new Integer(Integer.MAX_VALUE), true); assertEquals(new Integer(Integer.MAX_VALUE), field.get(publicChild)); field = parentClass.getDeclaredField("d"); FieldUtils.writeField(field, publicChild, new Double(Double.MAX_VALUE), true); assertEquals(new Double(Double.MAX_VALUE), field.get(publicChild)); } public void testWriteNamedField() throws Exception { FieldUtils.writeField(publicChild, "s", "S"); assertEquals("S", FieldUtils.readField(publicChild, "s")); try { FieldUtils.writeField(publicChild, "b", Boolean.TRUE); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // pass } try { FieldUtils.writeField(publicChild, "i", new Integer(1)); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // pass } try { FieldUtils.writeField(publicChild, "d", new Double(1.0)); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // pass } FieldUtils.writeField(publiclyShadowedChild, "s", "S"); assertEquals("S", FieldUtils.readField(publiclyShadowedChild, "s")); FieldUtils.writeField(publiclyShadowedChild, "b", Boolean.FALSE); assertEquals(Boolean.FALSE, FieldUtils.readField(publiclyShadowedChild, "b")); FieldUtils.writeField(publiclyShadowedChild, "i", new Integer(0)); assertEquals(new Integer(0), FieldUtils.readField(publiclyShadowedChild, "i")); FieldUtils.writeField(publiclyShadowedChild, "d", new Double(0.0)); assertEquals(new Double(0.0), FieldUtils.readField(publiclyShadowedChild, "d")); FieldUtils.writeField(privatelyShadowedChild, "s", "S"); assertEquals("S", FieldUtils.readField(privatelyShadowedChild, "s")); try { FieldUtils.writeField(privatelyShadowedChild, "b", Boolean.TRUE); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // pass } try { FieldUtils.writeField(privatelyShadowedChild, "i", new Integer(1)); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // pass } try { FieldUtils.writeField(privatelyShadowedChild, "d", new Double(1.0)); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // pass } } public void testWriteNamedFieldForceAccess() throws Exception { FieldUtils.writeField(publicChild, "s", "S", true); assertEquals("S", FieldUtils.readField(publicChild, "s", true)); FieldUtils.writeField(publicChild, "b", Boolean.TRUE, true); assertEquals(Boolean.TRUE, FieldUtils.readField(publicChild, "b", true)); FieldUtils.writeField(publicChild, "i", new Integer(1), true); assertEquals(new Integer(1), FieldUtils.readField(publicChild, "i", true)); FieldUtils.writeField(publicChild, "d", new Double(1.0), true); assertEquals(new Double(1.0), FieldUtils.readField(publicChild, "d", true)); FieldUtils.writeField(publiclyShadowedChild, "s", "S", true); assertEquals("S", FieldUtils.readField(publiclyShadowedChild, "s", true)); FieldUtils.writeField(publiclyShadowedChild, "b", Boolean.FALSE, true); assertEquals(Boolean.FALSE, FieldUtils.readField(publiclyShadowedChild, "b", true)); FieldUtils.writeField(publiclyShadowedChild, "i", new Integer(0), true); assertEquals(new Integer(0), FieldUtils.readField(publiclyShadowedChild, "i", true)); FieldUtils.writeField(publiclyShadowedChild, "d", new Double(0.0), true); assertEquals(new Double(0.0), FieldUtils.readField(publiclyShadowedChild, "d", true)); FieldUtils.writeField(privatelyShadowedChild, "s", "S", true); assertEquals("S", FieldUtils.readField(privatelyShadowedChild, "s", true)); FieldUtils.writeField(privatelyShadowedChild, "b", Boolean.FALSE, true); assertEquals(Boolean.FALSE, FieldUtils.readField(privatelyShadowedChild, "b", true)); FieldUtils.writeField(privatelyShadowedChild, "i", new Integer(0), true); assertEquals(new Integer(0), FieldUtils.readField(privatelyShadowedChild, "i", true)); FieldUtils.writeField(privatelyShadowedChild, "d", new Double(0.0), true); assertEquals(new Double(0.0), FieldUtils.readField(privatelyShadowedChild, "d", true)); } public void testWriteDeclaredNamedField() throws Exception { try { FieldUtils.writeDeclaredField(publicChild, "s", "S"); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // pass } try { FieldUtils.writeDeclaredField(publicChild, "b", Boolean.TRUE); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // pass } try { FieldUtils.writeDeclaredField(publicChild, "i", new Integer(1)); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // pass } try { FieldUtils.writeDeclaredField(publicChild, "d", new Double(1.0)); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // pass } FieldUtils.writeDeclaredField(publiclyShadowedChild, "s", "S"); assertEquals("S", FieldUtils.readDeclaredField(publiclyShadowedChild, "s")); FieldUtils.writeDeclaredField(publiclyShadowedChild, "b", Boolean.FALSE); assertEquals(Boolean.FALSE, FieldUtils.readDeclaredField(publiclyShadowedChild, "b")); FieldUtils.writeDeclaredField(publiclyShadowedChild, "i", new Integer(0)); assertEquals(new Integer(0), FieldUtils.readDeclaredField(publiclyShadowedChild, "i")); FieldUtils.writeDeclaredField(publiclyShadowedChild, "d", new Double(0.0)); assertEquals(new Double(0.0), FieldUtils.readDeclaredField(publiclyShadowedChild, "d")); try { FieldUtils.writeDeclaredField(privatelyShadowedChild, "s", "S"); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // pass } try { FieldUtils.writeDeclaredField(privatelyShadowedChild, "b", Boolean.TRUE); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // pass } try { FieldUtils.writeDeclaredField(privatelyShadowedChild, "i", new Integer(1)); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // pass } try { FieldUtils.writeDeclaredField(privatelyShadowedChild, "d", new Double(1.0)); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // pass } } public void testWriteDeclaredNamedFieldForceAccess() throws Exception { try { FieldUtils.writeDeclaredField(publicChild, "s", "S", true); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // pass } try { FieldUtils.writeDeclaredField(publicChild, "b", Boolean.TRUE, true); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // pass } try { FieldUtils.writeDeclaredField(publicChild, "i", new Integer(1), true); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // pass } try { FieldUtils.writeDeclaredField(publicChild, "d", new Double(1.0), true); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // pass } FieldUtils.writeDeclaredField(publiclyShadowedChild, "s", "S", true); assertEquals("S", FieldUtils.readDeclaredField(publiclyShadowedChild, "s", true)); FieldUtils.writeDeclaredField(publiclyShadowedChild, "b", Boolean.FALSE, true); assertEquals(Boolean.FALSE, FieldUtils.readDeclaredField(publiclyShadowedChild, "b", true)); FieldUtils.writeDeclaredField(publiclyShadowedChild, "i", new Integer(0), true); assertEquals(new Integer(0), FieldUtils.readDeclaredField(publiclyShadowedChild, "i", true)); FieldUtils.writeDeclaredField(publiclyShadowedChild, "d", new Double(0.0), true); assertEquals(new Double(0.0), FieldUtils.readDeclaredField(publiclyShadowedChild, "d", true)); FieldUtils.writeDeclaredField(privatelyShadowedChild, "s", "S", true); assertEquals("S", FieldUtils.readDeclaredField(privatelyShadowedChild, "s", true)); FieldUtils.writeDeclaredField(privatelyShadowedChild, "b", Boolean.FALSE, true); assertEquals(Boolean.FALSE, FieldUtils.readDeclaredField(privatelyShadowedChild, "b", true)); FieldUtils.writeDeclaredField(privatelyShadowedChild, "i", new Integer(0), true); assertEquals(new Integer(0), FieldUtils.readDeclaredField(privatelyShadowedChild, "i", true)); FieldUtils.writeDeclaredField(privatelyShadowedChild, "d", new Double(0.0), true); assertEquals(new Double(0.0), FieldUtils.readDeclaredField(privatelyShadowedChild, "d", true)); } public void testAmbig() { try { FieldUtils.getField(Ambig.class, "VALUE"); fail("should have failed on interface field ambiguity"); } catch (IllegalArgumentException e) { // pass } } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/reflect/MethodUtilsTest.java100644 0 0 36013 11513702436 26377 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.reflect; import java.lang.reflect.Method; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import junit.framework.TestCase; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.math.NumberUtils; import org.apache.commons.lang.mutable.Mutable; import org.apache.commons.lang.mutable.MutableObject; /** * Unit tests MethodUtils * @author mbenson * @version $Id: MethodUtilsTest.java 1057013 2011-01-09 20:04:16Z niallp $ */ public class MethodUtilsTest extends TestCase { public static class TestBean { public static String bar() { return "bar()"; } public static String bar(int i) { return "bar(int)"; } public static String bar(Integer i) { return "bar(Integer)"; } public static String bar(double d) { return "bar(double)"; } public static String bar(String s) { return "bar(String)"; } public static String bar(Object o) { return "bar(Object)"; } public String foo() { return "foo()"; } public String foo(int i) { return "foo(int)"; } public String foo(Integer i) { return "foo(Integer)"; } public String foo(double d) { return "foo(double)"; } public String foo(String s) { return "foo(String)"; } public String foo(Object o) { return "foo(Object)"; } } private static class TestMutable implements Mutable { public Object getValue() { return null; } public void setValue(Object value) { } } private TestBean testBean; private Map classCache; public MethodUtilsTest(String name) { super(name); classCache = new HashMap(); } protected void setUp() throws Exception { super.setUp(); testBean = new TestBean(); classCache.clear(); } public void testConstructor() throws Exception { assertNotNull(MethodUtils.class.newInstance()); } public void testInvokeMethod() throws Exception { assertEquals("foo()", MethodUtils.invokeMethod(testBean, "foo", ArrayUtils.EMPTY_CLASS_ARRAY)); assertEquals("foo()", MethodUtils.invokeMethod(testBean, "foo", (Class[]) null)); assertEquals("foo(String)", MethodUtils.invokeMethod(testBean, "foo", "")); assertEquals("foo(Object)", MethodUtils.invokeMethod(testBean, "foo", new Object())); assertEquals("foo(Object)", MethodUtils.invokeMethod(testBean, "foo", Boolean.TRUE)); assertEquals("foo(Integer)", MethodUtils.invokeMethod(testBean, "foo", NumberUtils.INTEGER_ONE)); assertEquals("foo(int)", MethodUtils.invokeMethod(testBean, "foo", NumberUtils.BYTE_ONE)); assertEquals("foo(double)", MethodUtils.invokeMethod(testBean, "foo", NumberUtils.LONG_ONE)); assertEquals("foo(double)", MethodUtils.invokeMethod(testBean, "foo", NumberUtils.DOUBLE_ONE)); } public void testInvokeExactMethod() throws Exception { assertEquals("foo()", MethodUtils.invokeMethod(testBean, "foo", ArrayUtils.EMPTY_CLASS_ARRAY)); assertEquals("foo()", MethodUtils.invokeMethod(testBean, "foo", (Class[]) null)); assertEquals("foo(String)", MethodUtils.invokeExactMethod(testBean, "foo", "")); assertEquals("foo(Object)", MethodUtils.invokeExactMethod(testBean, "foo", new Object())); assertEquals("foo(Integer)", MethodUtils.invokeExactMethod(testBean, "foo", NumberUtils.INTEGER_ONE)); assertEquals("foo(double)", MethodUtils.invokeExactMethod(testBean, "foo", new Object[] { NumberUtils.DOUBLE_ONE }, new Class[] { Double.TYPE })); try { MethodUtils .invokeExactMethod(testBean, "foo", NumberUtils.BYTE_ONE); fail("should throw NoSuchMethodException"); } catch (NoSuchMethodException e) { } try { MethodUtils .invokeExactMethod(testBean, "foo", NumberUtils.LONG_ONE); fail("should throw NoSuchMethodException"); } catch (NoSuchMethodException e) { } try { MethodUtils.invokeExactMethod(testBean, "foo", Boolean.TRUE); fail("should throw NoSuchMethodException"); } catch (NoSuchMethodException e) { } } public void testInvokeStaticMethod() throws Exception { assertEquals("bar()", MethodUtils.invokeStaticMethod(TestBean.class, "bar", ArrayUtils.EMPTY_CLASS_ARRAY)); assertEquals("bar()", MethodUtils.invokeStaticMethod(TestBean.class, "bar", (Class[]) null)); assertEquals("bar(String)", MethodUtils.invokeStaticMethod( TestBean.class, "bar", "")); assertEquals("bar(Object)", MethodUtils.invokeStaticMethod( TestBean.class, "bar", new Object())); assertEquals("bar(Object)", MethodUtils.invokeStaticMethod( TestBean.class, "bar", Boolean.TRUE)); assertEquals("bar(Integer)", MethodUtils.invokeStaticMethod( TestBean.class, "bar", NumberUtils.INTEGER_ONE)); assertEquals("bar(int)", MethodUtils.invokeStaticMethod(TestBean.class, "bar", NumberUtils.BYTE_ONE)); assertEquals("bar(double)", MethodUtils.invokeStaticMethod( TestBean.class, "bar", NumberUtils.LONG_ONE)); assertEquals("bar(double)", MethodUtils.invokeStaticMethod( TestBean.class, "bar", NumberUtils.DOUBLE_ONE)); } public void testInvokeExactStaticMethod() throws Exception { assertEquals("bar()", MethodUtils.invokeStaticMethod(TestBean.class, "bar", ArrayUtils.EMPTY_CLASS_ARRAY)); assertEquals("bar()", MethodUtils.invokeStaticMethod(TestBean.class, "bar", (Class[]) null)); assertEquals("bar(String)", MethodUtils.invokeExactStaticMethod( TestBean.class, "bar", "")); assertEquals("bar(Object)", MethodUtils.invokeExactStaticMethod( TestBean.class, "bar", new Object())); assertEquals("bar(Integer)", MethodUtils.invokeExactStaticMethod( TestBean.class, "bar", NumberUtils.INTEGER_ONE)); assertEquals("bar(double)", MethodUtils.invokeExactStaticMethod( TestBean.class, "bar", new Object[] { NumberUtils.DOUBLE_ONE }, new Class[] { Double.TYPE })); try { MethodUtils.invokeExactStaticMethod(TestBean.class, "bar", NumberUtils.BYTE_ONE); fail("should throw NoSuchMethodException"); } catch (NoSuchMethodException e) { } try { MethodUtils.invokeExactStaticMethod(TestBean.class, "bar", NumberUtils.LONG_ONE); fail("should throw NoSuchMethodException"); } catch (NoSuchMethodException e) { } try { MethodUtils.invokeExactStaticMethod(TestBean.class, "bar", Boolean.TRUE); fail("should throw NoSuchMethodException"); } catch (NoSuchMethodException e) { } } public void testGetAccessibleInterfaceMethod() throws Exception { Class[][] p = { ArrayUtils.EMPTY_CLASS_ARRAY, null }; for (int i = 0; i < p.length; i++) { Method method = TestMutable.class.getMethod("getValue", p[i]); Method accessibleMethod = MethodUtils.getAccessibleMethod(method); assertNotSame(accessibleMethod, method); assertSame(Mutable.class, accessibleMethod.getDeclaringClass()); } } public void testGetAccessibleInterfaceMethodFromDescription() throws Exception { Class[][] p = { ArrayUtils.EMPTY_CLASS_ARRAY, null }; for (int i = 0; i < p.length; i++) { Method accessibleMethod = MethodUtils.getAccessibleMethod( TestMutable.class, "getValue", p[i]); assertSame(Mutable.class, accessibleMethod.getDeclaringClass()); } } public void testGetAccessiblePublicMethod() throws Exception { assertSame(MutableObject.class, MethodUtils.getAccessibleMethod( MutableObject.class.getMethod("getValue", ArrayUtils.EMPTY_CLASS_ARRAY)).getDeclaringClass()); } public void testGetAccessiblePublicMethodFromDescription() throws Exception { assertSame(MutableObject.class, MethodUtils.getAccessibleMethod( MutableObject.class, "getValue", ArrayUtils.EMPTY_CLASS_ARRAY) .getDeclaringClass()); } public void testGetMatchingAccessibleMethod() throws Exception { expectMatchingAccessibleMethodParameterTypes(TestBean.class, "foo", ArrayUtils.EMPTY_CLASS_ARRAY, ArrayUtils.EMPTY_CLASS_ARRAY); expectMatchingAccessibleMethodParameterTypes(TestBean.class, "foo", null, ArrayUtils.EMPTY_CLASS_ARRAY); expectMatchingAccessibleMethodParameterTypes(TestBean.class, "foo", singletonArray(String.class), singletonArray(String.class)); expectMatchingAccessibleMethodParameterTypes(TestBean.class, "foo", singletonArray(Object.class), singletonArray(Object.class)); expectMatchingAccessibleMethodParameterTypes(TestBean.class, "foo", singletonArray(Boolean.class), singletonArray(Object.class)); expectMatchingAccessibleMethodParameterTypes(TestBean.class, "foo", singletonArray(Byte.class), singletonArray(Integer.TYPE)); expectMatchingAccessibleMethodParameterTypes(TestBean.class, "foo", singletonArray(Byte.TYPE), singletonArray(Integer.TYPE)); expectMatchingAccessibleMethodParameterTypes(TestBean.class, "foo", singletonArray(Short.class), singletonArray(Integer.TYPE)); expectMatchingAccessibleMethodParameterTypes(TestBean.class, "foo", singletonArray(Short.TYPE), singletonArray(Integer.TYPE)); expectMatchingAccessibleMethodParameterTypes(TestBean.class, "foo", singletonArray(Character.class), singletonArray(Integer.TYPE)); expectMatchingAccessibleMethodParameterTypes(TestBean.class, "foo", singletonArray(Character.TYPE), singletonArray(Integer.TYPE)); expectMatchingAccessibleMethodParameterTypes(TestBean.class, "foo", singletonArray(Integer.class), singletonArray(Integer.class)); expectMatchingAccessibleMethodParameterTypes(TestBean.class, "foo", singletonArray(Integer.TYPE), singletonArray(Integer.TYPE)); expectMatchingAccessibleMethodParameterTypes(TestBean.class, "foo", singletonArray(Long.class), singletonArray(Double.TYPE)); expectMatchingAccessibleMethodParameterTypes(TestBean.class, "foo", singletonArray(Long.TYPE), singletonArray(Double.TYPE)); expectMatchingAccessibleMethodParameterTypes(TestBean.class, "foo", singletonArray(Float.class), singletonArray(Double.TYPE)); expectMatchingAccessibleMethodParameterTypes(TestBean.class, "foo", singletonArray(Float.TYPE), singletonArray(Double.TYPE)); expectMatchingAccessibleMethodParameterTypes(TestBean.class, "foo", singletonArray(Double.class), singletonArray(Double.TYPE)); expectMatchingAccessibleMethodParameterTypes(TestBean.class, "foo", singletonArray(Double.TYPE), singletonArray(Double.TYPE)); expectMatchingAccessibleMethodParameterTypes(TestBean.class, "foo", singletonArray(Double.TYPE), singletonArray(Double.TYPE)); expectMatchingAccessibleMethodParameterTypes(InheritanceBean.class, "testOne", singletonArray(ParentObject.class), singletonArray(ParentObject.class)); expectMatchingAccessibleMethodParameterTypes(InheritanceBean.class, "testOne", singletonArray(ChildObject.class), singletonArray(ParentObject.class)); expectMatchingAccessibleMethodParameterTypes(InheritanceBean.class, "testTwo", singletonArray(ParentObject.class), singletonArray(GrandParentObject.class)); expectMatchingAccessibleMethodParameterTypes(InheritanceBean.class, "testTwo", singletonArray(ChildObject.class), singletonArray(ChildInterface.class)); } private void expectMatchingAccessibleMethodParameterTypes(Class cls, String methodName, Class[] requestTypes, Class[] actualTypes) { Method m = MethodUtils.getMatchingAccessibleMethod(cls, methodName, requestTypes); assertTrue(toString(m.getParameterTypes()) + " not equals " + toString(actualTypes), Arrays.equals(actualTypes, m .getParameterTypes())); } private String toString(Class[] c) { return Arrays.asList(c).toString(); } private Class[] singletonArray(Class c) { Class[] result = (Class[]) classCache.get(c); if (result == null) { result = new Class[] { c }; classCache.put(c, result); } return result; } public static class InheritanceBean { public void testOne(Object obj) {} public void testOne(GrandParentObject obj) {} public void testOne(ParentObject obj) {} public void testTwo(Object obj) {} public void testTwo(GrandParentObject obj) {} public void testTwo(ChildInterface obj) {} } interface ChildInterface {} public static class GrandParentObject {} public static class ParentObject extends GrandParentObject {} public static class ChildObject extends ParentObject implements ChildInterface {} } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/reflect/testbed/Ambig.java100644 0 0 1763 11513702436 25733 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.reflect.testbed; /** * @author mbenson * @version $Id: Ambig.java 653918 2008-05-06 20:45:11Z mbenson $ */ public class Ambig implements Foo, Bar { }commons-lang-2.6-src/src/test/java/org/apache/commons/lang/reflect/testbed/Bar.java100644 0 0 2016 11513702436 25410 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.reflect.testbed; /** * @author mbenson * @version $Id: Bar.java 653918 2008-05-06 20:45:11Z mbenson $ */ public interface Bar { public static final String VALUE = "bar"; }commons-lang-2.6-src/src/test/java/org/apache/commons/lang/reflect/testbed/Foo.java100644 0 0 2016 11513702436 25427 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.reflect.testbed; /** * @author mbenson * @version $Id: Foo.java 653918 2008-05-06 20:45:11Z mbenson $ */ public interface Foo { public static final String VALUE = "foo"; }commons-lang-2.6-src/src/test/java/org/apache/commons/lang/reflect/testbed/Parent.java100644 0 0 2124 11513702436 26135 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.reflect.testbed; /** * @author mbenson * @version $Id: Parent.java 653918 2008-05-06 20:45:11Z mbenson $ */ class Parent implements Foo { public String s = "s"; protected boolean b = false; int i = 0; private double d = 0.0; }././@LongLink100644 0 0 147 11513702661 10257 Lustar 0 0 commons-lang-2.6-src/src/test/java/org/apache/commons/lang/reflect/testbed/PrivatelyShadowedChild.javacommons-lang-2.6-src/src/test/java/org/apache/commons/lang/reflect/testbed/PrivatelyShadowedChild.ja100644 0 0 2202 11513702436 30754 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.reflect.testbed; /** * @author mbenson * @version $Id: PrivatelyShadowedChild.java 653918 2008-05-06 20:45:11Z mbenson $ */ public class PrivatelyShadowedChild extends Parent { private String s = "ss"; private boolean b = true; private int i = 1; private double d = 1.0; }commons-lang-2.6-src/src/test/java/org/apache/commons/lang/reflect/testbed/PublicChild.java100644 0 0 2044 11513702436 27067 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.reflect.testbed; /** * @author mbenson * @version $Id: PublicChild.java 653918 2008-05-06 20:45:11Z mbenson $ */ public class PublicChild extends Parent { static final String VALUE = "child"; }././@LongLink100644 0 0 146 11513702661 10256 Lustar 0 0 commons-lang-2.6-src/src/test/java/org/apache/commons/lang/reflect/testbed/PubliclyShadowedChild.javacommons-lang-2.6-src/src/test/java/org/apache/commons/lang/reflect/testbed/PubliclyShadowedChild.jav100644 0 0 2174 11513702436 30756 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.reflect.testbed; /** * @author mbenson * @version $Id: PubliclyShadowedChild.java 653918 2008-05-06 20:45:11Z mbenson $ */ public class PubliclyShadowedChild extends Parent { public String s = "ss"; public boolean b = true; public int i = 1; public double d = 1.0; }commons-lang-2.6-src/src/test/java/org/apache/commons/lang/reflect/testbed/StaticContainer.java100644 0 0 3514 11513702436 30002 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.reflect.testbed; /** * @author mbenson * @version $Id: StaticContainer.java 653918 2008-05-06 20:45:11Z mbenson $ */ public class StaticContainer { public static final Object IMMUTABLE_PUBLIC = "public"; protected static final Object IMMUTABLE_PROTECTED = "protected"; static final Object IMMUTABLE_PACKAGE = ""; private static final Object IMMUTABLE_PRIVATE = "private"; public static Object mutablePublic; protected static Object mutableProtected; static Object mutablePackage; private static Object mutablePrivate; public static void reset() { mutablePublic = null; mutableProtected = null; mutablePackage = null; mutablePrivate = null; } public static Object getMutableProtected() { return mutableProtected; } public static Object getMutablePackage() { return mutablePackage; } public static Object getMutablePrivate() { return mutablePrivate; } } ././@LongLink100644 0 0 145 11513702661 10255 Lustar 0 0 commons-lang-2.6-src/src/test/java/org/apache/commons/lang/reflect/testbed/StaticContainerChild.javacommons-lang-2.6-src/src/test/java/org/apache/commons/lang/reflect/testbed/StaticContainerChild.java100644 0 0 2031 11513702436 30737 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.reflect.testbed; /** * @author mbenson * @version $Id: StaticContainerChild.java 653918 2008-05-06 20:45:11Z mbenson $ */ public class StaticContainerChild extends StaticContainer { } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/SerializationUtilsTest.java100644 0 0 32702 11513702441 26345 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.io.Serializable; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.util.HashMap; import junit.framework.TestCase; /** * Unit tests {@link org.apache.commons.lang.SerializationUtils}. * * @author Apache Software Foundation * @author Ringo De Smet * @version $Id: SerializationUtilsTest.java 905687 2010-02-02 16:08:23Z niallp $ */ public class SerializationUtilsTest extends TestCase { static final String CLASS_NOT_FOUND_MESSAGE = "ClassNotFoundSerialization.readObject fake exception"; protected static final String SERIALIZE_IO_EXCEPTION_MESSAGE = "Anonymous OutputStream I/O exception"; private String iString; private Integer iInteger; private HashMap iMap; public SerializationUtilsTest(String name) { super(name); } protected void setUp() throws Exception { super.setUp(); iString = "foo"; iInteger = new Integer(7); iMap = new HashMap(); iMap.put("FOO", iString); iMap.put("BAR", iInteger); } //----------------------------------------------------------------------- public void testConstructor() { assertNotNull(new SerializationUtils()); Constructor[] cons = SerializationUtils.class.getDeclaredConstructors(); assertEquals(1, cons.length); assertEquals(true, Modifier.isPublic(cons[0].getModifiers())); assertEquals(true, Modifier.isPublic(SerializationUtils.class.getModifiers())); assertEquals(false, Modifier.isFinal(SerializationUtils.class.getModifiers())); } public void testException() { SerializationException serEx; Exception ex = new Exception(); serEx = new SerializationException(); assertSame(null, serEx.getMessage()); assertSame(null, serEx.getCause()); serEx = new SerializationException("Message"); assertSame("Message", serEx.getMessage()); assertSame(null, serEx.getCause()); serEx = new SerializationException(ex); assertEquals("java.lang.Exception", serEx.getMessage()); assertSame(ex, serEx.getCause()); serEx = new SerializationException("Message", ex); assertSame("Message", serEx.getMessage()); assertSame(ex, serEx.getCause()); } //----------------------------------------------------------------------- public void testSerializeStream() throws Exception { ByteArrayOutputStream streamTest = new ByteArrayOutputStream(); SerializationUtils.serialize(iMap, streamTest); ByteArrayOutputStream streamReal = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(streamReal); oos.writeObject(iMap); oos.flush(); oos.close(); byte[] testBytes = streamTest.toByteArray(); byte[] realBytes = streamReal.toByteArray(); assertEquals(testBytes.length, realBytes.length); for (int i = 0; i < realBytes.length; i++) { assertEquals(realBytes[i], testBytes[i]); } } public void testSerializeStreamUnserializable() throws Exception { ByteArrayOutputStream streamTest = new ByteArrayOutputStream(); try { iMap.put(new Object(), new Object()); SerializationUtils.serialize(iMap, streamTest); } catch (SerializationException ex) { return; } fail(); } public void testSerializeStreamNullObj() throws Exception { ByteArrayOutputStream streamTest = new ByteArrayOutputStream(); SerializationUtils.serialize(null, streamTest); ByteArrayOutputStream streamReal = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(streamReal); oos.writeObject(null); oos.flush(); oos.close(); byte[] testBytes = streamTest.toByteArray(); byte[] realBytes = streamReal.toByteArray(); assertEquals(testBytes.length, realBytes.length); for (int i = 0; i < realBytes.length; i++) { assertEquals(realBytes[i], testBytes[i]); } } public void testSerializeStreamObjNull() throws Exception { try { SerializationUtils.serialize(iMap, null); } catch (IllegalArgumentException ex) { return; } fail(); } public void testSerializeStreamNullNull() throws Exception { try { SerializationUtils.serialize(null, null); } catch (IllegalArgumentException ex) { return; } fail(); } public void testSerializeIOException() throws Exception { // forces an IOException when the ObjectOutputStream is created, to test not closing the stream // in the finally block OutputStream streamTest = new OutputStream() { public void write(int arg0) throws IOException { throw new IOException(SERIALIZE_IO_EXCEPTION_MESSAGE); } }; try { SerializationUtils.serialize(iMap, streamTest); } catch(SerializationException e) { assertEquals("java.io.IOException: " + SERIALIZE_IO_EXCEPTION_MESSAGE, e.getMessage()); } } //----------------------------------------------------------------------- public void testDeserializeStream() throws Exception { ByteArrayOutputStream streamReal = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(streamReal); oos.writeObject(iMap); oos.flush(); oos.close(); ByteArrayInputStream inTest = new ByteArrayInputStream(streamReal.toByteArray()); Object test = SerializationUtils.deserialize(inTest); assertNotNull(test); assertTrue(test instanceof HashMap); assertTrue(test != iMap); HashMap testMap = (HashMap) test; assertEquals(iString, testMap.get("FOO")); assertTrue(iString != testMap.get("FOO")); assertEquals(iInteger, testMap.get("BAR")); assertTrue(iInteger != testMap.get("BAR")); assertEquals(iMap, testMap); } public void testDeserializeStreamOfNull() throws Exception { ByteArrayOutputStream streamReal = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(streamReal); oos.writeObject(null); oos.flush(); oos.close(); ByteArrayInputStream inTest = new ByteArrayInputStream(streamReal.toByteArray()); Object test = SerializationUtils.deserialize(inTest); assertNull(test); } public void testDeserializeStreamNull() throws Exception { try { SerializationUtils.deserialize((InputStream) null); } catch (IllegalArgumentException ex) { return; } fail(); } public void testDeserializeStreamBadStream() throws Exception { try { SerializationUtils.deserialize(new ByteArrayInputStream(new byte[0])); } catch (SerializationException ex) { return; } fail(); } public void testDeserializeStreamClassNotFound() throws Exception { ByteArrayOutputStream streamReal = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(streamReal); oos.writeObject(new ClassNotFoundSerialization()); oos.flush(); oos.close(); ByteArrayInputStream inTest = new ByteArrayInputStream(streamReal.toByteArray()); try { Object test = SerializationUtils.deserialize(inTest); } catch(SerializationException se) { assertEquals("java.lang.ClassNotFoundException: " + CLASS_NOT_FOUND_MESSAGE, se.getMessage()); } } //----------------------------------------------------------------------- public void testSerializeBytes() throws Exception { byte[] testBytes = SerializationUtils.serialize(iMap); ByteArrayOutputStream streamReal = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(streamReal); oos.writeObject(iMap); oos.flush(); oos.close(); byte[] realBytes = streamReal.toByteArray(); assertEquals(testBytes.length, realBytes.length); for (int i = 0; i < realBytes.length; i++) { assertEquals(realBytes[i], testBytes[i]); } } public void testSerializeBytesUnserializable() throws Exception { try { iMap.put(new Object(), new Object()); SerializationUtils.serialize(iMap); } catch (SerializationException ex) { return; } fail(); } public void testSerializeBytesNull() throws Exception { byte[] testBytes = SerializationUtils.serialize(null); ByteArrayOutputStream streamReal = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(streamReal); oos.writeObject(null); oos.flush(); oos.close(); byte[] realBytes = streamReal.toByteArray(); assertEquals(testBytes.length, realBytes.length); for (int i = 0; i < realBytes.length; i++) { assertEquals(realBytes[i], testBytes[i]); } } //----------------------------------------------------------------------- public void testDeserializeBytes() throws Exception { ByteArrayOutputStream streamReal = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(streamReal); oos.writeObject(iMap); oos.flush(); oos.close(); Object test = SerializationUtils.deserialize(streamReal.toByteArray()); assertNotNull(test); assertTrue(test instanceof HashMap); assertTrue(test != iMap); HashMap testMap = (HashMap) test; assertEquals(iString, testMap.get("FOO")); assertTrue(iString != testMap.get("FOO")); assertEquals(iInteger, testMap.get("BAR")); assertTrue(iInteger != testMap.get("BAR")); assertEquals(iMap, testMap); } public void testDeserializeBytesOfNull() throws Exception { ByteArrayOutputStream streamReal = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(streamReal); oos.writeObject(null); oos.flush(); oos.close(); Object test = SerializationUtils.deserialize(streamReal.toByteArray()); assertNull(test); } public void testDeserializeBytesNull() throws Exception { try { SerializationUtils.deserialize((byte[]) null); } catch (IllegalArgumentException ex) { return; } fail(); } public void testDeserializeBytesBadStream() throws Exception { try { SerializationUtils.deserialize(new byte[0]); } catch (SerializationException ex) { return; } fail(); } //----------------------------------------------------------------------- public void testClone() throws Exception { Object test = SerializationUtils.clone(iMap); assertNotNull(test); assertTrue(test instanceof HashMap); assertTrue(test != iMap); HashMap testMap = (HashMap) test; assertEquals(iString, testMap.get("FOO")); assertTrue(iString != testMap.get("FOO")); assertEquals(iInteger, testMap.get("BAR")); assertTrue(iInteger != testMap.get("BAR")); assertEquals(iMap, testMap); } public void testCloneNull() throws Exception { Object test = SerializationUtils.clone(null); assertNull(test); } public void testCloneUnserializable() throws Exception { try { iMap.put(new Object(), new Object()); SerializationUtils.clone(iMap); } catch (SerializationException ex) { return; } fail(); } } class ClassNotFoundSerialization implements Serializable { private void readObject(ObjectInputStream in) throws ClassNotFoundException { throw new ClassNotFoundException(SerializationUtilsTest.CLASS_NOT_FOUND_MESSAGE); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/StringEscapeUtilsTest.java100644 0 0 42117 11513702441 26120 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang; import java.io.IOException; import java.io.StringWriter; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import junit.framework.TestCase; /** * Unit tests for {@link StringEscapeUtils}. * * @author Alexander Day Chaffee * @version $Id: StringEscapeUtilsTest.java 905628 2010-02-02 13:29:55Z niallp $ */ public class StringEscapeUtilsTest extends TestCase { private final static String FOO = "foo"; public StringEscapeUtilsTest(String name) { super(name); } //----------------------------------------------------------------------- public void testConstructor() { assertNotNull(new StringEscapeUtils()); Constructor[] cons = StringEscapeUtils.class.getDeclaredConstructors(); assertEquals(1, cons.length); assertEquals(true, Modifier.isPublic(cons[0].getModifiers())); assertEquals(true, Modifier.isPublic(StringEscapeUtils.class.getModifiers())); assertEquals(false, Modifier.isFinal(StringEscapeUtils.class.getModifiers())); } //----------------------------------------------------------------------- public void testEscapeJava() throws IOException { assertEquals(null, StringEscapeUtils.escapeJava(null)); try { StringEscapeUtils.escapeJava(null, null); fail(); } catch (IOException ex) { fail(); } catch (IllegalArgumentException ex) { } try { StringEscapeUtils.escapeJava(null, ""); fail(); } catch (IOException ex) { fail(); } catch (IllegalArgumentException ex) { } assertEscapeJava("empty string", "", ""); assertEscapeJava(FOO, FOO); assertEscapeJava("tab", "\\t", "\t"); assertEscapeJava("backslash", "\\\\", "\\"); assertEscapeJava("single quote should not be escaped", "'", "'"); assertEscapeJava("\\\\\\b\\t\\r", "\\\b\t\r"); assertEscapeJava("\\u1234", "\u1234"); assertEscapeJava("\\u0234", "\u0234"); assertEscapeJava("\\u00EF", "\u00ef"); assertEscapeJava("\\u0001", "\u0001"); assertEscapeJava("Should use capitalized unicode hex", "\\uABCD", "\uabcd"); assertEscapeJava("He didn't say, \\\"stop!\\\"", "He didn't say, \"stop!\""); assertEscapeJava("non-breaking space", "This space is non-breaking:" + "\\u00A0", "This space is non-breaking:\u00a0"); assertEscapeJava("\\uABCD\\u1234\\u012C", "\uABCD\u1234\u012C"); } /** * https://issues.apache.org/jira/browse/LANG-421 */ public void testEscapeJavaWithSlash() { final String input = "String with a slash (/) in it"; final String expected = input; final String actual = StringEscapeUtils.escapeJava(input); /** * In 2.4 StringEscapeUtils.escapeJava(String) escapes '/' characters, which are not a valid character to escape * in a Java string. */ assertEquals(expected, actual); } private void assertEscapeJava(String escaped, String original) throws IOException { assertEscapeJava(null, escaped, original); } private void assertEscapeJava(String message, String expected, String original) throws IOException { String converted = StringEscapeUtils.escapeJava(original); message = "escapeJava(String) failed" + (message == null ? "" : (": " + message)); assertEquals(message, expected, converted); StringWriter writer = new StringWriter(); StringEscapeUtils.escapeJava(writer, original); assertEquals(expected, writer.toString()); } public void testUnescapeJava() throws IOException { assertEquals(null, StringEscapeUtils.unescapeJava(null)); try { StringEscapeUtils.unescapeJava(null, null); fail(); } catch (IOException ex) { fail(); } catch (IllegalArgumentException ex) { } try { StringEscapeUtils.unescapeJava(null, ""); fail(); } catch (IOException ex) { fail(); } catch (IllegalArgumentException ex) { } try { StringEscapeUtils.unescapeJava("\\u02-3"); fail(); } catch (RuntimeException ex) { } assertUnescapeJava("", ""); assertUnescapeJava("test", "test"); assertUnescapeJava("\ntest\b", "\\ntest\\b"); assertUnescapeJava("\u123425foo\ntest\b", "\\u123425foo\\ntest\\b"); assertUnescapeJava("'\foo\teste\r", "\\'\\foo\\teste\\r"); assertUnescapeJava("\\", "\\"); //foo assertUnescapeJava("lowercase unicode", "\uABCDx", "\\uabcdx"); assertUnescapeJava("uppercase unicode", "\uABCDx", "\\uABCDx"); assertUnescapeJava("unicode as final character", "\uABCD", "\\uabcd"); } private void assertUnescapeJava(String unescaped, String original) throws IOException { assertUnescapeJava(null, unescaped, original); } private void assertUnescapeJava(String message, String unescaped, String original) throws IOException { String expected = unescaped; String actual = StringEscapeUtils.unescapeJava(original); assertEquals("unescape(String) failed" + (message == null ? "" : (": " + message)) + ": expected '" + StringEscapeUtils.escapeJava(expected) + // we escape this so we can see it in the error message "' actual '" + StringEscapeUtils.escapeJava(actual) + "'", expected, actual); StringWriter writer = new StringWriter(); StringEscapeUtils.unescapeJava(writer, original); assertEquals(unescaped, writer.toString()); } public void testEscapeJavaScript() { assertEquals(null, StringEscapeUtils.escapeJavaScript(null)); try { StringEscapeUtils.escapeJavaScript(null, null); fail(); } catch (IOException ex) { fail(); } catch (IllegalArgumentException ex) { } try { StringEscapeUtils.escapeJavaScript(null, ""); fail(); } catch (IOException ex) { fail(); } catch (IllegalArgumentException ex) { } assertEquals("He didn\\'t say, \\\"stop!\\\"", StringEscapeUtils.escapeJavaScript("He didn't say, \"stop!\"")); assertEquals("document.getElementById(\\\"test\\\").value = \\'';")); } // HTML and XML //-------------------------------------------------------------- String[][] htmlEscapes = { {"no escaping", "plain text", "plain text"}, {"no escaping", "plain text", "plain text"}, {"empty string", "", ""}, {"null", null, null}, {"ampersand", "bread & butter", "bread & butter"}, {"quotes", ""bread" & butter", "\"bread\" & butter"}, {"final character only", "greater than >", "greater than >"}, {"first character only", "< less than", "< less than"}, {"apostrophe", "Huntington's chorea", "Huntington's chorea"}, {"languages", "English,Français,日本語 (nihongo)", "English,Fran\u00E7ais,\u65E5\u672C\u8A9E (nihongo)"}, {"8-bit ascii doesn't number-escape", "~\u007F", "\u007E\u007F"}, {"8-bit ascii does number-escape", "€Ÿ", "\u0080\u009F"}, }; public void testEscapeHtml() { for (int i = 0; i < htmlEscapes.length; ++i) { String message = htmlEscapes[i][0]; String expected = htmlEscapes[i][1]; String original = htmlEscapes[i][2]; assertEquals(message, expected, StringEscapeUtils.escapeHtml(original)); StringWriter sw = new StringWriter(); try { StringEscapeUtils.escapeHtml(sw, original); } catch (IOException e) { } String actual = original == null ? null : sw.toString(); assertEquals(message, expected, actual); } } public void testUnescapeHtml() { for (int i = 0; i < htmlEscapes.length; ++i) { String message = htmlEscapes[i][0]; String expected = htmlEscapes[i][2]; String original = htmlEscapes[i][1]; assertEquals(message, expected, StringEscapeUtils.unescapeHtml(original)); StringWriter sw = new StringWriter(); try { StringEscapeUtils.unescapeHtml(sw, original); } catch (IOException e) { } String actual = original == null ? null : sw.toString(); assertEquals(message, expected, actual); } // \u00E7 is a cedilla (c with wiggle under) // note that the test string must be 7-bit-clean (unicode escaped) or else it will compile incorrectly // on some locales assertEquals("funny chars pass through OK", "Fran\u00E7ais", StringEscapeUtils.unescapeHtml("Fran\u00E7ais")); assertEquals("Hello&;World", StringEscapeUtils.unescapeHtml("Hello&;World")); assertEquals("Hello&#;World", StringEscapeUtils.unescapeHtml("Hello&#;World")); assertEquals("Hello&# ;World", StringEscapeUtils.unescapeHtml("Hello&# ;World")); assertEquals("Hello&##;World", StringEscapeUtils.unescapeHtml("Hello&##;World")); } public void testUnescapeHexCharsHtml() { // Simple easy to grok test assertEquals("hex number unescape", "\u0080\u009F", StringEscapeUtils.unescapeHtml("€Ÿ")); assertEquals("hex number unescape", "\u0080\u009F", StringEscapeUtils.unescapeHtml("€Ÿ")); // Test all Character values: for (char i = Character.MIN_VALUE; i < Character.MAX_VALUE; i++) { Character c1 = new Character(i); Character c2 = new Character((char)(i+1)); String expected = c1.toString() + c2.toString(); String escapedC1 = "&#x" + Integer.toHexString((c1.charValue())) + ";"; String escapedC2 = "&#x" + Integer.toHexString((c2.charValue())) + ";"; assertEquals("hex number unescape index " + (int)i, expected, StringEscapeUtils.unescapeHtml(escapedC1 + escapedC2)); } } public void testUnescapeUnknownEntity() throws Exception { assertEquals("&zzzz;", StringEscapeUtils.unescapeHtml("&zzzz;")); } public void testEscapeHtmlVersions() throws Exception { assertEquals("Β", StringEscapeUtils.escapeHtml("\u0392")); assertEquals("\u0392", StringEscapeUtils.unescapeHtml("Β")); //todo: refine API for escaping/unescaping specific HTML versions } public void testEscapeXml() throws Exception { assertEquals("<abc>", StringEscapeUtils.escapeXml("")); assertEquals("", StringEscapeUtils.unescapeXml("<abc>")); assertEquals("XML should use numbers, not names for HTML entities", "¡", StringEscapeUtils.escapeXml("\u00A1")); assertEquals("XML should use numbers, not names for HTML entities", "\u00A0", StringEscapeUtils.unescapeXml(" ")); assertEquals("ain't", StringEscapeUtils.unescapeXml("ain't")); assertEquals("ain't", StringEscapeUtils.escapeXml("ain't")); assertEquals("", StringEscapeUtils.escapeXml("")); assertEquals(null, StringEscapeUtils.escapeXml(null)); assertEquals(null, StringEscapeUtils.unescapeXml(null)); StringWriter sw = new StringWriter(); try { StringEscapeUtils.escapeXml(sw, ""); } catch (IOException e) { } assertEquals("XML was escaped incorrectly", "<abc>", sw.toString() ); sw = new StringWriter(); try { StringEscapeUtils.unescapeXml(sw, "<abc>"); } catch (IOException e) { } assertEquals("XML was unescaped incorrectly", "", sw.toString() ); } // SQL // see http://www.jguru.com/faq/view.jsp?EID=8881 //-------------------- public void testEscapeSql() throws Exception { assertEquals("don''t stop", StringEscapeUtils.escapeSql("don't stop")); assertEquals("", StringEscapeUtils.escapeSql("")); assertEquals(null, StringEscapeUtils.escapeSql(null)); } // Tests issue #38569 // http://issues.apache.org/bugzilla/show_bug.cgi?id=38569 public void testStandaloneAmphersand() { assertEquals("", StringEscapeUtils.unescapeHtml("<P&O>")); assertEquals("test & <", StringEscapeUtils.unescapeHtml("test & <")); assertEquals("", StringEscapeUtils.unescapeXml("<P&O>")); assertEquals("test & <", StringEscapeUtils.unescapeXml("test & <")); } public void testLang313() { assertEquals("& &", StringEscapeUtils.unescapeHtml("& &")); } public void testEscapeCsvString() throws Exception { assertEquals("foo.bar", StringEscapeUtils.escapeCsv("foo.bar")); assertEquals("\"foo,bar\"", StringEscapeUtils.escapeCsv("foo,bar")); assertEquals("\"foo\nbar\"", StringEscapeUtils.escapeCsv("foo\nbar")); assertEquals("\"foo\rbar\"", StringEscapeUtils.escapeCsv("foo\rbar")); assertEquals("\"foo\"\"bar\"", StringEscapeUtils.escapeCsv("foo\"bar")); assertEquals("", StringEscapeUtils.escapeCsv("")); assertEquals(null, StringEscapeUtils.escapeCsv(null)); } public void testEscapeCsvWriter() throws Exception { checkCsvEscapeWriter("foo.bar", "foo.bar"); checkCsvEscapeWriter("\"foo,bar\"", "foo,bar"); checkCsvEscapeWriter("\"foo\nbar\"", "foo\nbar"); checkCsvEscapeWriter("\"foo\rbar\"", "foo\rbar"); checkCsvEscapeWriter("\"foo\"\"bar\"", "foo\"bar"); checkCsvEscapeWriter("", null); checkCsvEscapeWriter("", ""); } private void checkCsvEscapeWriter(String expected, String value) { try { StringWriter writer = new StringWriter(); StringEscapeUtils.escapeCsv(writer, value); assertEquals(expected, writer.toString()); } catch (IOException e) { fail("Threw: " + e); } } public void testUnescapeCsvString() throws Exception { assertEquals("foo.bar", StringEscapeUtils.unescapeCsv("foo.bar")); assertEquals("foo,bar", StringEscapeUtils.unescapeCsv("\"foo,bar\"")); assertEquals("foo\nbar", StringEscapeUtils.unescapeCsv("\"foo\nbar\"")); assertEquals("foo\rbar", StringEscapeUtils.unescapeCsv("\"foo\rbar\"")); assertEquals("foo\"bar", StringEscapeUtils.unescapeCsv("\"foo\"\"bar\"")); assertEquals("", StringEscapeUtils.unescapeCsv("")); assertEquals(null, StringEscapeUtils.unescapeCsv(null)); assertEquals("\"foo.bar\"", StringEscapeUtils.unescapeCsv("\"foo.bar\"")); } public void testUnescapeCsvWriter() throws Exception { checkCsvUnescapeWriter("foo.bar", "foo.bar"); checkCsvUnescapeWriter("foo,bar", "\"foo,bar\""); checkCsvUnescapeWriter("foo\nbar", "\"foo\nbar\""); checkCsvUnescapeWriter("foo\rbar", "\"foo\rbar\""); checkCsvUnescapeWriter("foo\"bar", "\"foo\"\"bar\""); checkCsvUnescapeWriter("", null); checkCsvUnescapeWriter("", ""); checkCsvUnescapeWriter("\"foo.bar\"", "\"foo.bar\""); } private void checkCsvUnescapeWriter(String expected, String value) { try { StringWriter writer = new StringWriter(); StringEscapeUtils.unescapeCsv(writer, value); assertEquals(expected, writer.toString()); } catch (IOException e) { fail("Threw: " + e); } } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/StringUtilsEqualsIndexOfTest.java100644 0 0 132565 11513702440 27455 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang; import java.util.Locale; import junit.framework.TestCase; /** * Unit tests {@link org.apache.commons.lang.StringUtils} - Substring methods * * @author Apache Software Foundation * @author Ringo De Smet * @author Phil Steitz * @version $Id: StringUtilsEqualsIndexOfTest.java 1056797 2011-01-08 20:55:11Z niallp $ */ public class StringUtilsEqualsIndexOfTest extends TestCase { /** * Supplementary character U+20000 * See http://java.sun.com/developer/technicalArticles/Intl/Supplementary/ */ private static final String CharU20000 = "\uD840\uDC00"; /** * Supplementary character U+20001 * See http://java.sun.com/developer/technicalArticles/Intl/Supplementary/ */ private static final String CharU20001 = "\uD840\uDC01"; /** * Incomplete supplementary character U+20000, high surrogate only. * See http://java.sun.com/developer/technicalArticles/Intl/Supplementary/ */ private static final String CharUSuppCharHigh = "\uDC00"; /** * Incomplete supplementary character U+20000, low surrogate only. * See http://java.sun.com/developer/technicalArticles/Intl/Supplementary/ */ private static final String CharUSuppCharLow = "\uD840"; private static final String FOO = "foo"; private static final String BAR = "bar"; private static final String FOOBAR = "foobar"; private static final String[] FOOBAR_SUB_ARRAY = new String[] {"ob", "ba"}; public StringUtilsEqualsIndexOfTest(String name) { super(name); } public void testContains_Char() { assertEquals(false, StringUtils.contains(null, ' ')); assertEquals(false, StringUtils.contains("", ' ')); assertEquals(false, StringUtils.contains("", null)); assertEquals(false, StringUtils.contains(null, null)); assertEquals(true, StringUtils.contains("abc", 'a')); assertEquals(true, StringUtils.contains("abc", 'b')); assertEquals(true, StringUtils.contains("abc", 'c')); assertEquals(false, StringUtils.contains("abc", 'z')); } public void testContains_String() { assertEquals(false, StringUtils.contains(null, null)); assertEquals(false, StringUtils.contains(null, "")); assertEquals(false, StringUtils.contains(null, "a")); assertEquals(false, StringUtils.contains("", null)); assertEquals(true, StringUtils.contains("", "")); assertEquals(false, StringUtils.contains("", "a")); assertEquals(true, StringUtils.contains("abc", "a")); assertEquals(true, StringUtils.contains("abc", "b")); assertEquals(true, StringUtils.contains("abc", "c")); assertEquals(true, StringUtils.contains("abc", "abc")); assertEquals(false, StringUtils.contains("abc", "z")); } /** * See http://java.sun.com/developer/technicalArticles/Intl/Supplementary/ */ public void testContains_StringWithBadSupplementaryChars() { // Test edge case: 1/2 of a (broken) supplementary char assertEquals(false, StringUtils.contains(CharUSuppCharHigh, CharU20001)); assertEquals(false, StringUtils.contains(CharUSuppCharLow, CharU20001)); assertEquals(false, StringUtils.contains(CharU20001, CharUSuppCharHigh)); assertEquals(0, CharU20001.indexOf(CharUSuppCharLow)); assertEquals(true, StringUtils.contains(CharU20001, CharUSuppCharLow)); assertEquals(true, StringUtils.contains(CharU20001 + CharUSuppCharLow + "a", "a")); assertEquals(true, StringUtils.contains(CharU20001 + CharUSuppCharHigh + "a", "a")); } /** * See http://java.sun.com/developer/technicalArticles/Intl/Supplementary/ */ public void testContains_StringWithSupplementaryChars() { assertEquals(true, StringUtils.contains(CharU20000 + CharU20001, CharU20000)); assertEquals(true, StringUtils.contains(CharU20000 + CharU20001, CharU20001)); assertEquals(true, StringUtils.contains(CharU20000, CharU20000)); assertEquals(false, StringUtils.contains(CharU20000, CharU20001)); } public void testContainsAny_StringCharArray() { assertFalse(StringUtils.containsAny(null, (char[]) null)); assertFalse(StringUtils.containsAny(null, new char[0])); assertFalse(StringUtils.containsAny(null, new char[] { 'a', 'b' })); assertFalse(StringUtils.containsAny("", (char[]) null)); assertFalse(StringUtils.containsAny("", new char[0])); assertFalse(StringUtils.containsAny("", new char[] { 'a', 'b' })); assertFalse(StringUtils.containsAny("zzabyycdxx", (char[]) null)); assertFalse(StringUtils.containsAny("zzabyycdxx", new char[0])); assertTrue(StringUtils.containsAny("zzabyycdxx", new char[] { 'z', 'a' })); assertTrue(StringUtils.containsAny("zzabyycdxx", new char[] { 'b', 'y' })); assertFalse(StringUtils.containsAny("ab", new char[] { 'z' })); } /** * See http://java.sun.com/developer/technicalArticles/Intl/Supplementary/ */ public void testContainsAny_StringCharArrayWithBadSupplementaryChars() { // Test edge case: 1/2 of a (broken) supplementary char assertEquals(false, StringUtils.containsAny(CharUSuppCharHigh, CharU20001.toCharArray())); assertEquals(false, StringUtils.containsAny("abc" + CharUSuppCharHigh + "xyz", CharU20001.toCharArray())); assertEquals(-1, CharUSuppCharLow.indexOf(CharU20001)); assertEquals(false, StringUtils.containsAny(CharUSuppCharLow, CharU20001.toCharArray())); assertEquals(false, StringUtils.containsAny(CharU20001, CharUSuppCharHigh.toCharArray())); assertEquals(0, CharU20001.indexOf(CharUSuppCharLow)); assertEquals(true, StringUtils.containsAny(CharU20001, CharUSuppCharLow.toCharArray())); } /** * See http://java.sun.com/developer/technicalArticles/Intl/Supplementary/ */ public void testContainsAny_StringCharArrayWithSupplementaryChars() { assertEquals(true, StringUtils.containsAny(CharU20000 + CharU20001, CharU20000.toCharArray())); assertEquals(true, StringUtils.containsAny("a" + CharU20000 + CharU20001, "a".toCharArray())); assertEquals(true, StringUtils.containsAny(CharU20000 + "a" + CharU20001, "a".toCharArray())); assertEquals(true, StringUtils.containsAny(CharU20000 + CharU20001 + "a", "a".toCharArray())); assertEquals(true, StringUtils.containsAny(CharU20000 + CharU20001, CharU20001.toCharArray())); assertEquals(true, StringUtils.containsAny(CharU20000, CharU20000.toCharArray())); // Sanity check: assertEquals(-1, CharU20000.indexOf(CharU20001)); assertEquals(0, CharU20000.indexOf(CharU20001.charAt(0))); assertEquals(-1, CharU20000.indexOf(CharU20001.charAt(1))); // Test: assertEquals(false, StringUtils.containsAny(CharU20000, CharU20001.toCharArray())); assertEquals(false, StringUtils.containsAny(CharU20001, CharU20000.toCharArray())); } public void testContainsAny_StringString() { assertFalse(StringUtils.containsAny(null, (String) null)); assertFalse(StringUtils.containsAny(null, "")); assertFalse(StringUtils.containsAny(null, "ab")); assertFalse(StringUtils.containsAny("", (String) null)); assertFalse(StringUtils.containsAny("", "")); assertFalse(StringUtils.containsAny("", "ab")); assertFalse(StringUtils.containsAny("zzabyycdxx", (String) null)); assertFalse(StringUtils.containsAny("zzabyycdxx", "")); assertTrue(StringUtils.containsAny("zzabyycdxx", "za")); assertTrue(StringUtils.containsAny("zzabyycdxx", "by")); assertFalse(StringUtils.containsAny("ab", "z")); } /** * See http://java.sun.com/developer/technicalArticles/Intl/Supplementary/ */ public void testContainsAny_StringWithBadSupplementaryChars() { // Test edge case: 1/2 of a (broken) supplementary char assertEquals(false, StringUtils.containsAny(CharUSuppCharHigh, CharU20001)); assertEquals(-1, CharUSuppCharLow.indexOf(CharU20001)); assertEquals(false, StringUtils.containsAny(CharUSuppCharLow, CharU20001)); assertEquals(false, StringUtils.containsAny(CharU20001, CharUSuppCharHigh)); assertEquals(0, CharU20001.indexOf(CharUSuppCharLow)); assertEquals(true, StringUtils.containsAny(CharU20001, CharUSuppCharLow)); } /** * See http://java.sun.com/developer/technicalArticles/Intl/Supplementary/ */ public void testContainsAny_StringWithSupplementaryChars() { assertEquals(true, StringUtils.containsAny(CharU20000 + CharU20001, CharU20000)); assertEquals(true, StringUtils.containsAny(CharU20000 + CharU20001, CharU20001)); assertEquals(true, StringUtils.containsAny(CharU20000, CharU20000)); // Sanity check: assertEquals(-1, CharU20000.indexOf(CharU20001)); assertEquals(0, CharU20000.indexOf(CharU20001.charAt(0))); assertEquals(-1, CharU20000.indexOf(CharU20001.charAt(1))); // Test: assertEquals(false, StringUtils.containsAny(CharU20000, CharU20001)); assertEquals(false, StringUtils.containsAny(CharU20001, CharU20000)); } public void testContainsIgnoreCase_LocaleIndependence() { Locale orig = Locale.getDefault(); Locale[] locales = { Locale.ENGLISH, new Locale("tr", "", ""), Locale.getDefault() }; String[][] tdata = { { "i", "I" }, { "I", "i" }, { "\u03C2", "\u03C3" }, { "\u03A3", "\u03C2" }, { "\u03A3", "\u03C3" }, }; String[][] fdata = { { "\u00DF", "SS" }, }; try { for (int i = 0; i < locales.length; i++) { Locale.setDefault(locales[i]); for (int j = 0; j < tdata.length; j++) { assertTrue(Locale.getDefault() + ": " + j + " " + tdata[j][0] + " " + tdata[j][1], StringUtils .containsIgnoreCase(tdata[j][0], tdata[j][1])); } for (int j = 0; j < fdata.length; j++) { assertFalse(Locale.getDefault() + ": " + j + " " + fdata[j][0] + " " + fdata[j][1], StringUtils .containsIgnoreCase(fdata[j][0], fdata[j][1])); } } } finally { Locale.setDefault(orig); } } public void testContainsIgnoreCase_StringString() { assertFalse(StringUtils.containsIgnoreCase(null, null)); // Null tests assertFalse(StringUtils.containsIgnoreCase(null, "")); assertFalse(StringUtils.containsIgnoreCase(null, "a")); assertFalse(StringUtils.containsIgnoreCase(null, "abc")); assertFalse(StringUtils.containsIgnoreCase("", null)); assertFalse(StringUtils.containsIgnoreCase("a", null)); assertFalse(StringUtils.containsIgnoreCase("abc", null)); // Match len = 0 assertTrue(StringUtils.containsIgnoreCase("", "")); assertTrue(StringUtils.containsIgnoreCase("a", "")); assertTrue(StringUtils.containsIgnoreCase("abc", "")); // Match len = 1 assertFalse(StringUtils.containsIgnoreCase("", "a")); assertTrue(StringUtils.containsIgnoreCase("a", "a")); assertTrue(StringUtils.containsIgnoreCase("abc", "a")); assertFalse(StringUtils.containsIgnoreCase("", "A")); assertTrue(StringUtils.containsIgnoreCase("a", "A")); assertTrue(StringUtils.containsIgnoreCase("abc", "A")); // Match len > 1 assertFalse(StringUtils.containsIgnoreCase("", "abc")); assertFalse(StringUtils.containsIgnoreCase("a", "abc")); assertTrue(StringUtils.containsIgnoreCase("xabcz", "abc")); assertFalse(StringUtils.containsIgnoreCase("", "ABC")); assertFalse(StringUtils.containsIgnoreCase("a", "ABC")); assertTrue(StringUtils.containsIgnoreCase("xabcz", "ABC")); } public void testContainsNone_CharArray() { String str1 = "a"; String str2 = "b"; String str3 = "ab."; char[] chars1= {'b'}; char[] chars2= {'.'}; char[] chars3= {'c', 'd'}; char[] emptyChars = new char[0]; assertEquals(true, StringUtils.containsNone(null, (char[]) null)); assertEquals(true, StringUtils.containsNone("", (char[]) null)); assertEquals(true, StringUtils.containsNone(null, emptyChars)); assertEquals(true, StringUtils.containsNone(str1, emptyChars)); assertEquals(true, StringUtils.containsNone("", emptyChars)); assertEquals(true, StringUtils.containsNone("", chars1)); assertEquals(true, StringUtils.containsNone(str1, chars1)); assertEquals(true, StringUtils.containsNone(str1, chars2)); assertEquals(true, StringUtils.containsNone(str1, chars3)); assertEquals(false, StringUtils.containsNone(str2, chars1)); assertEquals(true, StringUtils.containsNone(str2, chars2)); assertEquals(true, StringUtils.containsNone(str2, chars3)); assertEquals(false, StringUtils.containsNone(str3, chars1)); assertEquals(false, StringUtils.containsNone(str3, chars2)); assertEquals(true, StringUtils.containsNone(str3, chars3)); } /** * See http://java.sun.com/developer/technicalArticles/Intl/Supplementary/ */ public void testContainsNone_CharArrayWithBadSupplementaryChars() { // Test edge case: 1/2 of a (broken) supplementary char assertEquals(true, StringUtils.containsNone(CharUSuppCharHigh, CharU20001.toCharArray())); assertEquals(-1, CharUSuppCharLow.indexOf(CharU20001)); assertEquals(true, StringUtils.containsNone(CharUSuppCharLow, CharU20001.toCharArray())); assertEquals(-1, CharU20001.indexOf(CharUSuppCharHigh)); assertEquals(true, StringUtils.containsNone(CharU20001, CharUSuppCharHigh.toCharArray())); assertEquals(0, CharU20001.indexOf(CharUSuppCharLow)); assertEquals(false, StringUtils.containsNone(CharU20001, CharUSuppCharLow.toCharArray())); } /** * See http://java.sun.com/developer/technicalArticles/Intl/Supplementary/ */ public void testContainsNone_CharArrayWithSupplementaryChars() { assertEquals(false, StringUtils.containsNone(CharU20000 + CharU20001, CharU20000.toCharArray())); assertEquals(false, StringUtils.containsNone(CharU20000 + CharU20001, CharU20001.toCharArray())); assertEquals(false, StringUtils.containsNone(CharU20000, CharU20000.toCharArray())); // Sanity check: assertEquals(-1, CharU20000.indexOf(CharU20001)); assertEquals(0, CharU20000.indexOf(CharU20001.charAt(0))); assertEquals(-1, CharU20000.indexOf(CharU20001.charAt(1))); // Test: assertEquals(true, StringUtils.containsNone(CharU20000, CharU20001.toCharArray())); assertEquals(true, StringUtils.containsNone(CharU20001, CharU20000.toCharArray())); } public void testContainsNone_String() { String str1 = "a"; String str2 = "b"; String str3 = "ab."; String chars1= "b"; String chars2= "."; String chars3= "cd"; assertEquals(true, StringUtils.containsNone(null, (String) null)); assertEquals(true, StringUtils.containsNone("", (String) null)); assertEquals(true, StringUtils.containsNone(null, "")); assertEquals(true, StringUtils.containsNone(str1, "")); assertEquals(true, StringUtils.containsNone("", "")); assertEquals(true, StringUtils.containsNone("", chars1)); assertEquals(true, StringUtils.containsNone(str1, chars1)); assertEquals(true, StringUtils.containsNone(str1, chars2)); assertEquals(true, StringUtils.containsNone(str1, chars3)); assertEquals(false, StringUtils.containsNone(str2, chars1)); assertEquals(true, StringUtils.containsNone(str2, chars2)); assertEquals(true, StringUtils.containsNone(str2, chars3)); assertEquals(false, StringUtils.containsNone(str3, chars1)); assertEquals(false, StringUtils.containsNone(str3, chars2)); assertEquals(true, StringUtils.containsNone(str3, chars3)); } /** * See http://java.sun.com/developer/technicalArticles/Intl/Supplementary/ */ public void testContainsNone_StringWithBadSupplementaryChars() { // Test edge case: 1/2 of a (broken) supplementary char assertEquals(true, StringUtils.containsNone(CharUSuppCharHigh, CharU20001)); assertEquals(-1, CharUSuppCharLow.indexOf(CharU20001)); assertEquals(true, StringUtils.containsNone(CharUSuppCharLow, CharU20001)); assertEquals(-1, CharU20001.indexOf(CharUSuppCharHigh)); assertEquals(true, StringUtils.containsNone(CharU20001, CharUSuppCharHigh)); assertEquals(0, CharU20001.indexOf(CharUSuppCharLow)); assertEquals(false, StringUtils.containsNone(CharU20001, CharUSuppCharLow)); } /** * See http://java.sun.com/developer/technicalArticles/Intl/Supplementary/ */ public void testContainsNone_StringWithSupplementaryChars() { assertEquals(false, StringUtils.containsNone(CharU20000 + CharU20001, CharU20000)); assertEquals(false, StringUtils.containsNone(CharU20000 + CharU20001, CharU20001)); assertEquals(false, StringUtils.containsNone(CharU20000, CharU20000)); // Sanity check: assertEquals(-1, CharU20000.indexOf(CharU20001)); assertEquals(0, CharU20000.indexOf(CharU20001.charAt(0))); assertEquals(-1, CharU20000.indexOf(CharU20001.charAt(1))); // Test: assertEquals(true, StringUtils.containsNone(CharU20000, CharU20001)); assertEquals(true, StringUtils.containsNone(CharU20001, CharU20000)); } public void testContainsOnly_CharArray() { String str1 = "a"; String str2 = "b"; String str3 = "ab"; char[] chars1= {'b'}; char[] chars2= {'a'}; char[] chars3= {'a', 'b'}; char[] emptyChars = new char[0]; assertEquals(false, StringUtils.containsOnly(null, (char[]) null)); assertEquals(false, StringUtils.containsOnly("", (char[]) null)); assertEquals(false, StringUtils.containsOnly(null, emptyChars)); assertEquals(false, StringUtils.containsOnly(str1, emptyChars)); assertEquals(true, StringUtils.containsOnly("", emptyChars)); assertEquals(true, StringUtils.containsOnly("", chars1)); assertEquals(false, StringUtils.containsOnly(str1, chars1)); assertEquals(true, StringUtils.containsOnly(str1, chars2)); assertEquals(true, StringUtils.containsOnly(str1, chars3)); assertEquals(true, StringUtils.containsOnly(str2, chars1)); assertEquals(false, StringUtils.containsOnly(str2, chars2)); assertEquals(true, StringUtils.containsOnly(str2, chars3)); assertEquals(false, StringUtils.containsOnly(str3, chars1)); assertEquals(false, StringUtils.containsOnly(str3, chars2)); assertEquals(true, StringUtils.containsOnly(str3, chars3)); } public void testContainsOnly_String() { String str1 = "a"; String str2 = "b"; String str3 = "ab"; String chars1= "b"; String chars2= "a"; String chars3= "ab"; assertEquals(false, StringUtils.containsOnly(null, (String) null)); assertEquals(false, StringUtils.containsOnly("", (String) null)); assertEquals(false, StringUtils.containsOnly(null, "")); assertEquals(false, StringUtils.containsOnly(str1, "")); assertEquals(true, StringUtils.containsOnly("", "")); assertEquals(true, StringUtils.containsOnly("", chars1)); assertEquals(false, StringUtils.containsOnly(str1, chars1)); assertEquals(true, StringUtils.containsOnly(str1, chars2)); assertEquals(true, StringUtils.containsOnly(str1, chars3)); assertEquals(true, StringUtils.containsOnly(str2, chars1)); assertEquals(false, StringUtils.containsOnly(str2, chars2)); assertEquals(true, StringUtils.containsOnly(str2, chars3)); assertEquals(false, StringUtils.containsOnly(str3, chars1)); assertEquals(false, StringUtils.containsOnly(str3, chars2)); assertEquals(true, StringUtils.containsOnly(str3, chars3)); } public void testEquals() { assertEquals(true, StringUtils.equals(null, null)); assertEquals(true, StringUtils.equals(FOO, FOO)); assertEquals(true, StringUtils.equals(FOO, new String(new char[] { 'f', 'o', 'o' }))); assertEquals(false, StringUtils.equals(FOO, new String(new char[] { 'f', 'O', 'O' }))); assertEquals(false, StringUtils.equals(FOO, BAR)); assertEquals(false, StringUtils.equals(FOO, null)); assertEquals(false, StringUtils.equals(null, FOO)); } public void testEqualsIgnoreCase() { assertEquals(true, StringUtils.equalsIgnoreCase(null, null)); assertEquals(true, StringUtils.equalsIgnoreCase(FOO, FOO)); assertEquals(true, StringUtils.equalsIgnoreCase(FOO, new String(new char[] { 'f', 'o', 'o' }))); assertEquals(true, StringUtils.equalsIgnoreCase(FOO, new String(new char[] { 'f', 'O', 'O' }))); assertEquals(false, StringUtils.equalsIgnoreCase(FOO, BAR)); assertEquals(false, StringUtils.equalsIgnoreCase(FOO, null)); assertEquals(false, StringUtils.equalsIgnoreCase(null, FOO)); } //----------------------------------------------------------------------- public void testIndexOf_char() { assertEquals(-1, StringUtils.indexOf(null, ' ')); assertEquals(-1, StringUtils.indexOf("", ' ')); assertEquals(0, StringUtils.indexOf("aabaabaa", 'a')); assertEquals(2, StringUtils.indexOf("aabaabaa", 'b')); } public void testIndexOf_charInt() { assertEquals(-1, StringUtils.indexOf(null, ' ', 0)); assertEquals(-1, StringUtils.indexOf(null, ' ', -1)); assertEquals(-1, StringUtils.indexOf("", ' ', 0)); assertEquals(-1, StringUtils.indexOf("", ' ', -1)); assertEquals(0, StringUtils.indexOf("aabaabaa", 'a', 0)); assertEquals(2, StringUtils.indexOf("aabaabaa", 'b', 0)); assertEquals(5, StringUtils.indexOf("aabaabaa", 'b', 3)); assertEquals(-1, StringUtils.indexOf("aabaabaa", 'b', 9)); assertEquals(2, StringUtils.indexOf("aabaabaa", 'b', -1)); } public void testIndexOf_String() { assertEquals(-1, StringUtils.indexOf(null, null)); assertEquals(-1, StringUtils.indexOf("", null)); assertEquals(0, StringUtils.indexOf("", "")); assertEquals(0, StringUtils.indexOf("aabaabaa", "a")); assertEquals(2, StringUtils.indexOf("aabaabaa", "b")); assertEquals(1, StringUtils.indexOf("aabaabaa", "ab")); assertEquals(0, StringUtils.indexOf("aabaabaa", "")); } public void testIndexOf_StringInt() { assertEquals(-1, StringUtils.indexOf(null, null, 0)); assertEquals(-1, StringUtils.indexOf(null, null, -1)); assertEquals(-1, StringUtils.indexOf(null, "", 0)); assertEquals(-1, StringUtils.indexOf(null, "", -1)); assertEquals(-1, StringUtils.indexOf("", null, 0)); assertEquals(-1, StringUtils.indexOf("", null, -1)); assertEquals(0, StringUtils.indexOf("", "", 0)); assertEquals(0, StringUtils.indexOf("", "", -1)); assertEquals(0, StringUtils.indexOf("", "", 9)); assertEquals(0, StringUtils.indexOf("abc", "", 0)); assertEquals(0, StringUtils.indexOf("abc", "", -1)); assertEquals(3, StringUtils.indexOf("abc", "", 9)); assertEquals(3, StringUtils.indexOf("abc", "", 3)); assertEquals(0, StringUtils.indexOf("aabaabaa", "a", 0)); assertEquals(2, StringUtils.indexOf("aabaabaa", "b", 0)); assertEquals(1, StringUtils.indexOf("aabaabaa", "ab", 0)); assertEquals(5, StringUtils.indexOf("aabaabaa", "b", 3)); assertEquals(-1, StringUtils.indexOf("aabaabaa", "b", 9)); assertEquals(2, StringUtils.indexOf("aabaabaa", "b", -1)); assertEquals(2,StringUtils.indexOf("aabaabaa", "", 2)); } public void testIndexOfAny_StringCharArray() { assertEquals(-1, StringUtils.indexOfAny(null, (char[]) null)); assertEquals(-1, StringUtils.indexOfAny(null, new char[0])); assertEquals(-1, StringUtils.indexOfAny(null, new char[] {'a','b'})); assertEquals(-1, StringUtils.indexOfAny("", (char[]) null)); assertEquals(-1, StringUtils.indexOfAny("", new char[0])); assertEquals(-1, StringUtils.indexOfAny("", new char[] {'a','b'})); assertEquals(-1, StringUtils.indexOfAny("zzabyycdxx", (char[]) null)); assertEquals(-1, StringUtils.indexOfAny("zzabyycdxx", new char[0])); assertEquals(0, StringUtils.indexOfAny("zzabyycdxx", new char[] {'z','a'})); assertEquals(3, StringUtils.indexOfAny("zzabyycdxx", new char[] {'b','y'})); assertEquals(-1, StringUtils.indexOfAny("ab", new char[] {'z'})); } /** * See http://java.sun.com/developer/technicalArticles/Intl/Supplementary/ */ public void testIndexOfAny_StringCharArrayWithSupplementaryChars() { assertEquals(0, StringUtils.indexOfAny(CharU20000 + CharU20001, CharU20000.toCharArray())); assertEquals(2, StringUtils.indexOfAny(CharU20000 + CharU20001, CharU20001.toCharArray())); assertEquals(0, StringUtils.indexOfAny(CharU20000, CharU20000.toCharArray())); assertEquals(-1, StringUtils.indexOfAny(CharU20000, CharU20001.toCharArray())); } public void testIndexOfAny_StringString() { assertEquals(-1, StringUtils.indexOfAny(null, (String) null)); assertEquals(-1, StringUtils.indexOfAny(null, "")); assertEquals(-1, StringUtils.indexOfAny(null, "ab")); assertEquals(-1, StringUtils.indexOfAny("", (String) null)); assertEquals(-1, StringUtils.indexOfAny("", "")); assertEquals(-1, StringUtils.indexOfAny("", "ab")); assertEquals(-1, StringUtils.indexOfAny("zzabyycdxx", (String) null)); assertEquals(-1, StringUtils.indexOfAny("zzabyycdxx", "")); assertEquals(0, StringUtils.indexOfAny("zzabyycdxx", "za")); assertEquals(3, StringUtils.indexOfAny("zzabyycdxx", "by")); assertEquals(-1, StringUtils.indexOfAny("ab", "z")); } public void testIndexOfAny_StringStringArray() { assertEquals(-1, StringUtils.indexOfAny(null, (String[]) null)); assertEquals(-1, StringUtils.indexOfAny(null, FOOBAR_SUB_ARRAY)); assertEquals(-1, StringUtils.indexOfAny(FOOBAR, (String[]) null)); assertEquals(2, StringUtils.indexOfAny(FOOBAR, FOOBAR_SUB_ARRAY)); assertEquals(-1, StringUtils.indexOfAny(FOOBAR, new String[0])); assertEquals(-1, StringUtils.indexOfAny(null, new String[0])); assertEquals(-1, StringUtils.indexOfAny("", new String[0])); assertEquals(-1, StringUtils.indexOfAny(FOOBAR, new String[] {"llll"})); assertEquals(0, StringUtils.indexOfAny(FOOBAR, new String[] {""})); assertEquals(0, StringUtils.indexOfAny("", new String[] {""})); assertEquals(-1, StringUtils.indexOfAny("", new String[] {"a"})); assertEquals(-1, StringUtils.indexOfAny("", new String[] {null})); assertEquals(-1, StringUtils.indexOfAny(FOOBAR, new String[] {null})); assertEquals(-1, StringUtils.indexOfAny(null, new String[] {null})); } /** * See http://java.sun.com/developer/technicalArticles/Intl/Supplementary/ */ public void testIndexOfAny_StringStringWithSupplementaryChars() { assertEquals(0, StringUtils.indexOfAny(CharU20000 + CharU20001, CharU20000)); assertEquals(2, StringUtils.indexOfAny(CharU20000 + CharU20001, CharU20001)); assertEquals(0, StringUtils.indexOfAny(CharU20000, CharU20000)); assertEquals(-1, StringUtils.indexOfAny(CharU20000, CharU20001)); } public void testIndexOfAnyBut_StringCharArray() { assertEquals(-1, StringUtils.indexOfAnyBut(null, (char[]) null)); assertEquals(-1, StringUtils.indexOfAnyBut(null, new char[0])); assertEquals(-1, StringUtils.indexOfAnyBut(null, new char[] {'a','b'})); assertEquals(-1, StringUtils.indexOfAnyBut("", (char[]) null)); assertEquals(-1, StringUtils.indexOfAnyBut("", new char[0])); assertEquals(-1, StringUtils.indexOfAnyBut("", new char[] {'a','b'})); assertEquals(-1, StringUtils.indexOfAnyBut("zzabyycdxx", (char[]) null)); assertEquals(-1, StringUtils.indexOfAnyBut("zzabyycdxx", new char[0])); assertEquals(3, StringUtils.indexOfAnyBut("zzabyycdxx", new char[] {'z','a'})); assertEquals(0, StringUtils.indexOfAnyBut("zzabyycdxx", new char[] {'b','y'})); assertEquals(-1, StringUtils.indexOfAnyBut("aba", new char[] {'a', 'b'})); assertEquals(0, StringUtils.indexOfAnyBut("aba", new char[] {'z'})); } public void testIndexOfAnyBut_StringCharArrayWithSupplementaryChars() { assertEquals(2, StringUtils.indexOfAnyBut(CharU20000 + CharU20001, CharU20000.toCharArray())); assertEquals(0, StringUtils.indexOfAnyBut(CharU20000 + CharU20001, CharU20001.toCharArray())); assertEquals(-1, StringUtils.indexOfAnyBut(CharU20000, CharU20000.toCharArray())); assertEquals(0, StringUtils.indexOfAnyBut(CharU20000, CharU20001.toCharArray())); } public void testIndexOfAnyBut_StringString() { assertEquals(-1, StringUtils.indexOfAnyBut(null, (String) null)); assertEquals(-1, StringUtils.indexOfAnyBut(null, "")); assertEquals(-1, StringUtils.indexOfAnyBut(null, "ab")); assertEquals(-1, StringUtils.indexOfAnyBut("", (String) null)); assertEquals(-1, StringUtils.indexOfAnyBut("", "")); assertEquals(-1, StringUtils.indexOfAnyBut("", "ab")); assertEquals(-1, StringUtils.indexOfAnyBut("zzabyycdxx", (String) null)); assertEquals(-1, StringUtils.indexOfAnyBut("zzabyycdxx", "")); assertEquals(3, StringUtils.indexOfAnyBut("zzabyycdxx", "za")); assertEquals(0, StringUtils.indexOfAnyBut("zzabyycdxx", "by")); assertEquals(0, StringUtils.indexOfAnyBut("ab", "z")); } public void testIndexOfAnyBut_StringStringWithSupplementaryChars() { assertEquals(2, StringUtils.indexOfAnyBut(CharU20000 + CharU20001, CharU20000)); assertEquals(0, StringUtils.indexOfAnyBut(CharU20000 + CharU20001, CharU20001)); assertEquals(-1, StringUtils.indexOfAnyBut(CharU20000, CharU20000)); assertEquals(0, StringUtils.indexOfAnyBut(CharU20000, CharU20001)); } public void testIndexOfIgnoreCase_String() { assertEquals(-1, StringUtils.indexOfIgnoreCase(null, null)); assertEquals(-1, StringUtils.indexOfIgnoreCase(null, "")); assertEquals(-1, StringUtils.indexOfIgnoreCase("", null)); assertEquals(0, StringUtils.indexOfIgnoreCase("", "")); assertEquals(0, StringUtils.indexOfIgnoreCase("aabaabaa", "a")); assertEquals(0, StringUtils.indexOfIgnoreCase("aabaabaa", "A")); assertEquals(2, StringUtils.indexOfIgnoreCase("aabaabaa", "b")); assertEquals(2, StringUtils.indexOfIgnoreCase("aabaabaa", "B")); assertEquals(1, StringUtils.indexOfIgnoreCase("aabaabaa", "ab")); assertEquals(1, StringUtils.indexOfIgnoreCase("aabaabaa", "AB")); assertEquals(0, StringUtils.indexOfIgnoreCase("aabaabaa", "")); } public void testIndexOfIgnoreCase_StringInt() { assertEquals(1, StringUtils.indexOfIgnoreCase("aabaabaa", "AB", -1)); assertEquals(1, StringUtils.indexOfIgnoreCase("aabaabaa", "AB", 0)); assertEquals(1, StringUtils.indexOfIgnoreCase("aabaabaa", "AB", 1)); assertEquals(4, StringUtils.indexOfIgnoreCase("aabaabaa", "AB", 2)); assertEquals(4, StringUtils.indexOfIgnoreCase("aabaabaa", "AB", 3)); assertEquals(4, StringUtils.indexOfIgnoreCase("aabaabaa", "AB", 4)); assertEquals(-1, StringUtils.indexOfIgnoreCase("aabaabaa", "AB", 5)); assertEquals(-1, StringUtils.indexOfIgnoreCase("aabaabaa", "AB", 6)); assertEquals(-1, StringUtils.indexOfIgnoreCase("aabaabaa", "AB", 7)); assertEquals(-1, StringUtils.indexOfIgnoreCase("aabaabaa", "AB", 8)); assertEquals(1, StringUtils.indexOfIgnoreCase("aab", "AB", 1)); assertEquals(5, StringUtils.indexOfIgnoreCase("aabaabaa", "", 5)); assertEquals(-1, StringUtils.indexOfIgnoreCase("ab", "AAB", 0)); assertEquals(-1, StringUtils.indexOfIgnoreCase("aab", "AAB", 1)); } public void testLastIndexOf_char() { assertEquals(-1, StringUtils.lastIndexOf(null, ' ')); assertEquals(-1, StringUtils.lastIndexOf("", ' ')); assertEquals(7, StringUtils.lastIndexOf("aabaabaa", 'a')); assertEquals(5, StringUtils.lastIndexOf("aabaabaa", 'b')); } public void testLastIndexOf_charInt() { assertEquals(-1, StringUtils.lastIndexOf(null, ' ', 0)); assertEquals(-1, StringUtils.lastIndexOf(null, ' ', -1)); assertEquals(-1, StringUtils.lastIndexOf("", ' ', 0)); assertEquals(-1, StringUtils.lastIndexOf("", ' ', -1)); assertEquals(7, StringUtils.lastIndexOf("aabaabaa", 'a', 8)); assertEquals(5, StringUtils.lastIndexOf("aabaabaa", 'b', 8)); assertEquals(2, StringUtils.lastIndexOf("aabaabaa", 'b', 3)); assertEquals(5, StringUtils.lastIndexOf("aabaabaa", 'b', 9)); assertEquals(-1, StringUtils.lastIndexOf("aabaabaa", 'b', -1)); assertEquals(0, StringUtils.lastIndexOf("aabaabaa", 'a', 0)); } public void testLastIndexOf_String() { assertEquals(-1, StringUtils.lastIndexOf(null, null)); assertEquals(-1, StringUtils.lastIndexOf("", null)); assertEquals(-1, StringUtils.lastIndexOf("", "a")); assertEquals(0, StringUtils.lastIndexOf("", "")); assertEquals(8, StringUtils.lastIndexOf("aabaabaa", "")); assertEquals(7, StringUtils.lastIndexOf("aabaabaa", "a")); assertEquals(5, StringUtils.lastIndexOf("aabaabaa", "b")); assertEquals(4, StringUtils.lastIndexOf("aabaabaa", "ab")); } public void testLastIndexOf_StringInt() { assertEquals(-1, StringUtils.lastIndexOf(null, null, 0)); assertEquals(-1, StringUtils.lastIndexOf(null, null, -1)); assertEquals(-1, StringUtils.lastIndexOf(null, "", 0)); assertEquals(-1, StringUtils.lastIndexOf(null, "", -1)); assertEquals(-1, StringUtils.lastIndexOf("", null, 0)); assertEquals(-1, StringUtils.lastIndexOf("", null, -1)); assertEquals(0, StringUtils.lastIndexOf("", "", 0)); assertEquals(-1, StringUtils.lastIndexOf("", "", -1)); assertEquals(0, StringUtils.lastIndexOf("", "", 9)); assertEquals(0, StringUtils.lastIndexOf("abc", "", 0)); assertEquals(-1, StringUtils.lastIndexOf("abc", "", -1)); assertEquals(3, StringUtils.lastIndexOf("abc", "", 9)); assertEquals(7, StringUtils.lastIndexOf("aabaabaa", "a", 8)); assertEquals(5, StringUtils.lastIndexOf("aabaabaa", "b", 8)); assertEquals(4, StringUtils.lastIndexOf("aabaabaa", "ab", 8)); assertEquals(2, StringUtils.lastIndexOf("aabaabaa", "b", 3)); assertEquals(5, StringUtils.lastIndexOf("aabaabaa", "b", 9)); assertEquals(-1, StringUtils.lastIndexOf("aabaabaa", "b", -1)); assertEquals(-1, StringUtils.lastIndexOf("aabaabaa", "b", 0)); assertEquals(0, StringUtils.lastIndexOf("aabaabaa", "a", 0)); } public void testLastIndexOfAny_StringStringArray() { assertEquals(-1, StringUtils.lastIndexOfAny(null, null)); assertEquals(-1, StringUtils.lastIndexOfAny(null, FOOBAR_SUB_ARRAY)); assertEquals(-1, StringUtils.lastIndexOfAny(FOOBAR, null)); assertEquals(3, StringUtils.lastIndexOfAny(FOOBAR, FOOBAR_SUB_ARRAY)); assertEquals(-1, StringUtils.lastIndexOfAny(FOOBAR, new String[0])); assertEquals(-1, StringUtils.lastIndexOfAny(null, new String[0])); assertEquals(-1, StringUtils.lastIndexOfAny("", new String[0])); assertEquals(-1, StringUtils.lastIndexOfAny(FOOBAR, new String[] {"llll"})); assertEquals(6, StringUtils.lastIndexOfAny(FOOBAR, new String[] {""})); assertEquals(0, StringUtils.lastIndexOfAny("", new String[] {""})); assertEquals(-1, StringUtils.lastIndexOfAny("", new String[] {"a"})); assertEquals(-1, StringUtils.lastIndexOfAny("", new String[] {null})); assertEquals(-1, StringUtils.lastIndexOfAny(FOOBAR, new String[] {null})); assertEquals(-1, StringUtils.lastIndexOfAny(null, new String[] {null})); } public void testLastIndexOfIgnoreCase_String() { assertEquals(-1, StringUtils.lastIndexOfIgnoreCase(null, null)); assertEquals(-1, StringUtils.lastIndexOfIgnoreCase("", null)); assertEquals(-1, StringUtils.lastIndexOfIgnoreCase(null, "")); assertEquals(-1, StringUtils.lastIndexOfIgnoreCase("", "a")); assertEquals(0, StringUtils.lastIndexOfIgnoreCase("", "")); assertEquals(8, StringUtils.lastIndexOfIgnoreCase("aabaabaa", "")); assertEquals(7, StringUtils.lastIndexOfIgnoreCase("aabaabaa", "a")); assertEquals(7, StringUtils.lastIndexOfIgnoreCase("aabaabaa", "A")); assertEquals(5, StringUtils.lastIndexOfIgnoreCase("aabaabaa", "b")); assertEquals(5, StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B")); assertEquals(4, StringUtils.lastIndexOfIgnoreCase("aabaabaa", "ab")); assertEquals(4, StringUtils.lastIndexOfIgnoreCase("aabaabaa", "AB")); assertEquals(-1, StringUtils.lastIndexOfIgnoreCase("ab", "AAB")); assertEquals(0, StringUtils.lastIndexOfIgnoreCase("aab", "AAB")); } public void testLastIndexOfIgnoreCase_StringInt() { assertEquals(-1, StringUtils.lastIndexOfIgnoreCase(null, null, 0)); assertEquals(-1, StringUtils.lastIndexOfIgnoreCase(null, null, -1)); assertEquals(-1, StringUtils.lastIndexOfIgnoreCase(null, "", 0)); assertEquals(-1, StringUtils.lastIndexOfIgnoreCase(null, "", -1)); assertEquals(-1, StringUtils.lastIndexOfIgnoreCase("", null, 0)); assertEquals(-1, StringUtils.lastIndexOfIgnoreCase("", null, -1)); assertEquals(0, StringUtils.lastIndexOfIgnoreCase("", "", 0)); assertEquals(-1, StringUtils.lastIndexOfIgnoreCase("", "", -1)); assertEquals(0, StringUtils.lastIndexOfIgnoreCase("", "", 9)); assertEquals(0, StringUtils.lastIndexOfIgnoreCase("abc", "", 0)); assertEquals(-1, StringUtils.lastIndexOfIgnoreCase("abc", "", -1)); assertEquals(3, StringUtils.lastIndexOfIgnoreCase("abc", "", 9)); assertEquals(7, StringUtils.lastIndexOfIgnoreCase("aabaabaa", "A", 8)); assertEquals(5, StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B", 8)); assertEquals(4, StringUtils.lastIndexOfIgnoreCase("aabaabaa", "AB", 8)); assertEquals(2, StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B", 3)); assertEquals(5, StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B", 9)); assertEquals(-1, StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B", -1)); assertEquals(-1, StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B", 0)); assertEquals(0, StringUtils.lastIndexOfIgnoreCase("aabaabaa", "A", 0)); assertEquals(1, StringUtils.lastIndexOfIgnoreCase("aab", "AB", 1)); } public void testLastOrdinalIndexOf() { assertEquals(-1, StringUtils.lastOrdinalIndexOf(null, "*", 42) ); assertEquals(-1, StringUtils.lastOrdinalIndexOf("*", null, 42) ); assertEquals(0, StringUtils.lastOrdinalIndexOf("", "", 42) ); assertEquals(7, StringUtils.lastOrdinalIndexOf("aabaabaa", "a", 1) ); assertEquals(6, StringUtils.lastOrdinalIndexOf("aabaabaa", "a", 2) ); assertEquals(5, StringUtils.lastOrdinalIndexOf("aabaabaa", "b", 1) ); assertEquals(2, StringUtils.lastOrdinalIndexOf("aabaabaa", "b", 2) ); assertEquals(4, StringUtils.lastOrdinalIndexOf("aabaabaa", "ab", 1) ); assertEquals(1, StringUtils.lastOrdinalIndexOf("aabaabaa", "ab", 2) ); assertEquals(8, StringUtils.lastOrdinalIndexOf("aabaabaa", "", 1) ); assertEquals(8, StringUtils.lastOrdinalIndexOf("aabaabaa", "", 2) ); } public void testOrdinalIndexOf() { assertEquals(-1, StringUtils.ordinalIndexOf(null, null, Integer.MIN_VALUE)); assertEquals(-1, StringUtils.ordinalIndexOf("", null, Integer.MIN_VALUE)); assertEquals(-1, StringUtils.ordinalIndexOf("", "", Integer.MIN_VALUE)); assertEquals(-1, StringUtils.ordinalIndexOf("aabaabaa", "a", Integer.MIN_VALUE)); assertEquals(-1, StringUtils.ordinalIndexOf("aabaabaa", "b", Integer.MIN_VALUE)); assertEquals(-1, StringUtils.ordinalIndexOf("aabaabaa", "ab", Integer.MIN_VALUE)); assertEquals(-1, StringUtils.ordinalIndexOf("aabaabaa", "", Integer.MIN_VALUE)); assertEquals(-1, StringUtils.ordinalIndexOf(null, null, -1)); assertEquals(-1, StringUtils.ordinalIndexOf("", null, -1)); assertEquals(-1, StringUtils.ordinalIndexOf("", "", -1)); assertEquals(-1, StringUtils.ordinalIndexOf("aabaabaa", "a", -1)); assertEquals(-1, StringUtils.ordinalIndexOf("aabaabaa", "b", -1)); assertEquals(-1, StringUtils.ordinalIndexOf("aabaabaa", "ab", -1)); assertEquals(-1, StringUtils.ordinalIndexOf("aabaabaa", "", -1)); assertEquals(-1, StringUtils.ordinalIndexOf(null, null, 0)); assertEquals(-1, StringUtils.ordinalIndexOf("", null, 0)); assertEquals(-1, StringUtils.ordinalIndexOf("", "", 0)); assertEquals(-1, StringUtils.ordinalIndexOf("aabaabaa", "a", 0)); assertEquals(-1, StringUtils.ordinalIndexOf("aabaabaa", "b", 0)); assertEquals(-1, StringUtils.ordinalIndexOf("aabaabaa", "ab", 0)); assertEquals(-1, StringUtils.ordinalIndexOf("aabaabaa", "", 0)); assertEquals(-1, StringUtils.ordinalIndexOf(null, null, 1)); assertEquals(-1, StringUtils.ordinalIndexOf("", null, 1)); assertEquals(0, StringUtils.ordinalIndexOf("", "", 1)); assertEquals(0, StringUtils.ordinalIndexOf("aabaabaa", "a", 1)); assertEquals(2, StringUtils.ordinalIndexOf("aabaabaa", "b", 1)); assertEquals(1, StringUtils.ordinalIndexOf("aabaabaa", "ab", 1)); assertEquals(0, StringUtils.ordinalIndexOf("aabaabaa", "", 1)); assertEquals(-1, StringUtils.ordinalIndexOf(null, null, 2)); assertEquals(-1, StringUtils.ordinalIndexOf("", null, 2)); assertEquals(0, StringUtils.ordinalIndexOf("", "", 2)); assertEquals(1, StringUtils.ordinalIndexOf("aabaabaa", "a", 2)); assertEquals(5, StringUtils.ordinalIndexOf("aabaabaa", "b", 2)); assertEquals(4, StringUtils.ordinalIndexOf("aabaabaa", "ab", 2)); assertEquals(0, StringUtils.ordinalIndexOf("aabaabaa", "", 2)); assertEquals(-1, StringUtils.ordinalIndexOf(null, null, Integer.MAX_VALUE)); assertEquals(-1, StringUtils.ordinalIndexOf("", null, Integer.MAX_VALUE)); assertEquals(0, StringUtils.ordinalIndexOf("", "", Integer.MAX_VALUE)); assertEquals(-1, StringUtils.ordinalIndexOf("aabaabaa", "a", Integer.MAX_VALUE)); assertEquals(-1, StringUtils.ordinalIndexOf("aabaabaa", "b", Integer.MAX_VALUE)); assertEquals(-1, StringUtils.ordinalIndexOf("aabaabaa", "ab", Integer.MAX_VALUE)); assertEquals(0, StringUtils.ordinalIndexOf("aabaabaa", "", Integer.MAX_VALUE)); assertEquals(-1, StringUtils.ordinalIndexOf("aaaaaaaaa", "a", 0)); assertEquals(0, StringUtils.ordinalIndexOf("aaaaaaaaa", "a", 1)); assertEquals(1, StringUtils.ordinalIndexOf("aaaaaaaaa", "a", 2)); assertEquals(2, StringUtils.ordinalIndexOf("aaaaaaaaa", "a", 3)); assertEquals(3, StringUtils.ordinalIndexOf("aaaaaaaaa", "a", 4)); assertEquals(4, StringUtils.ordinalIndexOf("aaaaaaaaa", "a", 5)); assertEquals(5, StringUtils.ordinalIndexOf("aaaaaaaaa", "a", 6)); assertEquals(6, StringUtils.ordinalIndexOf("aaaaaaaaa", "a", 7)); assertEquals(7, StringUtils.ordinalIndexOf("aaaaaaaaa", "a", 8)); assertEquals(8, StringUtils.ordinalIndexOf("aaaaaaaaa", "a", 9)); assertEquals(-1, StringUtils.ordinalIndexOf("aaaaaaaaa", "a", 10)); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/StringUtilsIsTest.java100644 0 0 21402 11513702441 25265 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang; import junit.framework.TestCase; /** * Unit tests {@link org.apache.commons.lang.StringUtils} - Substring methods * * @author Apache Software Foundation * @author Michael Davey * @version $Id: StringUtilsIsTest.java 905636 2010-02-02 14:03:32Z niallp $ */ public class StringUtilsIsTest extends TestCase { public StringUtilsIsTest(String name) { super(name); } //----------------------------------------------------------------------- public void testIsAlpha() { assertEquals(false, StringUtils.isAlpha(null)); assertEquals(true, StringUtils.isAlpha("")); assertEquals(false, StringUtils.isAlpha(" ")); assertEquals(true, StringUtils.isAlpha("a")); assertEquals(true, StringUtils.isAlpha("A")); assertEquals(true, StringUtils.isAlpha("kgKgKgKgkgkGkjkjlJlOKLgHdGdHgl")); assertEquals(false, StringUtils.isAlpha("ham kso")); assertEquals(false, StringUtils.isAlpha("1")); assertEquals(false, StringUtils.isAlpha("hkHKHik6iUGHKJgU7tUJgKJGI87GIkug")); assertEquals(false, StringUtils.isAlpha("_")); assertEquals(false, StringUtils.isAlpha("hkHKHik*khbkuh")); } public void testIsAlphanumeric() { assertEquals(false, StringUtils.isAlphanumeric(null)); assertEquals(true, StringUtils.isAlphanumeric("")); assertEquals(false, StringUtils.isAlphanumeric(" ")); assertEquals(true, StringUtils.isAlphanumeric("a")); assertEquals(true, StringUtils.isAlphanumeric("A")); assertEquals(true, StringUtils.isAlphanumeric("kgKgKgKgkgkGkjkjlJlOKLgHdGdHgl")); assertEquals(false, StringUtils.isAlphanumeric("ham kso")); assertEquals(true, StringUtils.isAlphanumeric("1")); assertEquals(true, StringUtils.isAlphanumeric("hkHKHik6iUGHKJgU7tUJgKJGI87GIkug")); assertEquals(false, StringUtils.isAlphanumeric("_")); assertEquals(false, StringUtils.isAlphanumeric("hkHKHik*khbkuh")); } public void testIsWhitespace() { assertEquals(false, StringUtils.isWhitespace(null)); assertEquals(true, StringUtils.isWhitespace("")); assertEquals(true, StringUtils.isWhitespace(" ")); assertEquals(true, StringUtils.isWhitespace("\t \n \t")); assertEquals(false, StringUtils.isWhitespace("\t aa\n \t")); assertEquals(true, StringUtils.isWhitespace(" ")); assertEquals(false, StringUtils.isWhitespace(" a ")); assertEquals(false, StringUtils.isWhitespace("a ")); assertEquals(false, StringUtils.isWhitespace(" a")); assertEquals(false, StringUtils.isWhitespace("aba")); assertEquals(true, StringUtils.isWhitespace(StringUtilsTest.WHITESPACE)); assertEquals(false, StringUtils.isWhitespace(StringUtilsTest.NON_WHITESPACE)); } public void testIsAlphaspace() { assertEquals(false, StringUtils.isAlphaSpace(null)); assertEquals(true, StringUtils.isAlphaSpace("")); assertEquals(true, StringUtils.isAlphaSpace(" ")); assertEquals(true, StringUtils.isAlphaSpace("a")); assertEquals(true, StringUtils.isAlphaSpace("A")); assertEquals(true, StringUtils.isAlphaSpace("kgKgKgKgkgkGkjkjlJlOKLgHdGdHgl")); assertEquals(true, StringUtils.isAlphaSpace("ham kso")); assertEquals(false, StringUtils.isAlphaSpace("1")); assertEquals(false, StringUtils.isAlphaSpace("hkHKHik6iUGHKJgU7tUJgKJGI87GIkug")); assertEquals(false, StringUtils.isAlphaSpace("_")); assertEquals(false, StringUtils.isAlphaSpace("hkHKHik*khbkuh")); } public void testIsAlphanumericSpace() { assertEquals(false, StringUtils.isAlphanumericSpace(null)); assertEquals(true, StringUtils.isAlphanumericSpace("")); assertEquals(true, StringUtils.isAlphanumericSpace(" ")); assertEquals(true, StringUtils.isAlphanumericSpace("a")); assertEquals(true, StringUtils.isAlphanumericSpace("A")); assertEquals(true, StringUtils.isAlphanumericSpace("kgKgKgKgkgkGkjkjlJlOKLgHdGdHgl")); assertEquals(true, StringUtils.isAlphanumericSpace("ham kso")); assertEquals(true, StringUtils.isAlphanumericSpace("1")); assertEquals(true, StringUtils.isAlphanumericSpace("hkHKHik6iUGHKJgU7tUJgKJGI87GIkug")); assertEquals(false, StringUtils.isAlphanumericSpace("_")); assertEquals(false, StringUtils.isAlphanumericSpace("hkHKHik*khbkuh")); } public void testIsAsciiPrintable_String() { assertEquals(false, StringUtils.isAsciiPrintable(null)); assertEquals(true, StringUtils.isAsciiPrintable("")); assertEquals(true, StringUtils.isAsciiPrintable(" ")); assertEquals(true, StringUtils.isAsciiPrintable("a")); assertEquals(true, StringUtils.isAsciiPrintable("A")); assertEquals(true, StringUtils.isAsciiPrintable("1")); assertEquals(true, StringUtils.isAsciiPrintable("Ceki")); assertEquals(true, StringUtils.isAsciiPrintable("!ab2c~")); assertEquals(true, StringUtils.isAsciiPrintable("1000")); assertEquals(true, StringUtils.isAsciiPrintable("10 00")); assertEquals(false, StringUtils.isAsciiPrintable("10\t00")); assertEquals(true, StringUtils.isAsciiPrintable("10.00")); assertEquals(true, StringUtils.isAsciiPrintable("10,00")); assertEquals(true, StringUtils.isAsciiPrintable("!ab-c~")); assertEquals(true, StringUtils.isAsciiPrintable("hkHK=Hik6i?UGH_KJgU7.tUJgKJ*GI87GI,kug")); assertEquals(true, StringUtils.isAsciiPrintable("\u0020")); assertEquals(true, StringUtils.isAsciiPrintable("\u0021")); assertEquals(true, StringUtils.isAsciiPrintable("\u007e")); assertEquals(false, StringUtils.isAsciiPrintable("\u007f")); assertEquals(true, StringUtils.isAsciiPrintable("G?lc?")); assertEquals(true, StringUtils.isAsciiPrintable("=?iso-8859-1?Q?G=FClc=FC?=")); assertEquals(false, StringUtils.isAsciiPrintable("G\u00fclc\u00fc")); } public void testIsNumeric() { assertEquals(false, StringUtils.isNumeric(null)); assertEquals(true, StringUtils.isNumeric("")); assertEquals(false, StringUtils.isNumeric(" ")); assertEquals(false, StringUtils.isNumeric("a")); assertEquals(false, StringUtils.isNumeric("A")); assertEquals(false, StringUtils.isNumeric("kgKgKgKgkgkGkjkjlJlOKLgHdGdHgl")); assertEquals(false, StringUtils.isNumeric("ham kso")); assertEquals(true, StringUtils.isNumeric("1")); assertEquals(true, StringUtils.isNumeric("1000")); assertEquals(false, StringUtils.isNumeric("2.3")); assertEquals(false, StringUtils.isNumeric("10 00")); assertEquals(false, StringUtils.isNumeric("hkHKHik6iUGHKJgU7tUJgKJGI87GIkug")); assertEquals(false, StringUtils.isNumeric("_")); assertEquals(false, StringUtils.isNumeric("hkHKHik*khbkuh")); } public void testIsNumericSpace() { assertEquals(false, StringUtils.isNumericSpace(null)); assertEquals(true, StringUtils.isNumericSpace("")); assertEquals(true, StringUtils.isNumericSpace(" ")); assertEquals(false, StringUtils.isNumericSpace("a")); assertEquals(false, StringUtils.isNumericSpace("A")); assertEquals(false, StringUtils.isNumericSpace("kgKgKgKgkgkGkjkjlJlOKLgHdGdHgl")); assertEquals(false, StringUtils.isNumericSpace("ham kso")); assertEquals(true, StringUtils.isNumericSpace("1")); assertEquals(true, StringUtils.isNumericSpace("1000")); assertEquals(false, StringUtils.isNumericSpace("2.3")); assertEquals(true, StringUtils.isNumericSpace("10 00")); assertEquals(false, StringUtils.isNumericSpace("hkHKHik6iUGHKJgU7tUJgKJGI87GIkug")); assertEquals(false, StringUtils.isNumericSpace("_")); assertEquals(false, StringUtils.isNumericSpace("hkHKHik*khbkuh")); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/StringUtilsStartsEndsWithTest.java100644 0 0 20627 11513702440 27647 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang; import junit.framework.TestCase; /** * Unit tests {@link org.apache.commons.lang.StringUtils} - StartsWith/EndsWith methods * * @version $Id: StringUtilsStartsEndsWithTest.java 1056871 2011-01-09 02:51:19Z niallp $ */ public class StringUtilsStartsEndsWithTest extends TestCase { private static final String foo = "foo"; private static final String bar = "bar"; private static final String foobar = "foobar"; private static final String FOO = "FOO"; private static final String BAR = "BAR"; private static final String FOOBAR = "FOOBAR"; public StringUtilsStartsEndsWithTest(String name) { super(name); } //----------------------------------------------------------------------- /** * Test StringUtils.startsWith() */ public void testStartsWith() { assertTrue("startsWith(null, null)", StringUtils.startsWith(null, (String)null)); assertFalse("startsWith(FOOBAR, null)", StringUtils.startsWith(FOOBAR, (String)null)); assertFalse("startsWith(null, FOO)", StringUtils.startsWith(null, FOO)); assertTrue("startsWith(FOOBAR, \"\")", StringUtils.startsWith(FOOBAR, "")); assertTrue("startsWith(foobar, foo)", StringUtils.startsWith(foobar, foo)); assertTrue("startsWith(FOOBAR, FOO)", StringUtils.startsWith(FOOBAR, FOO)); assertFalse("startsWith(foobar, FOO)", StringUtils.startsWith(foobar, FOO)); assertFalse("startsWith(FOOBAR, foo)", StringUtils.startsWith(FOOBAR, foo)); assertFalse("startsWith(foo, foobar)", StringUtils.startsWith(foo, foobar)); assertFalse("startsWith(foo, foobar)", StringUtils.startsWith(bar, foobar)); assertFalse("startsWith(foobar, bar)", StringUtils.startsWith(foobar, bar)); assertFalse("startsWith(FOOBAR, BAR)", StringUtils.startsWith(FOOBAR, BAR)); assertFalse("startsWith(foobar, BAR)", StringUtils.startsWith(foobar, BAR)); assertFalse("startsWith(FOOBAR, bar)", StringUtils.startsWith(FOOBAR, bar)); } /** * Test StringUtils.testStartsWithIgnoreCase() */ public void testStartsWithIgnoreCase() { assertTrue("startsWithIgnoreCase(null, null)", StringUtils.startsWithIgnoreCase(null, (String)null)); assertFalse("startsWithIgnoreCase(FOOBAR, null)", StringUtils.startsWithIgnoreCase(FOOBAR, (String)null)); assertFalse("startsWithIgnoreCase(null, FOO)", StringUtils.startsWithIgnoreCase(null, FOO)); assertTrue("startsWithIgnoreCase(FOOBAR, \"\")", StringUtils.startsWithIgnoreCase(FOOBAR, "")); assertTrue("startsWithIgnoreCase(foobar, foo)", StringUtils.startsWithIgnoreCase(foobar, foo)); assertTrue("startsWithIgnoreCase(FOOBAR, FOO)", StringUtils.startsWithIgnoreCase(FOOBAR, FOO)); assertTrue("startsWithIgnoreCase(foobar, FOO)", StringUtils.startsWithIgnoreCase(foobar, FOO)); assertTrue("startsWithIgnoreCase(FOOBAR, foo)", StringUtils.startsWithIgnoreCase(FOOBAR, foo)); assertFalse("startsWithIgnoreCase(foo, foobar)", StringUtils.startsWithIgnoreCase(foo, foobar)); assertFalse("startsWithIgnoreCase(foo, foobar)", StringUtils.startsWithIgnoreCase(bar, foobar)); assertFalse("startsWithIgnoreCase(foobar, bar)", StringUtils.startsWithIgnoreCase(foobar, bar)); assertFalse("startsWithIgnoreCase(FOOBAR, BAR)", StringUtils.startsWithIgnoreCase(FOOBAR, BAR)); assertFalse("startsWithIgnoreCase(foobar, BAR)", StringUtils.startsWithIgnoreCase(foobar, BAR)); assertFalse("startsWithIgnoreCase(FOOBAR, bar)", StringUtils.startsWithIgnoreCase(FOOBAR, bar)); } /** * Test StringUtils.endsWith() */ public void testEndsWith() { assertTrue("endsWith(null, null)", StringUtils.endsWith(null, (String)null)); assertFalse("endsWith(FOOBAR, null)", StringUtils.endsWith(FOOBAR, (String)null)); assertFalse("endsWith(null, FOO)", StringUtils.endsWith(null, FOO)); assertTrue("endsWith(FOOBAR, \"\")", StringUtils.endsWith(FOOBAR, "")); assertFalse("endsWith(foobar, foo)", StringUtils.endsWith(foobar, foo)); assertFalse("endsWith(FOOBAR, FOO)", StringUtils.endsWith(FOOBAR, FOO)); assertFalse("endsWith(foobar, FOO)", StringUtils.endsWith(foobar, FOO)); assertFalse("endsWith(FOOBAR, foo)", StringUtils.endsWith(FOOBAR, foo)); assertFalse("endsWith(foo, foobar)", StringUtils.endsWith(foo, foobar)); assertFalse("endsWith(foo, foobar)", StringUtils.endsWith(bar, foobar)); assertTrue("endsWith(foobar, bar)", StringUtils.endsWith(foobar, bar)); assertTrue("endsWith(FOOBAR, BAR)", StringUtils.endsWith(FOOBAR, BAR)); assertFalse("endsWith(foobar, BAR)", StringUtils.endsWith(foobar, BAR)); assertFalse("endsWith(FOOBAR, bar)", StringUtils.endsWith(FOOBAR, bar)); } /** * Test StringUtils.endsWithIgnoreCase() */ public void testEndsWithIgnoreCase() { assertTrue("endsWithIgnoreCase(null, null)", StringUtils.endsWithIgnoreCase(null, (String)null)); assertFalse("endsWithIgnoreCase(FOOBAR, null)", StringUtils.endsWithIgnoreCase(FOOBAR, (String)null)); assertFalse("endsWithIgnoreCase(null, FOO)", StringUtils.endsWithIgnoreCase(null, FOO)); assertTrue("endsWithIgnoreCase(FOOBAR, \"\")", StringUtils.endsWithIgnoreCase(FOOBAR, "")); assertFalse("endsWithIgnoreCase(foobar, foo)", StringUtils.endsWithIgnoreCase(foobar, foo)); assertFalse("endsWithIgnoreCase(FOOBAR, FOO)", StringUtils.endsWithIgnoreCase(FOOBAR, FOO)); assertFalse("endsWithIgnoreCase(foobar, FOO)", StringUtils.endsWithIgnoreCase(foobar, FOO)); assertFalse("endsWithIgnoreCase(FOOBAR, foo)", StringUtils.endsWithIgnoreCase(FOOBAR, foo)); assertFalse("endsWithIgnoreCase(foo, foobar)", StringUtils.endsWithIgnoreCase(foo, foobar)); assertFalse("endsWithIgnoreCase(foo, foobar)", StringUtils.endsWithIgnoreCase(bar, foobar)); assertTrue("endsWithIgnoreCase(foobar, bar)", StringUtils.endsWithIgnoreCase(foobar, bar)); assertTrue("endsWithIgnoreCase(FOOBAR, BAR)", StringUtils.endsWithIgnoreCase(FOOBAR, BAR)); assertTrue("endsWithIgnoreCase(foobar, BAR)", StringUtils.endsWithIgnoreCase(foobar, BAR)); assertTrue("endsWithIgnoreCase(FOOBAR, bar)", StringUtils.endsWithIgnoreCase(FOOBAR, bar)); // javadoc assertTrue(StringUtils.endsWithIgnoreCase("abcdef", "def")); assertTrue(StringUtils.endsWithIgnoreCase("ABCDEF", "def")); assertFalse(StringUtils.endsWithIgnoreCase("ABCDEF", "cde")); } public void testEndsWithAny() { assertFalse("StringUtils.endsWithAny(null, null)", StringUtils.endsWithAny(null, null)); assertFalse("StringUtils.endsWithAny(null, new String[] {abc})", StringUtils.endsWithAny(null, new String[] {"abc"})); assertFalse("StringUtils.endsWithAny(abcxyz, null)", StringUtils.endsWithAny("abcxyz", null)); assertTrue("StringUtils.endsWithAny(abcxyz, new String[] {\"\"})", StringUtils.endsWithAny("abcxyz", new String[] {""})); assertTrue("StringUtils.endsWithAny(abcxyz, new String[] {xyz})", StringUtils.endsWithAny("abcxyz", new String[] {"xyz"})); assertTrue("StringUtils.endsWithAny(abcxyz, new String[] {null, xyz, abc})", StringUtils.endsWithAny("abcxyz", new String[] {null, "xyz", "abc"})); assertFalse("StringUtils.endsWithAny(defg, new String[] {null, xyz, abc})", StringUtils.endsWithAny("defg", new String[] {null, "xyz", "abc"})); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/StringUtilsSubstringTest.java100644 0 0 40446 11513702441 26703 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang; import junit.framework.TestCase; /** * Unit tests {@link org.apache.commons.lang.StringUtils} - Substring methods * * @author Apache Software Foundation * @author Ringo De Smet * @author Phil Steitz * @version $Id: StringUtilsSubstringTest.java 905636 2010-02-02 14:03:32Z niallp $ */ public class StringUtilsSubstringTest extends TestCase { private static final String FOO = "foo"; private static final String BAR = "bar"; private static final String BAZ = "baz"; private static final String FOOBAR = "foobar"; private static final String SENTENCE = "foo bar baz"; public StringUtilsSubstringTest(String name) { super(name); } //----------------------------------------------------------------------- public void testSubstring_StringInt() { assertEquals(null, StringUtils.substring(null, 0)); assertEquals("", StringUtils.substring("", 0)); assertEquals("", StringUtils.substring("", 2)); assertEquals("", StringUtils.substring(SENTENCE, 80)); assertEquals(BAZ, StringUtils.substring(SENTENCE, 8)); assertEquals(BAZ, StringUtils.substring(SENTENCE, -3)); assertEquals(SENTENCE, StringUtils.substring(SENTENCE, 0)); assertEquals("abc", StringUtils.substring("abc", -4)); assertEquals("abc", StringUtils.substring("abc", -3)); assertEquals("bc", StringUtils.substring("abc", -2)); assertEquals("c", StringUtils.substring("abc", -1)); assertEquals("abc", StringUtils.substring("abc", 0)); assertEquals("bc", StringUtils.substring("abc", 1)); assertEquals("c", StringUtils.substring("abc", 2)); assertEquals("", StringUtils.substring("abc", 3)); assertEquals("", StringUtils.substring("abc", 4)); } public void testSubstring_StringIntInt() { assertEquals(null, StringUtils.substring(null, 0, 0)); assertEquals(null, StringUtils.substring(null, 1, 2)); assertEquals("", StringUtils.substring("", 0, 0)); assertEquals("", StringUtils.substring("", 1, 2)); assertEquals("", StringUtils.substring("", -2, -1)); assertEquals("", StringUtils.substring(SENTENCE, 8, 6)); assertEquals(FOO, StringUtils.substring(SENTENCE, 0, 3)); assertEquals("o", StringUtils.substring(SENTENCE, -9, 3)); assertEquals(FOO, StringUtils.substring(SENTENCE, 0, -8)); assertEquals("o", StringUtils.substring(SENTENCE, -9, -8)); assertEquals(SENTENCE, StringUtils.substring(SENTENCE, 0, 80)); assertEquals("", StringUtils.substring(SENTENCE, 2, 2)); assertEquals("b",StringUtils.substring("abc", -2, -1)); } public void testLeft_String() { assertSame(null, StringUtils.left(null, -1)); assertSame(null, StringUtils.left(null, 0)); assertSame(null, StringUtils.left(null, 2)); assertEquals("", StringUtils.left("", -1)); assertEquals("", StringUtils.left("", 0)); assertEquals("", StringUtils.left("", 2)); assertEquals("", StringUtils.left(FOOBAR, -1)); assertEquals("", StringUtils.left(FOOBAR, 0)); assertEquals(FOO, StringUtils.left(FOOBAR, 3)); assertSame(FOOBAR, StringUtils.left(FOOBAR, 80)); } public void testRight_String() { assertSame(null, StringUtils.right(null, -1)); assertSame(null, StringUtils.right(null, 0)); assertSame(null, StringUtils.right(null, 2)); assertEquals("", StringUtils.right("", -1)); assertEquals("", StringUtils.right("", 0)); assertEquals("", StringUtils.right("", 2)); assertEquals("", StringUtils.right(FOOBAR, -1)); assertEquals("", StringUtils.right(FOOBAR, 0)); assertEquals(BAR, StringUtils.right(FOOBAR, 3)); assertSame(FOOBAR, StringUtils.right(FOOBAR, 80)); } public void testMid_String() { assertSame(null, StringUtils.mid(null, -1, 0)); assertSame(null, StringUtils.mid(null, 0, -1)); assertSame(null, StringUtils.mid(null, 3, 0)); assertSame(null, StringUtils.mid(null, 3, 2)); assertEquals("", StringUtils.mid("", 0, -1)); assertEquals("", StringUtils.mid("", 0, 0)); assertEquals("", StringUtils.mid("", 0, 2)); assertEquals("", StringUtils.mid(FOOBAR, 3, -1)); assertEquals("", StringUtils.mid(FOOBAR, 3, 0)); assertEquals("b", StringUtils.mid(FOOBAR, 3, 1)); assertEquals(FOO, StringUtils.mid(FOOBAR, 0, 3)); assertEquals(BAR, StringUtils.mid(FOOBAR, 3, 3)); assertEquals(FOOBAR, StringUtils.mid(FOOBAR, 0, 80)); assertEquals(BAR, StringUtils.mid(FOOBAR, 3, 80)); assertEquals("", StringUtils.mid(FOOBAR, 9, 3)); assertEquals(FOO, StringUtils.mid(FOOBAR, -1, 3)); } //----------------------------------------------------------------------- public void testSubstringBefore_StringString() { assertEquals("foo", StringUtils.substringBefore("fooXXbarXXbaz", "XX")); assertEquals(null, StringUtils.substringBefore(null, null)); assertEquals(null, StringUtils.substringBefore(null, "")); assertEquals(null, StringUtils.substringBefore(null, "XX")); assertEquals("", StringUtils.substringBefore("", null)); assertEquals("", StringUtils.substringBefore("", "")); assertEquals("", StringUtils.substringBefore("", "XX")); assertEquals("foo", StringUtils.substringBefore("foo", null)); assertEquals("foo", StringUtils.substringBefore("foo", "b")); assertEquals("f", StringUtils.substringBefore("foot", "o")); assertEquals("", StringUtils.substringBefore("abc", "a")); assertEquals("a", StringUtils.substringBefore("abcba", "b")); assertEquals("ab", StringUtils.substringBefore("abc", "c")); assertEquals("", StringUtils.substringBefore("abc", "")); } public void testSubstringAfter_StringString() { assertEquals("barXXbaz", StringUtils.substringAfter("fooXXbarXXbaz", "XX")); assertEquals(null, StringUtils.substringAfter(null, null)); assertEquals(null, StringUtils.substringAfter(null, "")); assertEquals(null, StringUtils.substringAfter(null, "XX")); assertEquals("", StringUtils.substringAfter("", null)); assertEquals("", StringUtils.substringAfter("", "")); assertEquals("", StringUtils.substringAfter("", "XX")); assertEquals("", StringUtils.substringAfter("foo", null)); assertEquals("ot", StringUtils.substringAfter("foot", "o")); assertEquals("bc", StringUtils.substringAfter("abc", "a")); assertEquals("cba", StringUtils.substringAfter("abcba", "b")); assertEquals("", StringUtils.substringAfter("abc", "c")); assertEquals("abc", StringUtils.substringAfter("abc", "")); assertEquals("", StringUtils.substringAfter("abc", "d")); } public void testSubstringBeforeLast_StringString() { assertEquals("fooXXbar", StringUtils.substringBeforeLast("fooXXbarXXbaz", "XX")); assertEquals(null, StringUtils.substringBeforeLast(null, null)); assertEquals(null, StringUtils.substringBeforeLast(null, "")); assertEquals(null, StringUtils.substringBeforeLast(null, "XX")); assertEquals("", StringUtils.substringBeforeLast("", null)); assertEquals("", StringUtils.substringBeforeLast("", "")); assertEquals("", StringUtils.substringBeforeLast("", "XX")); assertEquals("foo", StringUtils.substringBeforeLast("foo", null)); assertEquals("foo", StringUtils.substringBeforeLast("foo", "b")); assertEquals("fo", StringUtils.substringBeforeLast("foo", "o")); assertEquals("abc\r\n", StringUtils.substringBeforeLast("abc\r\n", "d")); assertEquals("abc", StringUtils.substringBeforeLast("abcdabc", "d")); assertEquals("abcdabc", StringUtils.substringBeforeLast("abcdabcd", "d")); assertEquals("a", StringUtils.substringBeforeLast("abc", "b")); assertEquals("abc ", StringUtils.substringBeforeLast("abc \n", "\n")); assertEquals("a", StringUtils.substringBeforeLast("a", null)); assertEquals("a", StringUtils.substringBeforeLast("a", "")); assertEquals("", StringUtils.substringBeforeLast("a", "a")); } public void testSubstringAfterLast_StringString() { assertEquals("baz", StringUtils.substringAfterLast("fooXXbarXXbaz", "XX")); assertEquals(null, StringUtils.substringAfterLast(null, null)); assertEquals(null, StringUtils.substringAfterLast(null, "")); assertEquals(null, StringUtils.substringAfterLast(null, "XX")); assertEquals("", StringUtils.substringAfterLast("", null)); assertEquals("", StringUtils.substringAfterLast("", "")); assertEquals("", StringUtils.substringAfterLast("", "a")); assertEquals("", StringUtils.substringAfterLast("foo", null)); assertEquals("", StringUtils.substringAfterLast("foo", "b")); assertEquals("t", StringUtils.substringAfterLast("foot", "o")); assertEquals("bc", StringUtils.substringAfterLast("abc", "a")); assertEquals("a", StringUtils.substringAfterLast("abcba", "b")); assertEquals("", StringUtils.substringAfterLast("abc", "c")); assertEquals("", StringUtils.substringAfterLast("", "d")); assertEquals("", StringUtils.substringAfterLast("abc", "")); } //----------------------------------------------------------------------- public void testSubstringBetween_StringString() { assertEquals(null, StringUtils.substringBetween(null, "tag")); assertEquals("", StringUtils.substringBetween("", "")); assertEquals(null, StringUtils.substringBetween("", "abc")); assertEquals("", StringUtils.substringBetween(" ", " ")); assertEquals(null, StringUtils.substringBetween("abc", null)); assertEquals("", StringUtils.substringBetween("abc", "")); assertEquals(null, StringUtils.substringBetween("abc", "a")); assertEquals("bc", StringUtils.substringBetween("abca", "a")); assertEquals("bc", StringUtils.substringBetween("abcabca", "a")); assertEquals("bar", StringUtils.substringBetween("\nbar\n", "\n")); } public void testSubstringBetween_StringStringString() { assertEquals(null, StringUtils.substringBetween(null, "", "")); assertEquals(null, StringUtils.substringBetween("", null, "")); assertEquals(null, StringUtils.substringBetween("", "", null)); assertEquals("", StringUtils.substringBetween("", "", "")); assertEquals("", StringUtils.substringBetween("foo", "", "")); assertEquals(null, StringUtils.substringBetween("foo", "", "]")); assertEquals(null, StringUtils.substringBetween("foo", "[", "]")); assertEquals("", StringUtils.substringBetween(" ", " ", " ")); assertEquals("bar", StringUtils.substringBetween("bar", "", "") ); } /** * Tests the substringsBetween method that returns an String Array of substrings. */ public void testSubstringsBetween_StringStringString() { String[] results = StringUtils.substringsBetween("[one], [two], [three]", "[", "]"); assertEquals(3, results.length); assertEquals("one", results[0]); assertEquals("two", results[1]); assertEquals("three", results[2]); results = StringUtils.substringsBetween("[one], [two], three", "[", "]"); assertEquals(2, results.length); assertEquals("one", results[0]); assertEquals("two", results[1]); results = StringUtils.substringsBetween("[one], [two], three]", "[", "]"); assertEquals(2, results.length); assertEquals("one", results[0]); assertEquals("two", results[1]); results = StringUtils.substringsBetween("[one], two], three]", "[", "]"); assertEquals(1, results.length); assertEquals("one", results[0]); results = StringUtils.substringsBetween("one], two], [three]", "[", "]"); assertEquals(1, results.length); assertEquals("three", results[0]); // 'ab hello ba' will match, but 'ab non ba' won't // this is because the 'a' is shared between the two and can't be matched twice results = StringUtils.substringsBetween("aabhellobabnonba", "ab", "ba"); assertEquals(1, results.length); assertEquals("hello", results[0]); results = StringUtils.substringsBetween("one, two, three", "[", "]"); assertNull(results); results = StringUtils.substringsBetween("[one, two, three", "[", "]"); assertNull(results); results = StringUtils.substringsBetween("one, two, three]", "[", "]"); assertNull(results); results = StringUtils.substringsBetween("[one], [two], [three]", "[", null); assertNull(results); results = StringUtils.substringsBetween("[one], [two], [three]", null, "]"); assertNull(results); results = StringUtils.substringsBetween("[one], [two], [three]", "", ""); assertNull(results); results = StringUtils.substringsBetween(null, "[", "]"); assertNull(results); results = StringUtils.substringsBetween("", "[", "]"); assertEquals(0, results.length); } //----------------------------------------------------------------------- public void testCountMatches_String() { assertEquals(0, StringUtils.countMatches(null, null)); assertEquals(0, StringUtils.countMatches("blah", null)); assertEquals(0, StringUtils.countMatches(null, "DD")); assertEquals(0, StringUtils.countMatches("x", "")); assertEquals(0, StringUtils.countMatches("", "")); assertEquals(3, StringUtils.countMatches("one long someone sentence of one", "one")); assertEquals(0, StringUtils.countMatches("one long someone sentence of one", "two")); assertEquals(4, StringUtils.countMatches("oooooooooooo", "ooo")); } public void testDeprecatedGetNestedString_StringString() { assertEquals(null, StringUtils.getNestedString(null, "tag")); assertEquals("", StringUtils.getNestedString("", "")); assertEquals(null, StringUtils.getNestedString("", "abc")); assertEquals("", StringUtils.getNestedString(" ", " ")); assertEquals(null, StringUtils.getNestedString("abc", null)); assertEquals("", StringUtils.getNestedString("abc", "")); assertEquals(null, StringUtils.getNestedString("abc", "a")); assertEquals("bc", StringUtils.getNestedString("abca", "a")); assertEquals("bc", StringUtils.getNestedString("abcabca", "a")); assertEquals("bar", StringUtils.getNestedString("\nbar\n", "\n")); } public void testDeprecatedGetNestedString_StringStringString() { assertEquals(null, StringUtils.getNestedString(null, "", "")); assertEquals("", StringUtils.getNestedString("", "", "")); assertEquals("", StringUtils.getNestedString(" ", " ", " ")); assertEquals("bar", StringUtils.getNestedString("bar", "", "") ); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/StringUtilsTest.java100644 0 0 274453 11513702440 25030 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.Locale; import junit.framework.TestCase; /** * Unit tests {@link org.apache.commons.lang.StringUtils}. * * @author Apache Software Foundation * @author Daniel L. Rall * @author Ringo De Smet * @author Henning P. Schmiedehausen * @author Phil Steitz * @author Gary D. Gregory * @author Scott Johnson * @author Al Chou * @version $Id: StringUtilsTest.java 1058365 2011-01-13 00:04:49Z niallp $ */ public class StringUtilsTest extends TestCase { static final String WHITESPACE; static final String NON_WHITESPACE; static final String TRIMMABLE; static final String NON_TRIMMABLE; static { String ws = ""; String nws = ""; String tr = ""; String ntr = ""; for (int i = 0; i < Character.MAX_VALUE; i++) { if (Character.isWhitespace((char) i)) { ws += String.valueOf((char) i); if (i > 32) { ntr += String.valueOf((char) i); } } else if (i < 40) { nws += String.valueOf((char) i); } } for (int i = 0; i <= 32; i++) { tr += String.valueOf((char) i); } WHITESPACE = ws; NON_WHITESPACE = nws; TRIMMABLE = tr; NON_TRIMMABLE = ntr; } private static final String[] ARRAY_LIST = { "foo", "bar", "baz" }; private static final String[] EMPTY_ARRAY_LIST = {}; private static final String[] NULL_ARRAY_LIST = {null}; private static final String[] MIXED_ARRAY_LIST = {null, "", "foo"}; private static final Object[] MIXED_TYPE_LIST = {new String("foo"), new Long(2)}; private static final String SEPARATOR = ","; private static final char SEPARATOR_CHAR = ';'; private static final String TEXT_LIST = "foo,bar,baz"; private static final String TEXT_LIST_CHAR = "foo;bar;baz"; private static final String TEXT_LIST_NOSEP = "foobarbaz"; private static final String FOO_UNCAP = "foo"; private static final String FOO_CAP = "Foo"; private static final String SENTENCE_UNCAP = "foo bar baz"; private static final String SENTENCE_CAP = "Foo Bar Baz"; public StringUtilsTest(String name) { super(name); } //----------------------------------------------------------------------- public void testConstructor() { assertNotNull(new StringUtils()); Constructor[] cons = StringUtils.class.getDeclaredConstructors(); assertEquals(1, cons.length); assertEquals(true, Modifier.isPublic(cons[0].getModifiers())); assertEquals(true, Modifier.isPublic(StringUtils.class.getModifiers())); assertEquals(false, Modifier.isFinal(StringUtils.class.getModifiers())); } //----------------------------------------------------------------------- public void testCaseFunctions() { assertEquals(null, StringUtils.upperCase(null)); assertEquals(null, StringUtils.upperCase(null, Locale.ENGLISH)); assertEquals(null, StringUtils.lowerCase(null)); assertEquals(null, StringUtils.lowerCase(null, Locale.ENGLISH)); assertEquals(null, StringUtils.capitalize(null)); assertEquals(null, StringUtils.uncapitalise(null)); assertEquals(null, StringUtils.uncapitalize(null)); assertEquals("capitalise(String) failed", FOO_CAP, StringUtils.capitalise(FOO_UNCAP) ); assertEquals("capitalise(empty-string) failed", "", StringUtils.capitalise("") ); assertEquals("capitalise(single-char-string) failed", "X", StringUtils.capitalise("x") ); assertEquals("capitalize(String) failed", FOO_CAP, StringUtils.capitalize(FOO_UNCAP) ); assertEquals("capitalize(empty-string) failed", "", StringUtils.capitalize("") ); assertEquals("capitalize(single-char-string) failed", "X", StringUtils.capitalize("x") ); assertEquals("uncapitalise(String) failed", FOO_UNCAP, StringUtils.uncapitalise(FOO_CAP) ); assertEquals("uncapitalise(empty-string) failed", "", StringUtils.uncapitalise("") ); assertEquals("uncapitalise(single-char-string) failed", "x", StringUtils.uncapitalise("X") ); assertEquals("uncapitalize(String) failed", FOO_UNCAP, StringUtils.uncapitalize(FOO_CAP) ); assertEquals("uncapitalize(empty-string) failed", "", StringUtils.uncapitalize("") ); assertEquals("uncapitalize(single-char-string) failed", "x", StringUtils.uncapitalize("X") ); // reflection type of tests: Sentences. assertEquals("uncapitalise(capitalise(String)) failed", SENTENCE_UNCAP, StringUtils.uncapitalise(StringUtils.capitalise(SENTENCE_UNCAP)) ); assertEquals("capitalise(uncapitalise(String)) failed", SENTENCE_CAP, StringUtils.capitalise(StringUtils.uncapitalise(SENTENCE_CAP)) ); assertEquals("uncapitalize(capitalize(String)) failed", SENTENCE_UNCAP, StringUtils.uncapitalize(StringUtils.capitalize(SENTENCE_UNCAP)) ); assertEquals("capitalize(uncapitalize(String)) failed", SENTENCE_CAP, StringUtils.capitalize(StringUtils.uncapitalize(SENTENCE_CAP)) ); // reflection type of tests: One word. assertEquals("uncapitalise(capitalise(String)) failed", FOO_UNCAP, StringUtils.uncapitalise(StringUtils.capitalise(FOO_UNCAP)) ); assertEquals("capitalise(uncapitalise(String)) failed", FOO_CAP, StringUtils.capitalise(StringUtils.uncapitalise(FOO_CAP)) ); assertEquals("uncapitalize(capitalize(String)) failed", FOO_UNCAP, StringUtils.uncapitalize(StringUtils.capitalize(FOO_UNCAP)) ); assertEquals("capitalize(uncapitalize(String)) failed", FOO_CAP, StringUtils.capitalize(StringUtils.uncapitalize(FOO_CAP)) ); assertEquals("upperCase(String) failed", "FOO TEST THING", StringUtils.upperCase("fOo test THING") ); assertEquals("upperCase(empty-string) failed", "", StringUtils.upperCase("") ); assertEquals("lowerCase(String) failed", "foo test thing", StringUtils.lowerCase("fOo test THING") ); assertEquals("lowerCase(empty-string) failed", "", StringUtils.lowerCase("") ); assertEquals("upperCase(String, Locale) failed", "FOO TEST THING", StringUtils.upperCase("fOo test THING", Locale.ENGLISH) ); assertEquals("upperCase(empty-string, Locale) failed", "", StringUtils.upperCase("", Locale.ENGLISH) ); assertEquals("lowerCase(String, Locale) failed", "foo test thing", StringUtils.lowerCase("fOo test THING", Locale.ENGLISH) ); assertEquals("lowerCase(empty-string, Locale) failed", "", StringUtils.lowerCase("", Locale.ENGLISH) ); } public void testSwapCase_String() { assertEquals(null, StringUtils.swapCase(null)); assertEquals("", StringUtils.swapCase("")); assertEquals(" ", StringUtils.swapCase(" ")); assertEquals("i", WordUtils.swapCase("I") ); assertEquals("I", WordUtils.swapCase("i") ); assertEquals("I AM HERE 123", StringUtils.swapCase("i am here 123") ); assertEquals("i aM hERE 123", StringUtils.swapCase("I Am Here 123") ); assertEquals("I AM here 123", StringUtils.swapCase("i am HERE 123") ); assertEquals("i am here 123", StringUtils.swapCase("I AM HERE 123") ); String test = "This String contains a TitleCase character: \u01C8"; String expect = "tHIS sTRING CONTAINS A tITLEcASE CHARACTER: \u01C9"; assertEquals(expect, WordUtils.swapCase(test)); } //----------------------------------------------------------------------- public void testJoin_Objectarray() { assertEquals(null, StringUtils.join(null)); assertEquals("", StringUtils.join(EMPTY_ARRAY_LIST)); assertEquals("", StringUtils.join(NULL_ARRAY_LIST)); assertEquals("abc", StringUtils.join(new String[] {"a", "b", "c"})); assertEquals("a", StringUtils.join(new String[] {null, "a", ""})); assertEquals("foo", StringUtils.join(MIXED_ARRAY_LIST)); assertEquals("foo2", StringUtils.join(MIXED_TYPE_LIST)); } public void testJoin_ArrayChar() { assertEquals(null, StringUtils.join((Object[]) null, ',')); assertEquals(TEXT_LIST_CHAR, StringUtils.join(ARRAY_LIST, SEPARATOR_CHAR)); assertEquals("", StringUtils.join(EMPTY_ARRAY_LIST, SEPARATOR_CHAR)); assertEquals(";;foo", StringUtils.join(MIXED_ARRAY_LIST, SEPARATOR_CHAR)); assertEquals("foo;2", StringUtils.join(MIXED_TYPE_LIST, SEPARATOR_CHAR)); assertEquals("/", StringUtils.join(MIXED_ARRAY_LIST, '/', 0, MIXED_ARRAY_LIST.length-1)); assertEquals("foo", StringUtils.join(MIXED_TYPE_LIST, '/', 0, 1)); assertEquals("foo/2", StringUtils.join(MIXED_TYPE_LIST, '/', 0, 2)); assertEquals("2", StringUtils.join(MIXED_TYPE_LIST, '/', 1, 2)); assertEquals("", StringUtils.join(MIXED_TYPE_LIST, '/', 2, 1)); } public void testJoin_ArrayString() { assertEquals(null, StringUtils.join((Object[]) null, null)); assertEquals(TEXT_LIST_NOSEP, StringUtils.join(ARRAY_LIST, null)); assertEquals(TEXT_LIST_NOSEP, StringUtils.join(ARRAY_LIST, "")); assertEquals("", StringUtils.join(NULL_ARRAY_LIST, null)); assertEquals("", StringUtils.join(EMPTY_ARRAY_LIST, null)); assertEquals("", StringUtils.join(EMPTY_ARRAY_LIST, "")); assertEquals("", StringUtils.join(EMPTY_ARRAY_LIST, SEPARATOR)); assertEquals(TEXT_LIST, StringUtils.join(ARRAY_LIST, SEPARATOR)); assertEquals(",,foo", StringUtils.join(MIXED_ARRAY_LIST, SEPARATOR)); assertEquals("foo,2", StringUtils.join(MIXED_TYPE_LIST, SEPARATOR)); assertEquals("/", StringUtils.join(MIXED_ARRAY_LIST, "/", 0, MIXED_ARRAY_LIST.length-1)); assertEquals("", StringUtils.join(MIXED_ARRAY_LIST, "", 0, MIXED_ARRAY_LIST.length-1)); assertEquals("foo", StringUtils.join(MIXED_TYPE_LIST, "/", 0, 1)); assertEquals("foo/2", StringUtils.join(MIXED_TYPE_LIST, "/", 0, 2)); assertEquals("2", StringUtils.join(MIXED_TYPE_LIST, "/", 1, 2)); assertEquals("", StringUtils.join(MIXED_TYPE_LIST, "/", 2, 1)); } public void testJoin_IteratorChar() { assertEquals(null, StringUtils.join((Iterator) null, ',')); assertEquals(TEXT_LIST_CHAR, StringUtils.join(Arrays.asList(ARRAY_LIST).iterator(), SEPARATOR_CHAR)); assertEquals("", StringUtils.join(Arrays.asList(NULL_ARRAY_LIST).iterator(), SEPARATOR_CHAR)); assertEquals("", StringUtils.join(Arrays.asList(EMPTY_ARRAY_LIST).iterator(), SEPARATOR_CHAR)); assertEquals("foo", StringUtils.join(Collections.singleton("foo").iterator(), 'x')); } public void testJoin_IteratorString() { assertEquals(null, StringUtils.join((Iterator) null, null)); assertEquals(TEXT_LIST_NOSEP, StringUtils.join(Arrays.asList(ARRAY_LIST).iterator(), null)); assertEquals(TEXT_LIST_NOSEP, StringUtils.join(Arrays.asList(ARRAY_LIST).iterator(), "")); assertEquals("foo", StringUtils.join(Collections.singleton("foo").iterator(), "x")); assertEquals("foo", StringUtils.join(Collections.singleton("foo").iterator(), null)); assertEquals("", StringUtils.join(Arrays.asList(NULL_ARRAY_LIST).iterator(), null)); assertEquals("", StringUtils.join(Arrays.asList(EMPTY_ARRAY_LIST).iterator(), null)); assertEquals("", StringUtils.join(Arrays.asList(EMPTY_ARRAY_LIST).iterator(), "")); assertEquals("", StringUtils.join(Arrays.asList(EMPTY_ARRAY_LIST).iterator(), SEPARATOR)); assertEquals(TEXT_LIST, StringUtils.join(Arrays.asList(ARRAY_LIST).iterator(), SEPARATOR)); } public void testJoin_CollectionChar() { assertEquals(null, StringUtils.join((Collection) null, ',')); assertEquals(TEXT_LIST_CHAR, StringUtils.join(Arrays.asList(ARRAY_LIST), SEPARATOR_CHAR)); assertEquals("", StringUtils.join(Arrays.asList(NULL_ARRAY_LIST), SEPARATOR_CHAR)); assertEquals("", StringUtils.join(Arrays.asList(EMPTY_ARRAY_LIST), SEPARATOR_CHAR)); assertEquals("foo", StringUtils.join(Collections.singleton("foo"), 'x')); } public void testJoin_CollectionString() { assertEquals(null, StringUtils.join((Collection) null, null)); assertEquals(TEXT_LIST_NOSEP, StringUtils.join(Arrays.asList(ARRAY_LIST), null)); assertEquals(TEXT_LIST_NOSEP, StringUtils.join(Arrays.asList(ARRAY_LIST), "")); assertEquals("foo", StringUtils.join(Collections.singleton("foo"), "x")); assertEquals("foo", StringUtils.join(Collections.singleton("foo"), null)); assertEquals("", StringUtils.join(Arrays.asList(NULL_ARRAY_LIST), null)); assertEquals("", StringUtils.join(Arrays.asList(EMPTY_ARRAY_LIST), null)); assertEquals("", StringUtils.join(Arrays.asList(EMPTY_ARRAY_LIST), "")); assertEquals("", StringUtils.join(Arrays.asList(EMPTY_ARRAY_LIST), SEPARATOR)); assertEquals(TEXT_LIST, StringUtils.join(Arrays.asList(ARRAY_LIST), SEPARATOR)); } public void testDeprecatedConcatenate_Objectarray() { assertEquals(null, StringUtils.concatenate(null)); assertEquals("", StringUtils.concatenate(EMPTY_ARRAY_LIST)); assertEquals("", StringUtils.concatenate(NULL_ARRAY_LIST)); assertEquals("foo", StringUtils.concatenate(MIXED_ARRAY_LIST)); assertEquals("foo2", StringUtils.concatenate(MIXED_TYPE_LIST)); } public void testSplit_String() { assertEquals(null, StringUtils.split(null)); assertEquals(0, StringUtils.split("").length); String str = "a b .c"; String[] res = StringUtils.split(str); assertEquals(3, res.length); assertEquals("a", res[0]); assertEquals("b", res[1]); assertEquals(".c", res[2]); str = " a "; res = StringUtils.split(str); assertEquals(1, res.length); assertEquals("a", res[0]); str = "a" + WHITESPACE + "b" + NON_WHITESPACE + "c"; res = StringUtils.split(str); assertEquals(2, res.length); assertEquals("a", res[0]); assertEquals("b" + NON_WHITESPACE + "c", res[1]); } public void testSplit_StringChar() { assertEquals(null, StringUtils.split(null, '.')); assertEquals(0, StringUtils.split("", '.').length); String str = "a.b.. c"; String[] res = StringUtils.split(str, '.'); assertEquals(3, res.length); assertEquals("a", res[0]); assertEquals("b", res[1]); assertEquals(" c", res[2]); str = ".a."; res = StringUtils.split(str, '.'); assertEquals(1, res.length); assertEquals("a", res[0]); str = "a b c"; res = StringUtils.split(str,' '); assertEquals(3, res.length); assertEquals("a", res[0]); assertEquals("b", res[1]); assertEquals("c", res[2]); } public void testSplit_StringString_StringStringInt() { assertEquals(null, StringUtils.split(null, ".")); assertEquals(null, StringUtils.split(null, ".", 3)); assertEquals(0, StringUtils.split("", ".").length); assertEquals(0, StringUtils.split("", ".", 3).length); innerTestSplit('.', ".", ' '); innerTestSplit('.', ".", ','); innerTestSplit('.', ".,", 'x'); for (int i = 0; i < WHITESPACE.length(); i++) { for (int j = 0; j < NON_WHITESPACE.length(); j++) { innerTestSplit(WHITESPACE.charAt(i), null, NON_WHITESPACE.charAt(j)); innerTestSplit(WHITESPACE.charAt(i), String.valueOf(WHITESPACE.charAt(i)), NON_WHITESPACE.charAt(j)); } } String[] results = null; String[] expectedResults = {"ab", "de fg"}; results = StringUtils.split("ab de fg", null, 2); assertEquals(expectedResults.length, results.length); for (int i = 0; i < expectedResults.length; i++) { assertEquals(expectedResults[i], results[i]); } String[] expectedResults2 = {"ab", "cd:ef"}; results = StringUtils.split("ab:cd:ef",":", 2); assertEquals(expectedResults2.length, results.length); for (int i = 0; i < expectedResults2.length; i++) { assertEquals(expectedResults2[i], results[i]); } } private void innerTestSplit(char separator, String sepStr, char noMatch) { String msg = "Failed on separator hex(" + Integer.toHexString(separator) + "), noMatch hex(" + Integer.toHexString(noMatch) + "), sepStr(" + sepStr + ")"; final String str = "a" + separator + "b" + separator + separator + noMatch + "c"; String[] res; // (str, sepStr) res = StringUtils.split(str, sepStr); assertEquals(msg, 3, res.length); assertEquals(msg, "a", res[0]); assertEquals(msg, "b", res[1]); assertEquals(msg, noMatch + "c", res[2]); final String str2 = separator + "a" + separator; res = StringUtils.split(str2, sepStr); assertEquals(msg, 1, res.length); assertEquals(msg, "a", res[0]); res = StringUtils.split(str, sepStr, -1); assertEquals(msg, 3, res.length); assertEquals(msg, "a", res[0]); assertEquals(msg, "b", res[1]); assertEquals(msg, noMatch + "c", res[2]); res = StringUtils.split(str, sepStr, 0); assertEquals(msg, 3, res.length); assertEquals(msg, "a", res[0]); assertEquals(msg, "b", res[1]); assertEquals(msg, noMatch + "c", res[2]); res = StringUtils.split(str, sepStr, 1); assertEquals(msg, 1, res.length); assertEquals(msg, str, res[0]); res = StringUtils.split(str, sepStr, 2); assertEquals(msg, 2, res.length); assertEquals(msg, "a", res[0]); assertEquals(msg, str.substring(2), res[1]); } public void testSplitByWholeString_StringStringBoolean() { assertEquals( null, StringUtils.splitByWholeSeparator( null, "." ) ) ; assertEquals( 0, StringUtils.splitByWholeSeparator( "", "." ).length ) ; String stringToSplitOnNulls = "ab de fg" ; String[] splitOnNullExpectedResults = { "ab", "de", "fg" } ; String[] splitOnNullResults = StringUtils.splitByWholeSeparator( stringToSplitOnNulls, null ) ; assertEquals( splitOnNullExpectedResults.length, splitOnNullResults.length ) ; for ( int i = 0 ; i < splitOnNullExpectedResults.length ; i+= 1 ) { assertEquals( splitOnNullExpectedResults[i], splitOnNullResults[i] ) ; } String stringToSplitOnCharactersAndString = "abstemiouslyaeiouyabstemiously" ; String[] splitOnStringExpectedResults = { "abstemiously", "abstemiously" } ; String[] splitOnStringResults = StringUtils.splitByWholeSeparator( stringToSplitOnCharactersAndString, "aeiouy" ) ; assertEquals( splitOnStringExpectedResults.length, splitOnStringResults.length ) ; for ( int i = 0 ; i < splitOnStringExpectedResults.length ; i+= 1 ) { assertEquals( splitOnStringExpectedResults[i], splitOnStringResults[i] ) ; } String[] splitWithMultipleSeparatorExpectedResults = {"ab", "cd", "ef"}; String[] splitWithMultipleSeparator = StringUtils.splitByWholeSeparator("ab:cd::ef", ":"); assertEquals( splitWithMultipleSeparatorExpectedResults.length, splitWithMultipleSeparator.length ); for( int i = 0; i < splitWithMultipleSeparatorExpectedResults.length ; i++ ) { assertEquals( splitWithMultipleSeparatorExpectedResults[i], splitWithMultipleSeparator[i] ) ; } } public void testSplitByWholeString_StringStringBooleanInt() { assertEquals( null, StringUtils.splitByWholeSeparator( null, ".", 3 ) ) ; assertEquals( 0, StringUtils.splitByWholeSeparator( "", ".", 3 ).length ) ; String stringToSplitOnNulls = "ab de fg" ; String[] splitOnNullExpectedResults = { "ab", "de fg" } ; //String[] splitOnNullExpectedResults = { "ab", "de" } ; String[] splitOnNullResults = StringUtils.splitByWholeSeparator( stringToSplitOnNulls, null, 2 ) ; assertEquals( splitOnNullExpectedResults.length, splitOnNullResults.length ) ; for ( int i = 0 ; i < splitOnNullExpectedResults.length ; i+= 1 ) { assertEquals( splitOnNullExpectedResults[i], splitOnNullResults[i] ) ; } String stringToSplitOnCharactersAndString = "abstemiouslyaeiouyabstemiouslyaeiouyabstemiously" ; String[] splitOnStringExpectedResults = { "abstemiously", "abstemiouslyaeiouyabstemiously" } ; //String[] splitOnStringExpectedResults = { "abstemiously", "abstemiously" } ; String[] splitOnStringResults = StringUtils.splitByWholeSeparator( stringToSplitOnCharactersAndString, "aeiouy", 2 ) ; assertEquals( splitOnStringExpectedResults.length, splitOnStringResults.length ) ; for ( int i = 0 ; i < splitOnStringExpectedResults.length ; i++ ) { assertEquals( splitOnStringExpectedResults[i], splitOnStringResults[i] ) ; } } public void testSplitByWholeSeparatorPreserveAllTokens_StringStringInt() { assertEquals( null, StringUtils.splitByWholeSeparatorPreserveAllTokens( null, ".", -1 ) ) ; assertEquals( 0, StringUtils.splitByWholeSeparatorPreserveAllTokens( "", ".", -1 ).length ) ; // test whitespace String input = "ab de fg" ; String[] expected = new String[] { "ab", "", "", "de", "fg" } ; String[] actual = StringUtils.splitByWholeSeparatorPreserveAllTokens( input, null, -1 ) ; assertEquals( expected.length, actual.length ) ; for ( int i = 0 ; i < actual.length ; i+= 1 ) { assertEquals( expected[i], actual[i] ); } // test delimiter singlechar input = "1::2:::3::::4"; expected = new String[] { "1", "", "2", "", "", "3", "", "", "", "4" }; actual = StringUtils.splitByWholeSeparatorPreserveAllTokens( input, ":", -1 ) ; assertEquals( expected.length, actual.length ) ; for ( int i = 0 ; i < actual.length ; i+= 1 ) { assertEquals( expected[i], actual[i] ); } // test delimiter multichar input = "1::2:::3::::4"; expected = new String[] { "1", "2", ":3", "", "4" }; actual = StringUtils.splitByWholeSeparatorPreserveAllTokens( input, "::", -1 ) ; assertEquals( expected.length, actual.length ) ; for ( int i = 0 ; i < actual.length ; i+= 1 ) { assertEquals( expected[i], actual[i] ); } // test delimiter char with max input = "1::2::3:4"; expected = new String[] { "1", "", "2", ":3:4" }; actual = StringUtils.splitByWholeSeparatorPreserveAllTokens( input, ":", 4 ) ; assertEquals( expected.length, actual.length ) ; for ( int i = 0 ; i < actual.length ; i+= 1 ) { assertEquals( expected[i], actual[i] ); } } public void testSplitPreserveAllTokens_String() { assertEquals(null, StringUtils.splitPreserveAllTokens(null)); assertEquals(0, StringUtils.splitPreserveAllTokens("").length); String str = "abc def"; String[] res = StringUtils.splitPreserveAllTokens(str); assertEquals(2, res.length); assertEquals("abc", res[0]); assertEquals("def", res[1]); str = "abc def"; res = StringUtils.splitPreserveAllTokens(str); assertEquals(3, res.length); assertEquals("abc", res[0]); assertEquals("", res[1]); assertEquals("def", res[2]); str = " abc "; res = StringUtils.splitPreserveAllTokens(str); assertEquals(3, res.length); assertEquals("", res[0]); assertEquals("abc", res[1]); assertEquals("", res[2]); str = "a b .c"; res = StringUtils.splitPreserveAllTokens(str); assertEquals(3, res.length); assertEquals("a", res[0]); assertEquals("b", res[1]); assertEquals(".c", res[2]); str = " a b .c"; res = StringUtils.splitPreserveAllTokens(str); assertEquals(4, res.length); assertEquals("", res[0]); assertEquals("a", res[1]); assertEquals("b", res[2]); assertEquals(".c", res[3]); str = "a b .c"; res = StringUtils.splitPreserveAllTokens(str); assertEquals(5, res.length); assertEquals("a", res[0]); assertEquals("", res[1]); assertEquals("b", res[2]); assertEquals("", res[3]); assertEquals(".c", res[4]); str = " a "; res = StringUtils.splitPreserveAllTokens(str); assertEquals(4, res.length); assertEquals("", res[0]); assertEquals("a", res[1]); assertEquals("", res[2]); assertEquals("", res[3]); str = " a b"; res = StringUtils.splitPreserveAllTokens(str); assertEquals(4, res.length); assertEquals("", res[0]); assertEquals("a", res[1]); assertEquals("", res[2]); assertEquals("b", res[3]); str = "a" + WHITESPACE + "b" + NON_WHITESPACE + "c"; res = StringUtils.splitPreserveAllTokens(str); assertEquals(WHITESPACE.length() + 1, res.length); assertEquals("a", res[0]); for(int i = 1; i < WHITESPACE.length()-1; i++) { assertEquals("", res[i]); } assertEquals("b" + NON_WHITESPACE + "c", res[WHITESPACE.length()]); } public void testSplitPreserveAllTokens_StringChar() { assertEquals(null, StringUtils.splitPreserveAllTokens(null, '.')); assertEquals(0, StringUtils.splitPreserveAllTokens("", '.').length); String str = "a.b. c"; String[] res = StringUtils.splitPreserveAllTokens(str, '.'); assertEquals(3, res.length); assertEquals("a", res[0]); assertEquals("b", res[1]); assertEquals(" c", res[2]); str = "a.b.. c"; res = StringUtils.splitPreserveAllTokens(str, '.'); assertEquals(4, res.length); assertEquals("a", res[0]); assertEquals("b", res[1]); assertEquals("", res[2]); assertEquals(" c", res[3]); str = ".a."; res = StringUtils.splitPreserveAllTokens(str, '.'); assertEquals(3, res.length); assertEquals("", res[0]); assertEquals("a", res[1]); assertEquals("", res[2]); str = ".a.."; res = StringUtils.splitPreserveAllTokens(str, '.'); assertEquals(4, res.length); assertEquals("", res[0]); assertEquals("a", res[1]); assertEquals("", res[2]); assertEquals("", res[3]); str = "..a."; res = StringUtils.splitPreserveAllTokens(str, '.'); assertEquals(4, res.length); assertEquals("", res[0]); assertEquals("", res[1]); assertEquals("a", res[2]); assertEquals("", res[3]); str = "..a"; res = StringUtils.splitPreserveAllTokens(str, '.'); assertEquals(3, res.length); assertEquals("", res[0]); assertEquals("", res[1]); assertEquals("a", res[2]); str = "a b c"; res = StringUtils.splitPreserveAllTokens(str,' '); assertEquals(3, res.length); assertEquals("a", res[0]); assertEquals("b", res[1]); assertEquals("c", res[2]); str = "a b c"; res = StringUtils.splitPreserveAllTokens(str,' '); assertEquals(5, res.length); assertEquals("a", res[0]); assertEquals("", res[1]); assertEquals("b", res[2]); assertEquals("", res[3]); assertEquals("c", res[4]); str = " a b c"; res = StringUtils.splitPreserveAllTokens(str,' '); assertEquals(4, res.length); assertEquals("", res[0]); assertEquals("a", res[1]); assertEquals("b", res[2]); assertEquals("c", res[3]); str = " a b c"; res = StringUtils.splitPreserveAllTokens(str,' '); assertEquals(5, res.length); assertEquals("", res[0]); assertEquals("", res[1]); assertEquals("a", res[2]); assertEquals("b", res[3]); assertEquals("c", res[4]); str = "a b c "; res = StringUtils.splitPreserveAllTokens(str,' '); assertEquals(4, res.length); assertEquals("a", res[0]); assertEquals("b", res[1]); assertEquals("c", res[2]); assertEquals("", res[3]); str = "a b c "; res = StringUtils.splitPreserveAllTokens(str,' '); assertEquals(5, res.length); assertEquals("a", res[0]); assertEquals("b", res[1]); assertEquals("c", res[2]); assertEquals("", res[3]); assertEquals("", res[3]); // Match example in javadoc { String[] results = null; String[] expectedResults = {"a", "", "b", "c"}; results = StringUtils.splitPreserveAllTokens("a..b.c",'.'); assertEquals(expectedResults.length, results.length); for (int i = 0; i < expectedResults.length; i++) { assertEquals(expectedResults[i], results[i]); } } } public void testSplitPreserveAllTokens_StringString_StringStringInt() { assertEquals(null, StringUtils.splitPreserveAllTokens(null, ".")); assertEquals(null, StringUtils.splitPreserveAllTokens(null, ".", 3)); assertEquals(0, StringUtils.splitPreserveAllTokens("", ".").length); assertEquals(0, StringUtils.splitPreserveAllTokens("", ".", 3).length); innerTestSplitPreserveAllTokens('.', ".", ' '); innerTestSplitPreserveAllTokens('.', ".", ','); innerTestSplitPreserveAllTokens('.', ".,", 'x'); for (int i = 0; i < WHITESPACE.length(); i++) { for (int j = 0; j < NON_WHITESPACE.length(); j++) { innerTestSplitPreserveAllTokens(WHITESPACE.charAt(i), null, NON_WHITESPACE.charAt(j)); innerTestSplitPreserveAllTokens(WHITESPACE.charAt(i), String.valueOf(WHITESPACE.charAt(i)), NON_WHITESPACE.charAt(j)); } } { String[] results = null; String[] expectedResults = {"ab", "de fg"}; results = StringUtils.splitPreserveAllTokens("ab de fg", null, 2); assertEquals(expectedResults.length, results.length); for (int i = 0; i < expectedResults.length; i++) { assertEquals(expectedResults[i], results[i]); } } { String[] results = null; String[] expectedResults = {"ab", " de fg"}; results = StringUtils.splitPreserveAllTokens("ab de fg", null, 2); assertEquals(expectedResults.length, results.length); for (int i = 0; i < expectedResults.length; i++) { assertEquals(expectedResults[i], results[i]); } } { String[] results = null; String[] expectedResults = {"ab", "::de:fg"}; results = StringUtils.splitPreserveAllTokens("ab:::de:fg", ":", 2); assertEquals(expectedResults.length, results.length); for (int i = 0; i < expectedResults.length; i++) { assertEquals(expectedResults[i], results[i]); } } { String[] results = null; String[] expectedResults = {"ab", "", " de fg"}; results = StringUtils.splitPreserveAllTokens("ab de fg", null, 3); assertEquals(expectedResults.length, results.length); for (int i = 0; i < expectedResults.length; i++) { assertEquals(expectedResults[i], results[i]); } } { String[] results = null; String[] expectedResults = {"ab", "", "", "de fg"}; results = StringUtils.splitPreserveAllTokens("ab de fg", null, 4); assertEquals(expectedResults.length, results.length); for (int i = 0; i < expectedResults.length; i++) { assertEquals(expectedResults[i], results[i]); } } { String[] expectedResults = {"ab", "cd:ef"}; String[] results = null; results = StringUtils.splitPreserveAllTokens("ab:cd:ef",":", 2); assertEquals(expectedResults.length, results.length); for (int i = 0; i < expectedResults.length; i++) { assertEquals(expectedResults[i], results[i]); } } { String[] results = null; String[] expectedResults = {"ab", ":cd:ef"}; results = StringUtils.splitPreserveAllTokens("ab::cd:ef",":", 2); assertEquals(expectedResults.length, results.length); for (int i = 0; i < expectedResults.length; i++) { assertEquals(expectedResults[i], results[i]); } } { String[] results = null; String[] expectedResults = {"ab", "", ":cd:ef"}; results = StringUtils.splitPreserveAllTokens("ab:::cd:ef",":", 3); assertEquals(expectedResults.length, results.length); for (int i = 0; i < expectedResults.length; i++) { assertEquals(expectedResults[i], results[i]); } } { String[] results = null; String[] expectedResults = {"ab", "", "", "cd:ef"}; results = StringUtils.splitPreserveAllTokens("ab:::cd:ef",":", 4); assertEquals(expectedResults.length, results.length); for (int i = 0; i < expectedResults.length; i++) { assertEquals(expectedResults[i], results[i]); } } { String[] results = null; String[] expectedResults = {"", "ab", "", "", "cd:ef"}; results = StringUtils.splitPreserveAllTokens(":ab:::cd:ef",":", 5); assertEquals(expectedResults.length, results.length); for (int i = 0; i < expectedResults.length; i++) { assertEquals(expectedResults[i], results[i]); } } { String[] results = null; String[] expectedResults = {"", "", "ab", "", "", "cd:ef"}; results = StringUtils.splitPreserveAllTokens("::ab:::cd:ef",":", 6); assertEquals(expectedResults.length, results.length); for (int i = 0; i < expectedResults.length; i++) { assertEquals(expectedResults[i], results[i]); } } } private void innerTestSplitPreserveAllTokens(char separator, String sepStr, char noMatch) { String msg = "Failed on separator hex(" + Integer.toHexString(separator) + "), noMatch hex(" + Integer.toHexString(noMatch) + "), sepStr(" + sepStr + ")"; final String str = "a" + separator + "b" + separator + separator + noMatch + "c"; String[] res; // (str, sepStr) res = StringUtils.splitPreserveAllTokens(str, sepStr); assertEquals(msg, 4, res.length); assertEquals(msg, "a", res[0]); assertEquals(msg, "b", res[1]); assertEquals(msg, "", res[2]); assertEquals(msg, noMatch + "c", res[3]); final String str2 = separator + "a" + separator; res = StringUtils.splitPreserveAllTokens(str2, sepStr); assertEquals(msg, 3, res.length); assertEquals(msg, "", res[0]); assertEquals(msg, "a", res[1]); assertEquals(msg, "", res[2]); res = StringUtils.splitPreserveAllTokens(str, sepStr, -1); assertEquals(msg, 4, res.length); assertEquals(msg, "a", res[0]); assertEquals(msg, "b", res[1]); assertEquals(msg, "", res[2]); assertEquals(msg, noMatch + "c", res[3]); res = StringUtils.splitPreserveAllTokens(str, sepStr, 0); assertEquals(msg, 4, res.length); assertEquals(msg, "a", res[0]); assertEquals(msg, "b", res[1]); assertEquals(msg, "", res[2]); assertEquals(msg, noMatch + "c", res[3]); res = StringUtils.splitPreserveAllTokens(str, sepStr, 1); assertEquals(msg, 1, res.length); assertEquals(msg, str, res[0]); res = StringUtils.splitPreserveAllTokens(str, sepStr, 2); assertEquals(msg, 2, res.length); assertEquals(msg, "a", res[0]); assertEquals(msg, str.substring(2), res[1]); } public void testSplitByCharacterType() { assertNull(StringUtils.splitByCharacterType(null)); assertEquals(0, StringUtils.splitByCharacterType("").length); assertTrue(ArrayUtils.isEquals(new String[] { "ab", " ", "de", " ", "fg" }, StringUtils.splitByCharacterType("ab de fg"))); assertTrue(ArrayUtils.isEquals(new String[] { "ab", " ", "de", " ", "fg" }, StringUtils.splitByCharacterType("ab de fg"))); assertTrue(ArrayUtils.isEquals(new String[] { "ab", ":", "cd", ":", "ef" }, StringUtils.splitByCharacterType("ab:cd:ef"))); assertTrue(ArrayUtils.isEquals(new String[] { "number", "5" }, StringUtils.splitByCharacterType("number5"))); assertTrue(ArrayUtils.isEquals(new String[] { "foo", "B", "ar" }, StringUtils.splitByCharacterType("fooBar"))); assertTrue(ArrayUtils.isEquals(new String[] { "foo", "200", "B", "ar" }, StringUtils.splitByCharacterType("foo200Bar"))); assertTrue(ArrayUtils.isEquals(new String[] { "ASFR", "ules" }, StringUtils.splitByCharacterType("ASFRules"))); } public void testSplitByCharacterTypeCamelCase() { assertNull(StringUtils.splitByCharacterTypeCamelCase(null)); assertEquals(0, StringUtils.splitByCharacterTypeCamelCase("").length); assertTrue(ArrayUtils.isEquals(new String[] { "ab", " ", "de", " ", "fg" }, StringUtils.splitByCharacterTypeCamelCase("ab de fg"))); assertTrue(ArrayUtils.isEquals(new String[] { "ab", " ", "de", " ", "fg" }, StringUtils.splitByCharacterTypeCamelCase("ab de fg"))); assertTrue(ArrayUtils.isEquals(new String[] { "ab", ":", "cd", ":", "ef" }, StringUtils.splitByCharacterTypeCamelCase("ab:cd:ef"))); assertTrue(ArrayUtils.isEquals(new String[] { "number", "5" }, StringUtils.splitByCharacterTypeCamelCase("number5"))); assertTrue(ArrayUtils.isEquals(new String[] { "foo", "Bar" }, StringUtils.splitByCharacterTypeCamelCase("fooBar"))); assertTrue(ArrayUtils.isEquals(new String[] { "foo", "200", "Bar" }, StringUtils.splitByCharacterTypeCamelCase("foo200Bar"))); assertTrue(ArrayUtils.isEquals(new String[] { "ASF", "Rules" }, StringUtils.splitByCharacterTypeCamelCase("ASFRules"))); } public void testDeprecatedDeleteSpace_String() { assertEquals(null, StringUtils.deleteSpaces(null)); assertEquals("", StringUtils.deleteSpaces("")); assertEquals("", StringUtils.deleteSpaces(" \t\t\n\n ")); assertEquals("test", StringUtils.deleteSpaces("t \t\ne\rs\n\n \tt")); } public void testDeleteWhitespace_String() { assertEquals(null, StringUtils.deleteWhitespace(null)); assertEquals("", StringUtils.deleteWhitespace("")); assertEquals("", StringUtils.deleteWhitespace(" \u000C \t\t\u001F\n\n \u000B ")); assertEquals("", StringUtils.deleteWhitespace(StringUtilsTest.WHITESPACE)); assertEquals(StringUtilsTest.NON_WHITESPACE, StringUtils.deleteWhitespace(StringUtilsTest.NON_WHITESPACE)); // Note: u-2007 and u-000A both cause problems in the source code // it should ignore 2007 but delete 000A assertEquals("\u00A0\u202F", StringUtils.deleteWhitespace(" \u00A0 \t\t\n\n \u202F ")); assertEquals("\u00A0\u202F", StringUtils.deleteWhitespace("\u00A0\u202F")); assertEquals("test", StringUtils.deleteWhitespace("\u000Bt \t\n\u0009e\rs\n\n \tt")); } public void testLang623() { assertEquals("t", StringUtils.replaceChars("\u00DE", '\u00DE', 't')); assertEquals("t", StringUtils.replaceChars("\u00FE", '\u00FE', 't')); } public void testReplace_StringStringString() { assertEquals(null, StringUtils.replace(null, null, null)); assertEquals(null, StringUtils.replace(null, null, "any")); assertEquals(null, StringUtils.replace(null, "any", null)); assertEquals(null, StringUtils.replace(null, "any", "any")); assertEquals("", StringUtils.replace("", null, null)); assertEquals("", StringUtils.replace("", null, "any")); assertEquals("", StringUtils.replace("", "any", null)); assertEquals("", StringUtils.replace("", "any", "any")); assertEquals("FOO", StringUtils.replace("FOO", "", "any")); assertEquals("FOO", StringUtils.replace("FOO", null, "any")); assertEquals("FOO", StringUtils.replace("FOO", "F", null)); assertEquals("FOO", StringUtils.replace("FOO", null, null)); assertEquals("", StringUtils.replace("foofoofoo", "foo", "")); assertEquals("barbarbar", StringUtils.replace("foofoofoo", "foo", "bar")); assertEquals("farfarfar", StringUtils.replace("foofoofoo", "oo", "ar")); } public void testReplace_StringStringStringInt() { assertEquals(null, StringUtils.replace(null, null, null, 2)); assertEquals(null, StringUtils.replace(null, null, "any", 2)); assertEquals(null, StringUtils.replace(null, "any", null, 2)); assertEquals(null, StringUtils.replace(null, "any", "any", 2)); assertEquals("", StringUtils.replace("", null, null, 2)); assertEquals("", StringUtils.replace("", null, "any", 2)); assertEquals("", StringUtils.replace("", "any", null, 2)); assertEquals("", StringUtils.replace("", "any", "any", 2)); String str = new String(new char[] {'o', 'o', 'f', 'o', 'o'}); assertSame(str, StringUtils.replace(str, "x", "", -1)); assertEquals("f", StringUtils.replace("oofoo", "o", "", -1)); assertEquals("oofoo", StringUtils.replace("oofoo", "o", "", 0)); assertEquals("ofoo", StringUtils.replace("oofoo", "o", "", 1)); assertEquals("foo", StringUtils.replace("oofoo", "o", "", 2)); assertEquals("fo", StringUtils.replace("oofoo", "o", "", 3)); assertEquals("f", StringUtils.replace("oofoo", "o", "", 4)); assertEquals("f", StringUtils.replace("oofoo", "o", "", -5)); assertEquals("f", StringUtils.replace("oofoo", "o", "", 1000)); } public void testReplaceOnce_StringStringString() { assertEquals(null, StringUtils.replaceOnce(null, null, null)); assertEquals(null, StringUtils.replaceOnce(null, null, "any")); assertEquals(null, StringUtils.replaceOnce(null, "any", null)); assertEquals(null, StringUtils.replaceOnce(null, "any", "any")); assertEquals("", StringUtils.replaceOnce("", null, null)); assertEquals("", StringUtils.replaceOnce("", null, "any")); assertEquals("", StringUtils.replaceOnce("", "any", null)); assertEquals("", StringUtils.replaceOnce("", "any", "any")); assertEquals("FOO", StringUtils.replaceOnce("FOO", "", "any")); assertEquals("FOO", StringUtils.replaceOnce("FOO", null, "any")); assertEquals("FOO", StringUtils.replaceOnce("FOO", "F", null)); assertEquals("FOO", StringUtils.replaceOnce("FOO", null, null)); assertEquals("foofoo", StringUtils.replaceOnce("foofoofoo", "foo", "")); } /** * Test method for 'StringUtils.replaceEach(String, String[], String[])' */ public void testReplace_StringStringArrayStringArray() { //JAVADOC TESTS START assertNull(StringUtils.replaceEach(null, new String[]{"a"}, new String[]{"b"})); assertEquals(StringUtils.replaceEach("", new String[]{"a"}, new String[]{"b"}),""); assertEquals(StringUtils.replaceEach("aba", null, null),"aba"); assertEquals(StringUtils.replaceEach("aba", new String[0], null),"aba"); assertEquals(StringUtils.replaceEach("aba", null, new String[0]),"aba"); assertEquals(StringUtils.replaceEach("aba", new String[]{"a"}, null),"aba"); assertEquals(StringUtils.replaceEach("aba", new String[]{"a"}, new String[]{""}),"b"); assertEquals(StringUtils.replaceEach("aba", new String[]{null}, new String[]{"a"}),"aba"); assertEquals(StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"w", "t"}),"wcte"); assertEquals(StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"}),"dcte"); //JAVADOC TESTS END assertEquals("bcc", StringUtils.replaceEach("abc", new String[]{"a", "b"}, new String[]{"b", "c"})); assertEquals("q651.506bera", StringUtils.replaceEach("d216.102oren", new String[]{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "1", "2", "3", "4", "5", "6", "7", "8", "9"}, new String[]{"n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "5", "6", "7", "8", "9", "1", "2", "3", "4"})); // Test null safety inside arrays - LANG-552 assertEquals(StringUtils.replaceEach("aba", new String[]{"a"}, new String[]{null}),"aba"); assertEquals(StringUtils.replaceEach("aba", new String[]{"a", "b"}, new String[]{"c", null}),"cbc"); } /** * Test method for 'StringUtils.replaceEachRepeatedly(String, String[], String[])' */ public void testReplace_StringStringArrayStringArrayBoolean() { //JAVADOC TESTS START assertNull(StringUtils.replaceEachRepeatedly(null, new String[]{"a"}, new String[]{"b"})); assertEquals(StringUtils.replaceEachRepeatedly("", new String[]{"a"}, new String[]{"b"}),""); assertEquals(StringUtils.replaceEachRepeatedly("aba", null, null),"aba"); assertEquals(StringUtils.replaceEachRepeatedly("aba", new String[0], null),"aba"); assertEquals(StringUtils.replaceEachRepeatedly("aba", null, new String[0]),"aba"); assertEquals(StringUtils.replaceEachRepeatedly("aba", new String[0], null),"aba"); assertEquals(StringUtils.replaceEachRepeatedly("aba", new String[]{"a"}, new String[]{""}),"b"); assertEquals(StringUtils.replaceEachRepeatedly("aba", new String[]{null}, new String[]{"a"}),"aba"); assertEquals(StringUtils.replaceEachRepeatedly("abcde", new String[]{"ab", "d"}, new String[]{"w", "t"}),"wcte"); assertEquals(StringUtils.replaceEachRepeatedly("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"}),"tcte"); try { StringUtils.replaceEachRepeatedly("abcde", new String[]{"ab", "d"}, new String[]{"d", "ab"}); fail("Should be a circular reference"); } catch (IllegalStateException e) {} //JAVADOC TESTS END } public void testReplaceChars_StringCharChar() { assertEquals(null, StringUtils.replaceChars(null, 'b', 'z')); assertEquals("", StringUtils.replaceChars("", 'b', 'z')); assertEquals("azcza", StringUtils.replaceChars("abcba", 'b', 'z')); assertEquals("abcba", StringUtils.replaceChars("abcba", 'x', 'z')); } public void testReplaceChars_StringStringString() { assertEquals(null, StringUtils.replaceChars(null, null, null)); assertEquals(null, StringUtils.replaceChars(null, "", null)); assertEquals(null, StringUtils.replaceChars(null, "a", null)); assertEquals(null, StringUtils.replaceChars(null, null, "")); assertEquals(null, StringUtils.replaceChars(null, null, "x")); assertEquals("", StringUtils.replaceChars("", null, null)); assertEquals("", StringUtils.replaceChars("", "", null)); assertEquals("", StringUtils.replaceChars("", "a", null)); assertEquals("", StringUtils.replaceChars("", null, "")); assertEquals("", StringUtils.replaceChars("", null, "x")); assertEquals("abc", StringUtils.replaceChars("abc", null, null)); assertEquals("abc", StringUtils.replaceChars("abc", null, "")); assertEquals("abc", StringUtils.replaceChars("abc", null, "x")); assertEquals("abc", StringUtils.replaceChars("abc", "", null)); assertEquals("abc", StringUtils.replaceChars("abc", "", "")); assertEquals("abc", StringUtils.replaceChars("abc", "", "x")); assertEquals("ac", StringUtils.replaceChars("abc", "b", null)); assertEquals("ac", StringUtils.replaceChars("abc", "b", "")); assertEquals("axc", StringUtils.replaceChars("abc", "b", "x")); assertEquals("ayzya", StringUtils.replaceChars("abcba", "bc", "yz")); assertEquals("ayya", StringUtils.replaceChars("abcba", "bc", "y")); assertEquals("ayzya", StringUtils.replaceChars("abcba", "bc", "yzx")); assertEquals("abcba", StringUtils.replaceChars("abcba", "z", "w")); assertSame("abcba", StringUtils.replaceChars("abcba", "z", "w")); // Javadoc examples: assertEquals("jelly", StringUtils.replaceChars("hello", "ho", "jy")); assertEquals("ayzya", StringUtils.replaceChars("abcba", "bc", "yz")); assertEquals("ayya", StringUtils.replaceChars("abcba", "bc", "y")); assertEquals("ayzya", StringUtils.replaceChars("abcba", "bc", "yzx")); // From http://issues.apache.org/bugzilla/show_bug.cgi?id=25454 assertEquals("bcc", StringUtils.replaceChars("abc", "ab", "bc")); assertEquals("q651.506bera", StringUtils.replaceChars("d216.102oren", "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789", "nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM567891234")); } public void testDeprecatedOverlayString_StringStringIntInt() { assertEquals("overlayString(String, String, int, int) failed", "foo foor baz", StringUtils.overlayString(SENTENCE_UNCAP, FOO_UNCAP, 4, 6) ); assertEquals("abef", StringUtils.overlayString("abcdef", "", 2, 4)); assertEquals("abzzzzef", StringUtils.overlayString("abcdef", "zzzz", 2, 4)); assertEquals("abcdzzzzcdef", StringUtils.overlayString("abcdef", "zzzz", 4, 2)); try { StringUtils.overlayString(null, "zzzz", 2, 4); fail(); } catch (NullPointerException ex) {} try { StringUtils.overlayString("abcdef", null, 2, 4); fail(); } catch (NullPointerException ex) {} try { StringUtils.overlayString("abcdef", "zzzz", -1, 4); fail(); } catch (IndexOutOfBoundsException ex) {} try { StringUtils.overlayString("abcdef", "zzzz", 2, 8); fail(); } catch (IndexOutOfBoundsException ex) {} } public void testOverlay_StringStringIntInt() { assertEquals(null, StringUtils.overlay(null, null, 2, 4)); assertEquals(null, StringUtils.overlay(null, null, -2, -4)); assertEquals("", StringUtils.overlay("", null, 0, 0)); assertEquals("", StringUtils.overlay("", "", 0, 0)); assertEquals("zzzz", StringUtils.overlay("", "zzzz", 0, 0)); assertEquals("zzzz", StringUtils.overlay("", "zzzz", 2, 4)); assertEquals("zzzz", StringUtils.overlay("", "zzzz", -2, -4)); assertEquals("abef", StringUtils.overlay("abcdef", null, 2, 4)); assertEquals("abef", StringUtils.overlay("abcdef", null, 4, 2)); assertEquals("abef", StringUtils.overlay("abcdef", "", 2, 4)); assertEquals("abef", StringUtils.overlay("abcdef", "", 4, 2)); assertEquals("abzzzzef", StringUtils.overlay("abcdef", "zzzz", 2, 4)); assertEquals("abzzzzef", StringUtils.overlay("abcdef", "zzzz", 4, 2)); assertEquals("zzzzef", StringUtils.overlay("abcdef", "zzzz", -1, 4)); assertEquals("zzzzef", StringUtils.overlay("abcdef", "zzzz", 4, -1)); assertEquals("zzzzabcdef", StringUtils.overlay("abcdef", "zzzz", -2, -1)); assertEquals("zzzzabcdef", StringUtils.overlay("abcdef", "zzzz", -1, -2)); assertEquals("abcdzzzz", StringUtils.overlay("abcdef", "zzzz", 4, 10)); assertEquals("abcdzzzz", StringUtils.overlay("abcdef", "zzzz", 10, 4)); assertEquals("abcdefzzzz", StringUtils.overlay("abcdef", "zzzz", 8, 10)); assertEquals("abcdefzzzz", StringUtils.overlay("abcdef", "zzzz", 10, 8)); } public void testRepeat_StringInt() { assertEquals(null, StringUtils.repeat(null, 2)); assertEquals("", StringUtils.repeat("ab", 0)); assertEquals("", StringUtils.repeat("", 3)); assertEquals("aaa", StringUtils.repeat("a", 3)); assertEquals("ababab", StringUtils.repeat("ab", 3)); assertEquals("abcabcabc", StringUtils.repeat("abc", 3)); String str = StringUtils.repeat("a", 10000); // bigger than pad limit assertEquals(10000, str.length()); assertEquals(true, StringUtils.containsOnly(str, new char[] {'a'})); } public void testDeprecatedChompFunctions() { assertEquals("chompLast(String) failed", FOO_UNCAP, StringUtils.chompLast(FOO_UNCAP + "\n") ); assertEquals("chompLast(\"\") failed", "", StringUtils.chompLast("") ); assertEquals("chompLast(\"test\", \"test\") failed", "test", StringUtils.chompLast("test", "tst") ); assertEquals("getChomp(String, String) failed", "\n" + FOO_UNCAP, StringUtils.getChomp(FOO_UNCAP + "\n" + FOO_UNCAP, "\n") ); assertEquals("getChomp(String, String) failed", FOO_CAP, StringUtils.getChomp(FOO_CAP+FOO_CAP, FOO_CAP)); assertEquals("getChomp(String, String) failed", "", StringUtils.getChomp(FOO_UNCAP, FOO_CAP)); assertEquals("prechomp(String, String) failed", FOO_UNCAP, StringUtils.prechomp(FOO_UNCAP + "\n" + FOO_UNCAP, "\n") ); assertEquals("prechomp(String, String) failed", FOO_UNCAP, StringUtils.prechomp(FOO_UNCAP, FOO_CAP)); assertEquals("getPrechomp(String, String) failed", FOO_UNCAP + "\n", StringUtils.getPrechomp(FOO_UNCAP + "\n" + FOO_UNCAP, "\n") ); assertEquals("getPrechomp(String, String) failed", "", StringUtils.getPrechomp(FOO_CAP, FOO_UNCAP)); assertEquals("chopNewline(String, String) failed", FOO_UNCAP, StringUtils.chopNewline(FOO_UNCAP + "\r\n") ); } public void testRepeat_StringStringInt() { assertEquals(null, StringUtils.repeat(null, null, 2)); assertEquals(null, StringUtils.repeat(null, "x", 2)); assertEquals("", StringUtils.repeat("", null, 2)); assertEquals("", StringUtils.repeat("ab", "", 0)); assertEquals("", StringUtils.repeat("", "", 2)); assertEquals("xx", StringUtils.repeat("", "x", 3)); assertEquals("?, ?, ?", StringUtils.repeat("?", ", ", 3)); } public void testChop() { String[][] chopCases = { { FOO_UNCAP + "\r\n", FOO_UNCAP } , { FOO_UNCAP + "\n" , FOO_UNCAP } , { FOO_UNCAP + "\r", FOO_UNCAP }, { FOO_UNCAP + " \r", FOO_UNCAP + " " }, { "foo", "fo"}, { "foo\nfoo", "foo\nfo" }, { "\n", "" }, { "\r", "" }, { "\r\n", "" }, { null, null }, { "", "" }, { "a", "" }, }; for (int i = 0; i < chopCases.length; i++) { String original = chopCases[i][0]; String expectedResult = chopCases[i][1]; assertEquals("chop(String) failed", expectedResult, StringUtils.chop(original)); } } public void testChomp() { String[][] chompCases = { { FOO_UNCAP + "\r\n", FOO_UNCAP }, { FOO_UNCAP + "\n" , FOO_UNCAP }, { FOO_UNCAP + "\r", FOO_UNCAP }, { FOO_UNCAP + " \r", FOO_UNCAP + " " }, { FOO_UNCAP, FOO_UNCAP }, { FOO_UNCAP + "\n\n", FOO_UNCAP + "\n"}, { FOO_UNCAP + "\r\n\r\n", FOO_UNCAP + "\r\n" }, { "foo\nfoo", "foo\nfoo" }, { "foo\n\rfoo", "foo\n\rfoo" }, { "\n", "" }, { "\r", "" }, { "a", "a" }, { "\r\n", "" }, { "", "" }, { null, null }, { FOO_UNCAP + "\n\r", FOO_UNCAP + "\n"} }; for (int i = 0; i < chompCases.length; i++) { String original = chompCases[i][0]; String expectedResult = chompCases[i][1]; assertEquals("chomp(String) failed", expectedResult, StringUtils.chomp(original)); } assertEquals("chomp(String, String) failed", "foo", StringUtils.chomp("foobar", "bar")); assertEquals("chomp(String, String) failed", "foobar", StringUtils.chomp("foobar", "baz")); assertEquals("chomp(String, String) failed", "foo", StringUtils.chomp("foo", "foooo")); assertEquals("chomp(String, String) failed", "foobar", StringUtils.chomp("foobar", "")); assertEquals("chomp(String, String) failed", "foobar", StringUtils.chomp("foobar", null)); assertEquals("chomp(String, String) failed", "", StringUtils.chomp("", "foo")); assertEquals("chomp(String, String) failed", "", StringUtils.chomp("", null)); assertEquals("chomp(String, String) failed", "", StringUtils.chomp("", "")); assertEquals("chomp(String, String) failed", null, StringUtils.chomp(null, "foo")); assertEquals("chomp(String, String) failed", null, StringUtils.chomp(null, null)); assertEquals("chomp(String, String) failed", null, StringUtils.chomp(null, "")); assertEquals("chomp(String, String) failed", "", StringUtils.chomp("foo", "foo")); assertEquals("chomp(String, String) failed", " ", StringUtils.chomp(" foo", "foo")); assertEquals("chomp(String, String) failed", "foo ", StringUtils.chomp("foo ", "foo")); } public void testChopNewLine() { String[][] newLineCases = { { FOO_UNCAP + "\r\n", FOO_UNCAP } , { FOO_UNCAP + "\n" , FOO_UNCAP } , { FOO_UNCAP + "\r", FOO_UNCAP + "\r" }, { FOO_UNCAP, FOO_UNCAP }, { FOO_UNCAP + "\n" + FOO_UNCAP , FOO_UNCAP + "\n" + FOO_UNCAP }, { FOO_UNCAP + "\n\n", FOO_UNCAP + "\n"}, { "\n", "" }, { "", "" }, { "\r\n", "" } }; for (int i = 0; i < newLineCases.length; i++) { String original = newLineCases[i][0]; String expectedResult = newLineCases[i][1]; assertEquals("chopNewline(String) failed", expectedResult, StringUtils.chopNewline(original)); } } //----------------------------------------------------------------------- public void testRightPad_StringInt() { assertEquals(null, StringUtils.rightPad(null, 5)); assertEquals(" ", StringUtils.rightPad("", 5)); assertEquals("abc ", StringUtils.rightPad("abc", 5)); assertEquals("abc", StringUtils.rightPad("abc", 2)); assertEquals("abc", StringUtils.rightPad("abc", -1)); } public void testRightPad_StringIntChar() { assertEquals(null, StringUtils.rightPad(null, 5, ' ')); assertEquals(" ", StringUtils.rightPad("", 5, ' ')); assertEquals("abc ", StringUtils.rightPad("abc", 5, ' ')); assertEquals("abc", StringUtils.rightPad("abc", 2, ' ')); assertEquals("abc", StringUtils.rightPad("abc", -1, ' ')); assertEquals("abcxx", StringUtils.rightPad("abc", 5, 'x')); String str = StringUtils.rightPad("aaa", 10000, 'a'); // bigger than pad length assertEquals(10000, str.length()); assertEquals(true, StringUtils.containsOnly(str, new char[] {'a'})); } public void testRightPad_StringIntString() { assertEquals(null, StringUtils.rightPad(null, 5, "-+")); assertEquals(" ", StringUtils.rightPad("", 5, " ")); assertEquals(null, StringUtils.rightPad(null, 8, null)); assertEquals("abc-+-+", StringUtils.rightPad("abc", 7, "-+")); assertEquals("abc-+~", StringUtils.rightPad("abc", 6, "-+~")); assertEquals("abc-+", StringUtils.rightPad("abc", 5, "-+~")); assertEquals("abc", StringUtils.rightPad("abc", 2, " ")); assertEquals("abc", StringUtils.rightPad("abc", -1, " ")); assertEquals("abc ", StringUtils.rightPad("abc", 5, null)); assertEquals("abc ", StringUtils.rightPad("abc", 5, "")); } //----------------------------------------------------------------------- public void testLeftPad_StringInt() { assertEquals(null, StringUtils.leftPad(null, 5)); assertEquals(" ", StringUtils.leftPad("", 5)); assertEquals(" abc", StringUtils.leftPad("abc", 5)); assertEquals("abc", StringUtils.leftPad("abc", 2)); } public void testLeftPad_StringIntChar() { assertEquals(null, StringUtils.leftPad(null, 5, ' ')); assertEquals(" ", StringUtils.leftPad("", 5, ' ')); assertEquals(" abc", StringUtils.leftPad("abc", 5, ' ')); assertEquals("xxabc", StringUtils.leftPad("abc", 5, 'x')); assertEquals("\uffff\uffffabc", StringUtils.leftPad("abc", 5, '\uffff')); assertEquals("abc", StringUtils.leftPad("abc", 2, ' ')); String str = StringUtils.leftPad("aaa", 10000, 'a'); // bigger than pad length assertEquals(10000, str.length()); assertEquals(true, StringUtils.containsOnly(str, new char[] {'a'})); } public void testLeftPad_StringIntString() { assertEquals(null, StringUtils.leftPad(null, 5, "-+")); assertEquals(null, StringUtils.leftPad(null, 5, null)); assertEquals(" ", StringUtils.leftPad("", 5, " ")); assertEquals("-+-+abc", StringUtils.leftPad("abc", 7, "-+")); assertEquals("-+~abc", StringUtils.leftPad("abc", 6, "-+~")); assertEquals("-+abc", StringUtils.leftPad("abc", 5, "-+~")); assertEquals("abc", StringUtils.leftPad("abc", 2, " ")); assertEquals("abc", StringUtils.leftPad("abc", -1, " ")); assertEquals(" abc", StringUtils.leftPad("abc", 5, null)); assertEquals(" abc", StringUtils.leftPad("abc", 5, "")); } public void testLength() { assertEquals(0, StringUtils.length(null)); assertEquals(0, StringUtils.length("")); assertEquals(0, StringUtils.length(StringUtils.EMPTY)); assertEquals(1, StringUtils.length("A")); assertEquals(1, StringUtils.length(" ")); assertEquals(8, StringUtils.length("ABCDEFGH")); } //----------------------------------------------------------------------- public void testCenter_StringInt() { assertEquals(null, StringUtils.center(null, -1)); assertEquals(null, StringUtils.center(null, 4)); assertEquals(" ", StringUtils.center("", 4)); assertEquals("ab", StringUtils.center("ab", 0)); assertEquals("ab", StringUtils.center("ab", -1)); assertEquals("ab", StringUtils.center("ab", 1)); assertEquals(" ", StringUtils.center("", 4)); assertEquals(" ab ", StringUtils.center("ab", 4)); assertEquals("abcd", StringUtils.center("abcd", 2)); assertEquals(" a ", StringUtils.center("a", 4)); assertEquals(" a ", StringUtils.center("a", 5)); } public void testCenter_StringIntChar() { assertEquals(null, StringUtils.center(null, -1, ' ')); assertEquals(null, StringUtils.center(null, 4, ' ')); assertEquals(" ", StringUtils.center("", 4, ' ')); assertEquals("ab", StringUtils.center("ab", 0, ' ')); assertEquals("ab", StringUtils.center("ab", -1, ' ')); assertEquals("ab", StringUtils.center("ab", 1, ' ')); assertEquals(" ", StringUtils.center("", 4, ' ')); assertEquals(" ab ", StringUtils.center("ab", 4, ' ')); assertEquals("abcd", StringUtils.center("abcd", 2, ' ')); assertEquals(" a ", StringUtils.center("a", 4, ' ')); assertEquals(" a ", StringUtils.center("a", 5, ' ')); assertEquals("xxaxx", StringUtils.center("a", 5, 'x')); } public void testCenter_StringIntString() { assertEquals(null, StringUtils.center(null, 4, null)); assertEquals(null, StringUtils.center(null, -1, " ")); assertEquals(null, StringUtils.center(null, 4, " ")); assertEquals(" ", StringUtils.center("", 4, " ")); assertEquals("ab", StringUtils.center("ab", 0, " ")); assertEquals("ab", StringUtils.center("ab", -1, " ")); assertEquals("ab", StringUtils.center("ab", 1, " ")); assertEquals(" ", StringUtils.center("", 4, " ")); assertEquals(" ab ", StringUtils.center("ab", 4, " ")); assertEquals("abcd", StringUtils.center("abcd", 2, " ")); assertEquals(" a ", StringUtils.center("a", 4, " ")); assertEquals("yayz", StringUtils.center("a", 4, "yz")); assertEquals("yzyayzy", StringUtils.center("a", 7, "yz")); assertEquals(" abc ", StringUtils.center("abc", 7, null)); assertEquals(" abc ", StringUtils.center("abc", 7, "")); } //----------------------------------------------------------------------- public void testReverse_String() { assertEquals(null, StringUtils.reverse(null) ); assertEquals("", StringUtils.reverse("") ); assertEquals("sdrawkcab", StringUtils.reverse("backwards") ); } public void testReverseDelimited_StringChar() { assertEquals(null, StringUtils.reverseDelimited(null, '.') ); assertEquals("", StringUtils.reverseDelimited("", '.') ); assertEquals("c.b.a", StringUtils.reverseDelimited("a.b.c", '.') ); assertEquals("a b c", StringUtils.reverseDelimited("a b c", '.') ); assertEquals("", StringUtils.reverseDelimited("", '.') ); } public void testDeprecatedReverseDelimitedString_StringString() { assertEquals(null, StringUtils.reverseDelimitedString(null, null) ); assertEquals("", StringUtils.reverseDelimitedString("", null) ); assertEquals("", StringUtils.reverseDelimitedString("", ".") ); assertEquals("a.b.c", StringUtils.reverseDelimitedString("a.b.c", null) ); assertEquals("c b a", StringUtils.reverseDelimitedString("a b c", null) ); assertEquals("c.b.a", StringUtils.reverseDelimitedString("a.b.c", ".") ); } //----------------------------------------------------------------------- public void testDefault_String() { assertEquals("", StringUtils.defaultString(null)); assertEquals("", StringUtils.defaultString("")); assertEquals("abc", StringUtils.defaultString("abc")); } public void testDefault_StringString() { assertEquals("NULL", StringUtils.defaultString(null, "NULL")); assertEquals("", StringUtils.defaultString("", "NULL")); assertEquals("abc", StringUtils.defaultString("abc", "NULL")); } public void testDefaultIfEmpty_StringString() { assertEquals("NULL", StringUtils.defaultIfEmpty(null, "NULL")); assertEquals("NULL", StringUtils.defaultIfEmpty("", "NULL")); assertEquals("abc", StringUtils.defaultIfEmpty("abc", "NULL")); assertNull(StringUtils.defaultIfEmpty("", null)); } public void testDefaultIfBlank_StringString() { assertEquals("NULL", StringUtils.defaultIfBlank(null, "NULL")); assertEquals("NULL", StringUtils.defaultIfBlank("", "NULL")); assertEquals("NULL", StringUtils.defaultIfBlank(" ", "NULL")); assertEquals("abc", StringUtils.defaultIfBlank("abc", "NULL")); assertNull(StringUtils.defaultIfBlank("", null)); String s = StringUtils.defaultIfBlank("abc", "NULL"); assertEquals("abc", s); } //----------------------------------------------------------------------- public void testDeprecatedEscapeFunctions_String() { assertEquals("", StringUtils.escape("") ); assertEquals("abc", StringUtils.escape("abc") ); assertEquals("\\t", StringUtils.escape("\t") ); assertEquals("\\\\", StringUtils.escape("\\") ); assertEquals("\\\\\\b\\t\\r", StringUtils.escape("\\\b\t\r") ); assertEquals("\\u1234", StringUtils.escape("\u1234") ); assertEquals("\\u0234", StringUtils.escape("\u0234") ); assertEquals("\\u00FD", StringUtils.escape("\u00fd") ); } //----------------------------------------------------------------------- public void testAbbreviate_StringInt() { assertEquals(null, StringUtils.abbreviate(null, 10)); assertEquals("", StringUtils.abbreviate("", 10)); assertEquals("short", StringUtils.abbreviate("short", 10)); assertEquals("Now is ...", StringUtils.abbreviate("Now is the time for all good men to come to the aid of their party.", 10)); String raspberry = "raspberry peach"; assertEquals("raspberry p...", StringUtils.abbreviate(raspberry, 14)); assertEquals("raspberry peach", StringUtils.abbreviate("raspberry peach", 15)); assertEquals("raspberry peach", StringUtils.abbreviate("raspberry peach", 16)); assertEquals("abc...", StringUtils.abbreviate("abcdefg", 6)); assertEquals("abcdefg", StringUtils.abbreviate("abcdefg", 7)); assertEquals("abcdefg", StringUtils.abbreviate("abcdefg", 8)); assertEquals("a...", StringUtils.abbreviate("abcdefg", 4)); assertEquals("", StringUtils.abbreviate("", 4)); try { String res = StringUtils.abbreviate("abc", 3); fail("StringUtils.abbreviate expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // empty } } public void testAbbreviate_StringIntInt() { assertEquals(null, StringUtils.abbreviate(null, 10, 12)); assertEquals("", StringUtils.abbreviate("", 0, 10)); assertEquals("", StringUtils.abbreviate("", 2, 10)); try { String res = StringUtils.abbreviate("abcdefghij", 0, 3); fail("StringUtils.abbreviate expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // empty } try { String res = StringUtils.abbreviate("abcdefghij", 5, 6); fail("StringUtils.abbreviate expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // empty } String raspberry = "raspberry peach"; assertEquals("raspberry peach", StringUtils.abbreviate(raspberry, 11, 15)); assertEquals(null, StringUtils.abbreviate(null, 7, 14)); assertAbbreviateWithOffset("abcdefg...", -1, 10); assertAbbreviateWithOffset("abcdefg...", 0, 10); assertAbbreviateWithOffset("abcdefg...", 1, 10); assertAbbreviateWithOffset("abcdefg...", 2, 10); assertAbbreviateWithOffset("abcdefg...", 3, 10); assertAbbreviateWithOffset("abcdefg...", 4, 10); assertAbbreviateWithOffset("...fghi...", 5, 10); assertAbbreviateWithOffset("...ghij...", 6, 10); assertAbbreviateWithOffset("...hijk...", 7, 10); assertAbbreviateWithOffset("...ijklmno", 8, 10); assertAbbreviateWithOffset("...ijklmno", 9, 10); assertAbbreviateWithOffset("...ijklmno", 10, 10); assertAbbreviateWithOffset("...ijklmno", 10, 10); assertAbbreviateWithOffset("...ijklmno", 11, 10); assertAbbreviateWithOffset("...ijklmno", 12, 10); assertAbbreviateWithOffset("...ijklmno", 13, 10); assertAbbreviateWithOffset("...ijklmno", 14, 10); assertAbbreviateWithOffset("...ijklmno", 15, 10); assertAbbreviateWithOffset("...ijklmno", 16, 10); assertAbbreviateWithOffset("...ijklmno", Integer.MAX_VALUE, 10); } private void assertAbbreviateWithOffset(String expected, int offset, int maxWidth) { String abcdefghijklmno = "abcdefghijklmno"; String message = "abbreviate(String,int,int) failed"; String actual = StringUtils.abbreviate(abcdefghijklmno, offset, maxWidth); if (offset >= 0 && offset < abcdefghijklmno.length()) { assertTrue(message + " -- should contain offset character", actual.indexOf((char)('a'+offset)) != -1); } assertTrue(message + " -- should not be greater than maxWidth", actual.length() <= maxWidth); assertEquals(message, expected, actual); } public void testAbbreviateMiddle() { // javadoc examples assertNull( StringUtils.abbreviateMiddle(null, null, 0) ); assertEquals( "abc", StringUtils.abbreviateMiddle("abc", null, 0) ); assertEquals( "abc", StringUtils.abbreviateMiddle("abc", ".", 0) ); assertEquals( "abc", StringUtils.abbreviateMiddle("abc", ".", 3) ); assertEquals( "ab.f", StringUtils.abbreviateMiddle("abcdef", ".", 4) ); // JIRA issue (LANG-405) example (slightly different than actual expected result) assertEquals( "A very long text with un...f the text is complete.", StringUtils.abbreviateMiddle( "A very long text with unimportant stuff in the middle but interesting start and " + "end to see if the text is complete.", "...", 50) ); // Test a much longer text :) String longText = "Start text" + StringUtils.repeat("x", 10000) + "Close text"; assertEquals( "Start text->Close text", StringUtils.abbreviateMiddle( longText, "->", 22 ) ); // Test negative length assertEquals("abc", StringUtils.abbreviateMiddle("abc", ".", -1)); // Test boundaries // Fails to change anything as method ensures first and last char are kept assertEquals("abc", StringUtils.abbreviateMiddle("abc", ".", 1)); assertEquals("abc", StringUtils.abbreviateMiddle("abc", ".", 2)); // Test length of n=1 assertEquals("a", StringUtils.abbreviateMiddle("a", ".", 1)); // Test smallest length that can lead to success assertEquals("a.d", StringUtils.abbreviateMiddle("abcd", ".", 3)); // More from LANG-405 assertEquals("a..f", StringUtils.abbreviateMiddle("abcdef", "..", 4)); assertEquals("ab.ef", StringUtils.abbreviateMiddle("abcdef", ".", 5)); } //----------------------------------------------------------------------- public void testDifference_StringString() { assertEquals(null, StringUtils.difference(null, null)); assertEquals("", StringUtils.difference("", "")); assertEquals("abc", StringUtils.difference("", "abc")); assertEquals("", StringUtils.difference("abc", "")); assertEquals("i am a robot", StringUtils.difference(null, "i am a robot")); assertEquals("i am a machine", StringUtils.difference("i am a machine", null)); assertEquals("robot", StringUtils.difference("i am a machine", "i am a robot")); assertEquals("", StringUtils.difference("abc", "abc")); assertEquals("you are a robot", StringUtils.difference("i am a robot", "you are a robot")); } public void testDifferenceAt_StringString() { assertEquals(-1, StringUtils.indexOfDifference(null, null)); assertEquals(0, StringUtils.indexOfDifference(null, "i am a robot")); assertEquals(-1, StringUtils.indexOfDifference("", "")); assertEquals(0, StringUtils.indexOfDifference("", "abc")); assertEquals(0, StringUtils.indexOfDifference("abc", "")); assertEquals(0, StringUtils.indexOfDifference("i am a machine", null)); assertEquals(7, StringUtils.indexOfDifference("i am a machine", "i am a robot")); assertEquals(-1, StringUtils.indexOfDifference("foo", "foo")); assertEquals(0, StringUtils.indexOfDifference("i am a robot", "you are a robot")); //System.out.println("indexOfDiff: " + StringUtils.indexOfDifference("i am a robot", "not machine")); } //----------------------------------------------------------------------- public void testGetLevenshteinDistance_StringString() { assertEquals(0, StringUtils.getLevenshteinDistance("", "") ); assertEquals(1, StringUtils.getLevenshteinDistance("", "a") ); assertEquals(7, StringUtils.getLevenshteinDistance("aaapppp", "") ); assertEquals(1, StringUtils.getLevenshteinDistance("frog", "fog") ); assertEquals(3, StringUtils.getLevenshteinDistance("fly", "ant") ); assertEquals(7, StringUtils.getLevenshteinDistance("elephant", "hippo") ); assertEquals(7, StringUtils.getLevenshteinDistance("hippo", "elephant") ); assertEquals(8, StringUtils.getLevenshteinDistance("hippo", "zzzzzzzz") ); assertEquals(8, StringUtils.getLevenshteinDistance("zzzzzzzz", "hippo") ); assertEquals(1, StringUtils.getLevenshteinDistance("hello", "hallo") ); try { int d = StringUtils.getLevenshteinDistance("a", null); fail("expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // empty } try { int d = StringUtils.getLevenshteinDistance(null, "a"); fail("expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // empty } } /** * A sanity check for {@link StringUtils#EMPTY}. */ public void testEMPTY() { assertNotNull(StringUtils.EMPTY); assertEquals("", StringUtils.EMPTY); assertEquals(0, StringUtils.EMPTY.length()); } /** * Test for {@link StringUtils#isAllLowerCase(String)}. */ public void testIsAllLowerCase() { assertFalse(StringUtils.isAllLowerCase(null)); assertFalse(StringUtils.isAllLowerCase(StringUtils.EMPTY)); assertTrue(StringUtils.isAllLowerCase("abc")); assertFalse(StringUtils.isAllLowerCase("abc ")); assertFalse(StringUtils.isAllLowerCase("abC")); } /** * Test for {@link StringUtils#isAllUpperCase(String)}. */ public void testIsAllUpperCase() { assertFalse(StringUtils.isAllUpperCase(null)); assertFalse(StringUtils.isAllUpperCase(StringUtils.EMPTY)); assertTrue(StringUtils.isAllUpperCase("ABC")); assertFalse(StringUtils.isAllUpperCase("ABC ")); assertFalse(StringUtils.isAllUpperCase("aBC")); } public void testRemoveStart() { // StringUtils.removeStart("", *) = "" assertNull(StringUtils.removeStart(null, null)); assertNull(StringUtils.removeStart(null, "")); assertNull(StringUtils.removeStart(null, "a")); // StringUtils.removeStart(*, null) = * assertEquals(StringUtils.removeStart("", null), ""); assertEquals(StringUtils.removeStart("", ""), ""); assertEquals(StringUtils.removeStart("", "a"), ""); // All others: assertEquals(StringUtils.removeStart("www.domain.com", "www."), "domain.com"); assertEquals(StringUtils.removeStart("domain.com", "www."), "domain.com"); assertEquals(StringUtils.removeStart("domain.com", ""), "domain.com"); assertEquals(StringUtils.removeStart("domain.com", null), "domain.com"); } public void testRemoveStartIgnoreCase() { // StringUtils.removeStart("", *) = "" assertNull("removeStartIgnoreCase(null, null)", StringUtils.removeStartIgnoreCase(null, null)); assertNull("removeStartIgnoreCase(null, \"\")", StringUtils.removeStartIgnoreCase(null, "")); assertNull("removeStartIgnoreCase(null, \"a\")", StringUtils.removeStartIgnoreCase(null, "a")); // StringUtils.removeStart(*, null) = * assertEquals("removeStartIgnoreCase(\"\", null)", StringUtils.removeStartIgnoreCase("", null), ""); assertEquals("removeStartIgnoreCase(\"\", \"\")", StringUtils.removeStartIgnoreCase("", ""), ""); assertEquals("removeStartIgnoreCase(\"\", \"a\")", StringUtils.removeStartIgnoreCase("", "a"), ""); // All others: assertEquals("removeStartIgnoreCase(\"www.domain.com\", \"www.\")", StringUtils.removeStartIgnoreCase("www.domain.com", "www."), "domain.com"); assertEquals("removeStartIgnoreCase(\"domain.com\", \"www.\")", StringUtils.removeStartIgnoreCase("domain.com", "www."), "domain.com"); assertEquals("removeStartIgnoreCase(\"domain.com\", \"\")", StringUtils.removeStartIgnoreCase("domain.com", ""), "domain.com"); assertEquals("removeStartIgnoreCase(\"domain.com\", null)", StringUtils.removeStartIgnoreCase("domain.com", null), "domain.com"); // Case insensitive: assertEquals("removeStartIgnoreCase(\"www.domain.com\", \"WWW.\")", StringUtils.removeStartIgnoreCase("www.domain.com", "WWW."), "domain.com"); } public void testRemoveEnd() { // StringUtils.removeEnd("", *) = "" assertNull(StringUtils.removeEnd(null, null)); assertNull(StringUtils.removeEnd(null, "")); assertNull(StringUtils.removeEnd(null, "a")); // StringUtils.removeEnd(*, null) = * assertEquals(StringUtils.removeEnd("", null), ""); assertEquals(StringUtils.removeEnd("", ""), ""); assertEquals(StringUtils.removeEnd("", "a"), ""); // All others: assertEquals(StringUtils.removeEnd("www.domain.com.", ".com"), "www.domain.com."); assertEquals(StringUtils.removeEnd("www.domain.com", ".com"), "www.domain"); assertEquals(StringUtils.removeEnd("www.domain", ".com"), "www.domain"); assertEquals(StringUtils.removeEnd("domain.com", ""), "domain.com"); assertEquals(StringUtils.removeEnd("domain.com", null), "domain.com"); } public void testRemoveEndIgnoreCase() { // StringUtils.removeEndIgnoreCase("", *) = "" assertNull("removeEndIgnoreCase(null, null)", StringUtils.removeEndIgnoreCase(null, null)); assertNull("removeEndIgnoreCase(null, \"\")", StringUtils.removeEndIgnoreCase(null, "")); assertNull("removeEndIgnoreCase(null, \"a\")", StringUtils.removeEndIgnoreCase(null, "a")); // StringUtils.removeEnd(*, null) = * assertEquals("removeEndIgnoreCase(\"\", null)", StringUtils.removeEndIgnoreCase("", null), ""); assertEquals("removeEndIgnoreCase(\"\", \"\")", StringUtils.removeEndIgnoreCase("", ""), ""); assertEquals("removeEndIgnoreCase(\"\", \"a\")", StringUtils.removeEndIgnoreCase("", "a"), ""); // All others: assertEquals("removeEndIgnoreCase(\"www.domain.com.\", \".com\")", StringUtils.removeEndIgnoreCase("www.domain.com.", ".com"), "www.domain.com."); assertEquals("removeEndIgnoreCase(\"www.domain.com\", \".com\")", StringUtils.removeEndIgnoreCase("www.domain.com", ".com"), "www.domain"); assertEquals("removeEndIgnoreCase(\"www.domain\", \".com\")", StringUtils.removeEndIgnoreCase("www.domain", ".com"), "www.domain"); assertEquals("removeEndIgnoreCase(\"domain.com\", \"\")", StringUtils.removeEndIgnoreCase("domain.com", ""), "domain.com"); assertEquals("removeEndIgnoreCase(\"domain.com\", null)", StringUtils.removeEndIgnoreCase("domain.com", null), "domain.com"); // Case insensitive: assertEquals("removeEndIgnoreCase(\"www.domain.com\", \".COM\")", StringUtils.removeEndIgnoreCase("www.domain.com", ".COM"), "www.domain"); assertEquals("removeEndIgnoreCase(\"www.domain.COM\", \".com\")", StringUtils.removeEndIgnoreCase("www.domain.COM", ".com"), "www.domain"); } public void testRemove_String() { // StringUtils.remove(null, *) = null assertEquals(null, StringUtils.remove(null, null)); assertEquals(null, StringUtils.remove(null, "")); assertEquals(null, StringUtils.remove(null, "a")); // StringUtils.remove("", *) = "" assertEquals("", StringUtils.remove("", null)); assertEquals("", StringUtils.remove("", "")); assertEquals("", StringUtils.remove("", "a")); // StringUtils.remove(*, null) = * assertEquals(null, StringUtils.remove(null, null)); assertEquals("", StringUtils.remove("", null)); assertEquals("a", StringUtils.remove("a", null)); // StringUtils.remove(*, "") = * assertEquals(null, StringUtils.remove(null, "")); assertEquals("", StringUtils.remove("", "")); assertEquals("a", StringUtils.remove("a", "")); // StringUtils.remove("queued", "ue") = "qd" assertEquals("qd", StringUtils.remove("queued", "ue")); // StringUtils.remove("queued", "zz") = "queued" assertEquals("queued", StringUtils.remove("queued", "zz")); } public void testRemove_char() { // StringUtils.remove(null, *) = null assertEquals(null, StringUtils.remove(null, 'a')); assertEquals(null, StringUtils.remove(null, 'a')); assertEquals(null, StringUtils.remove(null, 'a')); // StringUtils.remove("", *) = "" assertEquals("", StringUtils.remove("", 'a')); assertEquals("", StringUtils.remove("", 'a')); assertEquals("", StringUtils.remove("", 'a')); // StringUtils.remove("queued", 'u') = "qeed" assertEquals("qeed", StringUtils.remove("queued", 'u')); // StringUtils.remove("queued", 'z') = "queued" assertEquals("queued", StringUtils.remove("queued", 'z')); } public void testDifferenceAt_StringArray(){ assertEquals(-1, StringUtils.indexOfDifference(null)); assertEquals(-1, StringUtils.indexOfDifference(new String[] {})); assertEquals(-1, StringUtils.indexOfDifference(new String[] {"abc"})); assertEquals(-1, StringUtils.indexOfDifference(new String[] {null, null})); assertEquals(-1, StringUtils.indexOfDifference(new String[] {"", ""})); assertEquals(0, StringUtils.indexOfDifference(new String[] {"", null})); assertEquals(0, StringUtils.indexOfDifference(new String[] {"abc", null, null})); assertEquals(0, StringUtils.indexOfDifference(new String[] {null, null, "abc"})); assertEquals(0, StringUtils.indexOfDifference(new String[] {"", "abc"})); assertEquals(0, StringUtils.indexOfDifference(new String[] {"abc", ""})); assertEquals(-1, StringUtils.indexOfDifference(new String[] {"abc", "abc"})); assertEquals(1, StringUtils.indexOfDifference(new String[] {"abc", "a"})); assertEquals(2, StringUtils.indexOfDifference(new String[] {"ab", "abxyz"})); assertEquals(2, StringUtils.indexOfDifference(new String[] {"abcde", "abxyz"})); assertEquals(0, StringUtils.indexOfDifference(new String[] {"abcde", "xyz"})); assertEquals(0, StringUtils.indexOfDifference(new String[] {"xyz", "abcde"})); assertEquals(7, StringUtils.indexOfDifference(new String[] {"i am a machine", "i am a robot"})); } public void testGetCommonPrefix_StringArray(){ assertEquals("", StringUtils.getCommonPrefix(null)); assertEquals("", StringUtils.getCommonPrefix(new String[] {})); assertEquals("abc", StringUtils.getCommonPrefix(new String[] {"abc"})); assertEquals("", StringUtils.getCommonPrefix(new String[] {null, null})); assertEquals("", StringUtils.getCommonPrefix(new String[] {"", ""})); assertEquals("", StringUtils.getCommonPrefix(new String[] {"", null})); assertEquals("", StringUtils.getCommonPrefix(new String[] {"abc", null, null})); assertEquals("", StringUtils.getCommonPrefix(new String[] {null, null, "abc"})); assertEquals("", StringUtils.getCommonPrefix(new String[] {"", "abc"})); assertEquals("", StringUtils.getCommonPrefix(new String[] {"abc", ""})); assertEquals("abc", StringUtils.getCommonPrefix(new String[] {"abc", "abc"})); assertEquals("a", StringUtils.getCommonPrefix(new String[] {"abc", "a"})); assertEquals("ab", StringUtils.getCommonPrefix(new String[] {"ab", "abxyz"})); assertEquals("ab", StringUtils.getCommonPrefix(new String[] {"abcde", "abxyz"})); assertEquals("", StringUtils.getCommonPrefix(new String[] {"abcde", "xyz"})); assertEquals("", StringUtils.getCommonPrefix(new String[] {"xyz", "abcde"})); assertEquals("i am a ", StringUtils.getCommonPrefix(new String[] {"i am a machine", "i am a robot"})); } public void testStartsWithAny() { assertFalse(StringUtils.startsWithAny(null, null)); assertFalse(StringUtils.startsWithAny(null, new String[] {"abc"})); assertFalse(StringUtils.startsWithAny("abcxyz", null)); assertFalse(StringUtils.startsWithAny("abcxyz", new String[] {})); assertTrue(StringUtils.startsWithAny("abcxyz", new String[] {"abc"})); assertTrue(StringUtils.startsWithAny("abcxyz", new String[] {null, "xyz", "abc"})); assertFalse(StringUtils.startsWithAny("abcxyz", new String[] {null, "xyz", "abcd"})); } public void testNormalizeSpace() { assertEquals(null, StringUtils.normalizeSpace(null)); assertEquals("", StringUtils.normalizeSpace("")); assertEquals("", StringUtils.normalizeSpace(" ")); assertEquals("", StringUtils.normalizeSpace("\t")); assertEquals("", StringUtils.normalizeSpace("\n")); assertEquals("", StringUtils.normalizeSpace("\u0009")); assertEquals("", StringUtils.normalizeSpace("\u000B")); assertEquals("", StringUtils.normalizeSpace("\u000C")); assertEquals("", StringUtils.normalizeSpace("\u001C")); assertEquals("", StringUtils.normalizeSpace("\u001D")); assertEquals("", StringUtils.normalizeSpace("\u001E")); assertEquals("", StringUtils.normalizeSpace("\u001F")); assertEquals("", StringUtils.normalizeSpace("\f")); assertEquals("", StringUtils.normalizeSpace("\r")); assertEquals("a", StringUtils.normalizeSpace(" a ")); assertEquals("a b c", StringUtils.normalizeSpace(" a b c ")); assertEquals("a b c", StringUtils.normalizeSpace("a\t\f\r b\u000B c\n")); assertEquals("", StringUtils.normalizeSpace(WHITESPACE)); assertEquals("A", StringUtils.normalizeSpace(WHITESPACE + " A " + WHITESPACE)); assertEquals("A B", StringUtils.normalizeSpace(WHITESPACE + " A " + WHITESPACE + " B " + WHITESPACE)); } public void testLANG666() { assertEquals("12",StringUtils.stripEnd("120.00", ".0")); assertEquals("121",StringUtils.stripEnd("121.00", ".0")); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/StringUtilsTrimEmptyTest.java100644 0 0 32250 11513702440 26646 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang; import junit.framework.TestCase; /** * Unit tests {@link org.apache.commons.lang.StringUtils} - Trim/Empty methods * * @author Apache Software Foundation * @author Ringo De Smet * @version $Id: StringUtilsTrimEmptyTest.java 905636 2010-02-02 14:03:32Z niallp $ */ public class StringUtilsTrimEmptyTest extends TestCase { private static final String FOO = "foo"; public StringUtilsTrimEmptyTest(String name) { super(name); } //----------------------------------------------------------------------- public void testIsEmpty() { assertEquals(true, StringUtils.isEmpty(null)); assertEquals(true, StringUtils.isEmpty("")); assertEquals(false, StringUtils.isEmpty(" ")); assertEquals(false, StringUtils.isEmpty("foo")); assertEquals(false, StringUtils.isEmpty(" foo ")); } public void testIsNotEmpty() { assertEquals(false, StringUtils.isNotEmpty(null)); assertEquals(false, StringUtils.isNotEmpty("")); assertEquals(true, StringUtils.isNotEmpty(" ")); assertEquals(true, StringUtils.isNotEmpty("foo")); assertEquals(true, StringUtils.isNotEmpty(" foo ")); } public void testIsBlank() { assertEquals(true, StringUtils.isBlank(null)); assertEquals(true, StringUtils.isBlank("")); assertEquals(true, StringUtils.isBlank(StringUtilsTest.WHITESPACE)); assertEquals(false, StringUtils.isBlank("foo")); assertEquals(false, StringUtils.isBlank(" foo ")); } public void testIsNotBlank() { assertEquals(false, StringUtils.isNotBlank(null)); assertEquals(false, StringUtils.isNotBlank("")); assertEquals(false, StringUtils.isNotBlank(StringUtilsTest.WHITESPACE)); assertEquals(true, StringUtils.isNotBlank("foo")); assertEquals(true, StringUtils.isNotBlank(" foo ")); } //----------------------------------------------------------------------- public void testDeprecatedClean() { assertEquals(FOO, StringUtils.clean(FOO + " ")); assertEquals(FOO, StringUtils.clean(" " + FOO + " ")); assertEquals(FOO, StringUtils.clean(" " + FOO)); assertEquals(FOO, StringUtils.clean(FOO + "")); assertEquals("", StringUtils.clean(" \t\r\n\b ")); assertEquals("", StringUtils.clean("")); assertEquals("", StringUtils.clean(null)); } public void testTrim() { assertEquals(FOO, StringUtils.trim(FOO + " ")); assertEquals(FOO, StringUtils.trim(" " + FOO + " ")); assertEquals(FOO, StringUtils.trim(" " + FOO)); assertEquals(FOO, StringUtils.trim(FOO + "")); assertEquals("", StringUtils.trim(" \t\r\n\b ")); assertEquals("", StringUtils.trim(StringUtilsTest.TRIMMABLE)); assertEquals(StringUtilsTest.NON_TRIMMABLE, StringUtils.trim(StringUtilsTest.NON_TRIMMABLE)); assertEquals("", StringUtils.trim("")); assertEquals(null, StringUtils.trim(null)); } public void testTrimToNull() { assertEquals(FOO, StringUtils.trimToNull(FOO + " ")); assertEquals(FOO, StringUtils.trimToNull(" " + FOO + " ")); assertEquals(FOO, StringUtils.trimToNull(" " + FOO)); assertEquals(FOO, StringUtils.trimToNull(FOO + "")); assertEquals(null, StringUtils.trimToNull(" \t\r\n\b ")); assertEquals(null, StringUtils.trimToNull(StringUtilsTest.TRIMMABLE)); assertEquals(StringUtilsTest.NON_TRIMMABLE, StringUtils.trimToNull(StringUtilsTest.NON_TRIMMABLE)); assertEquals(null, StringUtils.trimToNull("")); assertEquals(null, StringUtils.trimToNull(null)); } public void testTrimToEmpty() { assertEquals(FOO, StringUtils.trimToEmpty(FOO + " ")); assertEquals(FOO, StringUtils.trimToEmpty(" " + FOO + " ")); assertEquals(FOO, StringUtils.trimToEmpty(" " + FOO)); assertEquals(FOO, StringUtils.trimToEmpty(FOO + "")); assertEquals("", StringUtils.trimToEmpty(" \t\r\n\b ")); assertEquals("", StringUtils.trimToEmpty(StringUtilsTest.TRIMMABLE)); assertEquals(StringUtilsTest.NON_TRIMMABLE, StringUtils.trimToEmpty(StringUtilsTest.NON_TRIMMABLE)); assertEquals("", StringUtils.trimToEmpty("")); assertEquals("", StringUtils.trimToEmpty(null)); } //----------------------------------------------------------------------- public void testStrip_String() { assertEquals(null, StringUtils.strip(null)); assertEquals("", StringUtils.strip("")); assertEquals("", StringUtils.strip(" ")); assertEquals("abc", StringUtils.strip(" abc ")); assertEquals(StringUtilsTest.NON_WHITESPACE, StringUtils.strip(StringUtilsTest.WHITESPACE + StringUtilsTest.NON_WHITESPACE + StringUtilsTest.WHITESPACE)); } public void testStripToNull_String() { assertEquals(null, StringUtils.stripToNull(null)); assertEquals(null, StringUtils.stripToNull("")); assertEquals(null, StringUtils.stripToNull(" ")); assertEquals(null, StringUtils.stripToNull(StringUtilsTest.WHITESPACE)); assertEquals("ab c", StringUtils.stripToNull(" ab c ")); assertEquals(StringUtilsTest.NON_WHITESPACE, StringUtils.stripToNull(StringUtilsTest.WHITESPACE + StringUtilsTest.NON_WHITESPACE + StringUtilsTest.WHITESPACE)); } public void testStripToEmpty_String() { assertEquals("", StringUtils.stripToEmpty(null)); assertEquals("", StringUtils.stripToEmpty("")); assertEquals("", StringUtils.stripToEmpty(" ")); assertEquals("", StringUtils.stripToEmpty(StringUtilsTest.WHITESPACE)); assertEquals("ab c", StringUtils.stripToEmpty(" ab c ")); assertEquals(StringUtilsTest.NON_WHITESPACE, StringUtils.stripToEmpty(StringUtilsTest.WHITESPACE + StringUtilsTest.NON_WHITESPACE + StringUtilsTest.WHITESPACE)); } public void testStrip_StringString() { // null strip assertEquals(null, StringUtils.strip(null, null)); assertEquals("", StringUtils.strip("", null)); assertEquals("", StringUtils.strip(" ", null)); assertEquals("abc", StringUtils.strip(" abc ", null)); assertEquals(StringUtilsTest.NON_WHITESPACE, StringUtils.strip(StringUtilsTest.WHITESPACE + StringUtilsTest.NON_WHITESPACE + StringUtilsTest.WHITESPACE, null)); // "" strip assertEquals(null, StringUtils.strip(null, "")); assertEquals("", StringUtils.strip("", "")); assertEquals(" ", StringUtils.strip(" ", "")); assertEquals(" abc ", StringUtils.strip(" abc ", "")); assertEquals(StringUtilsTest.WHITESPACE, StringUtils.strip(StringUtilsTest.WHITESPACE, "")); // " " strip assertEquals(null, StringUtils.strip(null, " ")); assertEquals("", StringUtils.strip("", " ")); assertEquals("", StringUtils.strip(" ", " ")); assertEquals("abc", StringUtils.strip(" abc ", " ")); // "ab" strip assertEquals(null, StringUtils.strip(null, "ab")); assertEquals("", StringUtils.strip("", "ab")); assertEquals(" ", StringUtils.strip(" ", "ab")); assertEquals(" abc ", StringUtils.strip(" abc ", "ab")); assertEquals("c", StringUtils.strip("abcabab", "ab")); assertEquals(StringUtilsTest.WHITESPACE, StringUtils.strip(StringUtilsTest.WHITESPACE, "")); } public void testStripStart_StringString() { // null stripStart assertEquals(null, StringUtils.stripStart(null, null)); assertEquals("", StringUtils.stripStart("", null)); assertEquals("", StringUtils.stripStart(" ", null)); assertEquals("abc ", StringUtils.stripStart(" abc ", null)); assertEquals(StringUtilsTest.NON_WHITESPACE + StringUtilsTest.WHITESPACE, StringUtils.stripStart(StringUtilsTest.WHITESPACE + StringUtilsTest.NON_WHITESPACE + StringUtilsTest.WHITESPACE, null)); // "" stripStart assertEquals(null, StringUtils.stripStart(null, "")); assertEquals("", StringUtils.stripStart("", "")); assertEquals(" ", StringUtils.stripStart(" ", "")); assertEquals(" abc ", StringUtils.stripStart(" abc ", "")); assertEquals(StringUtilsTest.WHITESPACE, StringUtils.stripStart(StringUtilsTest.WHITESPACE, "")); // " " stripStart assertEquals(null, StringUtils.stripStart(null, " ")); assertEquals("", StringUtils.stripStart("", " ")); assertEquals("", StringUtils.stripStart(" ", " ")); assertEquals("abc ", StringUtils.stripStart(" abc ", " ")); // "ab" stripStart assertEquals(null, StringUtils.stripStart(null, "ab")); assertEquals("", StringUtils.stripStart("", "ab")); assertEquals(" ", StringUtils.stripStart(" ", "ab")); assertEquals(" abc ", StringUtils.stripStart(" abc ", "ab")); assertEquals("cabab", StringUtils.stripStart("abcabab", "ab")); assertEquals(StringUtilsTest.WHITESPACE, StringUtils.stripStart(StringUtilsTest.WHITESPACE, "")); } public void testStripEnd_StringString() { // null stripEnd assertEquals(null, StringUtils.stripEnd(null, null)); assertEquals("", StringUtils.stripEnd("", null)); assertEquals("", StringUtils.stripEnd(" ", null)); assertEquals(" abc", StringUtils.stripEnd(" abc ", null)); assertEquals(StringUtilsTest.WHITESPACE + StringUtilsTest.NON_WHITESPACE, StringUtils.stripEnd(StringUtilsTest.WHITESPACE + StringUtilsTest.NON_WHITESPACE + StringUtilsTest.WHITESPACE, null)); // "" stripEnd assertEquals(null, StringUtils.stripEnd(null, "")); assertEquals("", StringUtils.stripEnd("", "")); assertEquals(" ", StringUtils.stripEnd(" ", "")); assertEquals(" abc ", StringUtils.stripEnd(" abc ", "")); assertEquals(StringUtilsTest.WHITESPACE, StringUtils.stripEnd(StringUtilsTest.WHITESPACE, "")); // " " stripEnd assertEquals(null, StringUtils.stripEnd(null, " ")); assertEquals("", StringUtils.stripEnd("", " ")); assertEquals("", StringUtils.stripEnd(" ", " ")); assertEquals(" abc", StringUtils.stripEnd(" abc ", " ")); // "ab" stripEnd assertEquals(null, StringUtils.stripEnd(null, "ab")); assertEquals("", StringUtils.stripEnd("", "ab")); assertEquals(" ", StringUtils.stripEnd(" ", "ab")); assertEquals(" abc ", StringUtils.stripEnd(" abc ", "ab")); assertEquals("abc", StringUtils.stripEnd("abcabab", "ab")); assertEquals(StringUtilsTest.WHITESPACE, StringUtils.stripEnd(StringUtilsTest.WHITESPACE, "")); } public void testStripAll() { // test stripAll method, merely an array version of the above strip String[] empty = new String[0]; String[] fooSpace = new String[] { " "+FOO+" ", " "+FOO, FOO+" " }; String[] fooDots = new String[] { ".."+FOO+"..", ".."+FOO, FOO+".." }; String[] foo = new String[] { FOO, FOO, FOO }; assertEquals(null, StringUtils.stripAll(null)); assertArrayEquals(empty, StringUtils.stripAll(empty)); assertArrayEquals(foo, StringUtils.stripAll(fooSpace)); assertEquals(null, StringUtils.stripAll(null, null)); assertArrayEquals(foo, StringUtils.stripAll(fooSpace, null)); assertArrayEquals(foo, StringUtils.stripAll(fooDots, ".")); } private void assertArrayEquals(Object[] o1, Object[] o2) { if(o1 == null) { assertEquals(o1,o2); return; } assertEquals("Length not equal. ", o1.length, o2.length); int sz = o1.length; for(int i=0; inull Locale. * @param pattern MessageFormat pattern * @param args MessageFormat arguments * @param locales to test */ private void checkBuiltInFormat(String pattern, Object[] args, Locale[] locales) { checkBuiltInFormat(pattern, null, args, locales); } /** * Test a built in format for the specified Locales, plus null Locale. * @param pattern MessageFormat pattern * @param registry FormatFactory registry to use * @param args MessageFormat arguments * @param locales to test */ private void checkBuiltInFormat(String pattern, Map registry, Object[] args, Locale[] locales) { checkBuiltInFormat(pattern, registry, args, (Locale) null); for (int i = 0; i < locales.length; i++) { checkBuiltInFormat(pattern, registry, args, locales[i]); } } /** * Create an ExtendedMessageFormat for the specified pattern and locale and check the * formated output matches the expected result for the parameters. * @param pattern string * @param registry map * @param args Object[] * @param locale Locale */ private void checkBuiltInFormat(String pattern, Map registry, Object[] args, Locale locale) { StringBuffer buffer = new StringBuffer(); buffer.append("Pattern=["); buffer.append(pattern); buffer.append("], locale=["); buffer.append(locale); buffer.append("]"); MessageFormat mf = createMessageFormat(pattern, locale); // System.out.println(buffer + ", result=[" + mf.format(args) +"]"); ExtendedMessageFormat emf = null; if (locale == null) { emf = new ExtendedMessageFormat(pattern); } else { emf = new ExtendedMessageFormat(pattern, locale); } assertEquals("format " + buffer.toString(), mf.format(args), emf.format(args)); assertPatternsEqual("toPattern " + buffer.toString(), mf.toPattern(), emf.toPattern()); } //can't trust what MessageFormat does with toPattern() pre 1.4: private void assertPatternsEqual(String message, String expected, String actual) { if (SystemUtils.isJavaVersionAtLeast(1.4f)) { assertEquals(message, expected, actual); } } /** * Replace MessageFormat(String, Locale) constructor (not available until JDK 1.4). * @param pattern string * @param locale Locale * @return MessageFormat */ private MessageFormat createMessageFormat(String pattern, Locale locale) { MessageFormat result = new MessageFormat(pattern); if (locale != null) { result.setLocale(locale); result.applyPattern(pattern); } return result; } // ------------------------ Test Formats ------------------------ /** * {@link Format} implementation which converts to lower case. */ private static class LowerCaseFormat extends Format { public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) { return toAppendTo.append(((String)obj).toLowerCase()); } public Object parseObject(String source, ParsePosition pos) {throw new UnsupportedOperationException();} } /** * {@link Format} implementation which converts to upper case. */ private static class UpperCaseFormat extends Format { public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) { return toAppendTo.append(((String)obj).toUpperCase()); } public Object parseObject(String source, ParsePosition pos) {throw new UnsupportedOperationException();} } // ------------------------ Test Format Factories --------------- /** * {@link FormatFactory} implementation for lower case format. */ private static class LowerCaseFormatFactory implements FormatFactory { private static final Format LOWER_INSTANCE = new LowerCaseFormat(); public Format getFormat(String name, String arguments, Locale locale) { return LOWER_INSTANCE; } } /** * {@link FormatFactory} implementation for upper case format. */ private static class UpperCaseFormatFactory implements FormatFactory { private static final Format UPPER_INSTANCE = new UpperCaseFormat(); public Format getFormat(String name, String arguments, Locale locale) { return UPPER_INSTANCE; } } /** * {@link FormatFactory} implementation to override date format "short" to "default". */ private static class OverrideShortDateFormatFactory implements FormatFactory { public Format getFormat(String name, String arguments, Locale locale) { return !"short".equals(arguments) ? null : locale == null ? DateFormat .getDateInstance(DateFormat.DEFAULT) : DateFormat .getDateInstance(DateFormat.DEFAULT, locale); } } /** * Alternative ExtendedMessageFormat impl. */ private static class OtherExtendedMessageFormat extends ExtendedMessageFormat { public OtherExtendedMessageFormat(String pattern, Locale locale, Map registry) { super(pattern, locale, registry); } } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/text/StrBuilderAppendInsertTest.java100644 0 0 132075 11513702433 30114 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.text; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import junit.framework.TestCase; import org.apache.commons.lang.SystemUtils; /** * Unit tests for {@link org.apache.commons.lang.text.StrBuilder}. * * @version $Id: StrBuilderAppendInsertTest.java 905628 2010-02-02 13:29:55Z niallp $ */ public class StrBuilderAppendInsertTest extends TestCase { /** The system line separator. */ private static final String SEP = SystemUtils.LINE_SEPARATOR; /** Test subclass of Object, with a toString method. */ private static Object FOO = new Object() { public String toString() { return "foo"; } }; /** * Create a new test case with the specified name. * * @param name the name */ public StrBuilderAppendInsertTest(String name) { super(name); } //----------------------------------------------------------------------- public void testAppendNewLine() { StrBuilder sb = new StrBuilder("---"); sb.appendNewLine().append("+++"); assertEquals("---" + SEP + "+++", sb.toString()); sb = new StrBuilder("---"); sb.setNewLineText("#").appendNewLine().setNewLineText(null).appendNewLine(); assertEquals("---#" + SEP, sb.toString()); } //----------------------------------------------------------------------- public void testAppendWithNullText() { StrBuilder sb = new StrBuilder(); sb.setNullText("NULL"); assertEquals("", sb.toString()); sb.appendNull(); assertEquals("NULL", sb.toString()); sb.append((Object) null); assertEquals("NULLNULL", sb.toString()); sb.append(FOO); assertEquals("NULLNULLfoo", sb.toString()); sb.append((String) null); assertEquals("NULLNULLfooNULL", sb.toString()); sb.append(""); assertEquals("NULLNULLfooNULL", sb.toString()); sb.append("bar"); assertEquals("NULLNULLfooNULLbar", sb.toString()); sb.append((StringBuffer) null); assertEquals("NULLNULLfooNULLbarNULL", sb.toString()); sb.append(new StringBuffer("baz")); assertEquals("NULLNULLfooNULLbarNULLbaz", sb.toString()); } //----------------------------------------------------------------------- public void testAppend_Object() { StrBuilder sb = new StrBuilder(); sb.appendNull(); assertEquals("", sb.toString()); sb.append((Object) null); assertEquals("", sb.toString()); sb.append(FOO); assertEquals("foo", sb.toString()); sb.append((StringBuffer) null); assertEquals("foo", sb.toString()); sb.append(new StringBuffer("baz")); assertEquals("foobaz", sb.toString()); sb.append(new StrBuilder("yes")); assertEquals("foobazyes", sb.toString()); } //----------------------------------------------------------------------- public void testAppend_String() { StrBuilder sb = new StrBuilder(); sb.setNullText("NULL").append((String) null); assertEquals("NULL", sb.toString()); sb = new StrBuilder(); sb.append("foo"); assertEquals("foo", sb.toString()); sb.append(""); assertEquals("foo", sb.toString()); sb.append("bar"); assertEquals("foobar", sb.toString()); } //----------------------------------------------------------------------- public void testAppend_String_int_int() { StrBuilder sb = new StrBuilder(); sb.setNullText("NULL").append((String) null, 0, 1); assertEquals("NULL", sb.toString()); sb = new StrBuilder(); sb.append("foo", 0, 3); assertEquals("foo", sb.toString()); try { sb.append("bar", -1, 1); fail("append(char[], -1,) expected IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // expected } try { sb.append("bar", 3, 1); fail("append(char[], 3,) expected IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // expected } try { sb.append("bar", 1, -1); fail("append(char[],, -1) expected IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // expected } try { sb.append("bar", 1, 3); fail("append(char[], 1, 3) expected IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // expected } try { sb.append("bar", -1, 3); fail("append(char[], -1, 3) expected IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // expected } try { sb.append("bar", 4, 0); fail("append(char[], 4, 0) expected IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // expected } sb.append("bar", 3, 0); assertEquals("foo", sb.toString()); sb.append("abcbardef", 3, 3); assertEquals("foobar", sb.toString()); } //----------------------------------------------------------------------- public void testAppend_StringBuffer() { StrBuilder sb = new StrBuilder(); sb.setNullText("NULL").append((StringBuffer) null); assertEquals("NULL", sb.toString()); sb = new StrBuilder(); sb.append(new StringBuffer("foo")); assertEquals("foo", sb.toString()); sb.append(new StringBuffer("")); assertEquals("foo", sb.toString()); sb.append(new StringBuffer("bar")); assertEquals("foobar", sb.toString()); } //----------------------------------------------------------------------- public void testAppend_StringBuffer_int_int() { StrBuilder sb = new StrBuilder(); sb.setNullText("NULL").append((StringBuffer) null, 0, 1); assertEquals("NULL", sb.toString()); sb = new StrBuilder(); sb.append(new StringBuffer("foo"), 0, 3); assertEquals("foo", sb.toString()); try { sb.append(new StringBuffer("bar"), -1, 1); fail("append(char[], -1,) expected IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // expected } try { sb.append(new StringBuffer("bar"), 3, 1); fail("append(char[], 3,) expected IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // expected } try { sb.append(new StringBuffer("bar"), 1, -1); fail("append(char[],, -1) expected IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // expected } try { sb.append(new StringBuffer("bar"), 1, 3); fail("append(char[], 1, 3) expected IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // expected } try { sb.append(new StringBuffer("bar"), -1, 3); fail("append(char[], -1, 3) expected IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // expected } try { sb.append(new StringBuffer("bar"), 4, 0); fail("append(char[], 4, 0) expected IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // expected } sb.append(new StringBuffer("bar"), 3, 0); assertEquals("foo", sb.toString()); sb.append(new StringBuffer("abcbardef"), 3, 3); assertEquals("foobar", sb.toString()); } //----------------------------------------------------------------------- public void testAppend_StrBuilder() { StrBuilder sb = new StrBuilder(); sb.setNullText("NULL").append((StrBuilder) null); assertEquals("NULL", sb.toString()); sb = new StrBuilder(); sb.append(new StrBuilder("foo")); assertEquals("foo", sb.toString()); sb.append(new StrBuilder("")); assertEquals("foo", sb.toString()); sb.append(new StrBuilder("bar")); assertEquals("foobar", sb.toString()); } //----------------------------------------------------------------------- public void testAppend_StrBuilder_int_int() { StrBuilder sb = new StrBuilder(); sb.setNullText("NULL").append((StrBuilder) null, 0, 1); assertEquals("NULL", sb.toString()); sb = new StrBuilder(); sb.append(new StrBuilder("foo"), 0, 3); assertEquals("foo", sb.toString()); try { sb.append(new StrBuilder("bar"), -1, 1); fail("append(char[], -1,) expected IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // expected } try { sb.append(new StrBuilder("bar"), 3, 1); fail("append(char[], 3,) expected IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // expected } try { sb.append(new StrBuilder("bar"), 1, -1); fail("append(char[],, -1) expected IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // expected } try { sb.append(new StrBuilder("bar"), 1, 3); fail("append(char[], 1, 3) expected IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // expected } try { sb.append(new StrBuilder("bar"), -1, 3); fail("append(char[], -1, 3) expected IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // expected } try { sb.append(new StrBuilder("bar"), 4, 0); fail("append(char[], 4, 0) expected IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // expected } sb.append(new StrBuilder("bar"), 3, 0); assertEquals("foo", sb.toString()); sb.append(new StrBuilder("abcbardef"), 3, 3); assertEquals("foobar", sb.toString()); } //----------------------------------------------------------------------- public void testAppend_CharArray() { StrBuilder sb = new StrBuilder(); sb.setNullText("NULL").append((char[]) null); assertEquals("NULL", sb.toString()); sb = new StrBuilder(); sb.append(new char[0]); assertEquals("", sb.toString()); sb.append(new char[]{'f', 'o', 'o'}); assertEquals("foo", sb.toString()); } //----------------------------------------------------------------------- public void testAppend_CharArray_int_int() { StrBuilder sb = new StrBuilder(); sb.setNullText("NULL").append((char[]) null, 0, 1); assertEquals("NULL", sb.toString()); sb = new StrBuilder(); sb.append(new char[]{'f', 'o', 'o'}, 0, 3); assertEquals("foo", sb.toString()); try { sb.append(new char[]{'b', 'a', 'r'}, -1, 1); fail("append(char[], -1,) expected IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // expected } try { sb.append(new char[]{'b', 'a', 'r'}, 3, 1); fail("append(char[], 3,) expected IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // expected } try { sb.append(new char[]{'b', 'a', 'r'}, 1, -1); fail("append(char[],, -1) expected IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // expected } try { sb.append(new char[]{'b', 'a', 'r'}, 1, 3); fail("append(char[], 1, 3) expected IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // expected } try { sb.append(new char[]{'b', 'a', 'r'}, -1, 3); fail("append(char[], -1, 3) expected IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // expected } try { sb.append(new char[]{'b', 'a', 'r'}, 4, 0); fail("append(char[], 4, 0) expected IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // expected } sb.append(new char[]{'b', 'a', 'r'}, 3, 0); assertEquals("foo", sb.toString()); sb.append(new char[]{'a', 'b', 'c', 'b', 'a', 'r', 'd', 'e', 'f'}, 3, 3); assertEquals("foobar", sb.toString()); } //----------------------------------------------------------------------- public void testAppend_Boolean() { StrBuilder sb = new StrBuilder(); sb.append(true); assertEquals("true", sb.toString()); sb.append(false); assertEquals("truefalse", sb.toString()); sb.append('!'); assertEquals("truefalse!", sb.toString()); } //----------------------------------------------------------------------- public void testAppend_PrimitiveNumber() { StrBuilder sb = new StrBuilder(); sb.append(0); assertEquals("0", sb.toString()); sb.append(1L); assertEquals("01", sb.toString()); sb.append(2.3f); assertEquals("012.3", sb.toString()); sb.append(4.5d); assertEquals("012.34.5", sb.toString()); } //----------------------------------------------------------------------- public void testAppendln_Object() { StrBuilder sb = new StrBuilder(); sb.appendln((Object) null); assertEquals("" + SEP, sb.toString()); sb.appendln((Object) FOO); assertEquals(SEP + "foo" + SEP, sb.toString()); sb.appendln(new Integer(6)); assertEquals(SEP + "foo" + SEP + "6" + SEP, sb.toString()); } //----------------------------------------------------------------------- public void testAppendln_String() { final int[] count = new int[2]; StrBuilder sb = new StrBuilder() { public StrBuilder append(String str) { count[0]++; return super.append(str); } public StrBuilder appendNewLine() { count[1]++; return super.appendNewLine(); } }; sb.appendln("foo"); assertEquals("foo" + SEP, sb.toString()); assertEquals(2, count[0]); // appendNewLine() calls append(String) assertEquals(1, count[1]); } //----------------------------------------------------------------------- public void testAppendln_String_int_int() { final int[] count = new int[2]; StrBuilder sb = new StrBuilder() { public StrBuilder append(String str, int startIndex, int length) { count[0]++; return super.append(str, startIndex, length); } public StrBuilder appendNewLine() { count[1]++; return super.appendNewLine(); } }; sb.appendln("foo", 0, 3); assertEquals("foo" + SEP, sb.toString()); assertEquals(1, count[0]); assertEquals(1, count[1]); } //----------------------------------------------------------------------- public void testAppendln_StringBuffer() { final int[] count = new int[2]; StrBuilder sb = new StrBuilder() { public StrBuilder append(StringBuffer str) { count[0]++; return super.append(str); } public StrBuilder appendNewLine() { count[1]++; return super.appendNewLine(); } }; sb.appendln(new StringBuffer("foo")); assertEquals("foo" + SEP, sb.toString()); assertEquals(1, count[0]); assertEquals(1, count[1]); } //----------------------------------------------------------------------- public void testAppendln_StringBuffer_int_int() { final int[] count = new int[2]; StrBuilder sb = new StrBuilder() { public StrBuilder append(StringBuffer str, int startIndex, int length) { count[0]++; return super.append(str, startIndex, length); } public StrBuilder appendNewLine() { count[1]++; return super.appendNewLine(); } }; sb.appendln(new StringBuffer("foo"), 0, 3); assertEquals("foo" + SEP, sb.toString()); assertEquals(1, count[0]); assertEquals(1, count[1]); } //----------------------------------------------------------------------- public void testAppendln_StrBuilder() { final int[] count = new int[2]; StrBuilder sb = new StrBuilder() { public StrBuilder append(StrBuilder str) { count[0]++; return super.append(str); } public StrBuilder appendNewLine() { count[1]++; return super.appendNewLine(); } }; sb.appendln(new StrBuilder("foo")); assertEquals("foo" + SEP, sb.toString()); assertEquals(1, count[0]); assertEquals(1, count[1]); } //----------------------------------------------------------------------- public void testAppendln_StrBuilder_int_int() { final int[] count = new int[2]; StrBuilder sb = new StrBuilder() { public StrBuilder append(StrBuilder str, int startIndex, int length) { count[0]++; return super.append(str, startIndex, length); } public StrBuilder appendNewLine() { count[1]++; return super.appendNewLine(); } }; sb.appendln(new StrBuilder("foo"), 0, 3); assertEquals("foo" + SEP, sb.toString()); assertEquals(1, count[0]); assertEquals(1, count[1]); } //----------------------------------------------------------------------- public void testAppendln_CharArray() { final int[] count = new int[2]; StrBuilder sb = new StrBuilder() { public StrBuilder append(char[] str) { count[0]++; return super.append(str); } public StrBuilder appendNewLine() { count[1]++; return super.appendNewLine(); } }; sb.appendln("foo".toCharArray()); assertEquals("foo" + SEP, sb.toString()); assertEquals(1, count[0]); assertEquals(1, count[1]); } //----------------------------------------------------------------------- public void testAppendln_CharArray_int_int() { final int[] count = new int[2]; StrBuilder sb = new StrBuilder() { public StrBuilder append(char[] str, int startIndex, int length) { count[0]++; return super.append(str, startIndex, length); } public StrBuilder appendNewLine() { count[1]++; return super.appendNewLine(); } }; sb.appendln("foo".toCharArray(), 0, 3); assertEquals("foo" + SEP, sb.toString()); assertEquals(1, count[0]); assertEquals(1, count[1]); } //----------------------------------------------------------------------- public void testAppendln_Boolean() { StrBuilder sb = new StrBuilder(); sb.appendln(true); assertEquals("true" + SEP, sb.toString()); sb.clear(); sb.appendln(false); assertEquals("false" + SEP, sb.toString()); } //----------------------------------------------------------------------- public void testAppendln_PrimitiveNumber() { StrBuilder sb = new StrBuilder(); sb.appendln(0); assertEquals("0" + SEP, sb.toString()); sb.clear(); sb.appendln(1L); assertEquals("1" + SEP, sb.toString()); sb.clear(); sb.appendln(2.3f); assertEquals("2.3" + SEP, sb.toString()); sb.clear(); sb.appendln(4.5d); assertEquals("4.5" + SEP, sb.toString()); } //----------------------------------------------------------------------- public void testAppendPadding() { StrBuilder sb = new StrBuilder(); sb.append("foo"); assertEquals("foo", sb.toString()); sb.appendPadding(-1, '-'); assertEquals("foo", sb.toString()); sb.appendPadding(0, '-'); assertEquals("foo", sb.toString()); sb.appendPadding(1, '-'); assertEquals("foo-", sb.toString()); sb.appendPadding(16, '-'); assertEquals(20, sb.length()); // 12345678901234567890 assertEquals("foo-----------------", sb.toString()); } //----------------------------------------------------------------------- public void testAppendFixedWidthPadLeft() { StrBuilder sb = new StrBuilder(); sb.appendFixedWidthPadLeft("foo", -1, '-'); assertEquals("", sb.toString()); sb.clear(); sb.appendFixedWidthPadLeft("foo", 0, '-'); assertEquals("", sb.toString()); sb.clear(); sb.appendFixedWidthPadLeft("foo", 1, '-'); assertEquals("o", sb.toString()); sb.clear(); sb.appendFixedWidthPadLeft("foo", 2, '-'); assertEquals("oo", sb.toString()); sb.clear(); sb.appendFixedWidthPadLeft("foo", 3, '-'); assertEquals("foo", sb.toString()); sb.clear(); sb.appendFixedWidthPadLeft("foo", 4, '-'); assertEquals("-foo", sb.toString()); sb.clear(); sb.appendFixedWidthPadLeft("foo", 10, '-'); assertEquals(10, sb.length()); // 1234567890 assertEquals("-------foo", sb.toString()); sb.clear(); sb.setNullText("null"); sb.appendFixedWidthPadLeft(null, 5, '-'); assertEquals("-null", sb.toString()); } //----------------------------------------------------------------------- public void testAppendFixedWidthPadLeft_int() { StrBuilder sb = new StrBuilder(); sb.appendFixedWidthPadLeft(123, -1, '-'); assertEquals("", sb.toString()); sb.clear(); sb.appendFixedWidthPadLeft(123, 0, '-'); assertEquals("", sb.toString()); sb.clear(); sb.appendFixedWidthPadLeft(123, 1, '-'); assertEquals("3", sb.toString()); sb.clear(); sb.appendFixedWidthPadLeft(123, 2, '-'); assertEquals("23", sb.toString()); sb.clear(); sb.appendFixedWidthPadLeft(123, 3, '-'); assertEquals("123", sb.toString()); sb.clear(); sb.appendFixedWidthPadLeft(123, 4, '-'); assertEquals("-123", sb.toString()); sb.clear(); sb.appendFixedWidthPadLeft(123, 10, '-'); assertEquals(10, sb.length()); // 1234567890 assertEquals("-------123", sb.toString()); } //----------------------------------------------------------------------- public void testAppendFixedWidthPadRight() { StrBuilder sb = new StrBuilder(); sb.appendFixedWidthPadRight("foo", -1, '-'); assertEquals("", sb.toString()); sb.clear(); sb.appendFixedWidthPadRight("foo", 0, '-'); assertEquals("", sb.toString()); sb.clear(); sb.appendFixedWidthPadRight("foo", 1, '-'); assertEquals("f", sb.toString()); sb.clear(); sb.appendFixedWidthPadRight("foo", 2, '-'); assertEquals("fo", sb.toString()); sb.clear(); sb.appendFixedWidthPadRight("foo", 3, '-'); assertEquals("foo", sb.toString()); sb.clear(); sb.appendFixedWidthPadRight("foo", 4, '-'); assertEquals("foo-", sb.toString()); sb.clear(); sb.appendFixedWidthPadRight("foo", 10, '-'); assertEquals(10, sb.length()); // 1234567890 assertEquals("foo-------", sb.toString()); sb.clear(); sb.setNullText("null"); sb.appendFixedWidthPadRight(null, 5, '-'); assertEquals("null-", sb.toString()); } // See: http://issues.apache.org/jira/browse/LANG-299 public void testLang299() { StrBuilder sb = new StrBuilder(1); sb.appendFixedWidthPadRight("foo", 1, '-'); assertEquals("f", sb.toString()); } //----------------------------------------------------------------------- public void testAppendFixedWidthPadRight_int() { StrBuilder sb = new StrBuilder(); sb.appendFixedWidthPadRight(123, -1, '-'); assertEquals("", sb.toString()); sb.clear(); sb.appendFixedWidthPadRight(123, 0, '-'); assertEquals("", sb.toString()); sb.clear(); sb.appendFixedWidthPadRight(123, 1, '-'); assertEquals("1", sb.toString()); sb.clear(); sb.appendFixedWidthPadRight(123, 2, '-'); assertEquals("12", sb.toString()); sb.clear(); sb.appendFixedWidthPadRight(123, 3, '-'); assertEquals("123", sb.toString()); sb.clear(); sb.appendFixedWidthPadRight(123, 4, '-'); assertEquals("123-", sb.toString()); sb.clear(); sb.appendFixedWidthPadRight(123, 10, '-'); assertEquals(10, sb.length()); // 1234567890 assertEquals("123-------", sb.toString()); } //----------------------------------------------------------------------- public void testAppendAll_Array() { StrBuilder sb = new StrBuilder(); sb.appendAll((Object[]) null); assertEquals("", sb.toString()); sb.clear(); sb.appendAll(new Object[0]); assertEquals("", sb.toString()); sb.clear(); sb.appendAll(new Object[]{"foo", "bar", "baz"}); assertEquals("foobarbaz", sb.toString()); } //----------------------------------------------------------------------- public void testAppendAll_Collection() { StrBuilder sb = new StrBuilder(); sb.appendAll((Collection) null); assertEquals("", sb.toString()); sb.clear(); sb.appendAll(Collections.EMPTY_LIST); assertEquals("", sb.toString()); sb.clear(); sb.appendAll(Arrays.asList(new Object[]{"foo", "bar", "baz"})); assertEquals("foobarbaz", sb.toString()); } //----------------------------------------------------------------------- public void testAppendAll_Iterator() { StrBuilder sb = new StrBuilder(); sb.appendAll((Iterator) null); assertEquals("", sb.toString()); sb.clear(); sb.appendAll(Collections.EMPTY_LIST.iterator()); assertEquals("", sb.toString()); sb.clear(); sb.appendAll(Arrays.asList(new Object[]{"foo", "bar", "baz"}).iterator()); assertEquals("foobarbaz", sb.toString()); } //----------------------------------------------------------------------- public void testAppendWithSeparators_Array() { StrBuilder sb = new StrBuilder(); sb.appendWithSeparators((Object[]) null, ","); assertEquals("", sb.toString()); sb.clear(); sb.appendWithSeparators(new Object[0], ","); assertEquals("", sb.toString()); sb.clear(); sb.appendWithSeparators(new Object[]{"foo", "bar", "baz"}, ","); assertEquals("foo,bar,baz", sb.toString()); sb.clear(); sb.appendWithSeparators(new Object[]{"foo", "bar", "baz"}, null); assertEquals("foobarbaz", sb.toString()); sb.clear(); sb.appendWithSeparators(new Object[]{"foo", null, "baz"}, ","); assertEquals("foo,,baz", sb.toString()); } //----------------------------------------------------------------------- public void testAppendWithSeparators_Collection() { StrBuilder sb = new StrBuilder(); sb.appendWithSeparators((Collection) null, ","); assertEquals("", sb.toString()); sb.clear(); sb.appendWithSeparators(Collections.EMPTY_LIST, ","); assertEquals("", sb.toString()); sb.clear(); sb.appendWithSeparators(Arrays.asList(new Object[]{"foo", "bar", "baz"}), ","); assertEquals("foo,bar,baz", sb.toString()); sb.clear(); sb.appendWithSeparators(Arrays.asList(new Object[]{"foo", "bar", "baz"}), null); assertEquals("foobarbaz", sb.toString()); sb.clear(); sb.appendWithSeparators(Arrays.asList(new Object[]{"foo", null, "baz"}), ","); assertEquals("foo,,baz", sb.toString()); } //----------------------------------------------------------------------- public void testAppendWithSeparators_Iterator() { StrBuilder sb = new StrBuilder(); sb.appendWithSeparators((Iterator) null, ","); assertEquals("", sb.toString()); sb.clear(); sb.appendWithSeparators(Collections.EMPTY_LIST.iterator(), ","); assertEquals("", sb.toString()); sb.clear(); sb.appendWithSeparators(Arrays.asList(new Object[]{"foo", "bar", "baz"}).iterator(), ","); assertEquals("foo,bar,baz", sb.toString()); sb.clear(); sb.appendWithSeparators(Arrays.asList(new Object[]{"foo", "bar", "baz"}).iterator(), null); assertEquals("foobarbaz", sb.toString()); sb.clear(); sb.appendWithSeparators(Arrays.asList(new Object[]{"foo", null, "baz"}).iterator(), ","); assertEquals("foo,,baz", sb.toString()); } //----------------------------------------------------------------------- public void testAppendWithSeparatorsWithNullText() { StrBuilder sb = new StrBuilder(); sb.setNullText("null"); sb.appendWithSeparators(new Object[]{"foo", null, "baz"}, ","); assertEquals("foo,null,baz", sb.toString()); sb.clear(); sb.appendWithSeparators(Arrays.asList(new Object[]{"foo", null, "baz"}), ","); assertEquals("foo,null,baz", sb.toString()); } //----------------------------------------------------------------------- public void testAppendSeparator_String() { StrBuilder sb = new StrBuilder(); sb.appendSeparator(","); // no effect assertEquals("", sb.toString()); sb.append("foo"); assertEquals("foo", sb.toString()); sb.appendSeparator(","); assertEquals("foo,", sb.toString()); } //----------------------------------------------------------------------- public void testAppendSeparator_String_String() { StrBuilder sb = new StrBuilder(); final String startSeparator = "order by "; final String standardSeparator = ","; final String foo = "foo"; sb.appendSeparator(null, null); assertEquals("", sb.toString()); sb.appendSeparator(standardSeparator, null); assertEquals("", sb.toString()); sb.appendSeparator(standardSeparator, startSeparator); assertEquals(startSeparator, sb.toString()); sb.appendSeparator(null, null); assertEquals(startSeparator, sb.toString()); sb.appendSeparator(null, startSeparator); assertEquals(startSeparator, sb.toString()); sb.append(foo); assertEquals(startSeparator + foo, sb.toString()); sb.appendSeparator(standardSeparator, startSeparator); assertEquals(startSeparator + foo + standardSeparator, sb.toString()); } //----------------------------------------------------------------------- public void testAppendSeparator_char() { StrBuilder sb = new StrBuilder(); sb.appendSeparator(','); // no effect assertEquals("", sb.toString()); sb.append("foo"); assertEquals("foo", sb.toString()); sb.appendSeparator(','); assertEquals("foo,", sb.toString()); } public void testAppendSeparator_char_char() { StrBuilder sb = new StrBuilder(); final char startSeparator = ':'; final char standardSeparator = ','; final String foo = "foo"; sb.appendSeparator(standardSeparator, startSeparator); // no effect assertEquals(String.valueOf(startSeparator), sb.toString()); sb.append(foo); assertEquals(String.valueOf(startSeparator) + foo, sb.toString()); sb.appendSeparator(standardSeparator, startSeparator); assertEquals(String.valueOf(startSeparator) + foo + standardSeparator, sb.toString()); } //----------------------------------------------------------------------- public void testAppendSeparator_String_int() { StrBuilder sb = new StrBuilder(); sb.appendSeparator(",", 0); // no effect assertEquals("", sb.toString()); sb.append("foo"); assertEquals("foo", sb.toString()); sb.appendSeparator(",", 1); assertEquals("foo,", sb.toString()); sb.appendSeparator(",", -1); // no effect assertEquals("foo,", sb.toString()); } //----------------------------------------------------------------------- public void testAppendSeparator_char_int() { StrBuilder sb = new StrBuilder(); sb.appendSeparator(',', 0); // no effect assertEquals("", sb.toString()); sb.append("foo"); assertEquals("foo", sb.toString()); sb.appendSeparator(',', 1); assertEquals("foo,", sb.toString()); sb.appendSeparator(',', -1); // no effect assertEquals("foo,", sb.toString()); } //----------------------------------------------------------------------- public void testInsert() { StrBuilder sb = new StrBuilder(); sb.append("barbaz"); assertEquals("barbaz", sb.toString()); try { sb.insert(-1, FOO); fail("insert(-1, Object) expected StringIndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // expected } try { sb.insert(7, FOO); fail("insert(7, Object) expected StringIndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // expected } sb.insert(0, (Object) null); assertEquals("barbaz", sb.toString()); sb.insert(0, FOO); assertEquals("foobarbaz", sb.toString()); sb.clear(); sb.append("barbaz"); assertEquals("barbaz", sb.toString()); try { sb.insert(-1, "foo"); fail("insert(-1, String) expected StringIndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // expected } try { sb.insert(7, "foo"); fail("insert(7, String) expected StringIndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // expected } sb.insert(0, (String) null); assertEquals("barbaz", sb.toString()); sb.insert(0, "foo"); assertEquals("foobarbaz", sb.toString()); sb.clear(); sb.append("barbaz"); assertEquals("barbaz", sb.toString()); try { sb.insert(-1, new char[]{'f', 'o', 'o'}); fail("insert(-1, char[]) expected StringIndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // expected } try { sb.insert(7, new char[]{'f', 'o', 'o'}); fail("insert(7, char[]) expected StringIndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // expected } sb.insert(0, (char[]) null); assertEquals("barbaz", sb.toString()); sb.insert(0, new char[0]); assertEquals("barbaz", sb.toString()); sb.insert(0, new char[]{'f', 'o', 'o'}); assertEquals("foobarbaz", sb.toString()); sb.clear(); sb.append("barbaz"); assertEquals("barbaz", sb.toString()); try { sb.insert(-1, new char[]{'a', 'b', 'c', 'f', 'o', 'o', 'd', 'e', 'f'}, 3, 3); fail("insert(-1, char[], 3, 3) expected StringIndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // expected } try { sb.insert(7, new char[]{'a', 'b', 'c', 'f', 'o', 'o', 'd', 'e', 'f'}, 3, 3); fail("insert(7, char[], 3, 3) expected StringIndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // expected } sb.insert(0, (char[]) null, 0, 0); assertEquals("barbaz", sb.toString()); sb.insert(0, new char[0], 0, 0); assertEquals("barbaz", sb.toString()); try { sb.insert(0, new char[]{'a', 'b', 'c', 'f', 'o', 'o', 'd', 'e', 'f'}, -1, 3); fail("insert(0, char[], -1, 3) expected StringIndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // expected } try { sb.insert(0, new char[]{'a', 'b', 'c', 'f', 'o', 'o', 'd', 'e', 'f'}, 10, 3); fail("insert(0, char[], 10, 3) expected StringIndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // expected } try { sb.insert(0, new char[]{'a', 'b', 'c', 'f', 'o', 'o', 'd', 'e', 'f'}, 0, -1); fail("insert(0, char[], 0, -1) expected StringIndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // expected } try { sb.insert(0, new char[]{'a', 'b', 'c', 'f', 'o', 'o', 'd', 'e', 'f'}, 0, 10); fail("insert(0, char[], 0, 10) expected StringIndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // expected } sb.insert(0, new char[]{'a', 'b', 'c', 'f', 'o', 'o', 'd', 'e', 'f'}, 0, 0); assertEquals("barbaz", sb.toString()); sb.insert(0, new char[]{'a', 'b', 'c', 'f', 'o', 'o', 'd', 'e', 'f'}, 3, 3); assertEquals("foobarbaz", sb.toString()); sb.clear(); sb.append("barbaz"); assertEquals("barbaz", sb.toString()); try { sb.insert(-1, true); fail("insert(-1, boolean) expected StringIndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // expected } try { sb.insert(7, true); fail("insert(7, boolean) expected StringIndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // expected } sb.insert(0, true); assertEquals("truebarbaz", sb.toString()); sb.insert(0, false); assertEquals("falsetruebarbaz", sb.toString()); sb.clear(); sb.append("barbaz"); assertEquals("barbaz", sb.toString()); try { sb.insert(-1, '!'); fail("insert(-1, char) expected StringIndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // expected } try { sb.insert(7, '!'); fail("insert(7, char) expected StringIndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // expected } sb.insert(0, '!'); assertEquals("!barbaz", sb.toString()); sb.clear(); sb.append("barbaz"); assertEquals("barbaz", sb.toString()); try { sb.insert(-1, 0); fail("insert(-1, int) expected StringIndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // expected } try { sb.insert(7, 0); fail("insert(7, int) expected StringIndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // expected } sb.insert(0, '0'); assertEquals("0barbaz", sb.toString()); sb.clear(); sb.append("barbaz"); assertEquals("barbaz", sb.toString()); try { sb.insert(-1, 1L); fail("insert(-1, long) expected StringIndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // expected } try { sb.insert(7, 1L); fail("insert(7, long) expected StringIndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // expected } sb.insert(0, 1L); assertEquals("1barbaz", sb.toString()); sb.clear(); sb.append("barbaz"); assertEquals("barbaz", sb.toString()); try { sb.insert(-1, 2.3F); fail("insert(-1, float) expected StringIndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // expected } try { sb.insert(7, 2.3F); fail("insert(7, float) expected StringIndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // expected } sb.insert(0, 2.3F); assertEquals("2.3barbaz", sb.toString()); sb.clear(); sb.append("barbaz"); assertEquals("barbaz", sb.toString()); try { sb.insert(-1, 4.5D); fail("insert(-1, double) expected StringIndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // expected } try { sb.insert(7, 4.5D); fail("insert(7, double) expected StringIndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // expected } sb.insert(0, 4.5D); assertEquals("4.5barbaz", sb.toString()); } //----------------------------------------------------------------------- public void testInsertWithNullText() { StrBuilder sb = new StrBuilder(); sb.setNullText("null"); sb.append("barbaz"); assertEquals("barbaz", sb.toString()); try { sb.insert(-1, FOO); fail("insert(-1, Object) expected StringIndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // expected } try { sb.insert(7, FOO); fail("insert(7, Object) expected StringIndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // expected } sb.insert(0, (Object) null); assertEquals("nullbarbaz", sb.toString()); sb.insert(0, FOO); assertEquals("foonullbarbaz", sb.toString()); sb.clear(); sb.append("barbaz"); assertEquals("barbaz", sb.toString()); try { sb.insert(-1, "foo"); fail("insert(-1, String) expected StringIndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // expected } try { sb.insert(7, "foo"); fail("insert(7, String) expected StringIndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // expected } sb.insert(0, (String) null); assertEquals("nullbarbaz", sb.toString()); sb.insert(0, "foo"); assertEquals("foonullbarbaz", sb.toString()); sb.insert(0, (char[]) null); assertEquals("nullfoonullbarbaz", sb.toString()); sb.insert(0, (char[]) null, 0, 0); assertEquals("nullnullfoonullbarbaz", sb.toString()); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/text/StrBuilderTest.java100644 0 0 203612 11513702433 25573 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.text; import java.io.Reader; import java.io.Writer; import java.util.Arrays; import junit.framework.TestCase; import org.apache.commons.lang.ArrayUtils; /** * Unit tests for {@link org.apache.commons.lang.text.StrBuilder}. * * @author Michael Heuer * @version $Id: StrBuilderTest.java 1057349 2011-01-10 20:40:49Z niallp $ */ public class StrBuilderTest extends TestCase { /** * Create a new test case with the specified name. * * @param name * name */ public StrBuilderTest(String name) { super(name); } //----------------------------------------------------------------------- public void testConstructors() { StrBuilder sb0 = new StrBuilder(); assertEquals(32, sb0.capacity()); assertEquals(0, sb0.length()); assertEquals(0, sb0.size()); StrBuilder sb1 = new StrBuilder(32); assertEquals(32, sb1.capacity()); assertEquals(0, sb1.length()); assertEquals(0, sb1.size()); StrBuilder sb2 = new StrBuilder(0); assertEquals(32, sb2.capacity()); assertEquals(0, sb2.length()); assertEquals(0, sb2.size()); StrBuilder sb3 = new StrBuilder(-1); assertEquals(32, sb3.capacity()); assertEquals(0, sb3.length()); assertEquals(0, sb3.size()); StrBuilder sb4 = new StrBuilder(1); assertEquals(1, sb4.capacity()); assertEquals(0, sb4.length()); assertEquals(0, sb4.size()); StrBuilder sb5 = new StrBuilder((String) null); assertEquals(32, sb5.capacity()); assertEquals(0, sb5.length()); assertEquals(0, sb5.size()); StrBuilder sb6 = new StrBuilder(""); assertEquals(32, sb6.capacity()); assertEquals(0, sb6.length()); assertEquals(0, sb6.size()); StrBuilder sb7 = new StrBuilder("foo"); assertEquals(35, sb7.capacity()); assertEquals(3, sb7.length()); assertEquals(3, sb7.size()); } //----------------------------------------------------------------------- public void testChaining() { StrBuilder sb = new StrBuilder(); assertSame(sb, sb.setNewLineText(null)); assertSame(sb, sb.setNullText(null)); assertSame(sb, sb.setLength(1)); assertSame(sb, sb.setCharAt(0, 'a')); assertSame(sb, sb.ensureCapacity(0)); assertSame(sb, sb.minimizeCapacity()); assertSame(sb, sb.clear()); assertSame(sb, sb.reverse()); assertSame(sb, sb.trim()); } //----------------------------------------------------------------------- public void testGetSetNewLineText() { StrBuilder sb = new StrBuilder(); assertEquals(null, sb.getNewLineText()); sb.setNewLineText("#"); assertEquals("#", sb.getNewLineText()); sb.setNewLineText(""); assertEquals("", sb.getNewLineText()); sb.setNewLineText((String) null); assertEquals(null, sb.getNewLineText()); } //----------------------------------------------------------------------- public void testGetSetNullText() { StrBuilder sb = new StrBuilder(); assertEquals(null, sb.getNullText()); sb.setNullText("null"); assertEquals("null", sb.getNullText()); sb.setNullText(""); assertEquals(null, sb.getNullText()); sb.setNullText("NULL"); assertEquals("NULL", sb.getNullText()); sb.setNullText((String) null); assertEquals(null, sb.getNullText()); } //----------------------------------------------------------------------- public void testCapacityAndLength() { StrBuilder sb = new StrBuilder(); assertEquals(32, sb.capacity()); assertEquals(0, sb.length()); assertEquals(0, sb.size()); assertTrue(sb.isEmpty()); sb.minimizeCapacity(); assertEquals(0, sb.capacity()); assertEquals(0, sb.length()); assertEquals(0, sb.size()); assertTrue(sb.isEmpty()); sb.ensureCapacity(32); assertTrue(sb.capacity() >= 32); assertEquals(0, sb.length()); assertEquals(0, sb.size()); assertTrue(sb.isEmpty()); sb.append("foo"); assertTrue(sb.capacity() >= 32); assertEquals(3, sb.length()); assertEquals(3, sb.size()); assertTrue(sb.isEmpty() == false); sb.clear(); assertTrue(sb.capacity() >= 32); assertEquals(0, sb.length()); assertEquals(0, sb.size()); assertTrue(sb.isEmpty()); sb.append("123456789012345678901234567890123"); assertTrue(sb.capacity() > 32); assertEquals(33, sb.length()); assertEquals(33, sb.size()); assertTrue(sb.isEmpty() == false); sb.ensureCapacity(16); assertTrue(sb.capacity() > 16); assertEquals(33, sb.length()); assertEquals(33, sb.size()); assertTrue(sb.isEmpty() == false); sb.minimizeCapacity(); assertEquals(33, sb.capacity()); assertEquals(33, sb.length()); assertEquals(33, sb.size()); assertTrue(sb.isEmpty() == false); try { sb.setLength(-1); fail("setLength(-1) expected StringIndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // expected } sb.setLength(33); assertEquals(33, sb.capacity()); assertEquals(33, sb.length()); assertEquals(33, sb.size()); assertTrue(sb.isEmpty() == false); sb.setLength(16); assertTrue(sb.capacity() >= 16); assertEquals(16, sb.length()); assertEquals(16, sb.size()); assertEquals("1234567890123456", sb.toString()); assertTrue(sb.isEmpty() == false); sb.setLength(32); assertTrue(sb.capacity() >= 32); assertEquals(32, sb.length()); assertEquals(32, sb.size()); assertEquals("1234567890123456\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", sb.toString()); assertTrue(sb.isEmpty() == false); sb.setLength(0); assertTrue(sb.capacity() >= 32); assertEquals(0, sb.length()); assertEquals(0, sb.size()); assertTrue(sb.isEmpty()); } //----------------------------------------------------------------------- public void testLength() { StrBuilder sb = new StrBuilder(); assertEquals(0, sb.length()); sb.append("Hello"); assertEquals(5, sb.length()); } public void testSetLength() { StrBuilder sb = new StrBuilder(); sb.append("Hello"); sb.setLength(2); // shorten assertEquals("He", sb.toString()); sb.setLength(2); // no change assertEquals("He", sb.toString()); sb.setLength(3); // lengthen assertEquals("He\0", sb.toString()); try { sb.setLength(-1); fail("setLength(-1) expected StringIndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // expected } } //----------------------------------------------------------------------- public void testClone() throws Exception { StrBuilder sb = new StrBuilder(); sb.setNewLineText("NEWLINE"); sb.setNullText("NULLVALUE"); sb.append("abc"); assertEquals("before", "abc", sb.toString()); // Clone StrBuilder clone = (StrBuilder)sb.clone(); assertEquals("capacity", sb.capacity(), clone.capacity()); assertEquals("size", sb.size(), clone.size()); assertEquals("toString", sb.toString(), clone.toString()); // Modify Original sb.append("def"); assertEquals("original-1", "abcdef", sb.toString()); assertEquals("different", "abc", clone.toString()); // Modify Clone clone.append((String)null); assertEquals("append null", "abcNULLVALUE", clone.toString()); clone.appendNewLine(); assertEquals("append newline", "abcNULLVALUENEWLINE", clone.toString()); assertEquals("original-2", "abcdef", sb.toString()); } //----------------------------------------------------------------------- public void testCapacity() { StrBuilder sb = new StrBuilder(); assertEquals(sb.buffer.length, sb.capacity()); sb.append("HelloWorldHelloWorldHelloWorldHelloWorld"); assertEquals(sb.buffer.length, sb.capacity()); } public void testEnsureCapacity() { StrBuilder sb = new StrBuilder(); sb.ensureCapacity(2); assertEquals(true, sb.capacity() >= 2); sb.ensureCapacity(-1); assertEquals(true, sb.capacity() >= 0); sb.append("HelloWorld"); sb.ensureCapacity(40); assertEquals(true, sb.capacity() >= 40); } public void testMinimizeCapacity() { StrBuilder sb = new StrBuilder(); sb.minimizeCapacity(); assertEquals(0, sb.capacity()); sb.append("HelloWorld"); sb.minimizeCapacity(); assertEquals(10, sb.capacity()); } //----------------------------------------------------------------------- public void testSize() { StrBuilder sb = new StrBuilder(); assertEquals(0, sb.size()); sb.append("Hello"); assertEquals(5, sb.size()); } public void testIsEmpty() { StrBuilder sb = new StrBuilder(); assertEquals(true, sb.isEmpty()); sb.append("Hello"); assertEquals(false, sb.isEmpty()); sb.clear(); assertEquals(true, sb.isEmpty()); } public void testClear() { StrBuilder sb = new StrBuilder(); sb.append("Hello"); sb.clear(); assertEquals(0, sb.length()); assertEquals(true, sb.buffer.length >= 5); } //----------------------------------------------------------------------- public void testCharAt() { StrBuilder sb = new StrBuilder(); try { sb.charAt(0); fail("charAt(0) expected IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // expected } try { sb.charAt(-1); fail("charAt(-1) expected IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // expected } sb.append("foo"); assertEquals('f', sb.charAt(0)); assertEquals('o', sb.charAt(1)); assertEquals('o', sb.charAt(2)); try { sb.charAt(-1); fail("charAt(-1) expected IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // expected } try { sb.charAt(3); fail("charAt(3) expected IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // expected } } //----------------------------------------------------------------------- public void testSetCharAt() { StrBuilder sb = new StrBuilder(); try { sb.setCharAt(0, 'f'); fail("setCharAt(0,) expected IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // expected } try { sb.setCharAt(-1, 'f'); fail("setCharAt(-1,) expected IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // expected } sb.append("foo"); sb.setCharAt(0, 'b'); sb.setCharAt(1, 'a'); sb.setCharAt(2, 'r'); try { sb.setCharAt(3, '!'); fail("setCharAt(3,) expected IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { // expected } assertEquals("bar", sb.toString()); } //----------------------------------------------------------------------- public void testDeleteCharAt() { StrBuilder sb = new StrBuilder("abc"); sb.deleteCharAt(0); assertEquals("bc", sb.toString()); try { sb.deleteCharAt(1000); fail("Expected IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) {} } //----------------------------------------------------------------------- public void testToCharArray() { StrBuilder sb = new StrBuilder(); assertEquals(ArrayUtils.EMPTY_CHAR_ARRAY, sb.toCharArray()); char[] a = sb.toCharArray(); assertNotNull("toCharArray() result is null", a); assertEquals("toCharArray() result is too large", 0, a.length); sb.append("junit"); a = sb.toCharArray(); assertEquals("toCharArray() result incorrect length", 5, a.length); assertTrue("toCharArray() result does not match", Arrays.equals("junit".toCharArray(), a)); } public void testToCharArrayIntInt() { StrBuilder sb = new StrBuilder(); assertEquals(ArrayUtils.EMPTY_CHAR_ARRAY, sb.toCharArray(0, 0)); sb.append("junit"); char[] a = sb.toCharArray(0, 20); // too large test assertEquals("toCharArray(int,int) result incorrect length", 5, a.length); assertTrue("toCharArray(int,int) result does not match", Arrays.equals("junit".toCharArray(), a)); a = sb.toCharArray(0, 4); assertEquals("toCharArray(int,int) result incorrect length", 4, a.length); assertTrue("toCharArray(int,int) result does not match", Arrays.equals("juni".toCharArray(), a)); a = sb.toCharArray(0, 4); assertEquals("toCharArray(int,int) result incorrect length", 4, a.length); assertTrue("toCharArray(int,int) result does not match", Arrays.equals("juni".toCharArray(), a)); a = sb.toCharArray(0, 1); assertNotNull("toCharArray(int,int) result is null", a); try { sb.toCharArray(-1, 5); fail("no string index out of bound on -1"); } catch (IndexOutOfBoundsException e) { } try { sb.toCharArray(6, 5); fail("no string index out of bound on -1"); } catch (IndexOutOfBoundsException e) { } } public void testGetChars ( ) { StrBuilder sb = new StrBuilder(); char[] input = new char[10]; char[] a = sb.getChars(input); assertSame (input, a); assertTrue(Arrays.equals(new char[10], a)); sb.append("junit"); a = sb.getChars(input); assertSame(input, a); assertTrue(Arrays.equals(new char[] {'j','u','n','i','t',0,0,0,0,0},a)); a = sb.getChars(null); assertNotSame(input,a); assertEquals(5,a.length); assertTrue(Arrays.equals("junit".toCharArray(),a)); input = new char[5]; a = sb.getChars(input); assertSame(input, a); input = new char[4]; a = sb.getChars(input); assertNotSame(input, a); } public void testGetCharsIntIntCharArrayInt( ) { StrBuilder sb = new StrBuilder(); sb.append("junit"); char[] a = new char[5]; sb.getChars(0,5,a,0); assertTrue(Arrays.equals(new char[] {'j','u','n','i','t'},a)); a = new char[5]; sb.getChars(0,2,a,3); assertTrue(Arrays.equals(new char[] {0,0,0,'j','u'},a)); try { sb.getChars(-1,0,a,0); fail("no exception"); } catch (IndexOutOfBoundsException e) { } try { sb.getChars(0,-1,a,0); fail("no exception"); } catch (IndexOutOfBoundsException e) { } try { sb.getChars(0,20,a,0); fail("no exception"); } catch (IndexOutOfBoundsException e) { } try { sb.getChars(4,2,a,0); fail("no exception"); } catch (IndexOutOfBoundsException e) { } } //----------------------------------------------------------------------- public void testDeleteIntInt() { StrBuilder sb = new StrBuilder("abc"); sb.delete(0, 1); assertEquals("bc", sb.toString()); sb.delete(1, 2); assertEquals("b", sb.toString()); sb.delete(0, 1); assertEquals("", sb.toString()); sb.delete(0, 1000); assertEquals("", sb.toString()); try { sb.delete(1, 2); fail("Expected IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) {} try { sb.delete(-1, 1); fail("Expected IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) {} sb = new StrBuilder("anything"); try { sb.delete(2, 1); fail("Expected IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) {} } //----------------------------------------------------------------------- public void testDeleteAll_char() { StrBuilder sb = new StrBuilder("abcbccba"); sb.deleteAll('X'); assertEquals("abcbccba", sb.toString()); sb.deleteAll('a'); assertEquals("bcbccb", sb.toString()); sb.deleteAll('c'); assertEquals("bbb", sb.toString()); sb.deleteAll('b'); assertEquals("", sb.toString()); sb = new StrBuilder(""); sb.deleteAll('b'); assertEquals("", sb.toString()); } public void testDeleteFirst_char() { StrBuilder sb = new StrBuilder("abcba"); sb.deleteFirst('X'); assertEquals("abcba", sb.toString()); sb.deleteFirst('a'); assertEquals("bcba", sb.toString()); sb.deleteFirst('c'); assertEquals("bba", sb.toString()); sb.deleteFirst('b'); assertEquals("ba", sb.toString()); sb = new StrBuilder(""); sb.deleteFirst('b'); assertEquals("", sb.toString()); } // ----------------------------------------------------------------------- public void testDeleteAll_String() { StrBuilder sb = new StrBuilder("abcbccba"); sb.deleteAll((String) null); assertEquals("abcbccba", sb.toString()); sb.deleteAll(""); assertEquals("abcbccba", sb.toString()); sb.deleteAll("X"); assertEquals("abcbccba", sb.toString()); sb.deleteAll("a"); assertEquals("bcbccb", sb.toString()); sb.deleteAll("c"); assertEquals("bbb", sb.toString()); sb.deleteAll("b"); assertEquals("", sb.toString()); sb = new StrBuilder("abcbccba"); sb.deleteAll("bc"); assertEquals("acba", sb.toString()); sb = new StrBuilder(""); sb.deleteAll("bc"); assertEquals("", sb.toString()); } public void testDeleteFirst_String() { StrBuilder sb = new StrBuilder("abcbccba"); sb.deleteFirst((String) null); assertEquals("abcbccba", sb.toString()); sb.deleteFirst(""); assertEquals("abcbccba", sb.toString()); sb.deleteFirst("X"); assertEquals("abcbccba", sb.toString()); sb.deleteFirst("a"); assertEquals("bcbccba", sb.toString()); sb.deleteFirst("c"); assertEquals("bbccba", sb.toString()); sb.deleteFirst("b"); assertEquals("bccba", sb.toString()); sb = new StrBuilder("abcbccba"); sb.deleteFirst("bc"); assertEquals("abccba", sb.toString()); sb = new StrBuilder(""); sb.deleteFirst("bc"); assertEquals("", sb.toString()); } // ----------------------------------------------------------------------- public void testDeleteAll_StrMatcher() { StrBuilder sb = new StrBuilder("A0xA1A2yA3"); sb.deleteAll((StrMatcher) null); assertEquals("A0xA1A2yA3", sb.toString()); sb.deleteAll(A_NUMBER_MATCHER); assertEquals("xy", sb.toString()); sb = new StrBuilder("Ax1"); sb.deleteAll(A_NUMBER_MATCHER); assertEquals("Ax1", sb.toString()); sb = new StrBuilder(""); sb.deleteAll(A_NUMBER_MATCHER); assertEquals("", sb.toString()); } public void testDeleteFirst_StrMatcher() { StrBuilder sb = new StrBuilder("A0xA1A2yA3"); sb.deleteFirst((StrMatcher) null); assertEquals("A0xA1A2yA3", sb.toString()); sb.deleteFirst(A_NUMBER_MATCHER); assertEquals("xA1A2yA3", sb.toString()); sb = new StrBuilder("Ax1"); sb.deleteFirst(A_NUMBER_MATCHER); assertEquals("Ax1", sb.toString()); sb = new StrBuilder(""); sb.deleteFirst(A_NUMBER_MATCHER); assertEquals("", sb.toString()); } // ----------------------------------------------------------------------- public void testReplace_int_int_String() { StrBuilder sb = new StrBuilder("abc"); sb.replace(0, 1, "d"); assertEquals("dbc", sb.toString()); sb.replace(0, 1, "aaa"); assertEquals("aaabc", sb.toString()); sb.replace(0, 3, ""); assertEquals("bc", sb.toString()); sb.replace(1, 2, (String) null); assertEquals("b", sb.toString()); sb.replace(1, 1000, "text"); assertEquals("btext", sb.toString()); sb.replace(0, 1000, "text"); assertEquals("text", sb.toString()); sb = new StrBuilder("atext"); sb.replace(1, 1, "ny"); assertEquals("anytext", sb.toString()); try { sb.replace(2, 1, "anything"); fail("Expected IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) {} sb = new StrBuilder(); try { sb.replace(1, 2, "anything"); fail("Expected IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) {} try { sb.replace(-1, 1, "anything"); fail("Expected IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) {} } //----------------------------------------------------------------------- public void testReplaceAll_char_char() { StrBuilder sb = new StrBuilder("abcbccba"); sb.replaceAll('x', 'y'); assertEquals("abcbccba", sb.toString()); sb.replaceAll('a', 'd'); assertEquals("dbcbccbd", sb.toString()); sb.replaceAll('b', 'e'); assertEquals("dececced", sb.toString()); sb.replaceAll('c', 'f'); assertEquals("defeffed", sb.toString()); sb.replaceAll('d', 'd'); assertEquals("defeffed", sb.toString()); } //----------------------------------------------------------------------- public void testReplaceFirst_char_char() { StrBuilder sb = new StrBuilder("abcbccba"); sb.replaceFirst('x', 'y'); assertEquals("abcbccba", sb.toString()); sb.replaceFirst('a', 'd'); assertEquals("dbcbccba", sb.toString()); sb.replaceFirst('b', 'e'); assertEquals("decbccba", sb.toString()); sb.replaceFirst('c', 'f'); assertEquals("defbccba", sb.toString()); sb.replaceFirst('d', 'd'); assertEquals("defbccba", sb.toString()); } //----------------------------------------------------------------------- public void testReplaceAll_String_String() { StrBuilder sb = new StrBuilder("abcbccba"); sb.replaceAll((String) null, null); assertEquals("abcbccba", sb.toString()); sb.replaceAll((String) null, "anything"); assertEquals("abcbccba", sb.toString()); sb.replaceAll("", null); assertEquals("abcbccba", sb.toString()); sb.replaceAll("", "anything"); assertEquals("abcbccba", sb.toString()); sb.replaceAll("x", "y"); assertEquals("abcbccba", sb.toString()); sb.replaceAll("a", "d"); assertEquals("dbcbccbd", sb.toString()); sb.replaceAll("d", null); assertEquals("bcbccb", sb.toString()); sb.replaceAll("cb", "-"); assertEquals("b-c-", sb.toString()); sb = new StrBuilder("abcba"); sb.replaceAll("b", "xbx"); assertEquals("axbxcxbxa", sb.toString()); sb = new StrBuilder("bb"); sb.replaceAll("b", "xbx"); assertEquals("xbxxbx", sb.toString()); } public void testReplaceFirst_String_String() { StrBuilder sb = new StrBuilder("abcbccba"); sb.replaceFirst((String) null, null); assertEquals("abcbccba", sb.toString()); sb.replaceFirst((String) null, "anything"); assertEquals("abcbccba", sb.toString()); sb.replaceFirst("", null); assertEquals("abcbccba", sb.toString()); sb.replaceFirst("", "anything"); assertEquals("abcbccba", sb.toString()); sb.replaceFirst("x", "y"); assertEquals("abcbccba", sb.toString()); sb.replaceFirst("a", "d"); assertEquals("dbcbccba", sb.toString()); sb.replaceFirst("d", null); assertEquals("bcbccba", sb.toString()); sb.replaceFirst("cb", "-"); assertEquals("b-ccba", sb.toString()); sb = new StrBuilder("abcba"); sb.replaceFirst("b", "xbx"); assertEquals("axbxcba", sb.toString()); sb = new StrBuilder("bb"); sb.replaceFirst("b", "xbx"); assertEquals("xbxb", sb.toString()); } //----------------------------------------------------------------------- public void testReplaceAll_StrMatcher_String() { StrBuilder sb = new StrBuilder("abcbccba"); sb.replaceAll((StrMatcher) null, null); assertEquals("abcbccba", sb.toString()); sb.replaceAll((StrMatcher) null, "anything"); assertEquals("abcbccba", sb.toString()); sb.replaceAll(StrMatcher.noneMatcher(), null); assertEquals("abcbccba", sb.toString()); sb.replaceAll(StrMatcher.noneMatcher(), "anything"); assertEquals("abcbccba", sb.toString()); sb.replaceAll(StrMatcher.charMatcher('x'), "y"); assertEquals("abcbccba", sb.toString()); sb.replaceAll(StrMatcher.charMatcher('a'), "d"); assertEquals("dbcbccbd", sb.toString()); sb.replaceAll(StrMatcher.charMatcher('d'), null); assertEquals("bcbccb", sb.toString()); sb.replaceAll(StrMatcher.stringMatcher("cb"), "-"); assertEquals("b-c-", sb.toString()); sb = new StrBuilder("abcba"); sb.replaceAll(StrMatcher.charMatcher('b'), "xbx"); assertEquals("axbxcxbxa", sb.toString()); sb = new StrBuilder("bb"); sb.replaceAll(StrMatcher.charMatcher('b'), "xbx"); assertEquals("xbxxbx", sb.toString()); sb = new StrBuilder("A1-A2A3-A4"); sb.replaceAll(A_NUMBER_MATCHER, "***"); assertEquals("***-******-***", sb.toString()); } public void testReplaceFirst_StrMatcher_String() { StrBuilder sb = new StrBuilder("abcbccba"); sb.replaceFirst((StrMatcher) null, null); assertEquals("abcbccba", sb.toString()); sb.replaceFirst((StrMatcher) null, "anything"); assertEquals("abcbccba", sb.toString()); sb.replaceFirst(StrMatcher.noneMatcher(), null); assertEquals("abcbccba", sb.toString()); sb.replaceFirst(StrMatcher.noneMatcher(), "anything"); assertEquals("abcbccba", sb.toString()); sb.replaceFirst(StrMatcher.charMatcher('x'), "y"); assertEquals("abcbccba", sb.toString()); sb.replaceFirst(StrMatcher.charMatcher('a'), "d"); assertEquals("dbcbccba", sb.toString()); sb.replaceFirst(StrMatcher.charMatcher('d'), null); assertEquals("bcbccba", sb.toString()); sb.replaceFirst(StrMatcher.stringMatcher("cb"), "-"); assertEquals("b-ccba", sb.toString()); sb = new StrBuilder("abcba"); sb.replaceFirst(StrMatcher.charMatcher('b'), "xbx"); assertEquals("axbxcba", sb.toString()); sb = new StrBuilder("bb"); sb.replaceFirst(StrMatcher.charMatcher('b'), "xbx"); assertEquals("xbxb", sb.toString()); sb = new StrBuilder("A1-A2A3-A4"); sb.replaceFirst(A_NUMBER_MATCHER, "***"); assertEquals("***-A2A3-A4", sb.toString()); } //----------------------------------------------------------------------- public void testReplace_StrMatcher_String_int_int_int_VaryMatcher() { StrBuilder sb = new StrBuilder("abcbccba"); sb.replace((StrMatcher) null, "x", 0, sb.length(), -1); assertEquals("abcbccba", sb.toString()); sb.replace(StrMatcher.charMatcher('a'), "x", 0, sb.length(), -1); assertEquals("xbcbccbx", sb.toString()); sb.replace(StrMatcher.stringMatcher("cb"), "x", 0, sb.length(), -1); assertEquals("xbxcxx", sb.toString()); sb = new StrBuilder("A1-A2A3-A4"); sb.replace(A_NUMBER_MATCHER, "***", 0, sb.length(), -1); assertEquals("***-******-***", sb.toString()); sb = new StrBuilder(); sb.replace(A_NUMBER_MATCHER, "***", 0, sb.length(), -1); assertEquals("", sb.toString()); } public void testReplace_StrMatcher_String_int_int_int_VaryReplace() { StrBuilder sb = new StrBuilder("abcbccba"); sb.replace(StrMatcher.stringMatcher("cb"), "cb", 0, sb.length(), -1); assertEquals("abcbccba", sb.toString()); sb = new StrBuilder("abcbccba"); sb.replace(StrMatcher.stringMatcher("cb"), "-", 0, sb.length(), -1); assertEquals("ab-c-a", sb.toString()); sb = new StrBuilder("abcbccba"); sb.replace(StrMatcher.stringMatcher("cb"), "+++", 0, sb.length(), -1); assertEquals("ab+++c+++a", sb.toString()); sb = new StrBuilder("abcbccba"); sb.replace(StrMatcher.stringMatcher("cb"), "", 0, sb.length(), -1); assertEquals("abca", sb.toString()); sb = new StrBuilder("abcbccba"); sb.replace(StrMatcher.stringMatcher("cb"), null, 0, sb.length(), -1); assertEquals("abca", sb.toString()); } public void testReplace_StrMatcher_String_int_int_int_VaryStartIndex() { StrBuilder sb = new StrBuilder("aaxaaaayaa"); sb.replace(StrMatcher.stringMatcher("aa"), "-", 0, sb.length(), -1); assertEquals("-x--y-", sb.toString()); sb = new StrBuilder("aaxaaaayaa"); sb.replace(StrMatcher.stringMatcher("aa"), "-", 1, sb.length(), -1); assertEquals("aax--y-", sb.toString()); sb = new StrBuilder("aaxaaaayaa"); sb.replace(StrMatcher.stringMatcher("aa"), "-", 2, sb.length(), -1); assertEquals("aax--y-", sb.toString()); sb = new StrBuilder("aaxaaaayaa"); sb.replace(StrMatcher.stringMatcher("aa"), "-", 3, sb.length(), -1); assertEquals("aax--y-", sb.toString()); sb = new StrBuilder("aaxaaaayaa"); sb.replace(StrMatcher.stringMatcher("aa"), "-", 4, sb.length(), -1); assertEquals("aaxa-ay-", sb.toString()); sb = new StrBuilder("aaxaaaayaa"); sb.replace(StrMatcher.stringMatcher("aa"), "-", 5, sb.length(), -1); assertEquals("aaxaa-y-", sb.toString()); sb = new StrBuilder("aaxaaaayaa"); sb.replace(StrMatcher.stringMatcher("aa"), "-", 6, sb.length(), -1); assertEquals("aaxaaaay-", sb.toString()); sb = new StrBuilder("aaxaaaayaa"); sb.replace(StrMatcher.stringMatcher("aa"), "-", 7, sb.length(), -1); assertEquals("aaxaaaay-", sb.toString()); sb = new StrBuilder("aaxaaaayaa"); sb.replace(StrMatcher.stringMatcher("aa"), "-", 8, sb.length(), -1); assertEquals("aaxaaaay-", sb.toString()); sb = new StrBuilder("aaxaaaayaa"); sb.replace(StrMatcher.stringMatcher("aa"), "-", 9, sb.length(), -1); assertEquals("aaxaaaayaa", sb.toString()); sb = new StrBuilder("aaxaaaayaa"); sb.replace(StrMatcher.stringMatcher("aa"), "-", 10, sb.length(), -1); assertEquals("aaxaaaayaa", sb.toString()); sb = new StrBuilder("aaxaaaayaa"); try { sb.replace(StrMatcher.stringMatcher("aa"), "-", 11, sb.length(), -1); fail(); } catch (IndexOutOfBoundsException ex) {} assertEquals("aaxaaaayaa", sb.toString()); sb = new StrBuilder("aaxaaaayaa"); try { sb.replace(StrMatcher.stringMatcher("aa"), "-", -1, sb.length(), -1); fail(); } catch (IndexOutOfBoundsException ex) {} assertEquals("aaxaaaayaa", sb.toString()); } public void testReplace_StrMatcher_String_int_int_int_VaryEndIndex() { StrBuilder sb = new StrBuilder("aaxaaaayaa"); sb.replace(StrMatcher.stringMatcher("aa"), "-", 0, 0, -1); assertEquals("aaxaaaayaa", sb.toString()); sb = new StrBuilder("aaxaaaayaa"); sb.replace(StrMatcher.stringMatcher("aa"), "-", 0, 2, -1); assertEquals("-xaaaayaa", sb.toString()); sb = new StrBuilder("aaxaaaayaa"); sb.replace(StrMatcher.stringMatcher("aa"), "-", 0, 3, -1); assertEquals("-xaaaayaa", sb.toString()); sb = new StrBuilder("aaxaaaayaa"); sb.replace(StrMatcher.stringMatcher("aa"), "-", 0, 4, -1); assertEquals("-xaaaayaa", sb.toString()); sb = new StrBuilder("aaxaaaayaa"); sb.replace(StrMatcher.stringMatcher("aa"), "-", 0, 5, -1); assertEquals("-x-aayaa", sb.toString()); sb = new StrBuilder("aaxaaaayaa"); sb.replace(StrMatcher.stringMatcher("aa"), "-", 0, 6, -1); assertEquals("-x-aayaa", sb.toString()); sb = new StrBuilder("aaxaaaayaa"); sb.replace(StrMatcher.stringMatcher("aa"), "-", 0, 7, -1); assertEquals("-x--yaa", sb.toString()); sb = new StrBuilder("aaxaaaayaa"); sb.replace(StrMatcher.stringMatcher("aa"), "-", 0, 8, -1); assertEquals("-x--yaa", sb.toString()); sb = new StrBuilder("aaxaaaayaa"); sb.replace(StrMatcher.stringMatcher("aa"), "-", 0, 9, -1); assertEquals("-x--yaa", sb.toString()); sb = new StrBuilder("aaxaaaayaa"); sb.replace(StrMatcher.stringMatcher("aa"), "-", 0, 10, -1); assertEquals("-x--y-", sb.toString()); sb = new StrBuilder("aaxaaaayaa"); sb.replace(StrMatcher.stringMatcher("aa"), "-", 0, 1000, -1); assertEquals("-x--y-", sb.toString()); sb = new StrBuilder("aaxaaaayaa"); try { sb.replace(StrMatcher.stringMatcher("aa"), "-", 2, 1, -1); fail(); } catch (IndexOutOfBoundsException ex) {} assertEquals("aaxaaaayaa", sb.toString()); } public void testReplace_StrMatcher_String_int_int_int_VaryCount() { StrBuilder sb = new StrBuilder("aaxaaaayaa"); sb.replace(StrMatcher.stringMatcher("aa"), "-", 0, 10, -1); assertEquals("-x--y-", sb.toString()); sb = new StrBuilder("aaxaaaayaa"); sb.replace(StrMatcher.stringMatcher("aa"), "-", 0, 10, 0); assertEquals("aaxaaaayaa", sb.toString()); sb = new StrBuilder("aaxaaaayaa"); sb.replace(StrMatcher.stringMatcher("aa"), "-", 0, 10, 1); assertEquals("-xaaaayaa", sb.toString()); sb = new StrBuilder("aaxaaaayaa"); sb.replace(StrMatcher.stringMatcher("aa"), "-", 0, 10, 2); assertEquals("-x-aayaa", sb.toString()); sb = new StrBuilder("aaxaaaayaa"); sb.replace(StrMatcher.stringMatcher("aa"), "-", 0, 10, 3); assertEquals("-x--yaa", sb.toString()); sb = new StrBuilder("aaxaaaayaa"); sb.replace(StrMatcher.stringMatcher("aa"), "-", 0, 10, 4); assertEquals("-x--y-", sb.toString()); sb = new StrBuilder("aaxaaaayaa"); sb.replace(StrMatcher.stringMatcher("aa"), "-", 0, 10, 5); assertEquals("-x--y-", sb.toString()); } //----------------------------------------------------------------------- public void testReverse() { StrBuilder sb = new StrBuilder(); assertEquals("", sb.reverse().toString()); sb.clear().append(true); assertEquals("eurt", sb.reverse().toString()); assertEquals("true", sb.reverse().toString()); } //----------------------------------------------------------------------- public void testTrim() { StrBuilder sb = new StrBuilder(); assertEquals("", sb.reverse().toString()); sb.clear().append(" \u0000 "); assertEquals("", sb.trim().toString()); sb.clear().append(" \u0000 a b c"); assertEquals("a b c", sb.trim().toString()); sb.clear().append("a b c \u0000 "); assertEquals("a b c", sb.trim().toString()); sb.clear().append(" \u0000 a b c \u0000 "); assertEquals("a b c", sb.trim().toString()); sb.clear().append("a b c"); assertEquals("a b c", sb.trim().toString()); } //----------------------------------------------------------------------- public void testStartsWith() { StrBuilder sb = new StrBuilder(); assertFalse(sb.startsWith("a")); assertFalse(sb.startsWith(null)); assertTrue(sb.startsWith("")); sb.append("abc"); assertTrue(sb.startsWith("a")); assertTrue(sb.startsWith("ab")); assertTrue(sb.startsWith("abc")); assertFalse(sb.startsWith("cba")); } public void testEndsWith() { StrBuilder sb = new StrBuilder(); assertFalse(sb.endsWith("a")); assertFalse(sb.endsWith("c")); assertTrue(sb.endsWith("")); assertFalse(sb.endsWith(null)); sb.append("abc"); assertTrue(sb.endsWith("c")); assertTrue(sb.endsWith("bc")); assertTrue(sb.endsWith("abc")); assertFalse(sb.endsWith("cba")); assertFalse(sb.endsWith("abcd")); assertFalse(sb.endsWith(" abc")); assertFalse(sb.endsWith("abc ")); } //----------------------------------------------------------------------- public void testSubstringInt() { StrBuilder sb = new StrBuilder ("hello goodbye"); assertEquals ("goodbye", sb.substring(6)); assertEquals ("hello goodbye".substring(6), sb.substring(6)); assertEquals ("hello goodbye", sb.substring(0)); assertEquals ("hello goodbye".substring(0), sb.substring(0)); try { sb.substring(-1); fail (); } catch (IndexOutOfBoundsException e) {} try { sb.substring(15); fail (); } catch (IndexOutOfBoundsException e) {} } public void testSubstringIntInt() { StrBuilder sb = new StrBuilder ("hello goodbye"); assertEquals ("hello", sb.substring(0, 5)); assertEquals ("hello goodbye".substring(0, 6), sb.substring(0, 6)); assertEquals ("goodbye", sb.substring(6, 13)); assertEquals ("hello goodbye".substring(6,13), sb.substring(6, 13)); assertEquals ("goodbye", sb.substring(6, 20)); try { sb.substring(-1, 5); fail(); } catch (IndexOutOfBoundsException e) {} try { sb.substring(15, 20); fail(); } catch (IndexOutOfBoundsException e) {} } // ----------------------------------------------------------------------- public void testMidString() { StrBuilder sb = new StrBuilder("hello goodbye hello"); assertEquals("goodbye", sb.midString(6, 7)); assertEquals("hello", sb.midString(0, 5)); assertEquals("hello", sb.midString(-5, 5)); assertEquals("", sb.midString(0, -1)); assertEquals("", sb.midString(20, 2)); assertEquals("hello", sb.midString(14, 22)); } public void testRightString() { StrBuilder sb = new StrBuilder("left right"); assertEquals("right", sb.rightString(5)); assertEquals("", sb.rightString(0)); assertEquals("", sb.rightString(-5)); assertEquals("left right", sb.rightString(15)); } public void testLeftString() { StrBuilder sb = new StrBuilder("left right"); assertEquals("left", sb.leftString(4)); assertEquals("", sb.leftString(0)); assertEquals("", sb.leftString(-5)); assertEquals("left right", sb.leftString(15)); } // ----------------------------------------------------------------------- public void testContains_char() { StrBuilder sb = new StrBuilder("abcdefghijklmnopqrstuvwxyz"); assertEquals(true, sb.contains('a')); assertEquals(true, sb.contains('o')); assertEquals(true, sb.contains('z')); assertEquals(false, sb.contains('1')); } public void testContains_String() { StrBuilder sb = new StrBuilder("abcdefghijklmnopqrstuvwxyz"); assertEquals(true, sb.contains("a")); assertEquals(true, sb.contains("pq")); assertEquals(true, sb.contains("z")); assertEquals(false, sb.contains("zyx")); assertEquals(false, sb.contains((String) null)); } public void testContains_StrMatcher() { StrBuilder sb = new StrBuilder("abcdefghijklmnopqrstuvwxyz"); assertEquals(true, sb.contains(StrMatcher.charMatcher('a'))); assertEquals(true, sb.contains(StrMatcher.stringMatcher("pq"))); assertEquals(true, sb.contains(StrMatcher.charMatcher('z'))); assertEquals(false, sb.contains(StrMatcher.stringMatcher("zy"))); assertEquals(false, sb.contains((StrMatcher) null)); sb = new StrBuilder(); assertEquals(false, sb.contains(A_NUMBER_MATCHER)); sb.append("B A1 C"); assertEquals(true, sb.contains(A_NUMBER_MATCHER)); } // ----------------------------------------------------------------------- public void testIndexOf_char() { StrBuilder sb = new StrBuilder("abab"); assertEquals(0, sb.indexOf('a')); // should work like String#indexOf assertEquals("abab".indexOf('a'), sb.indexOf('a')); assertEquals(1, sb.indexOf('b')); assertEquals("abab".indexOf('b'), sb.indexOf('b')); assertEquals(-1, sb.indexOf('z')); } public void testIndexOf_char_int() { StrBuilder sb = new StrBuilder("abab"); assertEquals(0, sb.indexOf('a', -1)); assertEquals(0, sb.indexOf('a', 0)); assertEquals(2, sb.indexOf('a', 1)); assertEquals(-1, sb.indexOf('a', 4)); assertEquals(-1, sb.indexOf('a', 5)); // should work like String#indexOf assertEquals("abab".indexOf('a', 1), sb.indexOf('a', 1)); assertEquals(3, sb.indexOf('b', 2)); assertEquals("abab".indexOf('b', 2), sb.indexOf('b', 2)); assertEquals(-1, sb.indexOf('z', 2)); sb = new StrBuilder("xyzabc"); assertEquals(2, sb.indexOf('z', 0)); assertEquals(-1, sb.indexOf('z', 3)); } public void testLastIndexOf_char() { StrBuilder sb = new StrBuilder("abab"); assertEquals (2, sb.lastIndexOf('a')); //should work like String#lastIndexOf assertEquals ("abab".lastIndexOf('a'), sb.lastIndexOf('a')); assertEquals(3, sb.lastIndexOf('b')); assertEquals ("abab".lastIndexOf('b'), sb.lastIndexOf('b')); assertEquals (-1, sb.lastIndexOf('z')); } public void testLastIndexOf_char_int() { StrBuilder sb = new StrBuilder("abab"); assertEquals(-1, sb.lastIndexOf('a', -1)); assertEquals(0, sb.lastIndexOf('a', 0)); assertEquals(0, sb.lastIndexOf('a', 1)); // should work like String#lastIndexOf assertEquals("abab".lastIndexOf('a', 1), sb.lastIndexOf('a', 1)); assertEquals(1, sb.lastIndexOf('b', 2)); assertEquals("abab".lastIndexOf('b', 2), sb.lastIndexOf('b', 2)); assertEquals(-1, sb.lastIndexOf('z', 2)); sb = new StrBuilder("xyzabc"); assertEquals(2, sb.lastIndexOf('z', sb.length())); assertEquals(-1, sb.lastIndexOf('z', 1)); } // ----------------------------------------------------------------------- public void testIndexOf_String() { StrBuilder sb = new StrBuilder("abab"); assertEquals(0, sb.indexOf("a")); //should work like String#indexOf assertEquals("abab".indexOf("a"), sb.indexOf("a")); assertEquals(0, sb.indexOf("ab")); //should work like String#indexOf assertEquals("abab".indexOf("ab"), sb.indexOf("ab")); assertEquals(1, sb.indexOf("b")); assertEquals("abab".indexOf("b"), sb.indexOf("b")); assertEquals(1, sb.indexOf("ba")); assertEquals("abab".indexOf("ba"), sb.indexOf("ba")); assertEquals(-1, sb.indexOf("z")); assertEquals(-1, sb.indexOf((String) null)); } public void testIndexOf_String_int() { StrBuilder sb = new StrBuilder("abab"); assertEquals(0, sb.indexOf("a", -1)); assertEquals(0, sb.indexOf("a", 0)); assertEquals(2, sb.indexOf("a", 1)); assertEquals(2, sb.indexOf("a", 2)); assertEquals(-1, sb.indexOf("a", 3)); assertEquals(-1, sb.indexOf("a", 4)); assertEquals(-1, sb.indexOf("a", 5)); assertEquals(-1, sb.indexOf("abcdef", 0)); assertEquals(0, sb.indexOf("", 0)); assertEquals(1, sb.indexOf("", 1)); //should work like String#indexOf assertEquals ("abab".indexOf("a", 1), sb.indexOf("a", 1)); assertEquals(2, sb.indexOf("ab", 1)); //should work like String#indexOf assertEquals("abab".indexOf("ab", 1), sb.indexOf("ab", 1)); assertEquals(3, sb.indexOf("b", 2)); assertEquals("abab".indexOf("b", 2), sb.indexOf("b", 2)); assertEquals(1, sb.indexOf("ba", 1)); assertEquals("abab".indexOf("ba", 2), sb.indexOf("ba", 2)); assertEquals(-1, sb.indexOf("z", 2)); sb = new StrBuilder("xyzabc"); assertEquals(2, sb.indexOf("za", 0)); assertEquals(-1, sb.indexOf("za", 3)); assertEquals(-1, sb.indexOf((String) null, 2)); } public void testLastIndexOf_String() { StrBuilder sb = new StrBuilder("abab"); assertEquals(2, sb.lastIndexOf("a")); //should work like String#lastIndexOf assertEquals("abab".lastIndexOf("a"), sb.lastIndexOf("a")); assertEquals(2, sb.lastIndexOf("ab")); //should work like String#lastIndexOf assertEquals("abab".lastIndexOf("ab"), sb.lastIndexOf("ab")); assertEquals(3, sb.lastIndexOf("b")); assertEquals("abab".lastIndexOf("b"), sb.lastIndexOf("b")); assertEquals(1, sb.lastIndexOf("ba")); assertEquals("abab".lastIndexOf("ba"), sb.lastIndexOf("ba")); assertEquals(-1, sb.lastIndexOf("z")); assertEquals(-1, sb.lastIndexOf((String) null)); } public void testLastIndexOf_String_int() { StrBuilder sb = new StrBuilder("abab"); assertEquals(-1, sb.lastIndexOf("a", -1)); assertEquals(0, sb.lastIndexOf("a", 0)); assertEquals(0, sb.lastIndexOf("a", 1)); assertEquals(2, sb.lastIndexOf("a", 2)); assertEquals(2, sb.lastIndexOf("a", 3)); assertEquals(2, sb.lastIndexOf("a", 4)); assertEquals(2, sb.lastIndexOf("a", 5)); assertEquals(-1, sb.lastIndexOf("abcdef", 3)); assertEquals("abab".lastIndexOf("", 3), sb.lastIndexOf("", 3)); assertEquals("abab".lastIndexOf("", 1), sb.lastIndexOf("", 1)); //should work like String#lastIndexOf assertEquals("abab".lastIndexOf("a", 1), sb.lastIndexOf("a", 1)); assertEquals(0, sb.lastIndexOf("ab", 1)); //should work like String#lastIndexOf assertEquals("abab".lastIndexOf("ab", 1), sb.lastIndexOf("ab", 1)); assertEquals(1, sb.lastIndexOf("b", 2)); assertEquals("abab".lastIndexOf("b", 2), sb.lastIndexOf("b", 2)); assertEquals(1, sb.lastIndexOf("ba", 2)); assertEquals("abab".lastIndexOf("ba", 2), sb.lastIndexOf("ba", 2)); assertEquals(-1, sb.lastIndexOf("z", 2)); sb = new StrBuilder("xyzabc"); assertEquals(2, sb.lastIndexOf("za", sb.length())); assertEquals(-1, sb.lastIndexOf("za", 1)); assertEquals(-1, sb.lastIndexOf((String) null, 2)); } // ----------------------------------------------------------------------- public void testIndexOf_StrMatcher() { StrBuilder sb = new StrBuilder(); assertEquals(-1, sb.indexOf((StrMatcher) null)); assertEquals(-1, sb.indexOf(StrMatcher.charMatcher('a'))); sb.append("ab bd"); assertEquals(0, sb.indexOf(StrMatcher.charMatcher('a'))); assertEquals(1, sb.indexOf(StrMatcher.charMatcher('b'))); assertEquals(2, sb.indexOf(StrMatcher.spaceMatcher())); assertEquals(4, sb.indexOf(StrMatcher.charMatcher('d'))); assertEquals(-1, sb.indexOf(StrMatcher.noneMatcher())); assertEquals(-1, sb.indexOf((StrMatcher) null)); sb.append(" A1 junction"); assertEquals(6, sb.indexOf(A_NUMBER_MATCHER)); } public void testIndexOf_StrMatcher_int() { StrBuilder sb = new StrBuilder(); assertEquals(-1, sb.indexOf((StrMatcher) null, 2)); assertEquals(-1, sb.indexOf(StrMatcher.charMatcher('a'), 2)); assertEquals(-1, sb.indexOf(StrMatcher.charMatcher('a'), 0)); sb.append("ab bd"); assertEquals(0, sb.indexOf(StrMatcher.charMatcher('a'), -2)); assertEquals(0, sb.indexOf(StrMatcher.charMatcher('a'), 0)); assertEquals(-1, sb.indexOf(StrMatcher.charMatcher('a'), 2)); assertEquals(-1, sb.indexOf(StrMatcher.charMatcher('a'), 20)); assertEquals(1, sb.indexOf(StrMatcher.charMatcher('b'), -1)); assertEquals(1, sb.indexOf(StrMatcher.charMatcher('b'), 0)); assertEquals(1, sb.indexOf(StrMatcher.charMatcher('b'), 1)); assertEquals(3, sb.indexOf(StrMatcher.charMatcher('b'), 2)); assertEquals(3, sb.indexOf(StrMatcher.charMatcher('b'), 3)); assertEquals(-1, sb.indexOf(StrMatcher.charMatcher('b'), 4)); assertEquals(-1, sb.indexOf(StrMatcher.charMatcher('b'), 5)); assertEquals(-1, sb.indexOf(StrMatcher.charMatcher('b'), 6)); assertEquals(2, sb.indexOf(StrMatcher.spaceMatcher(), -2)); assertEquals(2, sb.indexOf(StrMatcher.spaceMatcher(), 0)); assertEquals(2, sb.indexOf(StrMatcher.spaceMatcher(), 2)); assertEquals(-1, sb.indexOf(StrMatcher.spaceMatcher(), 4)); assertEquals(-1, sb.indexOf(StrMatcher.spaceMatcher(), 20)); assertEquals(-1, sb.indexOf(StrMatcher.noneMatcher(), 0)); assertEquals(-1, sb.indexOf((StrMatcher) null, 0)); sb.append(" A1 junction with A2"); assertEquals(6, sb.indexOf(A_NUMBER_MATCHER, 5)); assertEquals(6, sb.indexOf(A_NUMBER_MATCHER, 6)); assertEquals(23, sb.indexOf(A_NUMBER_MATCHER, 7)); assertEquals(23, sb.indexOf(A_NUMBER_MATCHER, 22)); assertEquals(23, sb.indexOf(A_NUMBER_MATCHER, 23)); assertEquals(-1, sb.indexOf(A_NUMBER_MATCHER, 24)); } public void testLastIndexOf_StrMatcher() { StrBuilder sb = new StrBuilder(); assertEquals(-1, sb.lastIndexOf((StrMatcher) null)); assertEquals(-1, sb.lastIndexOf(StrMatcher.charMatcher('a'))); sb.append("ab bd"); assertEquals(0, sb.lastIndexOf(StrMatcher.charMatcher('a'))); assertEquals(3, sb.lastIndexOf(StrMatcher.charMatcher('b'))); assertEquals(2, sb.lastIndexOf(StrMatcher.spaceMatcher())); assertEquals(4, sb.lastIndexOf(StrMatcher.charMatcher('d'))); assertEquals(-1, sb.lastIndexOf(StrMatcher.noneMatcher())); assertEquals(-1, sb.lastIndexOf((StrMatcher) null)); sb.append(" A1 junction"); assertEquals(6, sb.lastIndexOf(A_NUMBER_MATCHER)); } public void testLastIndexOf_StrMatcher_int() { StrBuilder sb = new StrBuilder(); assertEquals(-1, sb.lastIndexOf((StrMatcher) null, 2)); assertEquals(-1, sb.lastIndexOf(StrMatcher.charMatcher('a'), 2)); assertEquals(-1, sb.lastIndexOf(StrMatcher.charMatcher('a'), 0)); assertEquals(-1, sb.lastIndexOf(StrMatcher.charMatcher('a'), -1)); sb.append("ab bd"); assertEquals(-1, sb.lastIndexOf(StrMatcher.charMatcher('a'), -2)); assertEquals(0, sb.lastIndexOf(StrMatcher.charMatcher('a'), 0)); assertEquals(0, sb.lastIndexOf(StrMatcher.charMatcher('a'), 2)); assertEquals(0, sb.lastIndexOf(StrMatcher.charMatcher('a'), 20)); assertEquals(-1, sb.lastIndexOf(StrMatcher.charMatcher('b'), -1)); assertEquals(-1, sb.lastIndexOf(StrMatcher.charMatcher('b'), 0)); assertEquals(1, sb.lastIndexOf(StrMatcher.charMatcher('b'), 1)); assertEquals(1, sb.lastIndexOf(StrMatcher.charMatcher('b'), 2)); assertEquals(3, sb.lastIndexOf(StrMatcher.charMatcher('b'), 3)); assertEquals(3, sb.lastIndexOf(StrMatcher.charMatcher('b'), 4)); assertEquals(3, sb.lastIndexOf(StrMatcher.charMatcher('b'), 5)); assertEquals(3, sb.lastIndexOf(StrMatcher.charMatcher('b'), 6)); assertEquals(-1, sb.lastIndexOf(StrMatcher.spaceMatcher(), -2)); assertEquals(-1, sb.lastIndexOf(StrMatcher.spaceMatcher(), 0)); assertEquals(2, sb.lastIndexOf(StrMatcher.spaceMatcher(), 2)); assertEquals(2, sb.lastIndexOf(StrMatcher.spaceMatcher(), 4)); assertEquals(2, sb.lastIndexOf(StrMatcher.spaceMatcher(), 20)); assertEquals(-1, sb.lastIndexOf(StrMatcher.noneMatcher(), 0)); assertEquals(-1, sb.lastIndexOf((StrMatcher) null, 0)); sb.append(" A1 junction with A2"); assertEquals(-1, sb.lastIndexOf(A_NUMBER_MATCHER, 5)); assertEquals(-1, sb.lastIndexOf(A_NUMBER_MATCHER, 6)); // A matches, 1 is outside bounds assertEquals(6, sb.lastIndexOf(A_NUMBER_MATCHER, 7)); assertEquals(6, sb.lastIndexOf(A_NUMBER_MATCHER, 22)); assertEquals(6, sb.lastIndexOf(A_NUMBER_MATCHER, 23)); // A matches, 2 is outside bounds assertEquals(23, sb.lastIndexOf(A_NUMBER_MATCHER, 24)); } static final StrMatcher A_NUMBER_MATCHER = new StrMatcher() { public int isMatch(char[] buffer, int pos, int bufferStart, int bufferEnd) { if (buffer[pos] == 'A') { pos++; if (pos < bufferEnd && buffer[pos] >= '0' && buffer[pos] <= '9') { return 2; } } return 0; } }; //----------------------------------------------------------------------- public void testAsTokenizer() throws Exception { // from Javadoc StrBuilder b = new StrBuilder(); b.append("a b "); StrTokenizer t = b.asTokenizer(); String[] tokens1 = t.getTokenArray(); assertEquals(2, tokens1.length); assertEquals("a", tokens1[0]); assertEquals("b", tokens1[1]); assertEquals(2, t.size()); b.append("c d "); String[] tokens2 = t.getTokenArray(); assertEquals(2, tokens2.length); assertEquals("a", tokens2[0]); assertEquals("b", tokens2[1]); assertEquals(2, t.size()); assertEquals("a", t.next()); assertEquals("b", t.next()); t.reset(); String[] tokens3 = t.getTokenArray(); assertEquals(4, tokens3.length); assertEquals("a", tokens3[0]); assertEquals("b", tokens3[1]); assertEquals("c", tokens3[2]); assertEquals("d", tokens3[3]); assertEquals(4, t.size()); assertEquals("a", t.next()); assertEquals("b", t.next()); assertEquals("c", t.next()); assertEquals("d", t.next()); assertEquals("a b c d ", t.getContent()); } // ----------------------------------------------------------------------- public void testAsReader() throws Exception { StrBuilder sb = new StrBuilder("some text"); Reader reader = sb.asReader(); assertEquals(true, reader.ready()); char[] buf = new char[40]; assertEquals(9, reader.read(buf)); assertEquals("some text", new String(buf, 0, 9)); assertEquals(-1, reader.read()); assertEquals(false, reader.ready()); assertEquals(0, reader.skip(2)); assertEquals(0, reader.skip(-1)); assertEquals(true, reader.markSupported()); reader = sb.asReader(); assertEquals('s', reader.read()); reader.mark(-1); char[] array = new char[3]; assertEquals(3, reader.read(array, 0, 3)); assertEquals('o', array[0]); assertEquals('m', array[1]); assertEquals('e', array[2]); reader.reset(); assertEquals(1, reader.read(array, 1, 1)); assertEquals('o', array[0]); assertEquals('o', array[1]); assertEquals('e', array[2]); assertEquals(2, reader.skip(2)); assertEquals(' ', reader.read()); assertEquals(true, reader.ready()); reader.close(); assertEquals(true, reader.ready()); reader = sb.asReader(); array = new char[3]; try { reader.read(array, -1, 0); fail(); } catch (IndexOutOfBoundsException ex) {} try { reader.read(array, 0, -1); fail(); } catch (IndexOutOfBoundsException ex) {} try { reader.read(array, 100, 1); fail(); } catch (IndexOutOfBoundsException ex) {} try { reader.read(array, 0, 100); fail(); } catch (IndexOutOfBoundsException ex) {} try { reader.read(array, Integer.MAX_VALUE, Integer.MAX_VALUE); fail(); } catch (IndexOutOfBoundsException ex) {} assertEquals(0, reader.read(array, 0, 0)); assertEquals(0, array[0]); assertEquals(0, array[1]); assertEquals(0, array[2]); reader.skip(9); assertEquals(-1, reader.read(array, 0, 1)); reader.reset(); array = new char[30]; assertEquals(9, reader.read(array, 0, 30)); } //----------------------------------------------------------------------- public void testAsWriter() throws Exception { StrBuilder sb = new StrBuilder("base"); Writer writer = sb.asWriter(); writer.write('l'); assertEquals("basel", sb.toString()); writer.write(new char[] {'i', 'n'}); assertEquals("baselin", sb.toString()); writer.write(new char[] {'n', 'e', 'r'}, 1, 2); assertEquals("baseliner", sb.toString()); writer.write(" rout"); assertEquals("baseliner rout", sb.toString()); writer.write("ping that server", 1, 3); assertEquals("baseliner routing", sb.toString()); writer.flush(); // no effect assertEquals("baseliner routing", sb.toString()); writer.close(); // no effect assertEquals("baseliner routing", sb.toString()); writer.write(" hi"); // works after close assertEquals("baseliner routing hi", sb.toString()); sb.setLength(4); // mix and match writer.write('d'); assertEquals("based", sb.toString()); } //----------------------------------------------------------------------- public void testEqualsIgnoreCase() { StrBuilder sb1 = new StrBuilder(); StrBuilder sb2 = new StrBuilder(); assertEquals(true, sb1.equalsIgnoreCase(sb1)); assertEquals(true, sb1.equalsIgnoreCase(sb2)); assertEquals(true, sb2.equalsIgnoreCase(sb2)); sb1.append("abc"); assertEquals(false, sb1.equalsIgnoreCase(sb2)); sb2.append("ABC"); assertEquals(true, sb1.equalsIgnoreCase(sb2)); sb2.clear().append("abc"); assertEquals(true, sb1.equalsIgnoreCase(sb2)); assertEquals(true, sb1.equalsIgnoreCase(sb1)); assertEquals(true, sb2.equalsIgnoreCase(sb2)); sb2.clear().append("aBc"); assertEquals(true, sb1.equalsIgnoreCase(sb2)); } //----------------------------------------------------------------------- public void testEquals() { StrBuilder sb1 = new StrBuilder(); StrBuilder sb2 = new StrBuilder(); assertEquals(true, sb1.equals(sb2)); assertEquals(true, sb1.equals(sb1)); assertEquals(true, sb2.equals(sb2)); assertEquals(true, sb1.equals((Object) sb2)); sb1.append("abc"); assertEquals(false, sb1.equals(sb2)); assertEquals(false, sb1.equals((Object) sb2)); sb2.append("ABC"); assertEquals(false, sb1.equals(sb2)); assertEquals(false, sb1.equals((Object) sb2)); sb2.clear().append("abc"); assertEquals(true, sb1.equals(sb2)); assertEquals(true, sb1.equals((Object) sb2)); assertEquals(false, sb1.equals(new Integer(1))); assertEquals(false, sb1.equals("abc")); } //----------------------------------------------------------------------- public void testHashCode() { StrBuilder sb = new StrBuilder(); int hc1a = sb.hashCode(); int hc1b = sb.hashCode(); assertEquals(0, hc1a); assertEquals(hc1a, hc1b); sb.append("abc"); int hc2a = sb.hashCode(); int hc2b = sb.hashCode(); assertEquals(true, hc2a != 0); assertEquals(hc2a, hc2b); } //----------------------------------------------------------------------- public void testToString() { StrBuilder sb = new StrBuilder("abc"); assertEquals("abc", sb.toString()); } //----------------------------------------------------------------------- public void testToStringBuffer() { StrBuilder sb = new StrBuilder(); assertEquals(new StringBuffer().toString(), sb.toStringBuffer().toString()); sb.append("junit"); assertEquals(new StringBuffer("junit").toString(), sb.toStringBuffer().toString()); } //----------------------------------------------------------------------- public void testLang294() { StrBuilder sb = new StrBuilder("\n%BLAH%\nDo more stuff\neven more stuff\n%BLAH%\n"); sb.deleteAll("\n%BLAH%"); assertEquals("\nDo more stuff\neven more stuff\n", sb.toString()); } public void testIndexOfLang294() { StrBuilder sb = new StrBuilder("onetwothree"); sb.deleteFirst("three"); assertEquals(-1, sb.indexOf("three")); } //----------------------------------------------------------------------- public void testLang295() { StrBuilder sb = new StrBuilder("onetwothree"); sb.deleteFirst("three"); assertFalse( "The contains(char) method is looking beyond the end of the string", sb.contains('h')); assertEquals( "The indexOf(char) method is looking beyond the end of the string", -1, sb.indexOf('h')); } //----------------------------------------------------------------------- public void testLang412Right() { StrBuilder sb = new StrBuilder(); sb.appendFixedWidthPadRight(null, 10, '*'); assertEquals( "Failed to invoke appendFixedWidthPadRight correctly", "**********", sb.toString()); } public void testLang412Left() { StrBuilder sb = new StrBuilder(); sb.appendFixedWidthPadLeft(null, 10, '*'); assertEquals( "Failed to invoke appendFixedWidthPadLeft correctly", "**********", sb.toString()); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/text/StrLookupTest.java100644 0 0 5247 11513702433 25422 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.text; import java.util.HashMap; import java.util.Map; import junit.framework.TestCase; /** * Test class for StrLookup. * * @version $Id: StrLookupTest.java 905628 2010-02-02 13:29:55Z niallp $ */ public class StrLookupTest extends TestCase { //----------------------------------------------------------------------- public void testNoneLookup() { assertEquals(null, StrLookup.noneLookup().lookup(null)); assertEquals(null, StrLookup.noneLookup().lookup("")); assertEquals(null, StrLookup.noneLookup().lookup("any")); } public void testSystemProperiesLookup() { assertEquals(System.getProperty("os.name"), StrLookup.systemPropertiesLookup().lookup("os.name")); assertEquals(null, StrLookup.systemPropertiesLookup().lookup("")); assertEquals(null, StrLookup.systemPropertiesLookup().lookup("other")); try { StrLookup.systemPropertiesLookup().lookup(null); fail(); } catch (NullPointerException ex) { // expected } } public void testMapLookup() { Map map = new HashMap(); map.put("key", "value"); map.put("number", new Integer(2)); assertEquals("value", StrLookup.mapLookup(map).lookup("key")); assertEquals("2", StrLookup.mapLookup(map).lookup("number")); assertEquals(null, StrLookup.mapLookup(map).lookup(null)); assertEquals(null, StrLookup.mapLookup(map).lookup("")); assertEquals(null, StrLookup.mapLookup(map).lookup("other")); } public void testMapLookup_nullMap() { Map map = null; assertEquals(null, StrLookup.mapLookup(map).lookup(null)); assertEquals(null, StrLookup.mapLookup(map).lookup("")); assertEquals(null, StrLookup.mapLookup(map).lookup("any")); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/text/StrMatcherTest.java100644 0 0 22734 11513702433 25554 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.text; import junit.framework.TestCase; /** * Unit tests for {@link org.apache.commons.lang.text.StrMatcher}. * * @version $Id: StrMatcherTest.java 905628 2010-02-02 13:29:55Z niallp $ */ public class StrMatcherTest extends TestCase { private static final char[] BUFFER1 = "0,1\t2 3\n\r\f\u0000'\"".toCharArray(); private static final char[] BUFFER2 = "abcdef".toCharArray(); /** * Create a new test case with the specified name. * * @param name the name */ public StrMatcherTest(String name) { super(name); } //----------------------------------------------------------------------- public void testCommaMatcher() { StrMatcher matcher = StrMatcher.commaMatcher(); assertSame(matcher, StrMatcher.commaMatcher()); assertEquals(0, matcher.isMatch(BUFFER1, 0)); assertEquals(1, matcher.isMatch(BUFFER1, 1)); assertEquals(0, matcher.isMatch(BUFFER1, 2)); } //----------------------------------------------------------------------- public void testTabMatcher() { StrMatcher matcher = StrMatcher.tabMatcher(); assertSame(matcher, StrMatcher.tabMatcher()); assertEquals(0, matcher.isMatch(BUFFER1, 2)); assertEquals(1, matcher.isMatch(BUFFER1, 3)); assertEquals(0, matcher.isMatch(BUFFER1, 4)); } //----------------------------------------------------------------------- public void testSpaceMatcher() { StrMatcher matcher = StrMatcher.spaceMatcher(); assertSame(matcher, StrMatcher.spaceMatcher()); assertEquals(0, matcher.isMatch(BUFFER1, 4)); assertEquals(1, matcher.isMatch(BUFFER1, 5)); assertEquals(0, matcher.isMatch(BUFFER1, 6)); } //----------------------------------------------------------------------- public void testSplitMatcher() { StrMatcher matcher = StrMatcher.splitMatcher(); assertSame(matcher, StrMatcher.splitMatcher()); assertEquals(0, matcher.isMatch(BUFFER1, 2)); assertEquals(1, matcher.isMatch(BUFFER1, 3)); assertEquals(0, matcher.isMatch(BUFFER1, 4)); assertEquals(1, matcher.isMatch(BUFFER1, 5)); assertEquals(0, matcher.isMatch(BUFFER1, 6)); assertEquals(1, matcher.isMatch(BUFFER1, 7)); assertEquals(1, matcher.isMatch(BUFFER1, 8)); assertEquals(1, matcher.isMatch(BUFFER1, 9)); assertEquals(0, matcher.isMatch(BUFFER1, 10)); } //----------------------------------------------------------------------- public void testTrimMatcher() { StrMatcher matcher = StrMatcher.trimMatcher(); assertSame(matcher, StrMatcher.trimMatcher()); assertEquals(0, matcher.isMatch(BUFFER1, 2)); assertEquals(1, matcher.isMatch(BUFFER1, 3)); assertEquals(0, matcher.isMatch(BUFFER1, 4)); assertEquals(1, matcher.isMatch(BUFFER1, 5)); assertEquals(0, matcher.isMatch(BUFFER1, 6)); assertEquals(1, matcher.isMatch(BUFFER1, 7)); assertEquals(1, matcher.isMatch(BUFFER1, 8)); assertEquals(1, matcher.isMatch(BUFFER1, 9)); assertEquals(1, matcher.isMatch(BUFFER1, 10)); } //----------------------------------------------------------------------- public void testSingleQuoteMatcher() { StrMatcher matcher = StrMatcher.singleQuoteMatcher(); assertSame(matcher, StrMatcher.singleQuoteMatcher()); assertEquals(0, matcher.isMatch(BUFFER1, 10)); assertEquals(1, matcher.isMatch(BUFFER1, 11)); assertEquals(0, matcher.isMatch(BUFFER1, 12)); } //----------------------------------------------------------------------- public void testDoubleQuoteMatcher() { StrMatcher matcher = StrMatcher.doubleQuoteMatcher(); assertSame(matcher, StrMatcher.doubleQuoteMatcher()); assertEquals(0, matcher.isMatch(BUFFER1, 11)); assertEquals(1, matcher.isMatch(BUFFER1, 12)); } //----------------------------------------------------------------------- public void testQuoteMatcher() { StrMatcher matcher = StrMatcher.quoteMatcher(); assertSame(matcher, StrMatcher.quoteMatcher()); assertEquals(0, matcher.isMatch(BUFFER1, 10)); assertEquals(1, matcher.isMatch(BUFFER1, 11)); assertEquals(1, matcher.isMatch(BUFFER1, 12)); } //----------------------------------------------------------------------- public void testNoneMatcher() { StrMatcher matcher = StrMatcher.noneMatcher(); assertSame(matcher, StrMatcher.noneMatcher()); assertEquals(0, matcher.isMatch(BUFFER1, 0)); assertEquals(0, matcher.isMatch(BUFFER1, 1)); assertEquals(0, matcher.isMatch(BUFFER1, 2)); assertEquals(0, matcher.isMatch(BUFFER1, 3)); assertEquals(0, matcher.isMatch(BUFFER1, 4)); assertEquals(0, matcher.isMatch(BUFFER1, 5)); assertEquals(0, matcher.isMatch(BUFFER1, 6)); assertEquals(0, matcher.isMatch(BUFFER1, 7)); assertEquals(0, matcher.isMatch(BUFFER1, 8)); assertEquals(0, matcher.isMatch(BUFFER1, 9)); assertEquals(0, matcher.isMatch(BUFFER1, 10)); assertEquals(0, matcher.isMatch(BUFFER1, 11)); assertEquals(0, matcher.isMatch(BUFFER1, 12)); } //----------------------------------------------------------------------- public void testCharMatcher_char() { StrMatcher matcher = StrMatcher.charMatcher('c'); assertEquals(0, matcher.isMatch(BUFFER2, 0)); assertEquals(0, matcher.isMatch(BUFFER2, 1)); assertEquals(1, matcher.isMatch(BUFFER2, 2)); assertEquals(0, matcher.isMatch(BUFFER2, 3)); assertEquals(0, matcher.isMatch(BUFFER2, 4)); assertEquals(0, matcher.isMatch(BUFFER2, 5)); } //----------------------------------------------------------------------- public void testCharSetMatcher_String() { StrMatcher matcher = StrMatcher.charSetMatcher("ace"); assertEquals(1, matcher.isMatch(BUFFER2, 0)); assertEquals(0, matcher.isMatch(BUFFER2, 1)); assertEquals(1, matcher.isMatch(BUFFER2, 2)); assertEquals(0, matcher.isMatch(BUFFER2, 3)); assertEquals(1, matcher.isMatch(BUFFER2, 4)); assertEquals(0, matcher.isMatch(BUFFER2, 5)); assertSame(StrMatcher.noneMatcher(), StrMatcher.charSetMatcher("")); assertSame(StrMatcher.noneMatcher(), StrMatcher.charSetMatcher((String) null)); assertTrue(StrMatcher.charSetMatcher("a") instanceof StrMatcher.CharMatcher); } //----------------------------------------------------------------------- public void testCharSetMatcher_charArray() { StrMatcher matcher = StrMatcher.charSetMatcher("ace".toCharArray()); assertEquals(1, matcher.isMatch(BUFFER2, 0)); assertEquals(0, matcher.isMatch(BUFFER2, 1)); assertEquals(1, matcher.isMatch(BUFFER2, 2)); assertEquals(0, matcher.isMatch(BUFFER2, 3)); assertEquals(1, matcher.isMatch(BUFFER2, 4)); assertEquals(0, matcher.isMatch(BUFFER2, 5)); assertSame(StrMatcher.noneMatcher(), StrMatcher.charSetMatcher(new char[0])); assertSame(StrMatcher.noneMatcher(), StrMatcher.charSetMatcher((char[]) null)); assertTrue(StrMatcher.charSetMatcher("a".toCharArray()) instanceof StrMatcher.CharMatcher); } //----------------------------------------------------------------------- public void testStringMatcher_String() { StrMatcher matcher = StrMatcher.stringMatcher("bc"); assertEquals(0, matcher.isMatch(BUFFER2, 0)); assertEquals(2, matcher.isMatch(BUFFER2, 1)); assertEquals(0, matcher.isMatch(BUFFER2, 2)); assertEquals(0, matcher.isMatch(BUFFER2, 3)); assertEquals(0, matcher.isMatch(BUFFER2, 4)); assertEquals(0, matcher.isMatch(BUFFER2, 5)); assertSame(StrMatcher.noneMatcher(), StrMatcher.stringMatcher("")); assertSame(StrMatcher.noneMatcher(), StrMatcher.stringMatcher((String) null)); } //----------------------------------------------------------------------- public void testMatcherIndices() { // remember that the API contract is tight for the isMatch() method // all the onus is on the caller, so invalid inputs are not // the concern of StrMatcher, and are not bugs StrMatcher matcher = StrMatcher.stringMatcher("bc"); assertEquals(2, matcher.isMatch(BUFFER2, 1, 1, BUFFER2.length)); assertEquals(2, matcher.isMatch(BUFFER2, 1, 0, 3)); assertEquals(0, matcher.isMatch(BUFFER2, 1, 0, 2)); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/text/StrSubstitutorTest.java100644 0 0 47711 11513702433 26542 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.text; import java.util.HashMap; import java.util.Map; import java.util.Properties; import junit.framework.TestCase; import org.apache.commons.lang.mutable.MutableObject; /** * Test class for StrSubstitutor. * * @author Oliver Heger * @version $Id: StrSubstitutorTest.java 1056876 2011-01-09 03:17:24Z niallp $ */ public class StrSubstitutorTest extends TestCase { private Map values; protected void setUp() throws Exception { super.setUp(); values = new HashMap(); values.put("animal", "quick brown fox"); values.put("target", "lazy dog"); } protected void tearDown() throws Exception { super.tearDown(); values = null; } //----------------------------------------------------------------------- /** * Tests simple key replace. */ public void testReplaceSimple() { doTestReplace("The quick brown fox jumps over the lazy dog.", "The ${animal} jumps over the ${target}.", true); } /** * Tests simple key replace. */ public void testReplaceSolo() { doTestReplace("quick brown fox", "${animal}", false); } /** * Tests replace with no variables. */ public void testReplaceNoVariables() { doTestNoReplace("The balloon arrived."); } /** * Tests replace with null. */ public void testReplaceNull() { doTestNoReplace(null); } /** * Tests replace with null. */ public void testReplaceEmpty() { doTestNoReplace(""); } /** * Tests key replace changing map after initialization (not recommended). */ public void testReplaceChangedMap() { StrSubstitutor sub = new StrSubstitutor(values); values.put("target", "moon"); assertEquals("The quick brown fox jumps over the moon.", sub.replace("The ${animal} jumps over the ${target}.")); } /** * Tests unknown key replace. */ public void testReplaceUnknownKey() { doTestReplace("The ${person} jumps over the lazy dog.", "The ${person} jumps over the ${target}.", true); } /** * Tests adjacent keys. */ public void testReplaceAdjacentAtStart() { values.put("code", "GBP"); values.put("amount", "12.50"); StrSubstitutor sub = new StrSubstitutor(values); assertEquals("GBP12.50 charged", sub.replace("${code}${amount} charged")); } /** * Tests adjacent keys. */ public void testReplaceAdjacentAtEnd() { values.put("code", "GBP"); values.put("amount", "12.50"); StrSubstitutor sub = new StrSubstitutor(values); assertEquals("Amount is GBP12.50", sub.replace("Amount is ${code}${amount}")); } /** * Tests simple recursive replace. */ public void testReplaceRecursive() { values.put("animal", "${critter}"); values.put("target", "${pet}"); values.put("pet", "${petCharacteristic} dog"); values.put("petCharacteristic", "lazy"); values.put("critter", "${critterSpeed} ${critterColor} ${critterType}"); values.put("critterSpeed", "quick"); values.put("critterColor", "brown"); values.put("critterType", "fox"); doTestReplace("The quick brown fox jumps over the lazy dog.", "The ${animal} jumps over the ${target}.", true); } /** * Tests escaping. */ public void testReplaceEscaping() { doTestReplace("The ${animal} jumps over the lazy dog.", "The $${animal} jumps over the ${target}.", true); } /** * Tests escaping. */ public void testReplaceSoloEscaping() { doTestReplace("${animal}", "$${animal}", false); } /** * Tests complex escaping. */ public void testReplaceComplexEscaping() { doTestReplace("The ${quick brown fox} jumps over the lazy dog.", "The $${${animal}} jumps over the ${target}.", true); } /** * Tests when no prefix or suffix. */ public void testReplaceNoPefixNoSuffix() { doTestReplace("The animal jumps over the lazy dog.", "The animal jumps over the ${target}.", true); } /** * Tests when no incomplete prefix. */ public void testReplaceIncompletePefix() { doTestReplace("The {animal} jumps over the lazy dog.", "The {animal} jumps over the ${target}.", true); } /** * Tests when prefix but no suffix. */ public void testReplacePrefixNoSuffix() { doTestReplace("The ${animal jumps over the ${target} lazy dog.", "The ${animal jumps over the ${target} ${target}.", true); } /** * Tests when suffix but no prefix. */ public void testReplaceNoPrefixSuffix() { doTestReplace("The animal} jumps over the lazy dog.", "The animal} jumps over the ${target}.", true); } /** * Tests when no variable name. */ public void testReplaceEmptyKeys() { doTestReplace("The ${} jumps over the lazy dog.", "The ${} jumps over the ${target}.", true); } /** * Tests replace creates output same as input. */ public void testReplaceToIdentical() { values.put("animal", "$${${thing}}"); values.put("thing", "animal"); doTestReplace("The ${animal} jumps.", "The ${animal} jumps.", true); } /** * Tests a cyclic replace operation. * The cycle should be detected and cause an exception to be thrown. */ public void testCyclicReplacement() { Map map = new HashMap(); map.put("animal", "${critter}"); map.put("target", "${pet}"); map.put("pet", "${petCharacteristic} dog"); map.put("petCharacteristic", "lazy"); map.put("critter", "${critterSpeed} ${critterColor} ${critterType}"); map.put("critterSpeed", "quick"); map.put("critterColor", "brown"); map.put("critterType", "${animal}"); StrSubstitutor sub = new StrSubstitutor(map); try { sub.replace("The ${animal} jumps over the ${target}."); fail("Cyclic replacement was not detected!"); } catch (IllegalStateException ex) { // expected } } /** * Tests interpolation with weird boundary patterns. */ public void testReplaceWeirdPattens() { doTestNoReplace(""); doTestNoReplace("${}"); doTestNoReplace("${ }"); doTestNoReplace("${\t}"); doTestNoReplace("${\n}"); doTestNoReplace("${\b}"); doTestNoReplace("${"); doTestNoReplace("$}"); doTestNoReplace("}"); doTestNoReplace("${}$"); doTestNoReplace("${${"); doTestNoReplace("${${}}"); doTestNoReplace("${$${}}"); doTestNoReplace("${$$${}}"); doTestNoReplace("${$$${$}}"); doTestNoReplace("${${}}"); doTestNoReplace("${${ }}"); } /** * Tests simple key replace. */ public void testReplacePartialString_noReplace() { StrSubstitutor sub = new StrSubstitutor(); assertEquals("${animal} jumps", sub.replace("The ${animal} jumps over the ${target}.", 4, 15)); } /** * Tests whether a variable can be replaced in a variable name. */ public void testReplaceInVariable() { values.put("animal.1", "fox"); values.put("animal.2", "mouse"); values.put("species", "2"); StrSubstitutor sub = new StrSubstitutor(values); sub.setEnableSubstitutionInVariables(true); assertEquals( "Wrong result (1)", "The mouse jumps over the lazy dog.", sub.replace("The ${animal.${species}} jumps over the ${target}.")); values.put("species", "1"); assertEquals( "Wrong result (2)", "The fox jumps over the lazy dog.", sub.replace("The ${animal.${species}} jumps over the ${target}.")); } /** * Tests whether substitution in variable names is disabled per default. */ public void testReplaceInVariableDisabled() { values.put("animal.1", "fox"); values.put("animal.2", "mouse"); values.put("species", "2"); StrSubstitutor sub = new StrSubstitutor(values); assertEquals( "Wrong result", "The ${animal.${species}} jumps over the lazy dog.", sub.replace("The ${animal.${species}} jumps over the ${target}.")); } /** * Tests complex and recursive substitution in variable names. */ public void testReplaceInVariableRecursive() { values.put("animal.2", "brown fox"); values.put("animal.1", "white mouse"); values.put("color", "white"); values.put("species.white", "1"); values.put("species.brown", "2"); StrSubstitutor sub = new StrSubstitutor(values); sub.setEnableSubstitutionInVariables(true); assertEquals( "Wrong result", "The white mouse jumps over the lazy dog.", sub.replace("The ${animal.${species.${color}}} jumps over the ${target}.")); } //----------------------------------------------------------------------- /** * Tests protected. */ public void testResolveVariable() { final StrBuilder builder = new StrBuilder("Hi ${name}!"); Map map = new HashMap(); map.put("name", "commons"); StrSubstitutor sub = new StrSubstitutor(map) { protected String resolveVariable(String variableName, StrBuilder buf, int startPos, int endPos) { assertEquals("name", variableName); assertSame(builder, buf); assertEquals(3, startPos); assertEquals(10, endPos); return "jakarta"; } }; sub.replaceIn(builder); assertEquals("Hi jakarta!", builder.toString()); } //----------------------------------------------------------------------- /** * Tests constructor. */ public void testConstructorNoArgs() { StrSubstitutor sub = new StrSubstitutor(); assertEquals("Hi ${name}", sub.replace("Hi ${name}")); } /** * Tests constructor. */ public void testConstructorMapPrefixSuffix() { Map map = new HashMap(); map.put("name", "commons"); StrSubstitutor sub = new StrSubstitutor(map, "<", ">"); assertEquals("Hi < commons", sub.replace("Hi $< ")); } /** * Tests constructor. */ public void testConstructorMapFull() { Map map = new HashMap(); map.put("name", "commons"); StrSubstitutor sub = new StrSubstitutor(map, "<", ">", '!'); assertEquals("Hi < commons", sub.replace("Hi !< ")); } //----------------------------------------------------------------------- /** * Tests get set. */ public void testGetSetEscape() { StrSubstitutor sub = new StrSubstitutor(); assertEquals('$', sub.getEscapeChar()); sub.setEscapeChar('<'); assertEquals('<', sub.getEscapeChar()); } /** * Tests get set. */ public void testGetSetPrefix() { StrSubstitutor sub = new StrSubstitutor(); assertEquals(true, sub.getVariablePrefixMatcher() instanceof StrMatcher.StringMatcher); sub.setVariablePrefix('<'); assertEquals(true, sub.getVariablePrefixMatcher() instanceof StrMatcher.CharMatcher); sub.setVariablePrefix("<<"); assertEquals(true, sub.getVariablePrefixMatcher() instanceof StrMatcher.StringMatcher); try { sub.setVariablePrefix((String) null); fail(); } catch (IllegalArgumentException ex) { // expected } assertEquals(true, sub.getVariablePrefixMatcher() instanceof StrMatcher.StringMatcher); StrMatcher matcher = StrMatcher.commaMatcher(); sub.setVariablePrefixMatcher(matcher); assertSame(matcher, sub.getVariablePrefixMatcher()); try { sub.setVariablePrefixMatcher((StrMatcher) null); fail(); } catch (IllegalArgumentException ex) { // expected } assertSame(matcher, sub.getVariablePrefixMatcher()); } /** * Tests get set. */ public void testGetSetSuffix() { StrSubstitutor sub = new StrSubstitutor(); assertEquals(true, sub.getVariableSuffixMatcher() instanceof StrMatcher.StringMatcher); sub.setVariableSuffix('<'); assertEquals(true, sub.getVariableSuffixMatcher() instanceof StrMatcher.CharMatcher); sub.setVariableSuffix("<<"); assertEquals(true, sub.getVariableSuffixMatcher() instanceof StrMatcher.StringMatcher); try { sub.setVariableSuffix((String) null); fail(); } catch (IllegalArgumentException ex) { // expected } assertEquals(true, sub.getVariableSuffixMatcher() instanceof StrMatcher.StringMatcher); StrMatcher matcher = StrMatcher.commaMatcher(); sub.setVariableSuffixMatcher(matcher); assertSame(matcher, sub.getVariableSuffixMatcher()); try { sub.setVariableSuffixMatcher((StrMatcher) null); fail(); } catch (IllegalArgumentException ex) { // expected } assertSame(matcher, sub.getVariableSuffixMatcher()); } //----------------------------------------------------------------------- /** * Tests static. */ public void testStaticReplace() { Map map = new HashMap(); map.put("name", "commons"); assertEquals("Hi commons!", StrSubstitutor.replace("Hi ${name}!", map)); } /** * Tests static. */ public void testStaticReplacePrefixSuffix() { Map map = new HashMap(); map.put("name", "commons"); assertEquals("Hi commons!", StrSubstitutor.replace("Hi !", map, "<", ">")); } /** * Tests interpolation with system properties. */ public void testStaticReplaceSystemProperties() { StrBuilder buf = new StrBuilder(); buf.append("Hi ").append(System.getProperty("user.name")); buf.append(", you are working with "); buf.append(System.getProperty("os.name")); buf.append(", your home directory is "); buf.append(System.getProperty("user.home")).append('.'); assertEquals(buf.toString(), StrSubstitutor.replaceSystemProperties("Hi ${user.name}, you are " + "working with ${os.name}, your home " + "directory is ${user.home}.")); } /** * Test the replace of a properties object */ public void testSubstitutetDefaultProperties(){ String org = "${doesnotwork}"; System.setProperty("doesnotwork", "It work's!"); // create a new Properties object with the System.getProperties as default Properties props = new Properties(System.getProperties()); assertEquals("It work's!",StrSubstitutor.replace(org, props)); } //----------------------------------------------------------------------- private void doTestReplace(String expectedResult, String replaceTemplate, boolean substring) { String expectedShortResult = expectedResult.substring(1, expectedResult.length() - 1); StrSubstitutor sub = new StrSubstitutor(values); // replace using String assertEquals(expectedResult, sub.replace(replaceTemplate)); if (substring) { assertEquals(expectedShortResult, sub.replace(replaceTemplate, 1, replaceTemplate.length() - 2)); } // replace using char[] char[] chars = replaceTemplate.toCharArray(); assertEquals(expectedResult, sub.replace(chars)); if (substring) { assertEquals(expectedShortResult, sub.replace(chars, 1, chars.length - 2)); } // replace using StringBuffer StringBuffer buf = new StringBuffer(replaceTemplate); assertEquals(expectedResult, sub.replace(buf)); if (substring) { assertEquals(expectedShortResult, sub.replace(buf, 1, buf.length() - 2)); } // replace using StrBuilder StrBuilder bld = new StrBuilder(replaceTemplate); assertEquals(expectedResult, sub.replace(bld)); if (substring) { assertEquals(expectedShortResult, sub.replace(bld, 1, bld.length() - 2)); } // replace using object MutableObject obj = new MutableObject(replaceTemplate); // toString returns template assertEquals(expectedResult, sub.replace(obj)); // replace in StringBuffer buf = new StringBuffer(replaceTemplate); assertEquals(true, sub.replaceIn(buf)); assertEquals(expectedResult, buf.toString()); if (substring) { buf = new StringBuffer(replaceTemplate); assertEquals(true, sub.replaceIn(buf, 1, buf.length() - 2)); assertEquals(expectedResult, buf.toString()); // expect full result as remainder is untouched } // replace in StrBuilder bld = new StrBuilder(replaceTemplate); assertEquals(true, sub.replaceIn(bld)); assertEquals(expectedResult, bld.toString()); if (substring) { bld = new StrBuilder(replaceTemplate); assertEquals(true, sub.replaceIn(bld, 1, bld.length() - 2)); assertEquals(expectedResult, bld.toString()); // expect full result as remainder is untouched } } private void doTestNoReplace(String replaceTemplate) { StrSubstitutor sub = new StrSubstitutor(values); if (replaceTemplate == null) { assertEquals(null, sub.replace((String) null)); assertEquals(null, sub.replace((String) null, 0, 100)); assertEquals(null, sub.replace((char[]) null)); assertEquals(null, sub.replace((char[]) null, 0, 100)); assertEquals(null, sub.replace((StringBuffer) null)); assertEquals(null, sub.replace((StringBuffer) null, 0, 100)); assertEquals(null, sub.replace((StrBuilder) null)); assertEquals(null, sub.replace((StrBuilder) null, 0, 100)); assertEquals(null, sub.replace((Object) null)); assertEquals(false, sub.replaceIn((StringBuffer) null)); assertEquals(false, sub.replaceIn((StringBuffer) null, 0, 100)); assertEquals(false, sub.replaceIn((StrBuilder) null)); assertEquals(false, sub.replaceIn((StrBuilder) null, 0, 100)); } else { assertEquals(replaceTemplate, sub.replace(replaceTemplate)); StrBuilder bld = new StrBuilder(replaceTemplate); assertEquals(false, sub.replaceIn(bld)); assertEquals(replaceTemplate, bld.toString()); } } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/text/StrTokenizerTest.java100644 0 0 75354 11513702433 26151 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.text; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.NoSuchElementException; import junit.framework.TestCase; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.ObjectUtils; /** * Unit test for Tokenizer. * * @author Matthew Inger */ public class StrTokenizerTest extends TestCase { private static final String CSV_SIMPLE_FIXTURE = "A,b,c"; private static final String TSV_SIMPLE_FIXTURE = "A\tb\tc"; /** * JUnit constructor. * * @param name */ public StrTokenizerTest(String name) { super(name); } private void checkClone(StrTokenizer tokenizer) { assertFalse(StrTokenizer.getCSVInstance() == tokenizer); assertFalse(StrTokenizer.getTSVInstance() == tokenizer); } // ----------------------------------------------------------------------- public void test1() { String input = "a;b;c;\"d;\"\"e\";f; ; ; "; StrTokenizer tok = new StrTokenizer(input); tok.setDelimiterChar(';'); tok.setQuoteChar('"'); tok.setIgnoredMatcher(StrMatcher.trimMatcher()); tok.setIgnoreEmptyTokens(false); String tokens[] = tok.getTokenArray(); String expected[] = new String[]{"a", "b", "c", "d;\"e", "f", "", "", "",}; assertEquals(ArrayUtils.toString(tokens), expected.length, tokens.length); for (int i = 0; i < expected.length; i++) { assertTrue("token[" + i + "] was '" + tokens[i] + "' but was expected to be '" + expected[i] + "'", ObjectUtils.equals(expected[i], tokens[i])); } } public void test2() { String input = "a;b;c ;\"d;\"\"e\";f; ; ;"; StrTokenizer tok = new StrTokenizer(input); tok.setDelimiterChar(';'); tok.setQuoteChar('"'); tok.setIgnoredMatcher(StrMatcher.noneMatcher()); tok.setIgnoreEmptyTokens(false); String tokens[] = tok.getTokenArray(); String expected[] = new String[]{"a", "b", "c ", "d;\"e", "f", " ", " ", "",}; assertEquals(ArrayUtils.toString(tokens), expected.length, tokens.length); for (int i = 0; i < expected.length; i++) { assertTrue("token[" + i + "] was '" + tokens[i] + "' but was expected to be '" + expected[i] + "'", ObjectUtils.equals(expected[i], tokens[i])); } } public void test3() { String input = "a;b; c;\"d;\"\"e\";f; ; ;"; StrTokenizer tok = new StrTokenizer(input); tok.setDelimiterChar(';'); tok.setQuoteChar('"'); tok.setIgnoredMatcher(StrMatcher.noneMatcher()); tok.setIgnoreEmptyTokens(false); String tokens[] = tok.getTokenArray(); String expected[] = new String[]{"a", "b", " c", "d;\"e", "f", " ", " ", "",}; assertEquals(ArrayUtils.toString(tokens), expected.length, tokens.length); for (int i = 0; i < expected.length; i++) { assertTrue("token[" + i + "] was '" + tokens[i] + "' but was expected to be '" + expected[i] + "'", ObjectUtils.equals(expected[i], tokens[i])); } } public void test4() { String input = "a;b; c;\"d;\"\"e\";f; ; ;"; StrTokenizer tok = new StrTokenizer(input); tok.setDelimiterChar(';'); tok.setQuoteChar('"'); tok.setIgnoredMatcher(StrMatcher.trimMatcher()); tok.setIgnoreEmptyTokens(true); String tokens[] = tok.getTokenArray(); String expected[] = new String[]{"a", "b", "c", "d;\"e", "f",}; assertEquals(ArrayUtils.toString(tokens), expected.length, tokens.length); for (int i = 0; i < expected.length; i++) { assertTrue("token[" + i + "] was '" + tokens[i] + "' but was expected to be '" + expected[i] + "'", ObjectUtils.equals(expected[i], tokens[i])); } } public void test5() { String input = "a;b; c;\"d;\"\"e\";f; ; ;"; StrTokenizer tok = new StrTokenizer(input); tok.setDelimiterChar(';'); tok.setQuoteChar('"'); tok.setIgnoredMatcher(StrMatcher.trimMatcher()); tok.setIgnoreEmptyTokens(false); tok.setEmptyTokenAsNull(true); String tokens[] = tok.getTokenArray(); String expected[] = new String[]{"a", "b", "c", "d;\"e", "f", null, null, null,}; assertEquals(ArrayUtils.toString(tokens), expected.length, tokens.length); for (int i = 0; i < expected.length; i++) { assertTrue("token[" + i + "] was '" + tokens[i] + "' but was expected to be '" + expected[i] + "'", ObjectUtils.equals(expected[i], tokens[i])); } } public void test6() { String input = "a;b; c;\"d;\"\"e\";f; ; ;"; StrTokenizer tok = new StrTokenizer(input); tok.setDelimiterChar(';'); tok.setQuoteChar('"'); tok.setIgnoredMatcher(StrMatcher.trimMatcher()); tok.setIgnoreEmptyTokens(false); // tok.setTreatingEmptyAsNull(true); String tokens[] = tok.getTokenArray(); String expected[] = new String[]{"a", "b", " c", "d;\"e", "f", null, null, null,}; int nextCount = 0; while (tok.hasNext()) { tok.next(); nextCount++; } int prevCount = 0; while (tok.hasPrevious()) { tok.previous(); prevCount++; } assertEquals(ArrayUtils.toString(tokens), expected.length, tokens.length); assertTrue("could not cycle through entire token list" + " using the 'hasNext' and 'next' methods", nextCount == expected.length); assertTrue("could not cycle through entire token list" + " using the 'hasPrevious' and 'previous' methods", prevCount == expected.length); } public void test7() { String input = "a b c \"d e\" f "; StrTokenizer tok = new StrTokenizer(input); tok.setDelimiterMatcher(StrMatcher.spaceMatcher()); tok.setQuoteMatcher(StrMatcher.doubleQuoteMatcher()); tok.setIgnoredMatcher(StrMatcher.noneMatcher()); tok.setIgnoreEmptyTokens(false); String tokens[] = tok.getTokenArray(); String expected[] = new String[]{"a", "", "", "b", "c", "d e", "f", "",}; assertEquals(ArrayUtils.toString(tokens), expected.length, tokens.length); for (int i = 0; i < expected.length; i++) { assertTrue("token[" + i + "] was '" + tokens[i] + "' but was expected to be '" + expected[i] + "'", ObjectUtils.equals(expected[i], tokens[i])); } } public void test8() { String input = "a b c \"d e\" f "; StrTokenizer tok = new StrTokenizer(input); tok.setDelimiterMatcher(StrMatcher.spaceMatcher()); tok.setQuoteMatcher(StrMatcher.doubleQuoteMatcher()); tok.setIgnoredMatcher(StrMatcher.noneMatcher()); tok.setIgnoreEmptyTokens(true); String tokens[] = tok.getTokenArray(); String expected[] = new String[]{"a", "b", "c", "d e", "f",}; assertEquals(ArrayUtils.toString(tokens), expected.length, tokens.length); for (int i = 0; i < expected.length; i++) { assertTrue("token[" + i + "] was '" + tokens[i] + "' but was expected to be '" + expected[i] + "'", ObjectUtils.equals(expected[i], tokens[i])); } } public void testBasic1() { String input = "a b c"; StrTokenizer tok = new StrTokenizer(input); assertEquals("a", tok.next()); assertEquals("b", tok.next()); assertEquals("c", tok.next()); assertEquals(false, tok.hasNext()); } public void testBasic2() { String input = "a \nb\fc"; StrTokenizer tok = new StrTokenizer(input); assertEquals("a", tok.next()); assertEquals("b", tok.next()); assertEquals("c", tok.next()); assertEquals(false, tok.hasNext()); } public void testBasic3() { String input = "a \nb\u0001\fc"; StrTokenizer tok = new StrTokenizer(input); assertEquals("a", tok.next()); assertEquals("b\u0001", tok.next()); assertEquals("c", tok.next()); assertEquals(false, tok.hasNext()); } public void testBasic4() { String input = "a \"b\" c"; StrTokenizer tok = new StrTokenizer(input); assertEquals("a", tok.next()); assertEquals("\"b\"", tok.next()); assertEquals("c", tok.next()); assertEquals(false, tok.hasNext()); } public void testBasic5() { String input = "a:b':c"; StrTokenizer tok = new StrTokenizer(input, ':', '\''); assertEquals("a", tok.next()); assertEquals("b'", tok.next()); assertEquals("c", tok.next()); assertEquals(false, tok.hasNext()); } public void testBasicDelim1() { String input = "a:b:c"; StrTokenizer tok = new StrTokenizer(input, ':'); assertEquals("a", tok.next()); assertEquals("b", tok.next()); assertEquals("c", tok.next()); assertEquals(false, tok.hasNext()); } public void testBasicDelim2() { String input = "a:b:c"; StrTokenizer tok = new StrTokenizer(input, ','); assertEquals("a:b:c", tok.next()); assertEquals(false, tok.hasNext()); } public void testBasicEmpty1() { String input = "a b c"; StrTokenizer tok = new StrTokenizer(input); tok.setIgnoreEmptyTokens(false); assertEquals("a", tok.next()); assertEquals("", tok.next()); assertEquals("b", tok.next()); assertEquals("c", tok.next()); assertEquals(false, tok.hasNext()); } public void testBasicEmpty2() { String input = "a b c"; StrTokenizer tok = new StrTokenizer(input); tok.setIgnoreEmptyTokens(false); tok.setEmptyTokenAsNull(true); assertEquals("a", tok.next()); assertEquals(null, tok.next()); assertEquals("b", tok.next()); assertEquals("c", tok.next()); assertEquals(false, tok.hasNext()); } public void testBasicQuoted1() { String input = "a 'b' c"; StrTokenizer tok = new StrTokenizer(input, ' ', '\''); assertEquals("a", tok.next()); assertEquals("b", tok.next()); assertEquals("c", tok.next()); assertEquals(false, tok.hasNext()); } public void testBasicQuoted2() { String input = "a:'b':"; StrTokenizer tok = new StrTokenizer(input, ':', '\''); tok.setIgnoreEmptyTokens(false); tok.setEmptyTokenAsNull(true); assertEquals("a", tok.next()); assertEquals("b", tok.next()); assertEquals(null, tok.next()); assertEquals(false, tok.hasNext()); } public void testBasicQuoted3() { String input = "a:'b''c'"; StrTokenizer tok = new StrTokenizer(input, ':', '\''); tok.setIgnoreEmptyTokens(false); tok.setEmptyTokenAsNull(true); assertEquals("a", tok.next()); assertEquals("b'c", tok.next()); assertEquals(false, tok.hasNext()); } public void testBasicQuoted4() { String input = "a: 'b' 'c' :d"; StrTokenizer tok = new StrTokenizer(input, ':', '\''); tok.setTrimmerMatcher(StrMatcher.trimMatcher()); tok.setIgnoreEmptyTokens(false); tok.setEmptyTokenAsNull(true); assertEquals("a", tok.next()); assertEquals("b c", tok.next()); assertEquals("d", tok.next()); assertEquals(false, tok.hasNext()); } public void testBasicQuoted5() { String input = "a: 'b'x'c' :d"; StrTokenizer tok = new StrTokenizer(input, ':', '\''); tok.setTrimmerMatcher(StrMatcher.trimMatcher()); tok.setIgnoreEmptyTokens(false); tok.setEmptyTokenAsNull(true); assertEquals("a", tok.next()); assertEquals("bxc", tok.next()); assertEquals("d", tok.next()); assertEquals(false, tok.hasNext()); } public void testBasicQuoted6() { String input = "a:'b'\"c':d"; StrTokenizer tok = new StrTokenizer(input, ':'); tok.setQuoteMatcher(StrMatcher.quoteMatcher()); assertEquals("a", tok.next()); assertEquals("b\"c:d", tok.next()); assertEquals(false, tok.hasNext()); } public void testBasicQuoted7() { String input = "a:\"There's a reason here\":b"; StrTokenizer tok = new StrTokenizer(input, ':'); tok.setQuoteMatcher(StrMatcher.quoteMatcher()); assertEquals("a", tok.next()); assertEquals("There's a reason here", tok.next()); assertEquals("b", tok.next()); assertEquals(false, tok.hasNext()); } public void testBasicQuotedTrimmed1() { String input = "a: 'b' :"; StrTokenizer tok = new StrTokenizer(input, ':', '\''); tok.setTrimmerMatcher(StrMatcher.trimMatcher()); tok.setIgnoreEmptyTokens(false); tok.setEmptyTokenAsNull(true); assertEquals("a", tok.next()); assertEquals("b", tok.next()); assertEquals(null, tok.next()); assertEquals(false, tok.hasNext()); } public void testBasicTrimmed1() { String input = "a: b : "; StrTokenizer tok = new StrTokenizer(input, ':'); tok.setTrimmerMatcher(StrMatcher.trimMatcher()); tok.setIgnoreEmptyTokens(false); tok.setEmptyTokenAsNull(true); assertEquals("a", tok.next()); assertEquals("b", tok.next()); assertEquals(null, tok.next()); assertEquals(false, tok.hasNext()); } public void testBasicTrimmed2() { String input = "a: b :"; StrTokenizer tok = new StrTokenizer(input, ':'); tok.setTrimmerMatcher(StrMatcher.stringMatcher(" ")); tok.setIgnoreEmptyTokens(false); tok.setEmptyTokenAsNull(true); assertEquals("a", tok.next()); assertEquals("b", tok.next()); assertEquals(null, tok.next()); assertEquals(false, tok.hasNext()); } public void testBasicIgnoreTrimmed1() { String input = "a: bIGNOREc : "; StrTokenizer tok = new StrTokenizer(input, ':'); tok.setIgnoredMatcher(StrMatcher.stringMatcher("IGNORE")); tok.setTrimmerMatcher(StrMatcher.trimMatcher()); tok.setIgnoreEmptyTokens(false); tok.setEmptyTokenAsNull(true); assertEquals("a", tok.next()); assertEquals("bc", tok.next()); assertEquals(null, tok.next()); assertEquals(false, tok.hasNext()); } public void testBasicIgnoreTrimmed2() { String input = "IGNOREaIGNORE: IGNORE bIGNOREc IGNORE : IGNORE "; StrTokenizer tok = new StrTokenizer(input, ':'); tok.setIgnoredMatcher(StrMatcher.stringMatcher("IGNORE")); tok.setTrimmerMatcher(StrMatcher.trimMatcher()); tok.setIgnoreEmptyTokens(false); tok.setEmptyTokenAsNull(true); assertEquals("a", tok.next()); assertEquals("bc", tok.next()); assertEquals(null, tok.next()); assertEquals(false, tok.hasNext()); } public void testBasicIgnoreTrimmed3() { String input = "IGNOREaIGNORE: IGNORE bIGNOREc IGNORE : IGNORE "; StrTokenizer tok = new StrTokenizer(input, ':'); tok.setIgnoredMatcher(StrMatcher.stringMatcher("IGNORE")); tok.setIgnoreEmptyTokens(false); tok.setEmptyTokenAsNull(true); assertEquals("a", tok.next()); assertEquals(" bc ", tok.next()); assertEquals(" ", tok.next()); assertEquals(false, tok.hasNext()); } public void testBasicIgnoreTrimmed4() { String input = "IGNOREaIGNORE: IGNORE 'bIGNOREc'IGNORE'd' IGNORE : IGNORE "; StrTokenizer tok = new StrTokenizer(input, ':', '\''); tok.setIgnoredMatcher(StrMatcher.stringMatcher("IGNORE")); tok.setTrimmerMatcher(StrMatcher.trimMatcher()); tok.setIgnoreEmptyTokens(false); tok.setEmptyTokenAsNull(true); assertEquals("a", tok.next()); assertEquals("bIGNOREcd", tok.next()); assertEquals(null, tok.next()); assertEquals(false, tok.hasNext()); } //----------------------------------------------------------------------- public void testListArray() { String input = "a b c"; StrTokenizer tok = new StrTokenizer(input); String[] array = tok.getTokenArray(); List list = tok.getTokenList(); assertEquals(Arrays.asList(array), list); assertEquals(3, list.size()); } //----------------------------------------------------------------------- public void testCSV(String data) { this.testXSVAbc(StrTokenizer.getCSVInstance(data)); this.testXSVAbc(StrTokenizer.getCSVInstance(data.toCharArray())); } public void testCSVEmpty() { this.testEmpty(StrTokenizer.getCSVInstance()); this.testEmpty(StrTokenizer.getCSVInstance("")); } public void testCSVSimple() { this.testCSV(CSV_SIMPLE_FIXTURE); } public void testCSVSimpleNeedsTrim() { this.testCSV(" " + CSV_SIMPLE_FIXTURE); this.testCSV(" \n\t " + CSV_SIMPLE_FIXTURE); this.testCSV(" \n " + CSV_SIMPLE_FIXTURE + "\n\n\r"); } void testEmpty(StrTokenizer tokenizer) { this.checkClone(tokenizer); assertEquals(false, tokenizer.hasNext()); assertEquals(false, tokenizer.hasPrevious()); assertEquals(null, tokenizer.nextToken()); assertEquals(0, tokenizer.size()); try { tokenizer.next(); fail(); } catch (NoSuchElementException ex) {} } public void testGetContent() { String input = "a b c \"d e\" f "; StrTokenizer tok = new StrTokenizer(input); assertEquals(input, tok.getContent()); tok = new StrTokenizer(input.toCharArray()); assertEquals(input, tok.getContent()); tok = new StrTokenizer(); assertEquals(null, tok.getContent()); } //----------------------------------------------------------------------- public void testChaining() { StrTokenizer tok = new StrTokenizer(); assertEquals(tok, tok.reset()); assertEquals(tok, tok.reset("")); assertEquals(tok, tok.reset(new char[0])); assertEquals(tok, tok.setDelimiterChar(' ')); assertEquals(tok, tok.setDelimiterString(" ")); assertEquals(tok, tok.setDelimiterMatcher(null)); assertEquals(tok, tok.setQuoteChar(' ')); assertEquals(tok, tok.setQuoteMatcher(null)); assertEquals(tok, tok.setIgnoredChar(' ')); assertEquals(tok, tok.setIgnoredMatcher(null)); assertEquals(tok, tok.setTrimmerMatcher(null)); assertEquals(tok, tok.setEmptyTokenAsNull(false)); assertEquals(tok, tok.setIgnoreEmptyTokens(false)); } /** * Tests that the {@link StrTokenizer#clone()} clone method catches {@link CloneNotSupportedException} and returns * null. */ public void testCloneNotSupportedException() { Object notCloned = (new StrTokenizer() { Object cloneReset() throws CloneNotSupportedException { throw new CloneNotSupportedException("test"); } }).clone(); assertNull(notCloned); } public void testCloneNull() { StrTokenizer tokenizer = new StrTokenizer((char[]) null); // Start sanity check assertEquals(null, tokenizer.nextToken()); tokenizer.reset(); assertEquals(null, tokenizer.nextToken()); // End sanity check StrTokenizer clonedTokenizer = (StrTokenizer) tokenizer.clone(); tokenizer.reset(); assertEquals(null, tokenizer.nextToken()); assertEquals(null, clonedTokenizer.nextToken()); } public void testCloneReset() { char[] input = new char[]{'a'}; StrTokenizer tokenizer = new StrTokenizer(input); // Start sanity check assertEquals("a", tokenizer.nextToken()); tokenizer.reset(); assertEquals("a", tokenizer.nextToken()); // End sanity check StrTokenizer clonedTokenizer = (StrTokenizer) tokenizer.clone(); input[0] = 'b'; tokenizer.reset(); assertEquals("b", tokenizer.nextToken()); assertEquals("a", clonedTokenizer.nextToken()); } // ----------------------------------------------------------------------- public void testConstructor_String() { StrTokenizer tok = new StrTokenizer("a b"); assertEquals("a", tok.next()); assertEquals("b", tok.next()); assertEquals(false, tok.hasNext()); tok = new StrTokenizer(""); assertEquals(false, tok.hasNext()); tok = new StrTokenizer((String) null); assertEquals(false, tok.hasNext()); } //----------------------------------------------------------------------- public void testConstructor_String_char() { StrTokenizer tok = new StrTokenizer("a b", ' '); assertEquals(1, tok.getDelimiterMatcher().isMatch(" ".toCharArray(), 0, 0, 1)); assertEquals("a", tok.next()); assertEquals("b", tok.next()); assertEquals(false, tok.hasNext()); tok = new StrTokenizer("", ' '); assertEquals(false, tok.hasNext()); tok = new StrTokenizer((String) null, ' '); assertEquals(false, tok.hasNext()); } //----------------------------------------------------------------------- public void testConstructor_String_char_char() { StrTokenizer tok = new StrTokenizer("a b", ' ', '"'); assertEquals(1, tok.getDelimiterMatcher().isMatch(" ".toCharArray(), 0, 0, 1)); assertEquals(1, tok.getQuoteMatcher().isMatch("\"".toCharArray(), 0, 0, 1)); assertEquals("a", tok.next()); assertEquals("b", tok.next()); assertEquals(false, tok.hasNext()); tok = new StrTokenizer("", ' ', '"'); assertEquals(false, tok.hasNext()); tok = new StrTokenizer((String) null, ' ', '"'); assertEquals(false, tok.hasNext()); } //----------------------------------------------------------------------- public void testConstructor_charArray() { StrTokenizer tok = new StrTokenizer("a b".toCharArray()); assertEquals("a", tok.next()); assertEquals("b", tok.next()); assertEquals(false, tok.hasNext()); tok = new StrTokenizer(new char[0]); assertEquals(false, tok.hasNext()); tok = new StrTokenizer((char[]) null); assertEquals(false, tok.hasNext()); } //----------------------------------------------------------------------- public void testConstructor_charArray_char() { StrTokenizer tok = new StrTokenizer("a b".toCharArray(), ' '); assertEquals(1, tok.getDelimiterMatcher().isMatch(" ".toCharArray(), 0, 0, 1)); assertEquals("a", tok.next()); assertEquals("b", tok.next()); assertEquals(false, tok.hasNext()); tok = new StrTokenizer(new char[0], ' '); assertEquals(false, tok.hasNext()); tok = new StrTokenizer((char[]) null, ' '); assertEquals(false, tok.hasNext()); } //----------------------------------------------------------------------- public void testConstructor_charArray_char_char() { StrTokenizer tok = new StrTokenizer("a b".toCharArray(), ' ', '"'); assertEquals(1, tok.getDelimiterMatcher().isMatch(" ".toCharArray(), 0, 0, 1)); assertEquals(1, tok.getQuoteMatcher().isMatch("\"".toCharArray(), 0, 0, 1)); assertEquals("a", tok.next()); assertEquals("b", tok.next()); assertEquals(false, tok.hasNext()); tok = new StrTokenizer(new char[0], ' ', '"'); assertEquals(false, tok.hasNext()); tok = new StrTokenizer((char[]) null, ' ', '"'); assertEquals(false, tok.hasNext()); } //----------------------------------------------------------------------- public void testReset() { StrTokenizer tok = new StrTokenizer("a b c"); assertEquals("a", tok.next()); assertEquals("b", tok.next()); assertEquals("c", tok.next()); assertEquals(false, tok.hasNext()); tok.reset(); assertEquals("a", tok.next()); assertEquals("b", tok.next()); assertEquals("c", tok.next()); assertEquals(false, tok.hasNext()); } //----------------------------------------------------------------------- public void testReset_String() { StrTokenizer tok = new StrTokenizer("x x x"); tok.reset("d e"); assertEquals("d", tok.next()); assertEquals("e", tok.next()); assertEquals(false, tok.hasNext()); tok.reset((String) null); assertEquals(false, tok.hasNext()); } //----------------------------------------------------------------------- public void testReset_charArray() { StrTokenizer tok = new StrTokenizer("x x x"); char[] array = new char[] {'a', ' ', 'c'}; tok.reset(array); array[1] = 'b'; // test linked array assertEquals("abc", tok.next()); assertEquals(false, tok.hasNext()); tok.reset((char[]) null); assertEquals(false, tok.hasNext()); } //----------------------------------------------------------------------- public void testTSV() { this.testXSVAbc(StrTokenizer.getTSVInstance(TSV_SIMPLE_FIXTURE)); this.testXSVAbc(StrTokenizer.getTSVInstance(TSV_SIMPLE_FIXTURE.toCharArray())); } public void testTSVEmpty() { this.testEmpty(StrTokenizer.getCSVInstance()); this.testEmpty(StrTokenizer.getCSVInstance("")); } void testXSVAbc(StrTokenizer tokenizer) { this.checkClone(tokenizer); assertEquals(-1, tokenizer.previousIndex()); assertEquals(0, tokenizer.nextIndex()); assertEquals(null, tokenizer.previousToken()); assertEquals("A", tokenizer.nextToken()); assertEquals(1, tokenizer.nextIndex()); assertEquals("b", tokenizer.nextToken()); assertEquals(2, tokenizer.nextIndex()); assertEquals("c", tokenizer.nextToken()); assertEquals(3, tokenizer.nextIndex()); assertEquals(null, tokenizer.nextToken()); assertEquals(3, tokenizer.nextIndex()); assertEquals("c", tokenizer.previousToken()); assertEquals(2, tokenizer.nextIndex()); assertEquals("b", tokenizer.previousToken()); assertEquals(1, tokenizer.nextIndex()); assertEquals("A", tokenizer.previousToken()); assertEquals(0, tokenizer.nextIndex()); assertEquals(null, tokenizer.previousToken()); assertEquals(0, tokenizer.nextIndex()); assertEquals(-1, tokenizer.previousIndex()); assertEquals(3, tokenizer.size()); } public void testIteration() { StrTokenizer tkn = new StrTokenizer("a b c"); assertEquals(false, tkn.hasPrevious()); try { tkn.previous(); fail(); } catch (NoSuchElementException ex) {} assertEquals(true, tkn.hasNext()); assertEquals("a", tkn.next()); try { tkn.remove(); fail(); } catch (UnsupportedOperationException ex) {} try { tkn.set("x"); fail(); } catch (UnsupportedOperationException ex) {} try { tkn.add("y"); fail(); } catch (UnsupportedOperationException ex) {} assertEquals(true, tkn.hasPrevious()); assertEquals(true, tkn.hasNext()); assertEquals("b", tkn.next()); assertEquals(true, tkn.hasPrevious()); assertEquals(true, tkn.hasNext()); assertEquals("c", tkn.next()); assertEquals(true, tkn.hasPrevious()); assertEquals(false, tkn.hasNext()); try { tkn.next(); fail(); } catch (NoSuchElementException ex) {} assertEquals(true, tkn.hasPrevious()); assertEquals(false, tkn.hasNext()); } //----------------------------------------------------------------------- public void testTokenizeSubclassInputChange() { StrTokenizer tkn = new StrTokenizer("a b c d e") { protected List tokenize(char[] chars, int offset, int count) { return super.tokenize("w x y z".toCharArray(), 2, 5); } }; assertEquals("x", tkn.next()); assertEquals("y", tkn.next()); } //----------------------------------------------------------------------- public void testTokenizeSubclassOutputChange() { StrTokenizer tkn = new StrTokenizer("a b c") { protected List tokenize(char[] chars, int offset, int count) { List list = super.tokenize(chars, offset, count); Collections.reverse(list); return list; } }; assertEquals("c", tkn.next()); assertEquals("b", tkn.next()); assertEquals("a", tkn.next()); } //----------------------------------------------------------------------- public void testToString() { StrTokenizer tkn = new StrTokenizer("a b c d e"); assertEquals("StrTokenizer[not tokenized yet]", tkn.toString()); tkn.next(); assertEquals("StrTokenizer[a, b, c, d, e]", tkn.toString()); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/time/DateFormatUtilsTest.java100644 0 0 27571 11513702435 26527 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.time; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.util.Calendar; import java.util.Locale; import java.util.TimeZone; import junit.framework.TestCase; /** * TestCase for DateFormatUtils. * * @author Apache Software Foundation * @author Apache Ant - DateUtilsTest * @author Stephane Bailliez * @author Stefan Bodewig * @author Gary Gregory */ public class DateFormatUtilsTest extends TestCase { public DateFormatUtilsTest(String s) { super(s); } //----------------------------------------------------------------------- public void testConstructor() { assertNotNull(new DateFormatUtils()); Constructor[] cons = DateFormatUtils.class.getDeclaredConstructors(); assertEquals(1, cons.length); assertEquals(true, Modifier.isPublic(cons[0].getModifiers())); assertEquals(true, Modifier.isPublic(DateFormatUtils.class.getModifiers())); assertEquals(false, Modifier.isFinal(DateFormatUtils.class.getModifiers())); } //----------------------------------------------------------------------- public void testFormat() { Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC")); c.set(2005,0,1,12,0,0); c.setTimeZone(TimeZone.getDefault()); StringBuffer buffer = new StringBuffer (); int year = c.get(Calendar.YEAR); int month = c.get(Calendar.MONTH) + 1; int day = c.get(Calendar.DAY_OF_MONTH); int hour = c.get(Calendar.HOUR_OF_DAY); buffer.append (year); buffer.append(month); buffer.append(day); buffer.append(hour); assertEquals(buffer.toString(), DateFormatUtils.format(c.getTime(), "yyyyMdH")); assertEquals(buffer.toString(), DateFormatUtils.format(c.getTime().getTime(), "yyyyMdH")); assertEquals(buffer.toString(), DateFormatUtils.format(c.getTime(), "yyyyMdH", Locale.US)); assertEquals(buffer.toString(), DateFormatUtils.format(c.getTime().getTime(), "yyyyMdH", Locale.US)); } //----------------------------------------------------------------------- public void testFormatCalendar() { Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC")); c.set(2005,0,1,12,0,0); c.setTimeZone(TimeZone.getDefault()); StringBuffer buffer = new StringBuffer (); int year = c.get(Calendar.YEAR); int month = c.get(Calendar.MONTH) + 1; int day = c.get(Calendar.DAY_OF_MONTH); int hour = c.get(Calendar.HOUR_OF_DAY); buffer.append (year); buffer.append(month); buffer.append(day); buffer.append(hour); assertEquals(buffer.toString(), DateFormatUtils.format(c, "yyyyMdH")); assertEquals(buffer.toString(), DateFormatUtils.format(c.getTime(), "yyyyMdH")); assertEquals(buffer.toString(), DateFormatUtils.format(c, "yyyyMdH", Locale.US)); assertEquals(buffer.toString(), DateFormatUtils.format(c.getTime(), "yyyyMdH", Locale.US)); } public void testFormatUTC() { Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC")); c.set(2005,0,1,12,0,0); assertEquals ("2005-01-01T12:00:00", DateFormatUtils.formatUTC(c.getTime(), DateFormatUtils.ISO_DATETIME_FORMAT.getPattern())); assertEquals ("2005-01-01T12:00:00", DateFormatUtils.formatUTC(c.getTime().getTime(), DateFormatUtils.ISO_DATETIME_FORMAT.getPattern())); assertEquals ("2005-01-01T12:00:00", DateFormatUtils.formatUTC(c.getTime(), DateFormatUtils.ISO_DATETIME_FORMAT.getPattern(), Locale.US)); assertEquals ("2005-01-01T12:00:00", DateFormatUtils.formatUTC(c.getTime().getTime(), DateFormatUtils.ISO_DATETIME_FORMAT.getPattern(), Locale.US)); } public void testDateTimeISO(){ TimeZone timeZone = TimeZone.getTimeZone("GMT-3"); Calendar cal = Calendar.getInstance(timeZone); cal.set(2002,1,23,9,11,12); String text = DateFormatUtils.format(cal.getTime(), DateFormatUtils.ISO_DATETIME_FORMAT.getPattern(), timeZone); assertEquals("2002-02-23T09:11:12", text); text = DateFormatUtils.format(cal.getTime().getTime(), DateFormatUtils.ISO_DATETIME_FORMAT.getPattern(), timeZone); assertEquals("2002-02-23T09:11:12", text); text = DateFormatUtils.ISO_DATETIME_FORMAT.format(cal); assertEquals("2002-02-23T09:11:12", text); text = DateFormatUtils.format(cal.getTime(), DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.getPattern(), timeZone); assertEquals("2002-02-23T09:11:12-03:00", text); text = DateFormatUtils.format(cal.getTime().getTime(), DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.getPattern(), timeZone); assertEquals("2002-02-23T09:11:12-03:00", text); text = DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.format(cal); assertEquals("2002-02-23T09:11:12-03:00", text); } public void testDateISO(){ TimeZone timeZone = TimeZone.getTimeZone("GMT-3"); Calendar cal = Calendar.getInstance(timeZone); cal.set(2002,1,23,10,11,12); String text = DateFormatUtils.format(cal.getTime(), DateFormatUtils.ISO_DATE_FORMAT.getPattern(), timeZone); assertEquals("2002-02-23", text); text = DateFormatUtils.format(cal.getTime().getTime(), DateFormatUtils.ISO_DATE_FORMAT.getPattern(), timeZone); assertEquals("2002-02-23", text); text = DateFormatUtils.ISO_DATE_FORMAT.format(cal); assertEquals("2002-02-23", text); text = DateFormatUtils.format(cal.getTime(), DateFormatUtils.ISO_DATE_TIME_ZONE_FORMAT.getPattern(), timeZone); assertEquals("2002-02-23-03:00", text); text = DateFormatUtils.format(cal.getTime().getTime(), DateFormatUtils.ISO_DATE_TIME_ZONE_FORMAT.getPattern(), timeZone); assertEquals("2002-02-23-03:00", text); text = DateFormatUtils.ISO_DATE_TIME_ZONE_FORMAT.format(cal); assertEquals("2002-02-23-03:00", text); } public void testTimeISO(){ TimeZone timeZone = TimeZone.getTimeZone("GMT-3"); Calendar cal = Calendar.getInstance(timeZone); cal.set(2002,1,23,10,11,12); String text = DateFormatUtils.format(cal.getTime(), DateFormatUtils.ISO_TIME_FORMAT.getPattern(), timeZone); assertEquals("T10:11:12", text); text = DateFormatUtils.format(cal.getTime().getTime(), DateFormatUtils.ISO_TIME_FORMAT.getPattern(), timeZone); assertEquals("T10:11:12", text); text = DateFormatUtils.ISO_TIME_FORMAT.format(cal); assertEquals("T10:11:12", text); text = DateFormatUtils.format(cal.getTime(), DateFormatUtils.ISO_TIME_TIME_ZONE_FORMAT.getPattern(), timeZone); assertEquals("T10:11:12-03:00", text); text = DateFormatUtils.format(cal.getTime().getTime(), DateFormatUtils.ISO_TIME_TIME_ZONE_FORMAT.getPattern(), timeZone); assertEquals("T10:11:12-03:00", text); text = DateFormatUtils.ISO_TIME_TIME_ZONE_FORMAT.format(cal); assertEquals("T10:11:12-03:00", text); } public void testTimeNoTISO(){ TimeZone timeZone = TimeZone.getTimeZone("GMT-3"); Calendar cal = Calendar.getInstance(timeZone); cal.set(2002,1,23,10,11,12); String text = DateFormatUtils.format(cal.getTime(), DateFormatUtils.ISO_TIME_NO_T_FORMAT.getPattern(), timeZone); assertEquals("10:11:12", text); text = DateFormatUtils.format(cal.getTime().getTime(), DateFormatUtils.ISO_TIME_NO_T_FORMAT.getPattern(), timeZone); assertEquals("10:11:12", text); text = DateFormatUtils.ISO_TIME_NO_T_FORMAT.format(cal); assertEquals("10:11:12", text); text = DateFormatUtils.format(cal.getTime(), DateFormatUtils.ISO_TIME_NO_T_TIME_ZONE_FORMAT.getPattern(), timeZone); assertEquals("10:11:12-03:00", text); text = DateFormatUtils.format(cal.getTime().getTime(), DateFormatUtils.ISO_TIME_NO_T_TIME_ZONE_FORMAT.getPattern(), timeZone); assertEquals("10:11:12-03:00", text); text = DateFormatUtils.ISO_TIME_NO_T_TIME_ZONE_FORMAT.format(cal); assertEquals("10:11:12-03:00", text); } public void testSMTP(){ TimeZone timeZone = TimeZone.getTimeZone("GMT-3"); Calendar cal = Calendar.getInstance(timeZone); cal.set(2003,5,8,10,11,12); String text = DateFormatUtils.format(cal.getTime(), DateFormatUtils.SMTP_DATETIME_FORMAT.getPattern(), timeZone, DateFormatUtils.SMTP_DATETIME_FORMAT.getLocale()); assertEquals("Sun, 08 Jun 2003 10:11:12 -0300", text); text = DateFormatUtils.format(cal.getTime().getTime(), DateFormatUtils.SMTP_DATETIME_FORMAT.getPattern(), timeZone, DateFormatUtils.SMTP_DATETIME_FORMAT.getLocale()); assertEquals("Sun, 08 Jun 2003 10:11:12 -0300", text); text = DateFormatUtils.SMTP_DATETIME_FORMAT.format(cal); assertEquals("Sun, 08 Jun 2003 10:11:12 -0300", text); // format UTC text = DateFormatUtils.formatUTC(cal.getTime().getTime(), DateFormatUtils.SMTP_DATETIME_FORMAT.getPattern(), DateFormatUtils.SMTP_DATETIME_FORMAT.getLocale()); assertEquals("Sun, 08 Jun 2003 13:11:12 +0000", text); } /* public void testLang312() { String pattern = "dd/MM/yyyy"; String expected = "19/04/1948"; TimeZone timeZone = TimeZone.getTimeZone("CET"); Locale locale = Locale.GERMANY; // show Calendar is good Calendar cal = Calendar.getInstance(timeZone, locale); cal.set(1948, 3, 19); assertEquals(expected, DateFormatUtils.format( cal.getTime(), pattern, timeZone, locale ) ); Date date = new Date(48, 3, 19); // test JDK java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(pattern, locale); sdf.setTimeZone(timeZone); // There's nothing we can do if the JDK fails, so just going to pring a warning in this case // assertEquals(expected, sdf.format( date ) ); if( ! expected.equals( sdf.format( date ) ) ) { System.out.println("WARNING: JDK test failed - testLang312()"); } // test Commons assertEquals(expected, DateFormatUtils.format( date, pattern, timeZone, locale ) ); } */ } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/time/DateUtilsFragmentTest.java100644 0 0 53337 11513702435 27041 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.time; import java.util.Calendar; import java.util.Date; import junit.framework.TestCase; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.time.DateFormatUtils; public class DateUtilsFragmentTest extends TestCase { private static final int months = 7; // second final prime before 12 private static final int days = 23; // second final prime before 31 (and valid) private static final int hours = 19; // second final prime before 24 private static final int minutes = 53; // second final prime before 60 private static final int seconds = 47; // third final prime before 60 private static final int millis = 991; // second final prime before 1000 private Date aDate; private Calendar aCalendar; protected void setUp() { aCalendar = Calendar.getInstance(); aCalendar.set(2005, months, days, hours, minutes, seconds); aCalendar.set(Calendar.MILLISECOND, millis); aDate = aCalendar.getTime(); } public void testNullDate() { try { DateUtils.getFragmentInMilliseconds((Date) null, Calendar.MILLISECOND); fail(); } catch(IllegalArgumentException iae) {} try { DateUtils.getFragmentInSeconds((Date) null, Calendar.MILLISECOND); fail(); } catch(IllegalArgumentException iae) {} try { DateUtils.getFragmentInMinutes((Date) null, Calendar.MILLISECOND); fail(); } catch(IllegalArgumentException iae) {} try { DateUtils.getFragmentInHours((Date) null, Calendar.MILLISECOND); fail(); } catch(IllegalArgumentException iae) {} try { DateUtils.getFragmentInDays((Date) null, Calendar.MILLISECOND); fail(); } catch(IllegalArgumentException iae) {} } public void testNullCalendar() { try { DateUtils.getFragmentInMilliseconds((Calendar) null, Calendar.MILLISECOND); fail(); } catch(IllegalArgumentException iae) {} try { DateUtils.getFragmentInSeconds((Calendar) null, Calendar.MILLISECOND); fail(); } catch(IllegalArgumentException iae) {} try { DateUtils.getFragmentInMinutes((Calendar) null, Calendar.MILLISECOND); fail(); } catch(IllegalArgumentException iae) {} try { DateUtils.getFragmentInHours((Calendar) null, Calendar.MILLISECOND); fail(); } catch(IllegalArgumentException iae) {} try { DateUtils.getFragmentInDays((Calendar) null, Calendar.MILLISECOND); fail(); } catch(IllegalArgumentException iae) {} } public void testInvalidFragmentWithDate() { try { DateUtils.getFragmentInMilliseconds(aDate, 0); fail(); } catch(IllegalArgumentException iae) {} try { DateUtils.getFragmentInSeconds(aDate, 0); fail(); } catch(IllegalArgumentException iae) {} try { DateUtils.getFragmentInMinutes(aDate, 0); fail(); } catch(IllegalArgumentException iae) {} try { DateUtils.getFragmentInHours(aDate, 0); fail(); } catch(IllegalArgumentException iae) {} try { DateUtils.getFragmentInDays(aDate, 0); fail(); } catch(IllegalArgumentException iae) {} } public void testInvalidFragmentWithCalendar() { try { DateUtils.getFragmentInMilliseconds(aCalendar, 0); fail(); } catch(IllegalArgumentException iae) {} try { DateUtils.getFragmentInSeconds(aCalendar, 0); fail(); } catch(IllegalArgumentException iae) {} try { DateUtils.getFragmentInMinutes(aCalendar, 0); fail(); } catch(IllegalArgumentException iae) {} try { DateUtils.getFragmentInHours(aCalendar, 0); fail(); } catch(IllegalArgumentException iae) {} try { DateUtils.getFragmentInDays(aCalendar, 0); fail(); } catch(IllegalArgumentException iae) {} } public void testMillisecondFragmentInLargerUnitWithDate() { assertEquals(0, DateUtils.getFragmentInMilliseconds(aDate, Calendar.MILLISECOND)); assertEquals(0, DateUtils.getFragmentInSeconds(aDate, Calendar.MILLISECOND)); assertEquals(0, DateUtils.getFragmentInMinutes(aDate, Calendar.MILLISECOND)); assertEquals(0, DateUtils.getFragmentInHours(aDate, Calendar.MILLISECOND)); assertEquals(0, DateUtils.getFragmentInDays(aDate, Calendar.MILLISECOND)); } public void testMillisecondFragmentInLargerUnitWithCalendar() { assertEquals(0, DateUtils.getFragmentInMilliseconds(aCalendar, Calendar.MILLISECOND)); assertEquals(0, DateUtils.getFragmentInSeconds(aCalendar, Calendar.MILLISECOND)); assertEquals(0, DateUtils.getFragmentInMinutes(aCalendar, Calendar.MILLISECOND)); assertEquals(0, DateUtils.getFragmentInHours(aCalendar, Calendar.MILLISECOND)); assertEquals(0, DateUtils.getFragmentInDays(aCalendar, Calendar.MILLISECOND)); } public void testSecondFragmentInLargerUnitWithDate() { assertEquals(0, DateUtils.getFragmentInSeconds(aDate, Calendar.SECOND)); assertEquals(0, DateUtils.getFragmentInMinutes(aDate, Calendar.SECOND)); assertEquals(0, DateUtils.getFragmentInHours(aDate, Calendar.SECOND)); assertEquals(0, DateUtils.getFragmentInDays(aDate, Calendar.SECOND)); } public void testSecondFragmentInLargerUnitWithCalendar() { assertEquals(0, DateUtils.getFragmentInSeconds(aCalendar, Calendar.SECOND)); assertEquals(0, DateUtils.getFragmentInMinutes(aCalendar, Calendar.SECOND)); assertEquals(0, DateUtils.getFragmentInHours(aCalendar, Calendar.SECOND)); assertEquals(0, DateUtils.getFragmentInDays(aCalendar, Calendar.SECOND)); } public void testMinuteFragmentInLargerUnitWithDate() { assertEquals(0, DateUtils.getFragmentInMinutes(aDate, Calendar.MINUTE)); assertEquals(0, DateUtils.getFragmentInHours(aDate, Calendar.MINUTE)); assertEquals(0, DateUtils.getFragmentInDays(aDate, Calendar.MINUTE)); } public void testMinuteFragmentInLargerUnitWithCalendar() { assertEquals(0, DateUtils.getFragmentInMinutes(aCalendar, Calendar.MINUTE)); assertEquals(0, DateUtils.getFragmentInHours(aCalendar, Calendar.MINUTE)); assertEquals(0, DateUtils.getFragmentInDays(aCalendar, Calendar.MINUTE)); } public void testHourOfDayFragmentInLargerUnitWithDate() { assertEquals(0, DateUtils.getFragmentInHours(aDate, Calendar.HOUR_OF_DAY)); assertEquals(0, DateUtils.getFragmentInDays(aDate, Calendar.HOUR_OF_DAY)); } public void testHourOfDayFragmentInLargerUnitWithCalendar() { assertEquals(0, DateUtils.getFragmentInHours(aCalendar, Calendar.HOUR_OF_DAY)); assertEquals(0, DateUtils.getFragmentInDays(aCalendar, Calendar.HOUR_OF_DAY)); } public void testDayOfYearFragmentInLargerUnitWithDate() { assertEquals(0, DateUtils.getFragmentInDays(aDate, Calendar.DAY_OF_YEAR)); } public void testDayOfYearFragmentInLargerUnitWithCalendar() { assertEquals(0, DateUtils.getFragmentInDays(aCalendar, Calendar.DAY_OF_YEAR)); } public void testDateFragmentInLargerUnitWithDate() { assertEquals(0, DateUtils.getFragmentInDays(aDate, Calendar.DATE)); } public void testDateFragmentInLargerUnitWithCalendar() { assertEquals(0, DateUtils.getFragmentInDays(aCalendar, Calendar.DATE)); } //Calendar.SECOND as useful fragment public void testMillisecondsOfSecondWithDate() { long testResult = DateUtils.getFragmentInMilliseconds(aDate, Calendar.SECOND); assertEquals(millis, testResult); } public void testMillisecondsOfSecondWithCalendar() { long testResult = DateUtils.getFragmentInMilliseconds(aCalendar, Calendar.SECOND); assertEquals(millis, testResult); assertEquals(aCalendar.get(Calendar.MILLISECOND), testResult); } //Calendar.MINUTE as useful fragment public void testMillisecondsOfMinuteWithDate() { long testResult = DateUtils.getFragmentInMilliseconds(aDate, Calendar.MINUTE); assertEquals(millis + (seconds * DateUtils.MILLIS_PER_SECOND), testResult); } public void testMillisecondsOfMinuteWithCalender() { long testResult = DateUtils.getFragmentInMilliseconds(aCalendar, Calendar.MINUTE); assertEquals(millis + (seconds * DateUtils.MILLIS_PER_SECOND), testResult); } public void testSecondsofMinuteWithDate() { long testResult = DateUtils.getFragmentInSeconds(aDate, Calendar.MINUTE); assertEquals(seconds, testResult); } public void testSecondsofMinuteWithCalendar() { long testResult = DateUtils.getFragmentInSeconds(aCalendar, Calendar.MINUTE); assertEquals(seconds, testResult); assertEquals(aCalendar.get(Calendar.SECOND), testResult); } //Calendar.HOUR_OF_DAY as useful fragment public void testMillisecondsOfHourWithDate() { long testResult = DateUtils.getFragmentInMilliseconds(aDate, Calendar.HOUR_OF_DAY); assertEquals(millis + (seconds * DateUtils.MILLIS_PER_SECOND) + (minutes * DateUtils.MILLIS_PER_MINUTE), testResult); } public void testMillisecondsOfHourWithCalendar() { long testResult = DateUtils.getFragmentInMilliseconds(aCalendar, Calendar.HOUR_OF_DAY); assertEquals(millis + (seconds * DateUtils.MILLIS_PER_SECOND) + (minutes * DateUtils.MILLIS_PER_MINUTE), testResult); } public void testSecondsofHourWithDate() { long testResult = DateUtils.getFragmentInSeconds(aDate, Calendar.HOUR_OF_DAY); assertEquals( seconds + (minutes * DateUtils.MILLIS_PER_MINUTE / DateUtils.MILLIS_PER_SECOND), testResult); } public void testSecondsofHourWithCalendar() { long testResult = DateUtils.getFragmentInSeconds(aCalendar, Calendar.HOUR_OF_DAY); assertEquals( seconds + (minutes * DateUtils.MILLIS_PER_MINUTE / DateUtils.MILLIS_PER_SECOND), testResult); } public void testMinutesOfHourWithDate() { long testResult = DateUtils.getFragmentInMinutes(aDate, Calendar.HOUR_OF_DAY); assertEquals(minutes, testResult); } public void testMinutesOfHourWithCalendar() { long testResult = DateUtils.getFragmentInMinutes(aCalendar, Calendar.HOUR_OF_DAY); assertEquals(minutes, testResult); } //Calendar.DATE and Calendar.DAY_OF_YEAR as useful fragment public void testMillisecondsOfDayWithDate() { long testresult = DateUtils.getFragmentInMilliseconds(aDate, Calendar.DATE); long expectedValue = millis + (seconds * DateUtils.MILLIS_PER_SECOND) + (minutes * DateUtils.MILLIS_PER_MINUTE) + (hours * DateUtils.MILLIS_PER_HOUR); assertEquals(expectedValue, testresult); testresult = DateUtils.getFragmentInMilliseconds(aDate, Calendar.DAY_OF_YEAR); assertEquals(expectedValue, testresult); } public void testMillisecondsOfDayWithCalendar() { long testresult = DateUtils.getFragmentInMilliseconds(aCalendar, Calendar.DATE); long expectedValue = millis + (seconds * DateUtils.MILLIS_PER_SECOND) + (minutes * DateUtils.MILLIS_PER_MINUTE) + (hours * DateUtils.MILLIS_PER_HOUR); assertEquals(expectedValue, testresult); testresult = DateUtils.getFragmentInMilliseconds(aCalendar, Calendar.DAY_OF_YEAR); assertEquals(expectedValue, testresult); } public void testSecondsOfDayWithDate() { long testresult = DateUtils.getFragmentInSeconds(aDate, Calendar.DATE); long expectedValue = seconds + ((minutes * DateUtils.MILLIS_PER_MINUTE) + (hours * DateUtils.MILLIS_PER_HOUR))/ DateUtils.MILLIS_PER_SECOND; assertEquals(expectedValue, testresult); testresult = DateUtils.getFragmentInSeconds(aDate, Calendar.DAY_OF_YEAR); assertEquals(expectedValue, testresult); } public void testSecondsOfDayWithCalendar() { long testresult = DateUtils.getFragmentInSeconds(aCalendar, Calendar.DATE); long expectedValue = seconds + ((minutes * DateUtils.MILLIS_PER_MINUTE) + (hours * DateUtils.MILLIS_PER_HOUR))/ DateUtils.MILLIS_PER_SECOND; assertEquals(expectedValue, testresult); testresult = DateUtils.getFragmentInSeconds(aCalendar, Calendar.DAY_OF_YEAR); assertEquals(expectedValue, testresult); } public void testMinutesOfDayWithDate() { long testResult = DateUtils.getFragmentInMinutes(aDate, Calendar.DATE); long expectedValue = minutes + ((hours * DateUtils.MILLIS_PER_HOUR))/ DateUtils.MILLIS_PER_MINUTE; assertEquals(expectedValue,testResult); testResult = DateUtils.getFragmentInMinutes(aDate, Calendar.DAY_OF_YEAR); assertEquals(expectedValue,testResult); } public void testMinutesOfDayWithCalendar() { long testResult = DateUtils.getFragmentInMinutes(aCalendar, Calendar.DATE); long expectedValue = minutes + ((hours * DateUtils.MILLIS_PER_HOUR))/ DateUtils.MILLIS_PER_MINUTE; assertEquals(expectedValue, testResult); testResult = DateUtils.getFragmentInMinutes(aCalendar, Calendar.DAY_OF_YEAR); assertEquals(expectedValue, testResult); } public void testHoursOfDayWithDate() { long testResult = DateUtils.getFragmentInHours(aDate, Calendar.DATE); long expectedValue = hours; assertEquals(expectedValue,testResult); testResult = DateUtils.getFragmentInHours(aDate, Calendar.DAY_OF_YEAR); assertEquals(expectedValue,testResult); } public void testHoursOfDayWithCalendar() { long testResult = DateUtils.getFragmentInHours(aCalendar, Calendar.DATE); long expectedValue = hours; assertEquals(expectedValue, testResult); testResult = DateUtils.getFragmentInHours(aCalendar, Calendar.DAY_OF_YEAR); assertEquals(expectedValue, testResult); } //Calendar.MONTH as useful fragment public void testMillisecondsOfMonthWithDate() { long testResult = DateUtils.getFragmentInMilliseconds(aDate, Calendar.MONTH); assertEquals(millis + (seconds * DateUtils.MILLIS_PER_SECOND) + (minutes * DateUtils.MILLIS_PER_MINUTE) + (hours * DateUtils.MILLIS_PER_HOUR) + (days * DateUtils.MILLIS_PER_DAY), testResult); } public void testMillisecondsOfMonthWithCalendar() { long testResult = DateUtils.getFragmentInMilliseconds(aCalendar, Calendar.MONTH); assertEquals(millis + (seconds * DateUtils.MILLIS_PER_SECOND) + (minutes * DateUtils.MILLIS_PER_MINUTE) + (hours * DateUtils.MILLIS_PER_HOUR) + (days * DateUtils.MILLIS_PER_DAY), testResult); } public void testSecondsOfMonthWithDate() { long testResult = DateUtils.getFragmentInSeconds(aDate, Calendar.MONTH); assertEquals( seconds + ((minutes * DateUtils.MILLIS_PER_MINUTE) + (hours * DateUtils.MILLIS_PER_HOUR) + (days * DateUtils.MILLIS_PER_DAY)) / DateUtils.MILLIS_PER_SECOND, testResult); } public void testSecondsOfMonthWithCalendar() { long testResult = DateUtils.getFragmentInSeconds(aCalendar, Calendar.MONTH); assertEquals( seconds + ((minutes * DateUtils.MILLIS_PER_MINUTE) + (hours * DateUtils.MILLIS_PER_HOUR) + (days * DateUtils.MILLIS_PER_DAY)) / DateUtils.MILLIS_PER_SECOND, testResult); } public void testMinutesOfMonthWithDate() { long testResult = DateUtils.getFragmentInMinutes(aDate, Calendar.MONTH); assertEquals(minutes + ((hours * DateUtils.MILLIS_PER_HOUR) + (days * DateUtils.MILLIS_PER_DAY)) / DateUtils.MILLIS_PER_MINUTE, testResult); } public void testMinutesOfMonthWithCalendar() { long testResult = DateUtils.getFragmentInMinutes(aCalendar, Calendar.MONTH); assertEquals( minutes +((hours * DateUtils.MILLIS_PER_HOUR) + (days * DateUtils.MILLIS_PER_DAY)) / DateUtils.MILLIS_PER_MINUTE, testResult); } public void testHoursOfMonthWithDate() { long testResult = DateUtils.getFragmentInHours(aDate, Calendar.MONTH); assertEquals(hours + ((days * DateUtils.MILLIS_PER_DAY)) / DateUtils.MILLIS_PER_HOUR, testResult); } public void testHoursOfMonthWithCalendar() { long testResult = DateUtils.getFragmentInHours(aCalendar, Calendar.MONTH); assertEquals( hours +((days * DateUtils.MILLIS_PER_DAY)) / DateUtils.MILLIS_PER_HOUR, testResult); } //Calendar.YEAR as useful fragment public void testMillisecondsOfYearWithDate() { long testResult = DateUtils.getFragmentInMilliseconds(aDate, Calendar.YEAR); Calendar cal = Calendar.getInstance(); cal.setTime(aDate); assertEquals(millis + (seconds * DateUtils.MILLIS_PER_SECOND) + (minutes * DateUtils.MILLIS_PER_MINUTE) + (hours * DateUtils.MILLIS_PER_HOUR) + (cal.get(Calendar.DAY_OF_YEAR) * DateUtils.MILLIS_PER_DAY), testResult); } public void testMillisecondsOfYearWithCalendar() { long testResult = DateUtils.getFragmentInMilliseconds(aCalendar, Calendar.YEAR); assertEquals(millis + (seconds * DateUtils.MILLIS_PER_SECOND) + (minutes * DateUtils.MILLIS_PER_MINUTE) + (hours * DateUtils.MILLIS_PER_HOUR) + (aCalendar.get(Calendar.DAY_OF_YEAR) * DateUtils.MILLIS_PER_DAY), testResult); } public void testSecondsOfYearWithDate() { long testResult = DateUtils.getFragmentInSeconds(aDate, Calendar.YEAR); Calendar cal = Calendar.getInstance(); cal.setTime(aDate); assertEquals( seconds + ((minutes * DateUtils.MILLIS_PER_MINUTE) + (hours * DateUtils.MILLIS_PER_HOUR) + (cal.get(Calendar.DAY_OF_YEAR) * DateUtils.MILLIS_PER_DAY)) / DateUtils.MILLIS_PER_SECOND, testResult); } public void testSecondsOfYearWithCalendar() { long testResult = DateUtils.getFragmentInSeconds(aCalendar, Calendar.YEAR); assertEquals( seconds + ((minutes * DateUtils.MILLIS_PER_MINUTE) + (hours * DateUtils.MILLIS_PER_HOUR) + (aCalendar.get(Calendar.DAY_OF_YEAR) * DateUtils.MILLIS_PER_DAY)) / DateUtils.MILLIS_PER_SECOND, testResult); } public void testMinutesOfYearWithDate() { long testResult = DateUtils.getFragmentInMinutes(aDate, Calendar.YEAR); Calendar cal = Calendar.getInstance(); cal.setTime(aDate); assertEquals(minutes + ((hours * DateUtils.MILLIS_PER_HOUR) + (cal.get(Calendar.DAY_OF_YEAR) * DateUtils.MILLIS_PER_DAY)) / DateUtils.MILLIS_PER_MINUTE, testResult); } public void testMinutesOfYearWithCalendar() { long testResult = DateUtils.getFragmentInMinutes(aCalendar, Calendar.YEAR); assertEquals( minutes +((hours * DateUtils.MILLIS_PER_HOUR) + (aCalendar.get(Calendar.DAY_OF_YEAR) * DateUtils.MILLIS_PER_DAY)) / DateUtils.MILLIS_PER_MINUTE, testResult); } public void testHoursOfYearWithDate() { long testResult = DateUtils.getFragmentInHours(aDate, Calendar.YEAR); Calendar cal = Calendar.getInstance(); cal.setTime(aDate); assertEquals(hours + ((cal.get(Calendar.DAY_OF_YEAR) * DateUtils.MILLIS_PER_DAY)) / DateUtils.MILLIS_PER_HOUR, testResult); } public void testHoursOfYearWithCalendar() { long testResult = DateUtils.getFragmentInHours(aCalendar, Calendar.YEAR); assertEquals( hours +((aCalendar.get(Calendar.DAY_OF_YEAR) * DateUtils.MILLIS_PER_DAY)) / DateUtils.MILLIS_PER_HOUR, testResult); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/time/DateUtilsRoundingTest.java100644 0 0 103215 11513702435 27072 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.time; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; import junit.framework.TestCase; /** * These Unit-tests will check all possible extremes when using some rounding-methods of DateUtils. * The extremes are tested at the switch-point in milliseconds * * According to the implementation SEMI_MONTH will either round/truncate to the 1st or 16th * When rounding Calendar.MONTH it depends on the number of days within that month. * A month with 28 days will be rounded up from the 15th * A month with 29 or 30 days will be rounded up from the 16th * A month with 31 days will be rounded up from the 17th * * @author Robert Scholte * @since 3.0 * */ // TODO: Add DateUtils.ceil()-tests if method is available public class DateUtilsRoundingTest extends TestCase { DateFormat dateTimeParser; Date januaryOneDate; Date targetYearDate; //No targetMonths, these must be tested for every type of month(28-31 days) Date targetDateDate, targetDayOfMonthDate, targetAmDate, targetPmDate; Date targetHourOfDayDate, targetHourDate; Date targetMinuteDate; Date targetSecondDate; Date targetMilliSecondDate; Calendar januaryOneCalendar; FastDateFormat fdf = DateFormatUtils.ISO_DATETIME_FORMAT; protected void setUp() throws Exception { super.setUp(); dateTimeParser = new SimpleDateFormat("MMM dd, yyyy H:mm:ss.SSS", Locale.ENGLISH); targetYearDate = dateTimeParser.parse("January 1, 2007 0:00:00.000"); targetDateDate = targetDayOfMonthDate = dateTimeParser.parse("June 1, 2008 0:00:00.000"); targetAmDate = dateTimeParser.parse("June 1, 2008 0:00:00.000"); targetPmDate = dateTimeParser.parse("June 1, 2008 12:00:00.000"); targetHourDate = dateTimeParser.parse("June 1, 2008 8:00:00.000"); targetHourOfDayDate = dateTimeParser.parse("June 1, 2008 8:00:00.000"); targetMinuteDate = dateTimeParser.parse("June 1, 2008 8:15:00.000"); targetSecondDate = dateTimeParser.parse("June 1, 2008 8:15:14.000"); targetMilliSecondDate = dateTimeParser.parse("June 1, 2008 8:15:14.231"); januaryOneDate = dateTimeParser.parse("January 1, 2008 0:00:00.000"); januaryOneCalendar = Calendar.getInstance(); januaryOneCalendar.setTime(januaryOneDate); } /** * Tests DateUtils.round()-method with Calendar.Year * * @throws Exception * @since 3.0 */ public void testRoundYear() throws Exception { final int calendarField = Calendar.YEAR; Date roundedUpDate = dateTimeParser.parse("January 1, 2008 0:00:00.000"); Date roundedDownDate = targetYearDate; Date lastRoundedDownDate = dateTimeParser.parse("June 30, 2007 23:59:59.999"); baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField); } /** * Tests DateUtils.round()-method with Calendar.MONTH * Includes rounding months with 28, 29, 30 and 31 days * Includes rounding to January 1 * * @throws Exception * @since 3.0 */ public void testRoundMonth() throws Exception { final int calendarField = Calendar.MONTH; Date roundedUpDate, roundedDownDate, lastRoundedDownDate; Date minDate, maxDate; //month with 28 days roundedUpDate = dateTimeParser.parse("March 1, 2007 0:00:00.000"); roundedDownDate = dateTimeParser.parse("February 1, 2007 0:00:00.000"); lastRoundedDownDate = dateTimeParser.parse("February 14, 2007 23:59:59.999"); baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField); //month with 29 days roundedUpDate = dateTimeParser.parse("March 1, 2008 0:00:00.000"); roundedDownDate = dateTimeParser.parse("February 1, 2008 0:00:00.000"); lastRoundedDownDate = dateTimeParser.parse("February 15, 2008 23:59:59.999"); baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField); //month with 30 days roundedUpDate = dateTimeParser.parse("May 1, 2008 0:00:00.000"); roundedDownDate = dateTimeParser.parse("April 1, 2008 0:00:00.000"); lastRoundedDownDate = dateTimeParser.parse("April 15, 2008 23:59:59.999"); baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField); //month with 31 days roundedUpDate = dateTimeParser.parse("June 1, 2008 0:00:00.000"); roundedDownDate = dateTimeParser.parse("May 1, 2008 0:00:00.000"); lastRoundedDownDate = dateTimeParser.parse("May 16, 2008 23:59:59.999"); baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField); //round to January 1 minDate = dateTimeParser.parse("December 17, 2007 00:00:00.000"); maxDate = dateTimeParser.parse("January 16, 2008 23:59:59.999"); roundToJanuaryFirst(minDate, maxDate, calendarField); } /** * Tests DateUtils.round()-method with DateUtils.SEMI_MONTH * Includes rounding months with 28, 29, 30 and 31 days, each with first and second half * Includes rounding to January 1 * * @throws Exception * @since 3.0 */ public void testRoundSemiMonth() throws Exception { final int calendarField = DateUtils.SEMI_MONTH; Date roundedUpDate, roundedDownDate, lastRoundedDownDate; Date minDate, maxDate; //month with 28 days (1) roundedUpDate = dateTimeParser.parse("February 16, 2007 0:00:00.000"); roundedDownDate = dateTimeParser.parse("February 1, 2007 0:00:00.000"); lastRoundedDownDate = dateTimeParser.parse("February 8, 2007 23:59:59.999"); baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField); //month with 28 days (2) roundedUpDate = dateTimeParser.parse("March 1, 2007 0:00:00.000"); roundedDownDate = dateTimeParser.parse("February 16, 2007 0:00:00.000"); lastRoundedDownDate = dateTimeParser.parse("February 23, 2007 23:59:59.999"); baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField); //month with 29 days (1) roundedUpDate = dateTimeParser.parse("February 16, 2008 0:00:00.000"); roundedDownDate = dateTimeParser.parse("February 1, 2008 0:00:00.000"); lastRoundedDownDate = dateTimeParser.parse("February 8, 2008 23:59:59.999"); baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField); //month with 29 days (2) roundedUpDate = dateTimeParser.parse("March 1, 2008 0:00:00.000"); roundedDownDate = dateTimeParser.parse("February 16, 2008 0:00:00.000"); lastRoundedDownDate = dateTimeParser.parse("February 23, 2008 23:59:59.999"); baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField); //month with 30 days (1) roundedUpDate = dateTimeParser.parse("April 16, 2008 0:00:00.000"); roundedDownDate = dateTimeParser.parse("April 1, 2008 0:00:00.000"); lastRoundedDownDate = dateTimeParser.parse("April 8, 2008 23:59:59.999"); baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField); //month with 30 days (2) roundedUpDate = dateTimeParser.parse("May 1, 2008 0:00:00.000"); roundedDownDate = dateTimeParser.parse("April 16, 2008 0:00:00.000"); lastRoundedDownDate = dateTimeParser.parse("April 23, 2008 23:59:59.999"); baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField); //month with 31 days (1) roundedUpDate = dateTimeParser.parse("May 16, 2008 0:00:00.000"); roundedDownDate = dateTimeParser.parse("May 1, 2008 0:00:00.000"); lastRoundedDownDate = dateTimeParser.parse("May 8, 2008 23:59:59.999"); baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField); //month with 31 days (2) roundedUpDate = dateTimeParser.parse("June 1, 2008 0:00:00.000"); roundedDownDate = dateTimeParser.parse("May 16, 2008 0:00:00.000"); lastRoundedDownDate = dateTimeParser.parse("May 23, 2008 23:59:59.999"); baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField); //round to January 1 minDate = dateTimeParser.parse("December 24, 2007 00:00:00.000"); maxDate = dateTimeParser.parse("January 8, 2008 23:59:59.999"); roundToJanuaryFirst(minDate, maxDate, calendarField); } /** * Tests DateUtils.round()-method with Calendar.DATE * Includes rounding the extremes of one day * Includes rounding to January 1 * * @throws Exception * @since 3.0 */ public void testRoundDate() throws Exception { final int calendarField = Calendar.DATE; Date roundedUpDate, roundedDownDate, lastRoundedDownDate; Date minDate, maxDate; roundedUpDate = dateTimeParser.parse("June 2, 2008 0:00:00.000"); roundedDownDate = targetDateDate; lastRoundedDownDate = dateTimeParser.parse("June 1, 2008 11:59:59.999"); baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField); //round to January 1 minDate = dateTimeParser.parse("December 31, 2007 12:00:00.000"); maxDate = dateTimeParser.parse("January 1, 2008 11:59:59.999"); roundToJanuaryFirst(minDate, maxDate, calendarField); } /** * Tests DateUtils.round()-method with Calendar.DAY_OF_MONTH * Includes rounding the extremes of one day * Includes rounding to January 1 * * @throws Exception * @since 3.0 */ public void testRoundDayOfMonth() throws Exception { final int calendarField = Calendar.DAY_OF_MONTH; Date roundedUpDate, roundedDownDate, lastRoundedDownDate; Date minDate, maxDate; roundedUpDate = dateTimeParser.parse("June 2, 2008 0:00:00.000"); roundedDownDate = targetDayOfMonthDate; lastRoundedDownDate = dateTimeParser.parse("June 1, 2008 11:59:59.999"); baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField); //round to January 1 minDate = dateTimeParser.parse("December 31, 2007 12:00:00.000"); maxDate = dateTimeParser.parse("January 1, 2008 11:59:59.999"); roundToJanuaryFirst(minDate, maxDate, calendarField); } /** * Tests DateUtils.round()-method with Calendar.AM_PM * Includes rounding the extremes of both AM and PM of one day * Includes rounding to January 1 * * @throws Exception * @3.0 */ public void testRoundAmPm() throws Exception { final int calendarField = Calendar.AM_PM; Date roundedUpDate, roundedDownDate, lastRoundedDownDate; Date minDate, maxDate; //AM roundedUpDate = dateTimeParser.parse("June 1, 2008 12:00:00.000"); roundedDownDate = targetAmDate; lastRoundedDownDate = dateTimeParser.parse("June 1, 2008 5:59:59.999"); baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField); //PM roundedUpDate = dateTimeParser.parse("June 2, 2008 0:00:00.000"); roundedDownDate = targetPmDate; lastRoundedDownDate = dateTimeParser.parse("June 1, 2008 17:59:59.999"); baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField); //round to January 1 minDate = dateTimeParser.parse("December 31, 2007 18:00:00.000"); maxDate = dateTimeParser.parse("January 1, 2008 5:59:59.999"); roundToJanuaryFirst(minDate, maxDate, calendarField); } /** * Tests DateUtils.round()-method with Calendar.HOUR_OF_DAY * Includes rounding the extremes of one hour * Includes rounding to January 1 * * @throws Exception * @since 3.0 */ public void testRoundHourOfDay() throws Exception { final int calendarField = Calendar.HOUR_OF_DAY; Date roundedUpDate, roundedDownDate, lastRoundedDownDate; Date minDate, maxDate; roundedUpDate = dateTimeParser.parse("June 1, 2008 9:00:00.000"); roundedDownDate = targetHourOfDayDate; lastRoundedDownDate = dateTimeParser.parse("June 1, 2008 8:29:59.999"); baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField); //round to January 1 minDate = dateTimeParser.parse("December 31, 2007 23:30:00.000"); maxDate = dateTimeParser.parse("January 1, 2008 0:29:59.999"); roundToJanuaryFirst(minDate, maxDate, calendarField); } /** * Tests DateUtils.round()-method with Calendar.HOUR * Includes rounding the extremes of one hour * Includes rounding to January 1 * * @throws Exception * @since 3.0 */ public void testRoundHour() throws Exception { final int calendarField = Calendar.HOUR; Date roundedUpDate, roundedDownDate, lastRoundedDownDate; Date minDate, maxDate; roundedUpDate = dateTimeParser.parse("June 1, 2008 9:00:00.000"); roundedDownDate = targetHourDate; lastRoundedDownDate = dateTimeParser.parse("June 1, 2008 8:29:59.999"); baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField); //round to January 1 minDate = dateTimeParser.parse("December 31, 2007 23:30:00.000"); maxDate = dateTimeParser.parse("January 1, 2008 0:29:59.999"); roundToJanuaryFirst(minDate, maxDate, calendarField); } /** * Tests DateUtils.round()-method with Calendar.MINUTE * Includes rounding the extremes of one minute * Includes rounding to January 1 * * @throws Exception * @since 3.0 */ public void testRoundMinute() throws Exception { final int calendarField = Calendar.MINUTE; Date roundedUpDate, roundedDownDate, lastRoundedDownDate; Date minDate, maxDate; roundedUpDate = dateTimeParser.parse("June 1, 2008 8:16:00.000"); roundedDownDate = targetMinuteDate; lastRoundedDownDate = dateTimeParser.parse("June 1, 2008 8:15:29.999"); baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField); //round to January 1 minDate = dateTimeParser.parse("December 31, 2007 23:59:30.000"); maxDate = dateTimeParser.parse("January 1, 2008 0:00:29.999"); roundToJanuaryFirst(minDate, maxDate, calendarField); } /** * Tests DateUtils.round()-method with Calendar.SECOND * Includes rounding the extremes of one second * Includes rounding to January 1 * * @throws Exception * @since 3.0 */ public void testRoundSecond() throws Exception { final int calendarField = Calendar.SECOND; Date roundedUpDate, roundedDownDate, lastRoundedDownDate; Date minDate, maxDate; roundedUpDate = dateTimeParser.parse("June 1, 2008 8:15:15.000"); roundedDownDate = targetSecondDate; lastRoundedDownDate = dateTimeParser.parse("June 1, 2008 8:15:14.499"); baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField); //round to January 1 minDate = dateTimeParser.parse("December 31, 2007 23:59:59.500"); maxDate = dateTimeParser.parse("January 1, 2008 0:00:00.499"); roundToJanuaryFirst(minDate, maxDate, calendarField); } /** * Tests DateUtils.round()-method with Calendar.MILLISECOND * Includes rounding the extremes of one second * Includes rounding to January 1 * * @throws Exception * @since 3.0 */ public void testRoundMilliSecond() throws Exception { final int calendarField = Calendar.MILLISECOND; Date roundedUpDate, roundedDownDate, lastRoundedDownDate; Date minDate, maxDate; roundedDownDate = lastRoundedDownDate = targetMilliSecondDate; roundedUpDate = dateTimeParser.parse("June 1, 2008 8:15:14.232"); baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField); //round to January 1 minDate = maxDate = januaryOneDate; roundToJanuaryFirst(minDate, maxDate, calendarField); } /** * Test DateUtils.truncate()-method with Calendar.YEAR * * @throws Exception * @since 3.0 */ public void testTruncateYear() throws Exception { final int calendarField = Calendar.YEAR; Date lastTruncateDate = dateTimeParser.parse("December 31, 2007 23:59:59.999"); baseTruncateTest(targetYearDate, lastTruncateDate, calendarField); } /** * Test DateUtils.truncate()-method with Calendar.MONTH * * @throws Exception * @since 3.0 */ public void testTruncateMonth() throws Exception { final int calendarField = Calendar.MONTH; Date truncatedDate = dateTimeParser.parse("March 1, 2008 0:00:00.000"); Date lastTruncateDate = dateTimeParser.parse("March 31, 2008 23:59:59.999"); baseTruncateTest(truncatedDate, lastTruncateDate, calendarField); } /** * Test DateUtils.truncate()-method with DateUtils.SEMI_MONTH * Includes truncating months with 28, 29, 30 and 31 days, each with first and second half * * @throws Exception * @since 3.0 */ public void testTruncateSemiMonth() throws Exception { final int calendarField = DateUtils.SEMI_MONTH; Date truncatedDate, lastTruncateDate; //month with 28 days (1) truncatedDate = dateTimeParser.parse("February 1, 2007 0:00:00.000"); lastTruncateDate = dateTimeParser.parse("February 15, 2007 23:59:59.999"); baseTruncateTest(truncatedDate, lastTruncateDate, calendarField); //month with 28 days (2) truncatedDate = dateTimeParser.parse("February 16, 2007 0:00:00.000"); lastTruncateDate = dateTimeParser.parse("February 28, 2007 23:59:59.999"); baseTruncateTest(truncatedDate, lastTruncateDate, calendarField); //month with 29 days (1) truncatedDate = dateTimeParser.parse("February 1, 2008 0:00:00.000"); lastTruncateDate = dateTimeParser.parse("February 15, 2008 23:59:59.999"); baseTruncateTest(truncatedDate, lastTruncateDate, calendarField); //month with 29 days (2) truncatedDate = dateTimeParser.parse("February 16, 2008 0:00:00.000"); lastTruncateDate = dateTimeParser.parse("February 29, 2008 23:59:59.999"); baseTruncateTest(truncatedDate, lastTruncateDate, calendarField); //month with 30 days (1) truncatedDate = dateTimeParser.parse("April 1, 2008 0:00:00.000"); lastTruncateDate = dateTimeParser.parse("April 15, 2008 23:59:59.999"); baseTruncateTest(truncatedDate, lastTruncateDate, calendarField); //month with 30 days (2) truncatedDate = dateTimeParser.parse("April 16, 2008 0:00:00.000"); lastTruncateDate = dateTimeParser.parse("April 30, 2008 23:59:59.999"); baseTruncateTest(truncatedDate, lastTruncateDate, calendarField); //month with 31 days (1) truncatedDate = dateTimeParser.parse("March 1, 2008 0:00:00.000"); lastTruncateDate = dateTimeParser.parse("March 15, 2008 23:59:59.999"); baseTruncateTest(truncatedDate, lastTruncateDate, calendarField); //month with 31 days (2) truncatedDate = dateTimeParser.parse("March 16, 2008 0:00:00.000"); lastTruncateDate = dateTimeParser.parse("March 31, 2008 23:59:59.999"); baseTruncateTest(truncatedDate, lastTruncateDate, calendarField); } /** * Test DateUtils.truncate()-method with Calendar.DATE * * @throws Exception * @since 3.0 */ public void testTruncateDate() throws Exception { final int calendarField = Calendar.DATE; Date lastTruncateDate = dateTimeParser.parse("June 1, 2008 23:59:59.999"); baseTruncateTest(targetDateDate, lastTruncateDate, calendarField); } /** * Test DateUtils.truncate()-method with Calendar.DAY_OF_MONTH * * @throws Exception * @since 3.0 */ public void testTruncateDayOfMonth() throws Exception { final int calendarField = Calendar.DAY_OF_MONTH; Date lastTruncateDate = dateTimeParser.parse("June 1, 2008 23:59:59.999"); baseTruncateTest(targetDayOfMonthDate, lastTruncateDate, calendarField); } /** * Test DateUtils.truncate()-method with Calendar.AM_PM * Includes truncating the extremes of both AM and PM of one day * * @throws Exception * @since 3.0 */ public void testTruncateAmPm() throws Exception { final int calendarField = Calendar.AM_PM; //AM Date lastTruncateDate = dateTimeParser.parse("June 1, 2008 11:59:59.999"); baseTruncateTest(targetAmDate, lastTruncateDate, calendarField); //PM lastTruncateDate = dateTimeParser.parse("June 1, 2008 23:59:59.999"); baseTruncateTest(targetPmDate, lastTruncateDate, calendarField); } /** * Test DateUtils.truncate()-method with Calendar.HOUR * * @throws Exception * @since 3.0 */ public void testTruncateHour() throws Exception { final int calendarField = Calendar.HOUR; Date lastTruncateDate = dateTimeParser.parse("June 1, 2008 8:59:59.999"); baseTruncateTest(targetHourDate, lastTruncateDate, calendarField); } /** * Test DateUtils.truncate()-method with Calendar.HOUR_OF_DAY * * @throws Exception * @since 3.0 */ public void testTruncateHourOfDay() throws Exception { final int calendarField = Calendar.HOUR_OF_DAY; Date lastTruncateDate = dateTimeParser.parse("June 1, 2008 8:59:59.999"); baseTruncateTest(targetHourOfDayDate, lastTruncateDate, calendarField); } /** * Test DateUtils.truncate()-method with Calendar.MINUTE * * @throws Exception * @since 3.0 */ public void testTruncateMinute() throws Exception { final int calendarField = Calendar.MINUTE; Date lastTruncateDate = dateTimeParser.parse("June 1, 2008 8:15:59.999"); baseTruncateTest(targetMinuteDate, lastTruncateDate, calendarField); } /** * Test DateUtils.truncate()-method with Calendar.SECOND * * @throws Exception * @since 3.0 */ public void testTruncateSecond() throws Exception { final int calendarField = Calendar.SECOND; Date lastTruncateDate = dateTimeParser.parse("June 1, 2008 8:15:14.999"); baseTruncateTest(targetSecondDate, lastTruncateDate, calendarField); } /** * Test DateUtils.truncate()-method with Calendar.SECOND * * @throws Exception * @since 3.0 */ public void testTruncateMilliSecond() throws Exception { final int calendarField = Calendar.MILLISECOND; baseTruncateTest(targetMilliSecondDate, targetMilliSecondDate, calendarField); } /** * When using this basetest all extremes are tested.
    * It will test the Date, Calendar and Object-implementation
    * lastRoundDownDate should round down to roundedDownDate
    * lastRoundDownDate + 1 millisecond should round up to roundedUpDate * * @param roundedUpDate the next rounded date after roundedDownDate when using calendarField * @param roundedDownDate the result if lastRoundDownDate was rounded with calendarField * @param lastRoundDownDate rounding this value with calendarField will result in roundedDownDate * @param calendarField * @since 3.0 */ protected void baseRoundTest(final Date roundedUpDate, final Date roundedDownDate, final Date lastRoundDownDate, final int calendarField) { Date firstRoundUpDate = DateUtils.addMilliseconds(lastRoundDownDate, 1); //Date-comparison assertEquals(roundedDownDate, DateUtils.round(roundedDownDate, calendarField)); assertEquals(roundedUpDate, DateUtils.round(roundedUpDate, calendarField)); assertEquals(roundedDownDate, DateUtils.round(lastRoundDownDate, calendarField)); assertEquals(roundedUpDate, DateUtils.round(firstRoundUpDate, calendarField)); //Calendar-initiations Calendar roundedUpCalendar, roundedDownCalendar, lastRoundDownCalendar, firstRoundUpCalendar; roundedDownCalendar = Calendar.getInstance(); roundedUpCalendar = Calendar.getInstance(); lastRoundDownCalendar = Calendar.getInstance(); firstRoundUpCalendar = Calendar.getInstance(); roundedDownCalendar.setTime(roundedDownDate); roundedUpCalendar.setTime(roundedUpDate); lastRoundDownCalendar.setTime(lastRoundDownDate); firstRoundUpCalendar.setTime(firstRoundUpDate); //Calendar-comparison assertEquals(roundedDownCalendar, DateUtils.round(roundedDownCalendar, calendarField)); assertEquals(roundedUpCalendar, DateUtils.round(roundedUpCalendar, calendarField)); assertEquals(roundedDownCalendar, DateUtils.round(lastRoundDownCalendar, calendarField)); assertEquals(roundedUpCalendar, DateUtils.round(firstRoundUpCalendar, calendarField)); //Object-comparison assertEquals(roundedDownDate, DateUtils.round((Object) roundedDownDate, calendarField)); assertEquals(roundedUpDate, DateUtils.round((Object) roundedUpDate, calendarField)); assertEquals(roundedDownDate, DateUtils.round((Object) lastRoundDownDate, calendarField)); assertEquals(roundedUpDate, DateUtils.round((Object) firstRoundUpDate, calendarField)); assertEquals(roundedDownDate, DateUtils.round((Object) roundedDownCalendar, calendarField)); assertEquals(roundedUpDate, DateUtils.round((Object) roundedUpCalendar, calendarField)); assertEquals(roundedDownDate, DateUtils.round((Object) lastRoundDownDate, calendarField)); assertEquals(roundedUpDate, DateUtils.round((Object) firstRoundUpDate, calendarField)); } /** * When using this basetest all extremes are tested.
    * It will test the Date, Calendar and Object-implementation
    * lastTruncateDate should round down to truncatedDate
    * lastTruncateDate + 1 millisecond should never round down to truncatedDate * * @param truncatedDate expected Date when lastTruncateDate is truncated with calendarField * @param lastTruncateDate the last possible Date which will truncate to truncatedDate with calendarField * @param calendarField a Calendar.field value * @since 3.0 */ protected void baseTruncateTest(final Date truncatedDate, final Date lastTruncateDate, final int calendarField) { Date nextTruncateDate = DateUtils.addMilliseconds(lastTruncateDate, 1); //Date-comparison assertEquals("Truncating "+ fdf.format(truncatedDate) +" as Date with CalendarField-value "+ calendarField +" must return itself", truncatedDate, DateUtils.truncate(truncatedDate, calendarField)); assertEquals(truncatedDate, DateUtils.truncate(lastTruncateDate, calendarField)); assertFalse(fdf.format(lastTruncateDate) +" is not an extreme when truncating as Date with CalendarField-value "+ calendarField, truncatedDate.equals(DateUtils.truncate(nextTruncateDate, calendarField))); //Calendar-initiations Calendar truncatedCalendar, lastTruncateCalendar, nextTruncateCalendar; truncatedCalendar = Calendar.getInstance(); lastTruncateCalendar = Calendar.getInstance(); nextTruncateCalendar = Calendar.getInstance(); truncatedCalendar.setTime(truncatedDate); lastTruncateCalendar.setTime(lastTruncateDate); nextTruncateCalendar.setTime(nextTruncateDate); //Calendar-comparison assertEquals("Truncating "+ fdf.format(truncatedCalendar) +" as Calendar with CalendarField-value "+ calendarField +" must return itself", truncatedCalendar, DateUtils.truncate(truncatedCalendar, calendarField)); assertEquals(truncatedCalendar, DateUtils.truncate(lastTruncateCalendar, calendarField)); assertFalse(fdf.format(lastTruncateCalendar) +" is not an extreme when truncating as Calendar with CalendarField-value "+ calendarField, truncatedCalendar.equals(DateUtils.truncate(nextTruncateCalendar, calendarField))); //Object-comparison assertEquals("Truncating "+ fdf.format(truncatedDate) +" as Date cast to Object with CalendarField-value "+ calendarField +" must return itself as Date", truncatedDate, DateUtils.truncate((Object) truncatedDate, calendarField)); assertEquals(truncatedDate, DateUtils.truncate((Object) lastTruncateDate, calendarField)); assertFalse(fdf.format(lastTruncateDate) +" is not an extreme when truncating as Date cast to Object with CalendarField-value "+ calendarField, truncatedDate.equals(DateUtils.truncate((Object) nextTruncateDate, calendarField))); assertEquals("Truncating "+ fdf.format(truncatedCalendar) +" as Calendar cast to Object with CalendarField-value "+ calendarField +" must return itself as Date", truncatedDate, DateUtils.truncate((Object) truncatedCalendar, calendarField)); assertEquals(truncatedDate, DateUtils.truncate((Object) lastTruncateCalendar, calendarField)); assertFalse(fdf.format(lastTruncateCalendar) +" is not an extreme when truncating as Calendar cast to Object with CalendarField-value "+ calendarField, truncatedDate.equals(DateUtils.truncate((Object) nextTruncateCalendar, calendarField))); } /** * * Any January 1 could be considered as the ultimate extreme. * Instead of comparing the results if the input has a difference of 1 millisecond we check the output to be exactly January first. * * @param minDate * @param maxDate * @param calendarField * @since 3.0 */ protected void roundToJanuaryFirst(Date minDate, Date maxDate, int calendarField) { assertEquals("Rounding "+ fdf.format(januaryOneDate) +" as Date with CalendarField-value "+ calendarField +" must return itself", januaryOneDate, DateUtils.round(januaryOneDate, calendarField)); assertEquals(januaryOneDate, DateUtils.round(minDate, calendarField)); assertEquals(januaryOneDate, DateUtils.round(maxDate, calendarField)); Calendar minCalendar = Calendar.getInstance(); minCalendar.setTime(minDate); Calendar maxCalendar = Calendar.getInstance(); maxCalendar.setTime(maxDate); assertEquals("Rounding "+ fdf.format(januaryOneCalendar) +" as Date with CalendarField-value "+ calendarField +" must return itself", januaryOneCalendar, DateUtils.round(januaryOneCalendar, calendarField)); assertEquals(januaryOneCalendar, DateUtils.round(minCalendar, calendarField)); assertEquals(januaryOneCalendar, DateUtils.round(maxCalendar, calendarField)); Date toPrevRoundDate = DateUtils.addMilliseconds(minDate, -1); Date toNextRoundDate = DateUtils.addMilliseconds(maxDate, 1); assertFalse(fdf.format(minDate) +" is not an lower-extreme when rounding as Date with CalendarField-value "+ calendarField, januaryOneDate.equals(DateUtils.round(toPrevRoundDate, calendarField))); assertFalse(fdf.format(maxDate) +" is not an upper-extreme when rounding as Date with CalendarField-value "+ calendarField, januaryOneDate.equals(DateUtils.round(toNextRoundDate, calendarField))); Calendar toPrevRoundCalendar = Calendar.getInstance(); toPrevRoundCalendar.setTime(toPrevRoundDate); Calendar toNextRoundCalendar = Calendar.getInstance(); toNextRoundCalendar.setTime(toNextRoundDate); assertFalse(fdf.format(minCalendar) +" is not an lower-extreme when rounding as Date with CalendarField-value "+ calendarField, januaryOneDate.equals(DateUtils.round(toPrevRoundDate, calendarField))); assertFalse(fdf.format(maxCalendar) +" is not an upper-extreme when rounding as Date with CalendarField-value "+ calendarField, januaryOneDate.equals(DateUtils.round(toNextRoundDate, calendarField))); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/time/DateUtilsTest.java100644 0 0 224336 11513702435 25374 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.time; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Iterator; import java.util.Locale; import java.util.NoSuchElementException; import java.util.TimeZone; import junit.framework.AssertionFailedError; import junit.framework.TestCase; import org.apache.commons.lang.SystemUtils; /** * Unit tests {@link org.apache.commons.lang.time.DateUtils}. * * @author Serge Knystautas * @author Steven Caswell */ public class DateUtilsTest extends TestCase { private static final long MILLIS_TEST; static { GregorianCalendar cal = new GregorianCalendar(2000, 6, 5, 4, 3, 2); cal.set(Calendar.MILLISECOND, 1); MILLIS_TEST = cal.getTime().getTime(); } DateFormat dateParser = null; DateFormat dateTimeParser = null; DateFormat timeZoneDateParser = null; Date dateAmPm1 = null; Date dateAmPm2 = null; Date dateAmPm3 = null; Date dateAmPm4 = null; Date date0 = null; Date date1 = null; Date date2 = null; Date date3 = null; Date date4 = null; Date date5 = null; Date date6 = null; Date date7 = null; Date date8 = null; Calendar calAmPm1 = null; Calendar calAmPm2 = null; Calendar calAmPm3 = null; Calendar calAmPm4 = null; Calendar cal1 = null; Calendar cal2 = null; Calendar cal3 = null; Calendar cal4 = null; Calendar cal5 = null; Calendar cal6 = null; Calendar cal7 = null; Calendar cal8 = null; TimeZone zone = null; TimeZone defaultZone = null; public DateUtilsTest(String name) { super(name); } protected void setUp() throws Exception { super.setUp(); dateParser = new SimpleDateFormat("MMM dd, yyyy", Locale.ENGLISH); dateTimeParser = new SimpleDateFormat("MMM dd, yyyy H:mm:ss.SSS", Locale.ENGLISH); dateAmPm1 = dateTimeParser.parse("February 3, 2002 01:10:00.000"); dateAmPm2 = dateTimeParser.parse("February 3, 2002 11:10:00.000"); dateAmPm3 = dateTimeParser.parse("February 3, 2002 13:10:00.000"); dateAmPm4 = dateTimeParser.parse("February 3, 2002 19:10:00.000"); date0 = dateTimeParser.parse("February 3, 2002 12:34:56.789"); date1 = dateTimeParser.parse("February 12, 2002 12:34:56.789"); date2 = dateTimeParser.parse("November 18, 2001 1:23:11.321"); defaultZone = TimeZone.getDefault(); zone = TimeZone.getTimeZone("MET"); TimeZone.setDefault(zone); dateTimeParser.setTimeZone(zone); date3 = dateTimeParser.parse("March 30, 2003 05:30:45.000"); date4 = dateTimeParser.parse("March 30, 2003 01:10:00.000"); date5 = dateTimeParser.parse("March 30, 2003 01:40:00.000"); date6 = dateTimeParser.parse("March 30, 2003 02:10:00.000"); date7 = dateTimeParser.parse("March 30, 2003 02:40:00.000"); date8 = dateTimeParser.parse("October 26, 2003 05:30:45.000"); dateTimeParser.setTimeZone(defaultZone); TimeZone.setDefault(defaultZone); calAmPm1 = Calendar.getInstance(); calAmPm1.setTime(dateAmPm1); calAmPm2 = Calendar.getInstance(); calAmPm2.setTime(dateAmPm2); calAmPm3 = Calendar.getInstance(); calAmPm3.setTime(dateAmPm3); calAmPm4 = Calendar.getInstance(); calAmPm4.setTime(dateAmPm4); cal1 = Calendar.getInstance(); cal1.setTime(date1); cal2 = Calendar.getInstance(); cal2.setTime(date2); TimeZone.setDefault(zone); cal3 = Calendar.getInstance(); cal3.setTime(date3); cal4 = Calendar.getInstance(); cal4.setTime(date4); cal5 = Calendar.getInstance(); cal5.setTime(date5); cal6 = Calendar.getInstance(); cal6.setTime(date6); cal7 = Calendar.getInstance(); cal7.setTime(date7); cal8 = Calendar.getInstance(); cal8.setTime(date8); TimeZone.setDefault(defaultZone); } //----------------------------------------------------------------------- public void testConstructor() { assertNotNull(new DateUtils()); Constructor[] cons = DateUtils.class.getDeclaredConstructors(); assertEquals(1, cons.length); assertEquals(true, Modifier.isPublic(cons[0].getModifiers())); assertEquals(true, Modifier.isPublic(DateUtils.class.getModifiers())); assertEquals(false, Modifier.isFinal(DateUtils.class.getModifiers())); } //----------------------------------------------------------------------- public void testIsSameDay_Date() { Date date1 = new GregorianCalendar(2004, 6, 9, 13, 45).getTime(); Date date2 = new GregorianCalendar(2004, 6, 9, 13, 45).getTime(); assertEquals(true, DateUtils.isSameDay(date1, date2)); date2 = new GregorianCalendar(2004, 6, 10, 13, 45).getTime(); assertEquals(false, DateUtils.isSameDay(date1, date2)); date1 = new GregorianCalendar(2004, 6, 10, 13, 45).getTime(); assertEquals(true, DateUtils.isSameDay(date1, date2)); date2 = new GregorianCalendar(2005, 6, 10, 13, 45).getTime(); assertEquals(false, DateUtils.isSameDay(date1, date2)); try { DateUtils.isSameDay((Date) null, (Date) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testIsSameDay_Cal() { GregorianCalendar cal1 = new GregorianCalendar(2004, 6, 9, 13, 45); GregorianCalendar cal2 = new GregorianCalendar(2004, 6, 9, 13, 45); assertEquals(true, DateUtils.isSameDay(cal1, cal2)); cal2.add(Calendar.DAY_OF_YEAR, 1); assertEquals(false, DateUtils.isSameDay(cal1, cal2)); cal1.add(Calendar.DAY_OF_YEAR, 1); assertEquals(true, DateUtils.isSameDay(cal1, cal2)); cal2.add(Calendar.YEAR, 1); assertEquals(false, DateUtils.isSameDay(cal1, cal2)); try { DateUtils.isSameDay((Calendar) null, (Calendar) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testIsSameInstant_Date() { Date date1 = new GregorianCalendar(2004, 6, 9, 13, 45).getTime(); Date date2 = new GregorianCalendar(2004, 6, 9, 13, 45).getTime(); assertEquals(true, DateUtils.isSameInstant(date1, date2)); date2 = new GregorianCalendar(2004, 6, 10, 13, 45).getTime(); assertEquals(false, DateUtils.isSameInstant(date1, date2)); date1 = new GregorianCalendar(2004, 6, 10, 13, 45).getTime(); assertEquals(true, DateUtils.isSameInstant(date1, date2)); date2 = new GregorianCalendar(2005, 6, 10, 13, 45).getTime(); assertEquals(false, DateUtils.isSameInstant(date1, date2)); try { DateUtils.isSameInstant((Date) null, (Date) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testIsSameInstant_Cal() { GregorianCalendar cal1 = new GregorianCalendar(TimeZone.getTimeZone("GMT+1")); GregorianCalendar cal2 = new GregorianCalendar(TimeZone.getTimeZone("GMT-1")); cal1.set(2004, 6, 9, 13, 45, 0); cal1.set(Calendar.MILLISECOND, 0); cal2.set(2004, 6, 9, 13, 45, 0); cal2.set(Calendar.MILLISECOND, 0); assertEquals(false, DateUtils.isSameInstant(cal1, cal2)); cal2.set(2004, 6, 9, 11, 45, 0); assertEquals(true, DateUtils.isSameInstant(cal1, cal2)); try { DateUtils.isSameInstant((Calendar) null, (Calendar) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testIsSameLocalTime_Cal() { GregorianCalendar cal1 = new GregorianCalendar(TimeZone.getTimeZone("GMT+1")); GregorianCalendar cal2 = new GregorianCalendar(TimeZone.getTimeZone("GMT-1")); cal1.set(2004, 6, 9, 13, 45, 0); cal1.set(Calendar.MILLISECOND, 0); cal2.set(2004, 6, 9, 13, 45, 0); cal2.set(Calendar.MILLISECOND, 0); assertEquals(true, DateUtils.isSameLocalTime(cal1, cal2)); cal2.set(2004, 6, 9, 11, 45, 0); assertEquals(false, DateUtils.isSameLocalTime(cal1, cal2)); try { DateUtils.isSameLocalTime((Calendar) null, (Calendar) null); fail(); } catch (IllegalArgumentException ex) {} } //----------------------------------------------------------------------- public void testParseDate() throws Exception { GregorianCalendar cal = new GregorianCalendar(1972, 11, 3); String dateStr = "1972-12-03"; String[] parsers = new String[] {"yyyy'-'DDD", "yyyy'-'MM'-'dd", "yyyyMMdd"}; Date date = DateUtils.parseDate(dateStr, parsers); assertEquals(cal.getTime(), date); dateStr = "1972-338"; date = DateUtils.parseDate(dateStr, parsers); assertEquals(cal.getTime(), date); dateStr = "19721203"; date = DateUtils.parseDate(dateStr, parsers); assertEquals(cal.getTime(), date); try { DateUtils.parseDate("PURPLE", parsers); fail(); } catch (ParseException ex) {} try { DateUtils.parseDate("197212AB", parsers); fail(); } catch (ParseException ex) {} try { DateUtils.parseDate(null, parsers); fail(); } catch (IllegalArgumentException ex) {} try { DateUtils.parseDate(dateStr, null); fail(); } catch (IllegalArgumentException ex) {} try { DateUtils.parseDate(dateStr, new String[0]); fail(); } catch (ParseException ex) {} } // LANG-486 public void testParseDateWithLeniency() throws Exception { GregorianCalendar cal = new GregorianCalendar(1998, 6, 30); String dateStr = "02 942, 1996"; String[] parsers = new String[] {"MM DDD, yyyy"}; Date date = DateUtils.parseDate(dateStr, parsers); assertEquals(cal.getTime(), date); try { date = DateUtils.parseDateStrictly(dateStr, parsers); fail(); } catch (ParseException ex) {} } //----------------------------------------------------------------------- public void testAddYears() throws Exception { Date base = new Date(MILLIS_TEST); Date result = DateUtils.addYears(base, 0); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 2, 1); result = DateUtils.addYears(base, 1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2001, 6, 5, 4, 3, 2, 1); result = DateUtils.addYears(base, -1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 1999, 6, 5, 4, 3, 2, 1); } //----------------------------------------------------------------------- public void testAddMonths() throws Exception { Date base = new Date(MILLIS_TEST); Date result = DateUtils.addMonths(base, 0); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 2, 1); result = DateUtils.addMonths(base, 1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 7, 5, 4, 3, 2, 1); result = DateUtils.addMonths(base, -1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 5, 5, 4, 3, 2, 1); } //----------------------------------------------------------------------- public void testAddWeeks() throws Exception { Date base = new Date(MILLIS_TEST); Date result = DateUtils.addWeeks(base, 0); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 2, 1); result = DateUtils.addWeeks(base, 1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 12, 4, 3, 2, 1); result = DateUtils.addWeeks(base, -1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); // july assertDate(result, 2000, 5, 28, 4, 3, 2, 1); // june } //----------------------------------------------------------------------- public void testAddDays() throws Exception { Date base = new Date(MILLIS_TEST); Date result = DateUtils.addDays(base, 0); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 2, 1); result = DateUtils.addDays(base, 1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 6, 4, 3, 2, 1); result = DateUtils.addDays(base, -1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 4, 4, 3, 2, 1); } //----------------------------------------------------------------------- public void testAddHours() throws Exception { Date base = new Date(MILLIS_TEST); Date result = DateUtils.addHours(base, 0); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 2, 1); result = DateUtils.addHours(base, 1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 5, 3, 2, 1); result = DateUtils.addHours(base, -1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 3, 3, 2, 1); } //----------------------------------------------------------------------- public void testAddMinutes() throws Exception { Date base = new Date(MILLIS_TEST); Date result = DateUtils.addMinutes(base, 0); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 2, 1); result = DateUtils.addMinutes(base, 1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 4, 2, 1); result = DateUtils.addMinutes(base, -1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 2, 2, 1); } //----------------------------------------------------------------------- public void testAddSeconds() throws Exception { Date base = new Date(MILLIS_TEST); Date result = DateUtils.addSeconds(base, 0); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 2, 1); result = DateUtils.addSeconds(base, 1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 3, 1); result = DateUtils.addSeconds(base, -1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 1, 1); } //----------------------------------------------------------------------- public void testAddMilliseconds() throws Exception { Date base = new Date(MILLIS_TEST); Date result = DateUtils.addMilliseconds(base, 0); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 2, 1); result = DateUtils.addMilliseconds(base, 1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 2, 2); result = DateUtils.addMilliseconds(base, -1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 2, 0); } //----------------------------------------------------------------------- public void testAddByField() throws Exception { Date base = new Date(MILLIS_TEST); Date result = DateUtils.add(base, Calendar.YEAR, 0); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 2, 1); result = DateUtils.add(base, Calendar.YEAR, 1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2001, 6, 5, 4, 3, 2, 1); result = DateUtils.add(base, Calendar.YEAR, -1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 1999, 6, 5, 4, 3, 2, 1); } // ----------------------------------------------------------------------- public void testSetYears() throws Exception { Date base = new Date(MILLIS_TEST); Date result = DateUtils.setYears(base, 2000); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 2, 1); result = DateUtils.setYears(base, 2008); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2008, 6, 5, 4, 3, 2, 1); result = DateUtils.setYears(base, 2005); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2005, 6, 5, 4, 3, 2, 1); } // ----------------------------------------------------------------------- public void testSetMonths() throws Exception { Date base = new Date(MILLIS_TEST); Date result = DateUtils.setMonths(base, 5); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 5, 5, 4, 3, 2, 1); result = DateUtils.setMonths(base, 1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 1, 5, 4, 3, 2, 1); try { result = DateUtils.setMonths(base, 12); fail("DateUtils.setMonths did not throw an expected IllegalArguementException."); } catch (IllegalArgumentException e) { } } // ----------------------------------------------------------------------- public void testSetDays() throws Exception { Date base = new Date(MILLIS_TEST); Date result = DateUtils.setDays(base, 1); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 1, 4, 3, 2, 1); result = DateUtils.setDays(base, 29); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 29, 4, 3, 2, 1); try { result = DateUtils.setDays(base, 32); fail("DateUtils.setDays did not throw an expected IllegalArguementException."); } catch (IllegalArgumentException e) { } } // ----------------------------------------------------------------------- public void testSetHours() throws Exception { Date base = new Date(MILLIS_TEST); Date result = DateUtils.setHours(base, 0); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 0, 3, 2, 1); result = DateUtils.setHours(base, 23); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 23, 3, 2, 1); try { result = DateUtils.setHours(base, 24); fail("DateUtils.setHours did not throw an expected IllegalArguementException."); } catch (IllegalArgumentException e) { } } // ----------------------------------------------------------------------- public void testSetMinutes() throws Exception { Date base = new Date(MILLIS_TEST); Date result = DateUtils.setMinutes(base, 0); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 0, 2, 1); result = DateUtils.setMinutes(base, 59); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 59, 2, 1); try { result = DateUtils.setMinutes(base, 60); fail("DateUtils.setMinutes did not throw an expected IllegalArguementException."); } catch (IllegalArgumentException e) { } } // ----------------------------------------------------------------------- public void testSetSeconds() throws Exception { Date base = new Date(MILLIS_TEST); Date result = DateUtils.setSeconds(base, 0); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 0, 1); result = DateUtils.setSeconds(base, 59); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 59, 1); try { result = DateUtils.setSeconds(base, 60); fail("DateUtils.setSeconds did not throw an expected IllegalArguementException."); } catch (IllegalArgumentException e) { } } // ----------------------------------------------------------------------- public void testSetMilliseconds() throws Exception { Date base = new Date(MILLIS_TEST); Date result = DateUtils.setMilliseconds(base, 0); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 2, 0); result = DateUtils.setMilliseconds(base, 999); assertNotSame(base, result); assertDate(base, 2000, 6, 5, 4, 3, 2, 1); assertDate(result, 2000, 6, 5, 4, 3, 2, 999); try { result = DateUtils.setMilliseconds(base, 1000); fail("DateUtils.setMilliseconds did not throw an expected IllegalArguementException."); } catch (IllegalArgumentException e) { } } //----------------------------------------------------------------------- private void assertDate(Date date, int year, int month, int day, int hour, int min, int sec, int mil) throws Exception { GregorianCalendar cal = new GregorianCalendar(); cal.setTime(date); assertEquals(year, cal.get(Calendar.YEAR)); assertEquals(month, cal.get(Calendar.MONTH)); assertEquals(day, cal.get(Calendar.DAY_OF_MONTH)); assertEquals(hour, cal.get(Calendar.HOUR_OF_DAY)); assertEquals(min, cal.get(Calendar.MINUTE)); assertEquals(sec, cal.get(Calendar.SECOND)); assertEquals(mil, cal.get(Calendar.MILLISECOND)); } //----------------------------------------------------------------------- public void testToCalendar() { assertEquals("Failed to convert to a Calendar and back", date1, DateUtils.toCalendar(date1).getTime()); try { DateUtils.toCalendar(null); fail("Expected NullPointerException to be thrown"); } catch(NullPointerException npe) { // expected } } //----------------------------------------------------------------------- /** * Tests various values with the round method */ public void testRound() throws Exception { // tests for public static Date round(Date date, int field) assertEquals("round year-1 failed", dateParser.parse("January 1, 2002"), DateUtils.round(date1, Calendar.YEAR)); assertEquals("round year-2 failed", dateParser.parse("January 1, 2002"), DateUtils.round(date2, Calendar.YEAR)); assertEquals("round month-1 failed", dateParser.parse("February 1, 2002"), DateUtils.round(date1, Calendar.MONTH)); assertEquals("round month-2 failed", dateParser.parse("December 1, 2001"), DateUtils.round(date2, Calendar.MONTH)); assertEquals("round semimonth-0 failed", dateParser.parse("February 1, 2002"), DateUtils.round(date0, DateUtils.SEMI_MONTH)); assertEquals("round semimonth-1 failed", dateParser.parse("February 16, 2002"), DateUtils.round(date1, DateUtils.SEMI_MONTH)); assertEquals("round semimonth-2 failed", dateParser.parse("November 16, 2001"), DateUtils.round(date2, DateUtils.SEMI_MONTH)); assertEquals("round date-1 failed", dateParser.parse("February 13, 2002"), DateUtils.round(date1, Calendar.DATE)); assertEquals("round date-2 failed", dateParser.parse("November 18, 2001"), DateUtils.round(date2, Calendar.DATE)); assertEquals("round hour-1 failed", dateTimeParser.parse("February 12, 2002 13:00:00.000"), DateUtils.round(date1, Calendar.HOUR)); assertEquals("round hour-2 failed", dateTimeParser.parse("November 18, 2001 1:00:00.000"), DateUtils.round(date2, Calendar.HOUR)); assertEquals("round minute-1 failed", dateTimeParser.parse("February 12, 2002 12:35:00.000"), DateUtils.round(date1, Calendar.MINUTE)); assertEquals("round minute-2 failed", dateTimeParser.parse("November 18, 2001 1:23:00.000"), DateUtils.round(date2, Calendar.MINUTE)); assertEquals("round second-1 failed", dateTimeParser.parse("February 12, 2002 12:34:57.000"), DateUtils.round(date1, Calendar.SECOND)); assertEquals("round second-2 failed", dateTimeParser.parse("November 18, 2001 1:23:11.000"), DateUtils.round(date2, Calendar.SECOND)); assertEquals("round ampm-1 failed", dateTimeParser.parse("February 3, 2002 00:00:00.000"), DateUtils.round(dateAmPm1, Calendar.AM_PM)); assertEquals("round ampm-2 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.round(dateAmPm2, Calendar.AM_PM)); assertEquals("round ampm-3 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.round(dateAmPm3, Calendar.AM_PM)); assertEquals("round ampm-4 failed", dateTimeParser.parse("February 4, 2002 00:00:00.000"), DateUtils.round(dateAmPm4, Calendar.AM_PM)); // tests for public static Date round(Object date, int field) assertEquals("round year-1 failed", dateParser.parse("January 1, 2002"), DateUtils.round((Object) date1, Calendar.YEAR)); assertEquals("round year-2 failed", dateParser.parse("January 1, 2002"), DateUtils.round((Object) date2, Calendar.YEAR)); assertEquals("round month-1 failed", dateParser.parse("February 1, 2002"), DateUtils.round((Object) date1, Calendar.MONTH)); assertEquals("round month-2 failed", dateParser.parse("December 1, 2001"), DateUtils.round((Object) date2, Calendar.MONTH)); assertEquals("round semimonth-1 failed", dateParser.parse("February 16, 2002"), DateUtils.round((Object) date1, DateUtils.SEMI_MONTH)); assertEquals("round semimonth-2 failed", dateParser.parse("November 16, 2001"), DateUtils.round((Object) date2, DateUtils.SEMI_MONTH)); assertEquals("round date-1 failed", dateParser.parse("February 13, 2002"), DateUtils.round((Object) date1, Calendar.DATE)); assertEquals("round date-2 failed", dateParser.parse("November 18, 2001"), DateUtils.round((Object) date2, Calendar.DATE)); assertEquals("round hour-1 failed", dateTimeParser.parse("February 12, 2002 13:00:00.000"), DateUtils.round((Object) date1, Calendar.HOUR)); assertEquals("round hour-2 failed", dateTimeParser.parse("November 18, 2001 1:00:00.000"), DateUtils.round((Object) date2, Calendar.HOUR)); assertEquals("round minute-1 failed", dateTimeParser.parse("February 12, 2002 12:35:00.000"), DateUtils.round((Object) date1, Calendar.MINUTE)); assertEquals("round minute-2 failed", dateTimeParser.parse("November 18, 2001 1:23:00.000"), DateUtils.round((Object) date2, Calendar.MINUTE)); assertEquals("round second-1 failed", dateTimeParser.parse("February 12, 2002 12:34:57.000"), DateUtils.round((Object) date1, Calendar.SECOND)); assertEquals("round second-2 failed", dateTimeParser.parse("November 18, 2001 1:23:11.000"), DateUtils.round((Object) date2, Calendar.SECOND)); assertEquals("round calendar second-1 failed", dateTimeParser.parse("February 12, 2002 12:34:57.000"), DateUtils.round((Object) cal1, Calendar.SECOND)); assertEquals("round calendar second-2 failed", dateTimeParser.parse("November 18, 2001 1:23:11.000"), DateUtils.round((Object) cal2, Calendar.SECOND)); assertEquals("round ampm-1 failed", dateTimeParser.parse("February 3, 2002 00:00:00.000"), DateUtils.round((Object) dateAmPm1, Calendar.AM_PM)); assertEquals("round ampm-2 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.round((Object) dateAmPm2, Calendar.AM_PM)); assertEquals("round ampm-3 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.round((Object) dateAmPm3, Calendar.AM_PM)); assertEquals("round ampm-4 failed", dateTimeParser.parse("February 4, 2002 00:00:00.000"), DateUtils.round((Object) dateAmPm4, Calendar.AM_PM)); try { DateUtils.round((Date) null, Calendar.SECOND); fail(); } catch (IllegalArgumentException ex) {} try { DateUtils.round((Calendar) null, Calendar.SECOND); fail(); } catch (IllegalArgumentException ex) {} try { DateUtils.round((Object) null, Calendar.SECOND); fail(); } catch (IllegalArgumentException ex) {} try { DateUtils.round("", Calendar.SECOND); fail(); } catch (ClassCastException ex) {} try { DateUtils.round(date1, -9999); fail(); } catch(IllegalArgumentException ex) {} assertEquals("round ampm-1 failed", dateTimeParser.parse("February 3, 2002 00:00:00.000"), DateUtils.round((Object) calAmPm1, Calendar.AM_PM)); assertEquals("round ampm-2 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.round((Object) calAmPm2, Calendar.AM_PM)); assertEquals("round ampm-3 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.round((Object) calAmPm3, Calendar.AM_PM)); assertEquals("round ampm-4 failed", dateTimeParser.parse("February 4, 2002 00:00:00.000"), DateUtils.round((Object) calAmPm4, Calendar.AM_PM)); // Fix for http://issues.apache.org/bugzilla/show_bug.cgi?id=25560 / LANG-13 // Test rounding across the beginning of daylight saving time TimeZone.setDefault(zone); dateTimeParser.setTimeZone(zone); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 00:00:00.000"), DateUtils.round(date4, Calendar.DATE)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 00:00:00.000"), DateUtils.round((Object) cal4, Calendar.DATE)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 00:00:00.000"), DateUtils.round(date5, Calendar.DATE)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 00:00:00.000"), DateUtils.round((Object) cal5, Calendar.DATE)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 00:00:00.000"), DateUtils.round(date6, Calendar.DATE)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 00:00:00.000"), DateUtils.round((Object) cal6, Calendar.DATE)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 00:00:00.000"), DateUtils.round(date7, Calendar.DATE)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 00:00:00.000"), DateUtils.round((Object) cal7, Calendar.DATE)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 01:00:00.000"), DateUtils.round(date4, Calendar.HOUR_OF_DAY)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 01:00:00.000"), DateUtils.round((Object) cal4, Calendar.HOUR_OF_DAY)); if (SystemUtils.isJavaVersionAtLeast(1.4f)) { assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 03:00:00.000"), DateUtils.round(date5, Calendar.HOUR_OF_DAY)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 03:00:00.000"), DateUtils.round((Object) cal5, Calendar.HOUR_OF_DAY)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 03:00:00.000"), DateUtils.round(date6, Calendar.HOUR_OF_DAY)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 03:00:00.000"), DateUtils.round((Object) cal6, Calendar.HOUR_OF_DAY)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 04:00:00.000"), DateUtils.round(date7, Calendar.HOUR_OF_DAY)); assertEquals("round MET date across DST change-over", dateTimeParser.parse("March 30, 2003 04:00:00.000"), DateUtils.round((Object) cal7, Calendar.HOUR_OF_DAY)); } else { this.warn("WARNING: Some date rounding tests not run since the current version is " + SystemUtils.JAVA_VERSION); } TimeZone.setDefault(defaultZone); dateTimeParser.setTimeZone(defaultZone); } /** * Tests the Changes Made by LANG-346 to the DateUtils.modify() private method invoked * by DateUtils.round(). */ public void testRoundLang346() throws Exception { TimeZone.setDefault(defaultZone); dateTimeParser.setTimeZone(defaultZone); Calendar testCalendar = Calendar.getInstance(); testCalendar.set(2007, 6, 2, 8, 8, 50); Date date = testCalendar.getTime(); assertEquals("Minute Round Up Failed", dateTimeParser.parse("July 2, 2007 08:09:00.000"), DateUtils.round(date, Calendar.MINUTE)); testCalendar.set(2007, 6, 2, 8, 8, 20); date = testCalendar.getTime(); assertEquals("Minute No Round Failed", dateTimeParser.parse("July 2, 2007 08:08:00.000"), DateUtils.round(date, Calendar.MINUTE)); testCalendar.set(2007, 6, 2, 8, 8, 50); testCalendar.set(Calendar.MILLISECOND, 600); date = testCalendar.getTime(); assertEquals("Second Round Up with 600 Milli Seconds Failed", dateTimeParser.parse("July 2, 2007 08:08:51.000"), DateUtils.round(date, Calendar.SECOND)); testCalendar.set(2007, 6, 2, 8, 8, 50); testCalendar.set(Calendar.MILLISECOND, 200); date = testCalendar.getTime(); assertEquals("Second Round Down with 200 Milli Seconds Failed", dateTimeParser.parse("July 2, 2007 08:08:50.000"), DateUtils.round(date, Calendar.SECOND)); testCalendar.set(2007, 6, 2, 8, 8, 20); testCalendar.set(Calendar.MILLISECOND, 600); date = testCalendar.getTime(); assertEquals("Second Round Up with 200 Milli Seconds Failed", dateTimeParser.parse("July 2, 2007 08:08:21.000"), DateUtils.round(date, Calendar.SECOND)); testCalendar.set(2007, 6, 2, 8, 8, 20); testCalendar.set(Calendar.MILLISECOND, 200); date = testCalendar.getTime(); assertEquals("Second Round Down with 200 Milli Seconds Failed", dateTimeParser.parse("July 2, 2007 08:08:20.000"), DateUtils.round(date, Calendar.SECOND)); testCalendar.set(2007, 6, 2, 8, 8, 50); date = testCalendar.getTime(); assertEquals("Hour Round Down Failed", dateTimeParser.parse("July 2, 2007 08:00:00.000"), DateUtils.round(date, Calendar.HOUR)); testCalendar.set(2007, 6, 2, 8, 31, 50); date = testCalendar.getTime(); assertEquals("Hour Round Up Failed", dateTimeParser.parse("July 2, 2007 09:00:00.000"), DateUtils.round(date, Calendar.HOUR)); } /** * Tests various values with the trunc method */ public void testTruncate() throws Exception { // tests public static Date truncate(Date date, int field) assertEquals("truncate year-1 failed", dateParser.parse("January 1, 2002"), DateUtils.truncate(date1, Calendar.YEAR)); assertEquals("truncate year-2 failed", dateParser.parse("January 1, 2001"), DateUtils.truncate(date2, Calendar.YEAR)); assertEquals("truncate month-1 failed", dateParser.parse("February 1, 2002"), DateUtils.truncate(date1, Calendar.MONTH)); assertEquals("truncate month-2 failed", dateParser.parse("November 1, 2001"), DateUtils.truncate(date2, Calendar.MONTH)); assertEquals("truncate semimonth-1 failed", dateParser.parse("February 1, 2002"), DateUtils.truncate(date1, DateUtils.SEMI_MONTH)); assertEquals("truncate semimonth-2 failed", dateParser.parse("November 16, 2001"), DateUtils.truncate(date2, DateUtils.SEMI_MONTH)); assertEquals("truncate date-1 failed", dateParser.parse("February 12, 2002"), DateUtils.truncate(date1, Calendar.DATE)); assertEquals("truncate date-2 failed", dateParser.parse("November 18, 2001"), DateUtils.truncate(date2, Calendar.DATE)); assertEquals("truncate hour-1 failed", dateTimeParser.parse("February 12, 2002 12:00:00.000"), DateUtils.truncate(date1, Calendar.HOUR)); assertEquals("truncate hour-2 failed", dateTimeParser.parse("November 18, 2001 1:00:00.000"), DateUtils.truncate(date2, Calendar.HOUR)); assertEquals("truncate minute-1 failed", dateTimeParser.parse("February 12, 2002 12:34:00.000"), DateUtils.truncate(date1, Calendar.MINUTE)); assertEquals("truncate minute-2 failed", dateTimeParser.parse("November 18, 2001 1:23:00.000"), DateUtils.truncate(date2, Calendar.MINUTE)); assertEquals("truncate second-1 failed", dateTimeParser.parse("February 12, 2002 12:34:56.000"), DateUtils.truncate(date1, Calendar.SECOND)); assertEquals("truncate second-2 failed", dateTimeParser.parse("November 18, 2001 1:23:11.000"), DateUtils.truncate(date2, Calendar.SECOND)); assertEquals("truncate ampm-1 failed", dateTimeParser.parse("February 3, 2002 00:00:00.000"), DateUtils.truncate(dateAmPm1, Calendar.AM_PM)); assertEquals("truncate ampm-2 failed", dateTimeParser.parse("February 3, 2002 00:00:00.000"), DateUtils.truncate(dateAmPm2, Calendar.AM_PM)); assertEquals("truncate ampm-3 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.truncate(dateAmPm3, Calendar.AM_PM)); assertEquals("truncate ampm-4 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.truncate(dateAmPm4, Calendar.AM_PM)); // tests public static Date truncate(Object date, int field) assertEquals("truncate year-1 failed", dateParser.parse("January 1, 2002"), DateUtils.truncate((Object) date1, Calendar.YEAR)); assertEquals("truncate year-2 failed", dateParser.parse("January 1, 2001"), DateUtils.truncate((Object) date2, Calendar.YEAR)); assertEquals("truncate month-1 failed", dateParser.parse("February 1, 2002"), DateUtils.truncate((Object) date1, Calendar.MONTH)); assertEquals("truncate month-2 failed", dateParser.parse("November 1, 2001"), DateUtils.truncate((Object) date2, Calendar.MONTH)); assertEquals("truncate semimonth-1 failed", dateParser.parse("February 1, 2002"), DateUtils.truncate((Object) date1, DateUtils.SEMI_MONTH)); assertEquals("truncate semimonth-2 failed", dateParser.parse("November 16, 2001"), DateUtils.truncate((Object) date2, DateUtils.SEMI_MONTH)); assertEquals("truncate date-1 failed", dateParser.parse("February 12, 2002"), DateUtils.truncate((Object) date1, Calendar.DATE)); assertEquals("truncate date-2 failed", dateParser.parse("November 18, 2001"), DateUtils.truncate((Object) date2, Calendar.DATE)); assertEquals("truncate hour-1 failed", dateTimeParser.parse("February 12, 2002 12:00:00.000"), DateUtils.truncate((Object) date1, Calendar.HOUR)); assertEquals("truncate hour-2 failed", dateTimeParser.parse("November 18, 2001 1:00:00.000"), DateUtils.truncate((Object) date2, Calendar.HOUR)); assertEquals("truncate minute-1 failed", dateTimeParser.parse("February 12, 2002 12:34:00.000"), DateUtils.truncate((Object) date1, Calendar.MINUTE)); assertEquals("truncate minute-2 failed", dateTimeParser.parse("November 18, 2001 1:23:00.000"), DateUtils.truncate((Object) date2, Calendar.MINUTE)); assertEquals("truncate second-1 failed", dateTimeParser.parse("February 12, 2002 12:34:56.000"), DateUtils.truncate((Object) date1, Calendar.SECOND)); assertEquals("truncate second-2 failed", dateTimeParser.parse("November 18, 2001 1:23:11.000"), DateUtils.truncate((Object) date2, Calendar.SECOND)); assertEquals("truncate ampm-1 failed", dateTimeParser.parse("February 3, 2002 00:00:00.000"), DateUtils.truncate((Object) dateAmPm1, Calendar.AM_PM)); assertEquals("truncate ampm-2 failed", dateTimeParser.parse("February 3, 2002 00:00:00.000"), DateUtils.truncate((Object) dateAmPm2, Calendar.AM_PM)); assertEquals("truncate ampm-3 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.truncate((Object) dateAmPm3, Calendar.AM_PM)); assertEquals("truncate ampm-4 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.truncate((Object) dateAmPm4, Calendar.AM_PM)); assertEquals("truncate calendar second-1 failed", dateTimeParser.parse("February 12, 2002 12:34:56.000"), DateUtils.truncate((Object) cal1, Calendar.SECOND)); assertEquals("truncate calendar second-2 failed", dateTimeParser.parse("November 18, 2001 1:23:11.000"), DateUtils.truncate((Object) cal2, Calendar.SECOND)); assertEquals("truncate ampm-1 failed", dateTimeParser.parse("February 3, 2002 00:00:00.000"), DateUtils.truncate((Object) calAmPm1, Calendar.AM_PM)); assertEquals("truncate ampm-2 failed", dateTimeParser.parse("February 3, 2002 00:00:00.000"), DateUtils.truncate((Object) calAmPm2, Calendar.AM_PM)); assertEquals("truncate ampm-3 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.truncate((Object) calAmPm3, Calendar.AM_PM)); assertEquals("truncate ampm-4 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.truncate((Object) calAmPm4, Calendar.AM_PM)); try { DateUtils.truncate((Date) null, Calendar.SECOND); fail(); } catch (IllegalArgumentException ex) {} try { DateUtils.truncate((Calendar) null, Calendar.SECOND); fail(); } catch (IllegalArgumentException ex) {} try { DateUtils.truncate((Object) null, Calendar.SECOND); fail(); } catch (IllegalArgumentException ex) {} try { DateUtils.truncate("", Calendar.SECOND); fail(); } catch (ClassCastException ex) {} // Fix for http://issues.apache.org/bugzilla/show_bug.cgi?id=25560 // Test truncate across beginning of daylight saving time TimeZone.setDefault(zone); dateTimeParser.setTimeZone(zone); assertEquals("truncate MET date across DST change-over", dateTimeParser.parse("March 30, 2003 00:00:00.000"), DateUtils.truncate(date3, Calendar.DATE)); assertEquals("truncate MET date across DST change-over", dateTimeParser.parse("March 30, 2003 00:00:00.000"), DateUtils.truncate((Object) cal3, Calendar.DATE)); // Test truncate across end of daylight saving time assertEquals("truncate MET date across DST change-over", dateTimeParser.parse("October 26, 2003 00:00:00.000"), DateUtils.truncate(date8, Calendar.DATE)); assertEquals("truncate MET date across DST change-over", dateTimeParser.parse("October 26, 2003 00:00:00.000"), DateUtils.truncate((Object) cal8, Calendar.DATE)); TimeZone.setDefault(defaultZone); dateTimeParser.setTimeZone(defaultZone); // Bug 31395, large dates Date endOfTime = new Date(Long.MAX_VALUE); // fyi: Sun Aug 17 07:12:55 CET 292278994 -- 807 millis GregorianCalendar endCal = new GregorianCalendar(); endCal.setTime(endOfTime); try { DateUtils.truncate(endCal, Calendar.DATE); fail(); } catch (ArithmeticException ex) {} endCal.set(Calendar.YEAR, 280000001); try { DateUtils.truncate(endCal, Calendar.DATE); fail(); } catch (ArithmeticException ex) {} endCal.set(Calendar.YEAR, 280000000); Calendar cal = DateUtils.truncate(endCal, Calendar.DATE); assertEquals(0, cal.get(Calendar.HOUR)); } /** * Tests for LANG-59 * * see http://issues.apache.org/jira/browse/LANG-59 */ public void testTruncateLang59() throws Exception { if (!SystemUtils.isJavaVersionAtLeast(1.4f)) { this.warn("WARNING: Test for LANG-59 not run since the current version is " + SystemUtils.JAVA_VERSION); return; } // Set TimeZone to Mountain Time TimeZone MST_MDT = TimeZone.getTimeZone("MST7MDT"); TimeZone.setDefault(MST_MDT); DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS z"); format.setTimeZone(MST_MDT); Date oct31_01MDT = new Date(1099206000000L); Date oct31MDT = new Date(oct31_01MDT.getTime() - 3600000L); // - 1 hour Date oct31_01_02MDT = new Date(oct31_01MDT.getTime() + 120000L); // + 2 minutes Date oct31_01_02_03MDT = new Date(oct31_01_02MDT.getTime() + 3000L); // + 3 seconds Date oct31_01_02_03_04MDT = new Date(oct31_01_02_03MDT.getTime() + 4L); // + 4 milliseconds assertEquals("Check 00:00:00.000", "2004-10-31 00:00:00.000 MDT", format.format(oct31MDT)); assertEquals("Check 01:00:00.000", "2004-10-31 01:00:00.000 MDT", format.format(oct31_01MDT)); assertEquals("Check 01:02:00.000", "2004-10-31 01:02:00.000 MDT", format.format(oct31_01_02MDT)); assertEquals("Check 01:02:03.000", "2004-10-31 01:02:03.000 MDT", format.format(oct31_01_02_03MDT)); assertEquals("Check 01:02:03.004", "2004-10-31 01:02:03.004 MDT", format.format(oct31_01_02_03_04MDT)); // ------- Demonstrate Problem ------- Calendar gval = Calendar.getInstance(); gval.setTime(new Date(oct31_01MDT.getTime())); gval.set(Calendar.MINUTE, gval.get(Calendar.MINUTE)); // set minutes to the same value assertEquals("Demonstrate Problem", gval.getTime().getTime(), oct31_01MDT.getTime() + 3600000L); // ---------- Test Truncate ---------- assertEquals("Truncate Calendar.MILLISECOND", oct31_01_02_03_04MDT, DateUtils.truncate(oct31_01_02_03_04MDT, Calendar.MILLISECOND)); assertEquals("Truncate Calendar.SECOND", oct31_01_02_03MDT, DateUtils.truncate(oct31_01_02_03_04MDT, Calendar.SECOND)); assertEquals("Truncate Calendar.MINUTE", oct31_01_02MDT, DateUtils.truncate(oct31_01_02_03_04MDT, Calendar.MINUTE)); assertEquals("Truncate Calendar.HOUR_OF_DAY", oct31_01MDT, DateUtils.truncate(oct31_01_02_03_04MDT, Calendar.HOUR_OF_DAY)); assertEquals("Truncate Calendar.HOUR", oct31_01MDT, DateUtils.truncate(oct31_01_02_03_04MDT, Calendar.HOUR)); assertEquals("Truncate Calendar.DATE", oct31MDT, DateUtils.truncate(oct31_01_02_03_04MDT, Calendar.DATE)); // ---------- Test Round (down) ---------- assertEquals("Round Calendar.MILLISECOND", oct31_01_02_03_04MDT, DateUtils.round(oct31_01_02_03_04MDT, Calendar.MILLISECOND)); assertEquals("Round Calendar.SECOND", oct31_01_02_03MDT, DateUtils.round(oct31_01_02_03_04MDT, Calendar.SECOND)); assertEquals("Round Calendar.MINUTE", oct31_01_02MDT, DateUtils.round(oct31_01_02_03_04MDT, Calendar.MINUTE)); assertEquals("Round Calendar.HOUR_OF_DAY", oct31_01MDT, DateUtils.round(oct31_01_02_03_04MDT, Calendar.HOUR_OF_DAY)); assertEquals("Round Calendar.HOUR", oct31_01MDT, DateUtils.round(oct31_01_02_03_04MDT, Calendar.HOUR)); assertEquals("Round Calendar.DATE", oct31MDT, DateUtils.round(oct31_01_02_03_04MDT, Calendar.DATE)); // restore default time zone TimeZone.setDefault(defaultZone); } // http://issues.apache.org/jira/browse/LANG-530 public void testLang530() throws ParseException { if (SystemUtils.isJavaVersionAtLeast(1.4f)) { Date d = new Date(); String isoDateStr = DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.format(d); Date d2 = DateUtils.parseDate(isoDateStr, new String[] { DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.getPattern() }); // the format loses milliseconds so have to reintroduce them assertEquals("Date not equal to itself ISO formatted and parsed", d.getTime(), d2.getTime() + d.getTime() % 1000); } else { this.warn("WARNING: Cannot test SimpleDateFormat with 'Z' since the current version is " + SystemUtils.JAVA_VERSION); } } /** * Tests various values with the ceiling method */ public void testCeil() throws Exception { // tests public static Date ceiling(Date date, int field) assertEquals("ceiling year-1 failed", dateParser.parse("January 1, 2003"), DateUtils.ceiling(date1, Calendar.YEAR)); assertEquals("ceiling year-2 failed", dateParser.parse("January 1, 2002"), DateUtils.ceiling(date2, Calendar.YEAR)); assertEquals("ceiling month-1 failed", dateParser.parse("March 1, 2002"), DateUtils.ceiling(date1, Calendar.MONTH)); assertEquals("ceiling month-2 failed", dateParser.parse("December 1, 2001"), DateUtils.ceiling(date2, Calendar.MONTH)); assertEquals("ceiling semimonth-1 failed", dateParser.parse("February 16, 2002"), DateUtils.ceiling(date1, DateUtils.SEMI_MONTH)); assertEquals("ceiling semimonth-2 failed", dateParser.parse("December 1, 2001"), DateUtils.ceiling(date2, DateUtils.SEMI_MONTH)); assertEquals("ceiling date-1 failed", dateParser.parse("February 13, 2002"), DateUtils.ceiling(date1, Calendar.DATE)); assertEquals("ceiling date-2 failed", dateParser.parse("November 19, 2001"), DateUtils.ceiling(date2, Calendar.DATE)); assertEquals("ceiling hour-1 failed", dateTimeParser.parse("February 12, 2002 13:00:00.000"), DateUtils.ceiling(date1, Calendar.HOUR)); assertEquals("ceiling hour-2 failed", dateTimeParser.parse("November 18, 2001 2:00:00.000"), DateUtils.ceiling(date2, Calendar.HOUR)); assertEquals("ceiling minute-1 failed", dateTimeParser.parse("February 12, 2002 12:35:00.000"), DateUtils.ceiling(date1, Calendar.MINUTE)); assertEquals("ceiling minute-2 failed", dateTimeParser.parse("November 18, 2001 1:24:00.000"), DateUtils.ceiling(date2, Calendar.MINUTE)); assertEquals("ceiling second-1 failed", dateTimeParser.parse("February 12, 2002 12:34:57.000"), DateUtils.ceiling(date1, Calendar.SECOND)); assertEquals("ceiling second-2 failed", dateTimeParser.parse("November 18, 2001 1:23:12.000"), DateUtils.ceiling(date2, Calendar.SECOND)); assertEquals("ceiling ampm-1 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.ceiling(dateAmPm1, Calendar.AM_PM)); assertEquals("ceiling ampm-2 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.ceiling(dateAmPm2, Calendar.AM_PM)); assertEquals("ceiling ampm-3 failed", dateTimeParser.parse("February 4, 2002 00:00:00.000"), DateUtils.ceiling(dateAmPm3, Calendar.AM_PM)); assertEquals("ceiling ampm-4 failed", dateTimeParser.parse("February 4, 2002 00:00:00.000"), DateUtils.ceiling(dateAmPm4, Calendar.AM_PM)); // tests public static Date ceiling(Object date, int field) assertEquals("ceiling year-1 failed", dateParser.parse("January 1, 2003"), DateUtils.ceiling((Object) date1, Calendar.YEAR)); assertEquals("ceiling year-2 failed", dateParser.parse("January 1, 2002"), DateUtils.ceiling((Object) date2, Calendar.YEAR)); assertEquals("ceiling month-1 failed", dateParser.parse("March 1, 2002"), DateUtils.ceiling((Object) date1, Calendar.MONTH)); assertEquals("ceiling month-2 failed", dateParser.parse("December 1, 2001"), DateUtils.ceiling((Object) date2, Calendar.MONTH)); assertEquals("ceiling semimonth-1 failed", dateParser.parse("February 16, 2002"), DateUtils.ceiling((Object) date1, DateUtils.SEMI_MONTH)); assertEquals("ceiling semimonth-2 failed", dateParser.parse("December 1, 2001"), DateUtils.ceiling((Object) date2, DateUtils.SEMI_MONTH)); assertEquals("ceiling date-1 failed", dateParser.parse("February 13, 2002"), DateUtils.ceiling((Object) date1, Calendar.DATE)); assertEquals("ceiling date-2 failed", dateParser.parse("November 19, 2001"), DateUtils.ceiling((Object) date2, Calendar.DATE)); assertEquals("ceiling hour-1 failed", dateTimeParser.parse("February 12, 2002 13:00:00.000"), DateUtils.ceiling((Object) date1, Calendar.HOUR)); assertEquals("ceiling hour-2 failed", dateTimeParser.parse("November 18, 2001 2:00:00.000"), DateUtils.ceiling((Object) date2, Calendar.HOUR)); assertEquals("ceiling minute-1 failed", dateTimeParser.parse("February 12, 2002 12:35:00.000"), DateUtils.ceiling((Object) date1, Calendar.MINUTE)); assertEquals("ceiling minute-2 failed", dateTimeParser.parse("November 18, 2001 1:24:00.000"), DateUtils.ceiling((Object) date2, Calendar.MINUTE)); assertEquals("ceiling second-1 failed", dateTimeParser.parse("February 12, 2002 12:34:57.000"), DateUtils.ceiling((Object) date1, Calendar.SECOND)); assertEquals("ceiling second-2 failed", dateTimeParser.parse("November 18, 2001 1:23:12.000"), DateUtils.ceiling((Object) date2, Calendar.SECOND)); assertEquals("ceiling ampm-1 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.ceiling((Object) dateAmPm1, Calendar.AM_PM)); assertEquals("ceiling ampm-2 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.ceiling((Object) dateAmPm2, Calendar.AM_PM)); assertEquals("ceiling ampm-3 failed", dateTimeParser.parse("February 4, 2002 00:00:00.000"), DateUtils.ceiling((Object) dateAmPm3, Calendar.AM_PM)); assertEquals("ceiling ampm-4 failed", dateTimeParser.parse("February 4, 2002 00:00:00.000"), DateUtils.ceiling((Object) dateAmPm4, Calendar.AM_PM)); assertEquals("ceiling calendar second-1 failed", dateTimeParser.parse("February 12, 2002 12:34:57.000"), DateUtils.ceiling((Object) cal1, Calendar.SECOND)); assertEquals("ceiling calendar second-2 failed", dateTimeParser.parse("November 18, 2001 1:23:12.000"), DateUtils.ceiling((Object) cal2, Calendar.SECOND)); assertEquals("ceiling ampm-1 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.ceiling((Object) calAmPm1, Calendar.AM_PM)); assertEquals("ceiling ampm-2 failed", dateTimeParser.parse("February 3, 2002 12:00:00.000"), DateUtils.ceiling((Object) calAmPm2, Calendar.AM_PM)); assertEquals("ceiling ampm-3 failed", dateTimeParser.parse("February 4, 2002 00:00:00.000"), DateUtils.ceiling((Object) calAmPm3, Calendar.AM_PM)); assertEquals("ceiling ampm-4 failed", dateTimeParser.parse("February 4, 2002 00:00:00.000"), DateUtils.ceiling((Object) calAmPm4, Calendar.AM_PM)); try { DateUtils.ceiling((Date) null, Calendar.SECOND); fail(); } catch (IllegalArgumentException ex) {} try { DateUtils.ceiling((Calendar) null, Calendar.SECOND); fail(); } catch (IllegalArgumentException ex) {} try { DateUtils.ceiling((Object) null, Calendar.SECOND); fail(); } catch (IllegalArgumentException ex) {} try { DateUtils.ceiling("", Calendar.SECOND); fail(); } catch (ClassCastException ex) {} try { DateUtils.ceiling(date1, -9999); fail(); } catch(IllegalArgumentException ex) {} // Fix for http://issues.apache.org/bugzilla/show_bug.cgi?id=25560 // == https://issues.apache.org/jira/browse/LANG-13 // Test ceiling across the beginning of daylight saving time TimeZone.setDefault(zone); dateTimeParser.setTimeZone(zone); assertEquals("ceiling MET date across DST change-over", dateTimeParser.parse("March 31, 2003 00:00:00.000"), DateUtils.ceiling(date4, Calendar.DATE)); assertEquals("ceiling MET date across DST change-over", dateTimeParser.parse("March 31, 2003 00:00:00.000"), DateUtils.ceiling((Object) cal4, Calendar.DATE)); assertEquals("ceiling MET date across DST change-over", dateTimeParser.parse("March 31, 2003 00:00:00.000"), DateUtils.ceiling(date5, Calendar.DATE)); assertEquals("ceiling MET date across DST change-over", dateTimeParser.parse("March 31, 2003 00:00:00.000"), DateUtils.ceiling((Object) cal5, Calendar.DATE)); assertEquals("ceiling MET date across DST change-over", dateTimeParser.parse("March 31, 2003 00:00:00.000"), DateUtils.ceiling(date6, Calendar.DATE)); assertEquals("ceiling MET date across DST change-over", dateTimeParser.parse("March 31, 2003 00:00:00.000"), DateUtils.ceiling((Object) cal6, Calendar.DATE)); assertEquals("ceiling MET date across DST change-over", dateTimeParser.parse("March 31, 2003 00:00:00.000"), DateUtils.ceiling(date7, Calendar.DATE)); assertEquals("ceiling MET date across DST change-over", dateTimeParser.parse("March 31, 2003 00:00:00.000"), DateUtils.ceiling((Object) cal7, Calendar.DATE)); if (SystemUtils.isJavaVersionAtLeast(1.4f)) { assertEquals("ceiling MET date across DST change-over", dateTimeParser.parse("March 30, 2003 03:00:00.000"), DateUtils.ceiling(date4, Calendar.HOUR_OF_DAY)); assertEquals("ceiling MET date across DST change-over", dateTimeParser.parse("March 30, 2003 03:00:00.000"), DateUtils.ceiling((Object) cal4, Calendar.HOUR_OF_DAY)); assertEquals("ceiling MET date across DST change-over", dateTimeParser.parse("March 30, 2003 03:00:00.000"), DateUtils.ceiling(date5, Calendar.HOUR_OF_DAY)); assertEquals("ceiling MET date across DST change-over", dateTimeParser.parse("March 30, 2003 03:00:00.000"), DateUtils.ceiling((Object) cal5, Calendar.HOUR_OF_DAY)); assertEquals("ceiling MET date across DST change-over", dateTimeParser.parse("March 30, 2003 04:00:00.000"), DateUtils.ceiling(date6, Calendar.HOUR_OF_DAY)); assertEquals("ceiling MET date across DST change-over", dateTimeParser.parse("March 30, 2003 04:00:00.000"), DateUtils.ceiling((Object) cal6, Calendar.HOUR_OF_DAY)); assertEquals("ceiling MET date across DST change-over", dateTimeParser.parse("March 30, 2003 04:00:00.000"), DateUtils.ceiling(date7, Calendar.HOUR_OF_DAY)); assertEquals("ceiling MET date across DST change-over", dateTimeParser.parse("March 30, 2003 04:00:00.000"), DateUtils.ceiling((Object) cal7, Calendar.HOUR_OF_DAY)); } else { this.warn("WARNING: Some date ceiling tests not run since the current version is " + SystemUtils.JAVA_VERSION); } TimeZone.setDefault(defaultZone); dateTimeParser.setTimeZone(defaultZone); // Bug 31395, large dates Date endOfTime = new Date(Long.MAX_VALUE); // fyi: Sun Aug 17 07:12:55 CET 292278994 -- 807 millis GregorianCalendar endCal = new GregorianCalendar(); endCal.setTime(endOfTime); try { DateUtils.ceiling(endCal, Calendar.DATE); fail(); } catch (ArithmeticException ex) {} endCal.set(Calendar.YEAR, 280000001); try { DateUtils.ceiling(endCal, Calendar.DATE); fail(); } catch (ArithmeticException ex) {} endCal.set(Calendar.YEAR, 280000000); Calendar cal = DateUtils.ceiling(endCal, Calendar.DATE); assertEquals(0, cal.get(Calendar.HOUR)); } /** * Tests the iterator exceptions */ public void testIteratorEx() throws Exception { try { DateUtils.iterator(Calendar.getInstance(), -9999); } catch (IllegalArgumentException ex) {} try { DateUtils.iterator((Date) null, DateUtils.RANGE_WEEK_CENTER); fail(); } catch (IllegalArgumentException ex) {} try { DateUtils.iterator((Calendar) null, DateUtils.RANGE_WEEK_CENTER); fail(); } catch (IllegalArgumentException ex) {} try { DateUtils.iterator((Object) null, DateUtils.RANGE_WEEK_CENTER); fail(); } catch (IllegalArgumentException ex) {} try { DateUtils.iterator("", DateUtils.RANGE_WEEK_CENTER); fail(); } catch (ClassCastException ex) {} } /** * Tests the calendar iterator for week ranges */ public void testWeekIterator() throws Exception { Calendar now = Calendar.getInstance(); for (int i = 0; i< 7; i++) { Calendar today = DateUtils.truncate(now, Calendar.DATE); Calendar sunday = DateUtils.truncate(now, Calendar.DATE); sunday.add(Calendar.DATE, 1 - sunday.get(Calendar.DAY_OF_WEEK)); Calendar monday = DateUtils.truncate(now, Calendar.DATE); if (monday.get(Calendar.DAY_OF_WEEK) == 1) { //This is sunday... roll back 6 days monday.add(Calendar.DATE, -6); } else { monday.add(Calendar.DATE, 2 - monday.get(Calendar.DAY_OF_WEEK)); } Calendar centered = DateUtils.truncate(now, Calendar.DATE); centered.add(Calendar.DATE, -3); Iterator it = DateUtils.iterator(now, DateUtils.RANGE_WEEK_SUNDAY); assertWeekIterator(it, sunday); it = DateUtils.iterator(now, DateUtils.RANGE_WEEK_MONDAY); assertWeekIterator(it, monday); it = DateUtils.iterator(now, DateUtils.RANGE_WEEK_RELATIVE); assertWeekIterator(it, today); it = DateUtils.iterator(now, DateUtils.RANGE_WEEK_CENTER); assertWeekIterator(it, centered); it = DateUtils.iterator((Object) now, DateUtils.RANGE_WEEK_CENTER); assertWeekIterator(it, centered); it = DateUtils.iterator((Object) now.getTime(), DateUtils.RANGE_WEEK_CENTER); assertWeekIterator(it, centered); try { it.next(); fail(); } catch (NoSuchElementException ex) {} it = DateUtils.iterator(now, DateUtils.RANGE_WEEK_CENTER); it.next(); try { it.remove(); } catch( UnsupportedOperationException ex) {} now.add(Calendar.DATE,1); } } /** * Tests the calendar iterator for month-based ranges */ public void testMonthIterator() throws Exception { Iterator it = DateUtils.iterator(date1, DateUtils.RANGE_MONTH_SUNDAY); assertWeekIterator(it, dateParser.parse("January 27, 2002"), dateParser.parse("March 2, 2002")); it = DateUtils.iterator(date1, DateUtils.RANGE_MONTH_MONDAY); assertWeekIterator(it, dateParser.parse("January 28, 2002"), dateParser.parse("March 3, 2002")); it = DateUtils.iterator(date2, DateUtils.RANGE_MONTH_SUNDAY); assertWeekIterator(it, dateParser.parse("October 28, 2001"), dateParser.parse("December 1, 2001")); it = DateUtils.iterator(date2, DateUtils.RANGE_MONTH_MONDAY); assertWeekIterator(it, dateParser.parse("October 29, 2001"), dateParser.parse("December 2, 2001")); } /** * This checks that this is a 7 element iterator of Calendar objects * that are dates (no time), and exactly 1 day spaced after each other. */ private static void assertWeekIterator(Iterator it, Calendar start) { Calendar end = (Calendar) start.clone(); end.add(Calendar.DATE, 6); assertWeekIterator(it, start, end); } /** * Convenience method for when working with Date objects */ private static void assertWeekIterator(Iterator it, Date start, Date end) { Calendar calStart = Calendar.getInstance(); calStart.setTime(start); Calendar calEnd = Calendar.getInstance(); calEnd.setTime(end); assertWeekIterator(it, calStart, calEnd); } /** * This checks that this is a 7 divisble iterator of Calendar objects * that are dates (no time), and exactly 1 day spaced after each other * (in addition to the proper start and stop dates) */ private static void assertWeekIterator(Iterator it, Calendar start, Calendar end) { Calendar cal = (Calendar) it.next(); assertEquals("", start, cal, 0); Calendar last = null; int count = 1; while (it.hasNext()) { //Check this is just a date (no time component) assertEquals("", cal, DateUtils.truncate(cal, Calendar.DATE), 0); last = cal; cal = (Calendar) it.next(); count++; //Check that this is one day more than the last date last.add(Calendar.DATE, 1); assertEquals("", last, cal, 0); } if (count % 7 != 0) { throw new AssertionFailedError("There were " + count + " days in this iterator"); } assertEquals("", end, cal, 0); } /** * Used to check that Calendar objects are close enough * delta is in milliseconds */ private static void assertEquals(String message, Calendar cal1, Calendar cal2, long delta) { if (Math.abs(cal1.getTime().getTime() - cal2.getTime().getTime()) > delta) { throw new AssertionFailedError( message + " expected " + cal1.getTime() + " but got " + cal2.getTime()); } } void warn(String msg) { System.err.println(msg); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/time/DurationFormatUtilsTest.java100644 0 0 75615 11513702435 27441 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.time; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.util.Calendar; import java.util.TimeZone; import junit.framework.TestCase; /** * TestCase for DurationFormatUtils. * * @author Apache Software Foundation * @author Apache Ant - DateUtilsTest * @author Stephane Bailliez * @author Stefan Bodewig * @author Gary Gregory */ public class DurationFormatUtilsTest extends TestCase { public DurationFormatUtilsTest(String s) { super(s); } // ----------------------------------------------------------------------- public void testConstructor() { assertNotNull(new DurationFormatUtils()); Constructor[] cons = DurationFormatUtils.class.getDeclaredConstructors(); assertEquals(1, cons.length); assertEquals(true, Modifier.isPublic(cons[0].getModifiers())); assertEquals(true, Modifier.isPublic(DurationFormatUtils.class.getModifiers())); assertEquals(false, Modifier.isFinal(DurationFormatUtils.class.getModifiers())); } // ----------------------------------------------------------------------- public void testFormatDurationWords() { String text = null; text = DurationFormatUtils.formatDurationWords(50 * 1000, true, false); assertEquals("50 seconds", text); text = DurationFormatUtils.formatDurationWords(65 * 1000, true, false); assertEquals("1 minute 5 seconds", text); text = DurationFormatUtils.formatDurationWords(120 * 1000, true, false); assertEquals("2 minutes 0 seconds", text); text = DurationFormatUtils.formatDurationWords(121 * 1000, true, false); assertEquals("2 minutes 1 second", text); text = DurationFormatUtils.formatDurationWords(72 * 60 * 1000, true, false); assertEquals("1 hour 12 minutes 0 seconds", text); text = DurationFormatUtils.formatDurationWords(24 * 60 * 60 * 1000, true, false); assertEquals("1 day 0 hours 0 minutes 0 seconds", text); text = DurationFormatUtils.formatDurationWords(50 * 1000, true, true); assertEquals("50 seconds", text); text = DurationFormatUtils.formatDurationWords(65 * 1000, true, true); assertEquals("1 minute 5 seconds", text); text = DurationFormatUtils.formatDurationWords(120 * 1000, true, true); assertEquals("2 minutes", text); text = DurationFormatUtils.formatDurationWords(121 * 1000, true, true); assertEquals("2 minutes 1 second", text); text = DurationFormatUtils.formatDurationWords(72 * 60 * 1000, true, true); assertEquals("1 hour 12 minutes", text); text = DurationFormatUtils.formatDurationWords(24 * 60 * 60 * 1000, true, true); assertEquals("1 day", text); text = DurationFormatUtils.formatDurationWords(50 * 1000, false, true); assertEquals("0 days 0 hours 0 minutes 50 seconds", text); text = DurationFormatUtils.formatDurationWords(65 * 1000, false, true); assertEquals("0 days 0 hours 1 minute 5 seconds", text); text = DurationFormatUtils.formatDurationWords(120 * 1000, false, true); assertEquals("0 days 0 hours 2 minutes", text); text = DurationFormatUtils.formatDurationWords(121 * 1000, false, true); assertEquals("0 days 0 hours 2 minutes 1 second", text); text = DurationFormatUtils.formatDurationWords(72 * 60 * 1000, false, true); assertEquals("0 days 1 hour 12 minutes", text); text = DurationFormatUtils.formatDurationWords(24 * 60 * 60 * 1000, false, true); assertEquals("1 day", text); text = DurationFormatUtils.formatDurationWords(50 * 1000, false, false); assertEquals("0 days 0 hours 0 minutes 50 seconds", text); text = DurationFormatUtils.formatDurationWords(65 * 1000, false, false); assertEquals("0 days 0 hours 1 minute 5 seconds", text); text = DurationFormatUtils.formatDurationWords(120 * 1000, false, false); assertEquals("0 days 0 hours 2 minutes 0 seconds", text); text = DurationFormatUtils.formatDurationWords(121 * 1000, false, false); assertEquals("0 days 0 hours 2 minutes 1 second", text); text = DurationFormatUtils.formatDurationWords(72 * 60 * 1000, false, false); assertEquals("0 days 1 hour 12 minutes 0 seconds", text); text = DurationFormatUtils.formatDurationWords(24 * 60 * 60 * 1000 + 72 * 60 * 1000, false, false); assertEquals("1 day 1 hour 12 minutes 0 seconds", text); text = DurationFormatUtils.formatDurationWords(2 * 24 * 60 * 60 * 1000 + 72 * 60 * 1000, false, false); assertEquals("2 days 1 hour 12 minutes 0 seconds", text); for (int i = 2; i < 31; i++) { text = DurationFormatUtils.formatDurationWords(i * 24 * 60 * 60 * 1000, false, false); // assertEquals(i + " days 0 hours 0 minutes 0 seconds", text); // // junit.framework.ComparisonFailure: expected:<25 days 0 hours 0 minutes 0...> but was:<-24 days -17 hours // -2 minutes -47...> // at junit.framework.Assert.assertEquals(Assert.java:81) // at junit.framework.Assert.assertEquals(Assert.java:87) // at // org.apache.commons.lang.time.DurationFormatUtilsTest.testFormatDurationWords(DurationFormatUtilsTest.java:124) // at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) // at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) // at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) // at java.lang.reflect.Method.invoke(Method.java:324) // at junit.framework.TestCase.runTest(TestCase.java:154) // at junit.framework.TestCase.runBare(TestCase.java:127) // at junit.framework.TestResult$1.protect(TestResult.java:106) // at junit.framework.TestResult.runProtected(TestResult.java:124) // at junit.framework.TestResult.run(TestResult.java:109) // at junit.framework.TestCase.run(TestCase.java:118) // at junit.framework.TestSuite.runTest(TestSuite.java:208) // at junit.framework.TestSuite.run(TestSuite.java:203) // at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:478) // at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:344) // at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196) } } /** * Tests that "1 s" gets converted to "1 " but that "11 s" is left alone. */ public void testFormatDurationPluralWords() { long oneSecond = 1000; long oneMinute = oneSecond * 60; long oneHour = oneMinute * 60; long oneDay = oneHour * 24; String text = null; text = DurationFormatUtils.formatDurationWords(oneSecond, false, false); assertEquals("0 days 0 hours 0 minutes 1 second", text); text = DurationFormatUtils.formatDurationWords(oneSecond * 2, false, false); assertEquals("0 days 0 hours 0 minutes 2 seconds", text); text = DurationFormatUtils.formatDurationWords(oneSecond * 11, false, false); assertEquals("0 days 0 hours 0 minutes 11 seconds", text); text = DurationFormatUtils.formatDurationWords(oneMinute, false, false); assertEquals("0 days 0 hours 1 minute 0 seconds", text); text = DurationFormatUtils.formatDurationWords(oneMinute * 2, false, false); assertEquals("0 days 0 hours 2 minutes 0 seconds", text); text = DurationFormatUtils.formatDurationWords(oneMinute * 11, false, false); assertEquals("0 days 0 hours 11 minutes 0 seconds", text); text = DurationFormatUtils.formatDurationWords(oneMinute + oneSecond, false, false); assertEquals("0 days 0 hours 1 minute 1 second", text); text = DurationFormatUtils.formatDurationWords(oneHour, false, false); assertEquals("0 days 1 hour 0 minutes 0 seconds", text); text = DurationFormatUtils.formatDurationWords(oneHour * 2, false, false); assertEquals("0 days 2 hours 0 minutes 0 seconds", text); text = DurationFormatUtils.formatDurationWords(oneHour * 11, false, false); assertEquals("0 days 11 hours 0 minutes 0 seconds", text); text = DurationFormatUtils.formatDurationWords(oneHour + oneMinute + oneSecond, false, false); assertEquals("0 days 1 hour 1 minute 1 second", text); text = DurationFormatUtils.formatDurationWords(oneDay, false, false); assertEquals("1 day 0 hours 0 minutes 0 seconds", text); text = DurationFormatUtils.formatDurationWords(oneDay * 2, false, false); assertEquals("2 days 0 hours 0 minutes 0 seconds", text); text = DurationFormatUtils.formatDurationWords(oneDay * 11, false, false); assertEquals("11 days 0 hours 0 minutes 0 seconds", text); text = DurationFormatUtils.formatDurationWords(oneDay + oneHour + oneMinute + oneSecond, false, false); assertEquals("1 day 1 hour 1 minute 1 second", text); } public void testFormatDurationHMS() { long time = 0; assertEquals("0:00:00.000", DurationFormatUtils.formatDurationHMS(time)); time = 1; assertEquals("0:00:00.001", DurationFormatUtils.formatDurationHMS(time)); time = 15; assertEquals("0:00:00.015", DurationFormatUtils.formatDurationHMS(time)); time = 165; assertEquals("0:00:00.165", DurationFormatUtils.formatDurationHMS(time)); time = 1675; assertEquals("0:00:01.675", DurationFormatUtils.formatDurationHMS(time)); time = 13465; assertEquals("0:00:13.465", DurationFormatUtils.formatDurationHMS(time)); time = 72789; assertEquals("0:01:12.789", DurationFormatUtils.formatDurationHMS(time)); time = 12789 + 32 * 60000; assertEquals("0:32:12.789", DurationFormatUtils.formatDurationHMS(time)); time = 12789 + 62 * 60000; assertEquals("1:02:12.789", DurationFormatUtils.formatDurationHMS(time)); } public void testFormatDurationISO() { assertEquals("P0Y0M0DT0H0M0.000S", DurationFormatUtils.formatDurationISO(0L)); assertEquals("P0Y0M0DT0H0M0.001S", DurationFormatUtils.formatDurationISO(1L)); assertEquals("P0Y0M0DT0H0M0.010S", DurationFormatUtils.formatDurationISO(10L)); assertEquals("P0Y0M0DT0H0M0.100S", DurationFormatUtils.formatDurationISO(100L)); assertEquals("P0Y0M0DT0H1M15.321S", DurationFormatUtils.formatDurationISO(75321L)); } public void testFormatDuration() { long duration = 0; assertEquals("0", DurationFormatUtils.formatDuration(duration, "y")); assertEquals("0", DurationFormatUtils.formatDuration(duration, "M")); assertEquals("0", DurationFormatUtils.formatDuration(duration, "d")); assertEquals("0", DurationFormatUtils.formatDuration(duration, "H")); assertEquals("0", DurationFormatUtils.formatDuration(duration, "m")); assertEquals("0", DurationFormatUtils.formatDuration(duration, "s")); assertEquals("0", DurationFormatUtils.formatDuration(duration, "S")); assertEquals("0000", DurationFormatUtils.formatDuration(duration, "SSSS")); assertEquals("0000", DurationFormatUtils.formatDuration(duration, "yyyy")); assertEquals("0000", DurationFormatUtils.formatDuration(duration, "yyMM")); duration = 60 * 1000; assertEquals("0", DurationFormatUtils.formatDuration(duration, "y")); assertEquals("0", DurationFormatUtils.formatDuration(duration, "M")); assertEquals("0", DurationFormatUtils.formatDuration(duration, "d")); assertEquals("0", DurationFormatUtils.formatDuration(duration, "H")); assertEquals("1", DurationFormatUtils.formatDuration(duration, "m")); assertEquals("60", DurationFormatUtils.formatDuration(duration, "s")); assertEquals("60000", DurationFormatUtils.formatDuration(duration, "S")); assertEquals("01:00", DurationFormatUtils.formatDuration(duration, "mm:ss")); Calendar base = Calendar.getInstance(); base.set(2000, 0, 1, 0, 0, 0); base.set(Calendar.MILLISECOND, 0); Calendar cal = Calendar.getInstance(); cal.set(2003, 1, 1, 0, 0, 0); cal.set(Calendar.MILLISECOND, 0); duration = cal.getTime().getTime() - base.getTime().getTime(); // duration from 2000-01-01 to cal // don't use 1970 in test as time zones were less reliable in 1970 than now // remember that duration formatting ignores time zones, working on strict hour lengths int days = 366 + 365 + 365 + 31; assertEquals("0 0 " + days, DurationFormatUtils.formatDuration(duration, "y M d")); } public void testFormatPeriodISO() { TimeZone timeZone = TimeZone.getTimeZone("GMT-3"); Calendar base = Calendar.getInstance(timeZone); base.set(1970, 0, 1, 0, 0, 0); base.set(Calendar.MILLISECOND, 0); Calendar cal = Calendar.getInstance(timeZone); cal.set(2002, 1, 23, 9, 11, 12); cal.set(Calendar.MILLISECOND, 1); String text; // repeat a test from testDateTimeISO to compare extended and not extended. text = DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.format(cal); assertEquals("2002-02-23T09:11:12-03:00", text); // test fixture is the same as above, but now with extended format. text = DurationFormatUtils.formatPeriod(base.getTime().getTime(), cal.getTime().getTime(), DurationFormatUtils.ISO_EXTENDED_FORMAT_PATTERN, false, timeZone); assertEquals("P32Y1M22DT9H11M12.001S", text); // test fixture from example in http://www.w3.org/TR/xmlschema-2/#duration cal.set(1971, 1, 3, 10, 30, 0); cal.set(Calendar.MILLISECOND, 0); text = DurationFormatUtils.formatPeriod(base.getTime().getTime(), cal.getTime().getTime(), DurationFormatUtils.ISO_EXTENDED_FORMAT_PATTERN, false, timeZone); assertEquals("P1Y1M2DT10H30M0.000S", text); // want a way to say 'don't print the seconds in format()' or other fields for that matter: // assertEquals("P1Y2M3DT10H30M", text); } public void testFormatPeriod() { Calendar cal1970 = Calendar.getInstance(); cal1970.set(1970, 0, 1, 0, 0, 0); cal1970.set(Calendar.MILLISECOND, 0); long time1970 = cal1970.getTime().getTime(); assertEquals("0", DurationFormatUtils.formatPeriod(time1970, time1970, "y")); assertEquals("0", DurationFormatUtils.formatPeriod(time1970, time1970, "M")); assertEquals("0", DurationFormatUtils.formatPeriod(time1970, time1970, "d")); assertEquals("0", DurationFormatUtils.formatPeriod(time1970, time1970, "H")); assertEquals("0", DurationFormatUtils.formatPeriod(time1970, time1970, "m")); assertEquals("0", DurationFormatUtils.formatPeriod(time1970, time1970, "s")); assertEquals("0", DurationFormatUtils.formatPeriod(time1970, time1970, "S")); assertEquals("0000", DurationFormatUtils.formatPeriod(time1970, time1970, "SSSS")); assertEquals("0000", DurationFormatUtils.formatPeriod(time1970, time1970, "yyyy")); assertEquals("0000", DurationFormatUtils.formatPeriod(time1970, time1970, "yyMM")); long time = time1970 + 60 * 1000; assertEquals("0", DurationFormatUtils.formatPeriod(time1970, time, "y")); assertEquals("0", DurationFormatUtils.formatPeriod(time1970, time, "M")); assertEquals("0", DurationFormatUtils.formatPeriod(time1970, time, "d")); assertEquals("0", DurationFormatUtils.formatPeriod(time1970, time, "H")); assertEquals("1", DurationFormatUtils.formatPeriod(time1970, time, "m")); assertEquals("60", DurationFormatUtils.formatPeriod(time1970, time, "s")); assertEquals("60000", DurationFormatUtils.formatPeriod(time1970, time, "S")); assertEquals("01:00", DurationFormatUtils.formatPeriod(time1970, time, "mm:ss")); Calendar cal = Calendar.getInstance(); cal.set(1973, 6, 1, 0, 0, 0); cal.set(Calendar.MILLISECOND, 0); time = cal.getTime().getTime(); assertEquals("36", DurationFormatUtils.formatPeriod(time1970, time, "yM")); assertEquals("3 years 6 months", DurationFormatUtils.formatPeriod(time1970, time, "y' years 'M' months'")); assertEquals("03/06", DurationFormatUtils.formatPeriod(time1970, time, "yy/MM")); cal.set(1973, 10, 1, 0, 0, 0); cal.set(Calendar.MILLISECOND, 0); time = cal.getTime().getTime(); assertEquals("310", DurationFormatUtils.formatPeriod(time1970, time, "yM")); assertEquals("3 years 10 months", DurationFormatUtils.formatPeriod(time1970, time, "y' years 'M' months'")); assertEquals("03/10", DurationFormatUtils.formatPeriod(time1970, time, "yy/MM")); cal.set(1974, 0, 1, 0, 0, 0); cal.set(Calendar.MILLISECOND, 0); time = cal.getTime().getTime(); assertEquals("40", DurationFormatUtils.formatPeriod(time1970, time, "yM")); assertEquals("4 years 0 months", DurationFormatUtils.formatPeriod(time1970, time, "y' years 'M' months'")); assertEquals("04/00", DurationFormatUtils.formatPeriod(time1970, time, "yy/MM")); assertEquals("48", DurationFormatUtils.formatPeriod(time1970, time, "M")); assertEquals("48", DurationFormatUtils.formatPeriod(time1970, time, "MM")); assertEquals("048", DurationFormatUtils.formatPeriod(time1970, time, "MMM")); } public void testLexx() { // tests each constant assertArrayEquals(new DurationFormatUtils.Token[]{ new DurationFormatUtils.Token(DurationFormatUtils.y, 1), new DurationFormatUtils.Token(DurationFormatUtils.M, 1), new DurationFormatUtils.Token(DurationFormatUtils.d, 1), new DurationFormatUtils.Token(DurationFormatUtils.H, 1), new DurationFormatUtils.Token(DurationFormatUtils.m, 1), new DurationFormatUtils.Token(DurationFormatUtils.s, 1), new DurationFormatUtils.Token(DurationFormatUtils.S, 1)}, DurationFormatUtils.lexx("yMdHmsS")); // tests the ISO8601-like assertArrayEquals(new DurationFormatUtils.Token[]{ new DurationFormatUtils.Token(DurationFormatUtils.H, 1), new DurationFormatUtils.Token(new StringBuffer(":"), 1), new DurationFormatUtils.Token(DurationFormatUtils.m, 2), new DurationFormatUtils.Token(new StringBuffer(":"), 1), new DurationFormatUtils.Token(DurationFormatUtils.s, 2), new DurationFormatUtils.Token(new StringBuffer("."), 1), new DurationFormatUtils.Token(DurationFormatUtils.S, 3)}, DurationFormatUtils.lexx("H:mm:ss.SSS")); // test the iso extended format assertArrayEquals(new DurationFormatUtils.Token[]{ new DurationFormatUtils.Token(new StringBuffer("P"), 1), new DurationFormatUtils.Token(DurationFormatUtils.y, 4), new DurationFormatUtils.Token(new StringBuffer("Y"), 1), new DurationFormatUtils.Token(DurationFormatUtils.M, 1), new DurationFormatUtils.Token(new StringBuffer("M"), 1), new DurationFormatUtils.Token(DurationFormatUtils.d, 1), new DurationFormatUtils.Token(new StringBuffer("DT"), 1), new DurationFormatUtils.Token(DurationFormatUtils.H, 1), new DurationFormatUtils.Token(new StringBuffer("H"), 1), new DurationFormatUtils.Token(DurationFormatUtils.m, 1), new DurationFormatUtils.Token(new StringBuffer("M"), 1), new DurationFormatUtils.Token(DurationFormatUtils.s, 1), new DurationFormatUtils.Token(new StringBuffer("."), 1), new DurationFormatUtils.Token(DurationFormatUtils.S, 1), new DurationFormatUtils.Token(new StringBuffer("S"), 1)}, DurationFormatUtils .lexx(DurationFormatUtils.ISO_EXTENDED_FORMAT_PATTERN)); // test failures in equals DurationFormatUtils.Token token = new DurationFormatUtils.Token(DurationFormatUtils.y, 4); assertFalse("Token equal to non-Token class. ", token.equals(new Object())); assertFalse("Token equal to Token with wrong value class. ", token.equals(new DurationFormatUtils.Token( new Object()))); assertFalse("Token equal to Token with different count. ", token.equals(new DurationFormatUtils.Token( DurationFormatUtils.y, 1))); DurationFormatUtils.Token numToken = new DurationFormatUtils.Token(new Integer(1), 4); assertTrue("Token with Number value not equal to itself. ", numToken.equals(numToken)); } // http://issues.apache.org/bugzilla/show_bug.cgi?id=38401 public void testBugzilla38401() { assertEqualDuration( "0000/00/30 16:00:00 000", new int[] { 2006, 0, 26, 18, 47, 34 }, new int[] { 2006, 1, 26, 10, 47, 34 }, "yyyy/MM/dd HH:mm:ss SSS"); } // https://issues.apache.org/jira/browse/LANG-281 public void testJiraLang281() { assertEqualDuration( "09", new int[] { 2005, 11, 31, 0, 0, 0 }, new int[] { 2006, 9, 6, 0, 0, 0 }, "MM"); } // Testing the under a day range in DurationFormatUtils.formatPeriod public void testLowDurations() { for(int hr=0; hr < 24; hr++) { for(int min=0; min < 60; min++) { for(int sec=0; sec < 60; sec++) { assertEqualDuration( hr + ":" + min + ":" + sec, new int[] { 2000, 0, 1, 0, 0, 0, 0 }, new int[] { 2000, 0, 1, hr, min, sec }, "H:m:s" ); } } } } // Attempting to test edge cases in DurationFormatUtils.formatPeriod public void testEdgeDurations() { assertEqualDuration( "01", new int[] { 2006, 0, 15, 0, 0, 0 }, new int[] { 2006, 2, 10, 0, 0, 0 }, "MM"); assertEqualDuration( "12", new int[] { 2005, 0, 15, 0, 0, 0 }, new int[] { 2006, 0, 15, 0, 0, 0 }, "MM"); assertEqualDuration( "12", new int[] { 2005, 0, 15, 0, 0, 0 }, new int[] { 2006, 0, 16, 0, 0, 0 }, "MM"); assertEqualDuration( "11", new int[] { 2005, 0, 15, 0, 0, 0 }, new int[] { 2006, 0, 14, 0, 0, 0 }, "MM"); assertEqualDuration( "01 26", new int[] { 2006, 0, 15, 0, 0, 0 }, new int[] { 2006, 2, 10, 0, 0, 0 }, "MM dd"); assertEqualDuration( "54", new int[] { 2006, 0, 15, 0, 0, 0 }, new int[] { 2006, 2, 10, 0, 0, 0 }, "dd"); assertEqualDuration( "09 12", new int[] { 2006, 1, 20, 0, 0, 0 }, new int[] { 2006, 11, 4, 0, 0, 0 }, "MM dd"); assertEqualDuration( "287", new int[] { 2006, 1, 20, 0, 0, 0 }, new int[] { 2006, 11, 4, 0, 0, 0 }, "dd"); assertEqualDuration( "11 30", new int[] { 2006, 0, 2, 0, 0, 0 }, new int[] { 2007, 0, 1, 0, 0, 0 }, "MM dd"); assertEqualDuration( "364", new int[] { 2006, 0, 2, 0, 0, 0 }, new int[] { 2007, 0, 1, 0, 0, 0 }, "dd"); assertEqualDuration( "12 00", new int[] { 2006, 0, 1, 0, 0, 0 }, new int[] { 2007, 0, 1, 0, 0, 0 }, "MM dd"); assertEqualDuration( "365", new int[] { 2006, 0, 1, 0, 0, 0 }, new int[] { 2007, 0, 1, 0, 0, 0 }, "dd"); assertEqualDuration( "31", new int[] { 2006, 0, 1, 0, 0, 0 }, new int[] { 2006, 1, 1, 0, 0, 0 }, "dd"); assertEqualDuration( "92", new int[] { 2005, 9, 1, 0, 0, 0 }, new int[] { 2006, 0, 1, 0, 0, 0 }, "dd"); assertEqualDuration( "77", new int[] { 2005, 9, 16, 0, 0, 0 }, new int[] { 2006, 0, 1, 0, 0, 0 }, "dd"); // test month larger in start than end assertEqualDuration( "136", new int[] { 2005, 9, 16, 0, 0, 0 }, new int[] { 2006, 2, 1, 0, 0, 0 }, "dd"); // test when start in leap year assertEqualDuration( "136", new int[] { 2004, 9, 16, 0, 0, 0 }, new int[] { 2005, 2, 1, 0, 0, 0 }, "dd"); // test when end in leap year assertEqualDuration( "137", new int[] { 2003, 9, 16, 0, 0, 0 }, new int[] { 2004, 2, 1, 0, 0, 0 }, "dd"); // test when end in leap year but less than end of feb assertEqualDuration( "135", new int[] { 2003, 9, 16, 0, 0, 0 }, new int[] { 2004, 1, 28, 0, 0, 0 }, "dd"); assertEqualDuration( "364", new int[] { 2007, 0, 2, 0, 0, 0 }, new int[] { 2008, 0, 1, 0, 0, 0 }, "dd"); assertEqualDuration( "729", new int[] { 2006, 0, 2, 0, 0, 0 }, new int[] { 2008, 0, 1, 0, 0, 0 }, "dd"); assertEqualDuration( "365", new int[] { 2007, 2, 2, 0, 0, 0 }, new int[] { 2008, 2, 1, 0, 0, 0 }, "dd"); assertEqualDuration( "333", new int[] { 2007, 1, 2, 0, 0, 0 }, new int[] { 2008, 0, 1, 0, 0, 0 }, "dd"); assertEqualDuration( "28", new int[] { 2008, 1, 2, 0, 0, 0 }, new int[] { 2008, 2, 1, 0, 0, 0 }, "dd"); assertEqualDuration( "393", new int[] { 2007, 1, 2, 0, 0, 0 }, new int[] { 2008, 2, 1, 0, 0, 0 }, "dd"); assertEqualDuration( "369", new int[] { 2004, 0, 29, 0, 0, 0 }, new int[] { 2005, 1, 1, 0, 0, 0 }, "dd"); assertEqualDuration( "338", new int[] { 2004, 1, 29, 0, 0, 0 }, new int[] { 2005, 1, 1, 0, 0, 0 }, "dd"); assertEqualDuration( "28", new int[] { 2004, 2, 8, 0, 0, 0 }, new int[] { 2004, 3, 5, 0, 0, 0 }, "dd"); assertEqualDuration( "48", new int[] { 1992, 1, 29, 0, 0, 0 }, new int[] { 1996, 1, 29, 0, 0, 0 }, "M"); // this seems odd - and will fail if I throw it in as a brute force // below as it expects the answer to be 12. It's a tricky edge case assertEqualDuration( "11", new int[] { 1996, 1, 29, 0, 0, 0 }, new int[] { 1997, 1, 28, 0, 0, 0 }, "M"); // again - this seems odd assertEqualDuration( "11 28", new int[] { 1996, 1, 29, 0, 0, 0 }, new int[] { 1997, 1, 28, 0, 0, 0 }, "M d"); } public void testDurationsByBruteForce() { bruteForce(2006, 0, 1, "d", Calendar.DAY_OF_MONTH); bruteForce(2006, 0, 2, "d", Calendar.DAY_OF_MONTH); bruteForce(2007, 1, 2, "d", Calendar.DAY_OF_MONTH); bruteForce(2004, 1, 29, "d", Calendar.DAY_OF_MONTH); bruteForce(1996, 1, 29, "d", Calendar.DAY_OF_MONTH); bruteForce(1969, 1, 28, "M", Calendar.MONTH); // tests for 48 years //bruteForce(1996, 1, 29, "M", Calendar.MONTH); // this will fail } private int FOUR_YEARS = 365 * 3 + 366; // Takes a minute to run, so generally turned off // public void testBrutally() { // Calendar c = Calendar.getInstance(); // c.set(2004, 0, 1, 0, 0, 0); // for (int i=0; i < FOUR_YEARS; i++) { // bruteForce(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH), "d", Calendar.DAY_OF_MONTH ); // c.add(Calendar.DAY_OF_MONTH, 1); // } // } private void bruteForce(int year, int month, int day, String format, int calendarType) { String msg = year + "-" + month + "-" + day + " to "; Calendar c = Calendar.getInstance(); c.set(year, month, day, 0, 0, 0); int[] array1 = new int[] { year, month, day, 0, 0, 0 }; int[] array2 = new int[] { year, month, day, 0, 0, 0 }; for (int i=0; i < FOUR_YEARS; i++) { array2[0] = c.get(Calendar.YEAR); array2[1] = c.get(Calendar.MONTH); array2[2] = c.get(Calendar.DAY_OF_MONTH); String tmpMsg = msg + array2[0] + "-" + array2[1] + "-" + array2[2] + " at "; assertEqualDuration( tmpMsg + i, Integer.toString(i), array1, array2, format ); c.add(calendarType, 1); } } private void assertEqualDuration(String expected, int[] start, int[] end, String format) { assertEqualDuration(null, expected, start, end, format); } private void assertEqualDuration(String message, String expected, int[] start, int[] end, String format) { Calendar cal1 = Calendar.getInstance(); cal1.set(start[0], start[1], start[2], start[3], start[4], start[5]); cal1.set(Calendar.MILLISECOND, 0); Calendar cal2 = Calendar.getInstance(); cal2.set(end[0], end[1], end[2], end[3], end[4], end[5]); cal2.set(Calendar.MILLISECOND, 0); long milli1 = cal1.getTime().getTime(); long milli2 = cal2.getTime().getTime(); String result = DurationFormatUtils.formatPeriod(milli1, milli2, format); if (message == null) { assertEquals(expected, result); } else { assertEquals(message, expected, result); } } private void assertArrayEquals(DurationFormatUtils.Token[] obj1, DurationFormatUtils.Token[] obj2) { assertEquals("Arrays are unequal length. ", obj1.length, obj2.length); for (int i = 0; i < obj1.length; i++) { assertTrue("Index " + i + " not equal, " + obj1[i] + " vs " + obj2[i], obj1[i].equals(obj2[i])); } } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/time/FastDateFormatTest.java100644 0 0 35176 11513702435 26324 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.time; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Locale; import java.util.TimeZone; import junit.framework.TestCase; import org.apache.commons.lang.SerializationUtils; /** * Unit tests {@link org.apache.commons.lang.time.FastDateFormat}. * * @author Sean Schofield * @author Gary Gregory * @author Fredrik Westermarck * @since 2.0 * @version $Id: FastDateFormatTest.java 1056869 2011-01-09 02:41:34Z niallp $ */ public class FastDateFormatTest extends TestCase { public FastDateFormatTest(String name) { super(name); } public void test_getInstance() { FastDateFormat format1 = FastDateFormat.getInstance(); FastDateFormat format2 = FastDateFormat.getInstance(); assertSame(format1, format2); assertEquals(new SimpleDateFormat().toPattern(), format1.getPattern()); } public void test_getInstance_String() { FastDateFormat format1 = FastDateFormat.getInstance("MM/DD/yyyy"); FastDateFormat format2 = FastDateFormat.getInstance("MM-DD-yyyy"); FastDateFormat format3 = FastDateFormat.getInstance("MM-DD-yyyy"); assertTrue(format1 != format2); // -- junit 3.8 version -- assertFalse(format1 == format2); assertSame(format2, format3); assertEquals("MM/DD/yyyy", format1.getPattern()); assertEquals(TimeZone.getDefault(), format1.getTimeZone()); assertEquals(TimeZone.getDefault(), format2.getTimeZone()); assertEquals(false, format1.getTimeZoneOverridesCalendar()); assertEquals(false, format2.getTimeZoneOverridesCalendar()); } public void test_getInstance_String_TimeZone() { Locale realDefaultLocale = Locale.getDefault(); TimeZone realDefaultZone = TimeZone.getDefault(); try { Locale.setDefault(Locale.US); TimeZone.setDefault(TimeZone.getTimeZone("America/New_York")); FastDateFormat format1 = FastDateFormat.getInstance("MM/DD/yyyy", TimeZone.getTimeZone("Atlantic/Reykjavik")); FastDateFormat format2 = FastDateFormat.getInstance("MM/DD/yyyy"); FastDateFormat format3 = FastDateFormat.getInstance("MM/DD/yyyy", TimeZone.getDefault()); FastDateFormat format4 = FastDateFormat.getInstance("MM/DD/yyyy", TimeZone.getDefault()); FastDateFormat format5 = FastDateFormat.getInstance("MM-DD-yyyy", TimeZone.getDefault()); FastDateFormat format6 = FastDateFormat.getInstance("MM-DD-yyyy"); assertTrue(format1 != format2); // -- junit 3.8 version -- assertFalse(format1 == format2); assertEquals(TimeZone.getTimeZone("Atlantic/Reykjavik"), format1.getTimeZone()); assertEquals(true, format1.getTimeZoneOverridesCalendar()); assertEquals(TimeZone.getDefault(), format2.getTimeZone()); assertEquals(false, format2.getTimeZoneOverridesCalendar()); assertSame(format3, format4); assertTrue(format3 != format5); // -- junit 3.8 version -- assertFalse(format3 == format5); assertTrue(format4 != format6); // -- junit 3.8 version -- assertFalse(format3 == format5); } finally { Locale.setDefault(realDefaultLocale); TimeZone.setDefault(realDefaultZone); } } public void test_getInstance_String_Locale() { Locale realDefaultLocale = Locale.getDefault(); try { Locale.setDefault(Locale.US); FastDateFormat format1 = FastDateFormat.getInstance("MM/DD/yyyy", Locale.GERMANY); FastDateFormat format2 = FastDateFormat.getInstance("MM/DD/yyyy"); FastDateFormat format3 = FastDateFormat.getInstance("MM/DD/yyyy", Locale.GERMANY); assertTrue(format1 != format2); // -- junit 3.8 version -- assertFalse(format1 == format2); assertSame(format1, format3); assertSame(Locale.GERMANY, format1.getLocale()); } finally { Locale.setDefault(realDefaultLocale); } } public void test_changeDefault_Locale_DateInstance() { Locale realDefaultLocale = Locale.getDefault(); try { Locale.setDefault(Locale.US); FastDateFormat format1 = FastDateFormat.getDateInstance(FastDateFormat.FULL, Locale.GERMANY); FastDateFormat format2 = FastDateFormat.getDateInstance(FastDateFormat.FULL); Locale.setDefault(Locale.GERMANY); FastDateFormat format3 = FastDateFormat.getDateInstance(FastDateFormat.FULL); assertSame(Locale.GERMANY, format1.getLocale()); assertSame(Locale.US, format2.getLocale()); assertSame(Locale.GERMANY, format3.getLocale()); assertTrue(format1 != format2); // -- junit 3.8 version -- assertFalse(format1 == format2); assertTrue(format2 != format3); } finally { Locale.setDefault(realDefaultLocale); } } public void test_changeDefault_Locale_DateTimeInstance() { Locale realDefaultLocale = Locale.getDefault(); try { Locale.setDefault(Locale.US); FastDateFormat format1 = FastDateFormat.getDateTimeInstance(FastDateFormat.FULL, FastDateFormat.FULL, Locale.GERMANY); FastDateFormat format2 = FastDateFormat.getDateTimeInstance(FastDateFormat.FULL, FastDateFormat.FULL); Locale.setDefault(Locale.GERMANY); FastDateFormat format3 = FastDateFormat.getDateTimeInstance(FastDateFormat.FULL, FastDateFormat.FULL); assertSame(Locale.GERMANY, format1.getLocale()); assertSame(Locale.US, format2.getLocale()); assertSame(Locale.GERMANY, format3.getLocale()); assertTrue(format1 != format2); // -- junit 3.8 version -- assertFalse(format1 == format2); assertTrue(format2 != format3); } finally { Locale.setDefault(realDefaultLocale); } } public void test_getInstance_String_TimeZone_Locale() { Locale realDefaultLocale = Locale.getDefault(); TimeZone realDefaultZone = TimeZone.getDefault(); try { Locale.setDefault(Locale.US); TimeZone.setDefault(TimeZone.getTimeZone("America/New_York")); FastDateFormat format1 = FastDateFormat.getInstance("MM/DD/yyyy", TimeZone.getTimeZone("Atlantic/Reykjavik"), Locale.GERMANY); FastDateFormat format2 = FastDateFormat.getInstance("MM/DD/yyyy", Locale.GERMANY); FastDateFormat format3 = FastDateFormat.getInstance("MM/DD/yyyy", TimeZone.getDefault(), Locale.GERMANY); assertTrue(format1 != format2); // -- junit 3.8 version -- assertNotSame(format1, format2); assertEquals(TimeZone.getTimeZone("Atlantic/Reykjavik"), format1.getTimeZone()); assertEquals(TimeZone.getDefault(), format2.getTimeZone()); assertEquals(TimeZone.getDefault(), format3.getTimeZone()); assertEquals(true, format1.getTimeZoneOverridesCalendar()); assertEquals(false, format2.getTimeZoneOverridesCalendar()); assertEquals(true, format3.getTimeZoneOverridesCalendar()); assertEquals(Locale.GERMANY, format1.getLocale()); assertEquals(Locale.GERMANY, format2.getLocale()); assertEquals(Locale.GERMANY, format3.getLocale()); } finally { Locale.setDefault(realDefaultLocale); TimeZone.setDefault(realDefaultZone); } } public void testFormat() { Locale realDefaultLocale = Locale.getDefault(); TimeZone realDefaultZone = TimeZone.getDefault(); try { Locale.setDefault(Locale.US); TimeZone.setDefault(TimeZone.getTimeZone("America/New_York")); FastDateFormat fdf = null; SimpleDateFormat sdf = null; GregorianCalendar cal1 = new GregorianCalendar(2003, 0, 10, 15, 33, 20); GregorianCalendar cal2 = new GregorianCalendar(2003, 6, 10, 9, 00, 00); Date date1 = cal1.getTime(); Date date2 = cal2.getTime(); long millis1 = date1.getTime(); long millis2 = date2.getTime(); fdf = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ss"); sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); assertEquals(sdf.format(date1), fdf.format(date1)); assertEquals("2003-01-10T15:33:20", fdf.format(date1)); assertEquals("2003-01-10T15:33:20", fdf.format(cal1)); assertEquals("2003-01-10T15:33:20", fdf.format(millis1)); assertEquals("2003-07-10T09:00:00", fdf.format(date2)); assertEquals("2003-07-10T09:00:00", fdf.format(cal2)); assertEquals("2003-07-10T09:00:00", fdf.format(millis2)); fdf = FastDateFormat.getInstance("Z"); assertEquals("-0500", fdf.format(date1)); assertEquals("-0500", fdf.format(cal1)); assertEquals("-0500", fdf.format(millis1)); fdf = FastDateFormat.getInstance("Z"); assertEquals("-0400", fdf.format(date2)); assertEquals("-0400", fdf.format(cal2)); assertEquals("-0400", fdf.format(millis2)); fdf = FastDateFormat.getInstance("ZZ"); assertEquals("-05:00", fdf.format(date1)); assertEquals("-05:00", fdf.format(cal1)); assertEquals("-05:00", fdf.format(millis1)); fdf = FastDateFormat.getInstance("ZZ"); assertEquals("-04:00", fdf.format(date2)); assertEquals("-04:00", fdf.format(cal2)); assertEquals("-04:00", fdf.format(millis2)); String pattern = "GGGG GGG GG G yyyy yyy yy y MMMM MMM MM M" + " dddd ddd dd d DDDD DDD DD D EEEE EEE EE E aaaa aaa aa a zzzz zzz zz z"; fdf = FastDateFormat.getInstance(pattern); sdf = new SimpleDateFormat(pattern); assertEquals(sdf.format(date1), fdf.format(date1)); assertEquals(sdf.format(date2), fdf.format(date2)); } finally { Locale.setDefault(realDefaultLocale); TimeZone.setDefault(realDefaultZone); } } /** * Test case for {@link FastDateFormat#getDateInstance(int, java.util.Locale)}. */ public void testShortDateStyleWithLocales() { Locale usLocale = Locale.US; Locale swedishLocale = new Locale("sv", "SE"); Calendar cal = Calendar.getInstance(); cal.set(2004, 1, 3); FastDateFormat fdf = FastDateFormat.getDateInstance(FastDateFormat.SHORT, usLocale); assertEquals("2/3/04", fdf.format(cal)); fdf = FastDateFormat.getDateInstance(FastDateFormat.SHORT, swedishLocale); assertEquals("2004-02-03", fdf.format(cal)); } /** * Tests that pre-1000AD years get padded with yyyy */ public void testLowYearPadding() { Calendar cal = Calendar.getInstance(); FastDateFormat format = FastDateFormat.getInstance("yyyy/MM/DD"); cal.set(1,0,1); assertEquals("0001/01/01", format.format(cal)); cal.set(10,0,1); assertEquals("0010/01/01", format.format(cal)); cal.set(100,0,1); assertEquals("0100/01/01", format.format(cal)); cal.set(999,0,1); assertEquals("0999/01/01", format.format(cal)); } /** * Show Bug #39410 is solved */ public void testMilleniumBug() { Calendar cal = Calendar.getInstance(); FastDateFormat format = FastDateFormat.getInstance("dd.MM.yyyy"); cal.set(1000,0,1); assertEquals("01.01.1000", format.format(cal)); } /** * testLowYearPadding showed that the date was buggy * This test confirms it, getting 366 back as a date */ // TODO: Fix this problem public void testSimpleDate() { Calendar cal = Calendar.getInstance(); FastDateFormat format = FastDateFormat.getInstance("yyyy/MM/dd"); cal.set(2004,11,31); assertEquals("2004/12/31", format.format(cal)); cal.set(999,11,31); assertEquals("0999/12/31", format.format(cal)); cal.set(1,2,2); assertEquals("0001/03/02", format.format(cal)); } public void testLang303() { Calendar cal = Calendar.getInstance(); cal.set(2004,11,31); FastDateFormat format = FastDateFormat.getInstance("yyyy/MM/dd"); String output = format.format(cal); format = (FastDateFormat) SerializationUtils.deserialize( SerializationUtils.serialize( format ) ); assertEquals(output, format.format(cal)); } public void testLang538() { final String dateTime = "2009-10-16T16:42:16.000Z"; // more commonly constructed with: cal = new GregorianCalendar(2009, 9, 16, 8, 42, 16) // for the unit test to work in any time zone, constructing with GMT-8 rather than default locale time zone GregorianCalendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT-8")); cal.clear(); cal.set(2009, 9, 16, 8, 42, 16); FastDateFormat format = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", TimeZone.getTimeZone("GMT")); assertEquals("dateTime", dateTime, format.format(cal)); } public void testLang645() { Locale locale = new Locale("sv", "SE"); Calendar cal = Calendar.getInstance(); cal.set(2010, 0, 1, 12, 0, 0); Date d = cal.getTime(); FastDateFormat fdf = FastDateFormat.getInstance("EEEE', week 'ww", locale); assertEquals("fredag, week 53", fdf.format(d)); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/time/StopWatchTest.java100644 0 0 16573 11513702435 25374 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang.time; import junit.framework.Assert; import junit.framework.TestCase; /** * TestCase for StopWatch. * * @author Apache Software Foundation * @version $Id: StopWatchTest.java 905636 2010-02-02 14:03:32Z niallp $ */ public class StopWatchTest extends TestCase { public StopWatchTest(String s) { super(s); } //----------------------------------------------------------------------- public void testStopWatchSimple(){ StopWatch watch = new StopWatch(); watch.start(); try {Thread.sleep(550);} catch (InterruptedException ex) {} watch.stop(); long time = watch.getTime(); assertEquals(time, watch.getTime()); assertTrue(time >= 500); assertTrue(time < 700); watch.reset(); assertEquals(0, watch.getTime()); } public void testStopWatchSimpleGet(){ StopWatch watch = new StopWatch(); assertEquals(0, watch.getTime()); assertEquals("0:00:00.000", watch.toString()); watch.start(); try {Thread.sleep(500);} catch (InterruptedException ex) {} assertTrue(watch.getTime() < 2000); } public void testStopWatchSplit(){ StopWatch watch = new StopWatch(); watch.start(); try {Thread.sleep(550);} catch (InterruptedException ex) {} watch.split(); long splitTime = watch.getSplitTime(); String splitStr = watch.toSplitString(); try {Thread.sleep(550);} catch (InterruptedException ex) {} watch.unsplit(); try {Thread.sleep(550);} catch (InterruptedException ex) {} watch.stop(); long totalTime = watch.getTime(); assertEquals("Formatted split string not the correct length", splitStr.length(), 11); assertTrue(splitTime >= 500); assertTrue(splitTime < 700); assertTrue(totalTime >= 1500); assertTrue(totalTime < 1900); } public void testStopWatchSuspend(){ StopWatch watch = new StopWatch(); watch.start(); try {Thread.sleep(550);} catch (InterruptedException ex) {} watch.suspend(); long suspendTime = watch.getTime(); try {Thread.sleep(550);} catch (InterruptedException ex) {} watch.resume(); try {Thread.sleep(550);} catch (InterruptedException ex) {} watch.stop(); long totalTime = watch.getTime(); assertTrue(suspendTime >= 500); assertTrue(suspendTime < 700); assertTrue(totalTime >= 1000); assertTrue(totalTime < 1300); } public void testLang315() { StopWatch watch = new StopWatch(); watch.start(); try {Thread.sleep(200);} catch (InterruptedException ex) {} watch.suspend(); long suspendTime = watch.getTime(); try {Thread.sleep(200);} catch (InterruptedException ex) {} watch.stop(); long totalTime = watch.getTime(); assertTrue( suspendTime == totalTime ); } // test bad states public void testBadStates() { StopWatch watch = new StopWatch(); try { watch.stop(); fail("Calling stop on an unstarted StopWatch should throw an exception. "); } catch(IllegalStateException ise) { // expected } try { watch.stop(); fail("Calling stop on an unstarted StopWatch should throw an exception. "); } catch(IllegalStateException ise) { // expected } try { watch.suspend(); fail("Calling suspend on an unstarted StopWatch should throw an exception. "); } catch(IllegalStateException ise) { // expected } try { watch.split(); fail("Calling split on a non-running StopWatch should throw an exception. "); } catch(IllegalStateException ise) { // expected } try { watch.unsplit(); fail("Calling unsplit on an unsplit StopWatch should throw an exception. "); } catch(IllegalStateException ise) { // expected } try { watch.resume(); fail("Calling resume on an unsuspended StopWatch should throw an exception. "); } catch(IllegalStateException ise) { // expected } watch.start(); try { watch.start(); fail("Calling start on a started StopWatch should throw an exception. "); } catch(IllegalStateException ise) { // expected } try { watch.unsplit(); fail("Calling unsplit on an unsplit StopWatch should throw an exception. "); } catch(IllegalStateException ise) { // expected } try { watch.getSplitTime(); fail("Calling getSplitTime on an unsplit StopWatch should throw an exception. "); } catch(IllegalStateException ise) { // expected } try { watch.resume(); fail("Calling resume on an unsuspended StopWatch should throw an exception. "); } catch(IllegalStateException ise) { // expected } watch.stop(); try { watch.start(); fail("Calling start on a stopped StopWatch should throw an exception as it needs to be reset. "); } catch(IllegalStateException ise) { // expected } } public void testGetStartTime() { long beforeStopWatch = System.currentTimeMillis(); StopWatch watch = new StopWatch(); try { watch.getStartTime(); fail("Calling getStartTime on an unstarted StopWatch should throw an exception"); } catch (IllegalStateException expected) { // expected } watch.start(); try { watch.getStartTime(); Assert.assertTrue(watch.getStartTime() >= beforeStopWatch); } catch (IllegalStateException ex) { fail("Start time should be available: " + ex.getMessage()); } watch.reset(); try { watch.getStartTime(); fail("Calling getStartTime on a reset, but unstarted StopWatch should throw an exception"); } catch (IllegalStateException expected) { // expected } } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/UnhandledExceptionTest.java100644 0 0 4055 11513702441 26250 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang; import junit.framework.TestCase; import org.apache.commons.lang.exception.Nestable; /** * JUnit tests. * * @author Matthew Hawthorne * @version $Id: UnhandledExceptionTest.java 905628 2010-02-02 13:29:55Z niallp $ * @see UnhandledException */ public class UnhandledExceptionTest extends TestCase { public UnhandledExceptionTest(String testName) { super(testName); } // testConstructor public void testConstructor_throwable_nullInput() { final Throwable t = null; new UnhandledException(t); } public void testConstructor_stringAndThrowable_nullInput() { new UnhandledException(null, null); } // testGetCause public void testGetCause() { final Throwable t = new NullPointerException(); final Nestable n = new UnhandledException(t); assertEquals(t, n.getCause()); } public void testGetCauseAndGetMessage() { final Throwable t = new NullPointerException(); final String msg = "nullArg"; final Nestable n = new UnhandledException(msg, t); assertEquals(t, n.getCause()); assertEquals(msg, n.getMessage()); } } // UnhandledExceptionTest commons-lang-2.6-src/src/test/java/org/apache/commons/lang/ValidateTest.java100644 0 0 35336 11513702441 24246 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "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 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.commons.lang; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import junit.framework.TestCase; /** * Unit tests {@link org.apache.commons.lang.Validate}. * * @author Apache Software Foundation * @author Norm Deane * @version $Id: ValidateTest.java 905636 2010-02-02 14:03:32Z niallp $ */ public class ValidateTest extends TestCase { public ValidateTest(String name) { super(name); } //----------------------------------------------------------------------- public void testIsTrue1() { Validate.isTrue(true); try { Validate.isTrue(false); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { assertEquals("The validated expression is false", ex.getMessage()); } } //----------------------------------------------------------------------- public void testIsTrue2() { Validate.isTrue(true, "MSG"); try { Validate.isTrue(false, "MSG"); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { assertEquals("MSG", ex.getMessage()); } } //----------------------------------------------------------------------- public void testIsTrue3() { Validate.isTrue(true, "MSG", new Integer(6)); try { Validate.isTrue(false, "MSG", new Integer(6)); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { assertEquals("MSG6", ex.getMessage()); } } //----------------------------------------------------------------------- public void testIsTrue4() { Validate.isTrue(true, "MSG", 7); try { Validate.isTrue(false, "MSG", 7); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { assertEquals("MSG7", ex.getMessage()); } } //----------------------------------------------------------------------- public void testIsTrue5() { Validate.isTrue(true, "MSG", 7.4d); try { Validate.isTrue(false, "MSG", 7.4d); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { assertEquals("MSG7.4", ex.getMessage()); } } //----------------------------------------------------------------------- public void testNotNull1() { Validate.notNull(new Object()); try { Validate.notNull(null); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { assertEquals("The validated object is null", ex.getMessage()); } } //----------------------------------------------------------------------- public void testNotNull2() { Validate.notNull(new Object(), "MSG"); try { Validate.notNull(null, "MSG"); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { assertEquals("MSG", ex.getMessage()); } } //----------------------------------------------------------------------- public void testNotEmptyArray1() { Validate.notEmpty(new Object[] {null}); try { Validate.notEmpty((Object[]) null); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { assertEquals("The validated array is empty", ex.getMessage()); } try { Validate.notEmpty(new Object[0]); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { assertEquals("The validated array is empty", ex.getMessage()); } } //----------------------------------------------------------------------- public void testNotEmptyArray2() { Validate.notEmpty(new Object[] {null}, "MSG"); try { Validate.notEmpty((Object[]) null, "MSG"); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { assertEquals("MSG", ex.getMessage()); } try { Validate.notEmpty(new Object[0], "MSG"); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { assertEquals("MSG", ex.getMessage()); } } //----------------------------------------------------------------------- public void testNotEmptyCollection1() { Collection coll = new ArrayList(); try { Validate.notEmpty((Collection) null); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { assertEquals("The validated collection is empty", ex.getMessage()); } try { Validate.notEmpty(coll); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { assertEquals("The validated collection is empty", ex.getMessage()); } coll.add(new Integer(8)); Validate.notEmpty(coll); } //----------------------------------------------------------------------- public void testNotEmptyCollection2() { Collection coll = new ArrayList(); try { Validate.notEmpty((Collection) null, "MSG"); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { assertEquals("MSG", ex.getMessage()); } try { Validate.notEmpty(coll, "MSG"); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { assertEquals("MSG", ex.getMessage()); } coll.add(new Integer(8)); Validate.notEmpty(coll, "MSG"); } //----------------------------------------------------------------------- public void testNotEmptyMap1() { Map map = new HashMap(); try { Validate.notEmpty((Map) null); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { assertEquals("The validated map is empty", ex.getMessage()); } try { Validate.notEmpty(map); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { assertEquals("The validated map is empty", ex.getMessage()); } map.put("ll", new Integer(8)); Validate.notEmpty(map); } //----------------------------------------------------------------------- public void testNotEmptyMap2() { Map map = new HashMap(); try { Validate.notEmpty((Map) null, "MSG"); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { assertEquals("MSG", ex.getMessage()); } try { Validate.notEmpty(map, "MSG"); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { assertEquals("MSG", ex.getMessage()); } map.put("ll", new Integer(8)); Validate.notEmpty(map, "MSG"); } //----------------------------------------------------------------------- public void testNotEmptyString1() { Validate.notEmpty("hjl"); try { Validate.notEmpty((String) null); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { assertEquals("The validated string is empty", ex.getMessage()); } try { Validate.notEmpty(""); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { assertEquals("The validated string is empty", ex.getMessage()); } } //----------------------------------------------------------------------- public void testNotEmptyString2() { Validate.notEmpty("a", "MSG"); try { Validate.notEmpty((String) null, "MSG"); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { assertEquals("MSG", ex.getMessage()); } try { Validate.notEmpty("", "MSG"); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { assertEquals("MSG", ex.getMessage()); } } //----------------------------------------------------------------------- public void testNoNullElementsArray1() { String[] array = new String[] {"a", "b"}; Validate.noNullElements(array); try { Validate.noNullElements((Object[]) null); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { assertEquals("The validated object is null", ex.getMessage()); } array[1] = null; try { Validate.noNullElements(array); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { assertEquals("The validated array contains null element at index: 1", ex.getMessage()); } } //----------------------------------------------------------------------- public void testNoNullElementsArray2() { String[] array = new String[] {"a", "b"}; Validate.noNullElements(array, "MSG"); try { Validate.noNullElements((Object[]) null, "MSG"); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { assertEquals("The validated object is null", ex.getMessage()); } array[1] = null; try { Validate.noNullElements(array, "MSG"); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { assertEquals("MSG", ex.getMessage()); } } //----------------------------------------------------------------------- public void testNoNullElementsCollection1() { List coll = new ArrayList(); coll.add("a"); coll.add("b"); Validate.noNullElements(coll); try { Validate.noNullElements((Collection) null); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { assertEquals("The validated object is null", ex.getMessage()); } coll.set(1, null); try { Validate.noNullElements(coll); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { assertEquals("The validated collection contains null element at index: 1", ex.getMessage()); } } //----------------------------------------------------------------------- public void testNoNullElementsCollection2() { List coll = new ArrayList(); coll.add("a"); coll.add("b"); Validate.noNullElements(coll, "MSG"); try { Validate.noNullElements((Collection) null, "MSG"); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { assertEquals("The validated object is null", ex.getMessage()); } coll.set(1, null); try { Validate.noNullElements(coll, "MSG"); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { assertEquals("MSG", ex.getMessage()); } } //----------------------------------------------------------------------- public void testAllElementsOfType() { List coll = new ArrayList(); coll.add("a"); coll.add("b"); Validate.allElementsOfType(coll, String.class, "MSG"); Validate.allElementsOfType(coll, String.class); try { Validate.allElementsOfType(coll, Integer.class, "MSG"); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { assertEquals("MSG", ex.getMessage()); } coll.set(1, Boolean.FALSE); try { Validate.allElementsOfType(coll, String.class); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { assertEquals("The validated collection contains an element not of type java.lang.String at index: 1", ex.getMessage()); } coll = new ArrayList(); coll.add(new Integer(5)); coll.add(new Double(2.0d)); Validate.allElementsOfType(coll, Number.class, "MSG"); try { Validate.allElementsOfType(coll, Integer.class, "MSG"); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { assertEquals("MSG", ex.getMessage()); } try { Validate.allElementsOfType(coll, Double.class, "MSG"); fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { assertEquals("MSG", ex.getMessage()); } } public void testConstructor() { assertNotNull(new Validate()); Constructor[] cons = Validate.class.getDeclaredConstructors(); assertEquals(1, cons.length); assertEquals(true, Modifier.isPublic(cons[0].getModifiers())); assertEquals(true, Modifier.isPublic(Validate.class.getModifiers())); assertEquals(false, Modifier.isFinal(Validate.class.getModifiers())); } } commons-lang-2.6-src/src/test/java/org/apache/commons/lang/WordUtilsTest.java100644 0 0 52553 11513702441 24451 0ustar 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import junit.framework.TestCase; /** * Unit tests for WordUtils class. * * @author Apache Software Foundation * @author Ringo De Smet * @version $Id: WordUtilsTest.java 905636 2010-02-02 14:03:32Z niallp $ */ public class WordUtilsTest extends TestCase { public WordUtilsTest(String name) { super(name); } //----------------------------------------------------------------------- public void testConstructor() { assertNotNull(new WordUtils()); Constructor[] cons = WordUtils.class.getDeclaredConstructors(); assertEquals(1, cons.length); assertEquals(true, Modifier.isPublic(cons[0].getModifiers())); assertEquals(true, Modifier.isPublic(WordUtils.class.getModifiers())); assertEquals(false, Modifier.isFinal(WordUtils.class.getModifiers())); } //----------------------------------------------------------------------- public void testWrap_StringInt() { assertEquals(null, WordUtils.wrap(null, 20)); assertEquals(null, WordUtils.wrap(null, -1)); assertEquals("", WordUtils.wrap("", 20)); assertEquals("", WordUtils.wrap("", -1)); // normal String systemNewLine = System.getProperty("line.separator"); String input = "Here is one line of text that is going to be wrapped after 20 columns."; String expected = "Here is one line of" + systemNewLine + "text that is going" + systemNewLine + "to be wrapped after" + systemNewLine + "20 columns."; assertEquals(expected, WordUtils.wrap(input, 20)); // long word at end input = "Click here to jump to the jakarta website - http://jakarta.apache.org"; expected = "Click here to jump" + systemNewLine + "to the jakarta" + systemNewLine + "website -" + systemNewLine + "http://jakarta.apache.org"; assertEquals(expected, WordUtils.wrap(input, 20)); // long word in middle input = "Click here, http://jakarta.apache.org, to jump to the jakarta website"; expected = "Click here," + systemNewLine + "http://jakarta.apache.org," + systemNewLine + "to jump to the" + systemNewLine + "jakarta website"; assertEquals(expected, WordUtils.wrap(input, 20)); } public void testWrap_StringIntStringBoolean() { assertEquals(null, WordUtils.wrap(null, 20, "\n", false)); assertEquals(null, WordUtils.wrap(null, 20, "\n", true)); assertEquals(null, WordUtils.wrap(null, 20, null, true)); assertEquals(null, WordUtils.wrap(null, 20, null, false)); assertEquals(null, WordUtils.wrap(null, -1, null, true)); assertEquals(null, WordUtils.wrap(null, -1, null, false)); assertEquals("", WordUtils.wrap("", 20, "\n", false)); assertEquals("", WordUtils.wrap("", 20, "\n", true)); assertEquals("", WordUtils.wrap("", 20, null, false)); assertEquals("", WordUtils.wrap("", 20, null, true)); assertEquals("", WordUtils.wrap("", -1, null, false)); assertEquals("", WordUtils.wrap("", -1, null, true)); // normal String input = "Here is one line of text that is going to be wrapped after 20 columns."; String expected = "Here is one line of\ntext that is going\nto be wrapped after\n20 columns."; assertEquals(expected, WordUtils.wrap(input, 20, "\n", false)); assertEquals(expected, WordUtils.wrap(input, 20, "\n", true)); // unusual newline char input = "Here is one line of text that is going to be wrapped after 20 columns."; expected = "Here is one line of
    text that is going
    to be wrapped after
    20 columns."; assertEquals(expected, WordUtils.wrap(input, 20, "
    ", false)); assertEquals(expected, WordUtils.wrap(input, 20, "
    ", true)); // short line length input = "Here is one line"; expected = "Here\nis one\nline"; assertEquals(expected, WordUtils.wrap(input, 6, "\n", false)); expected = "Here\nis\none\nline"; assertEquals(expected, WordUtils.wrap(input, 2, "\n", false)); assertEquals(expected, WordUtils.wrap(input, -1, "\n", false)); // system newline char String systemNewLine = System.getProperty("line.separator"); input = "Here is one line of text that is going to be wrapped after 20 columns."; expected = "Here is one line of" + systemNewLine + "text that is going" + systemNewLine + "to be wrapped after" + systemNewLine + "20 columns."; assertEquals(expected, WordUtils.wrap(input, 20, null, false)); assertEquals(expected, WordUtils.wrap(input, 20, null, true)); // with extra spaces input = " Here: is one line of text that is going to be wrapped after 20 columns."; expected = "Here: is one line\nof text that is \ngoing to be \nwrapped after 20 \ncolumns."; assertEquals(expected, WordUtils.wrap(input, 20, "\n", false)); assertEquals(expected, WordUtils.wrap(input, 20, "\n", true)); // with tab input = "Here is\tone line of text that is going to be wrapped after 20 columns."; expected = "Here is\tone line of\ntext that is going\nto be wrapped after\n20 columns."; assertEquals(expected, WordUtils.wrap(input, 20, "\n", false)); assertEquals(expected, WordUtils.wrap(input, 20, "\n", true)); // with tab at wrapColumn input = "Here is one line of\ttext that is going to be wrapped after 20 columns."; expected = "Here is one line\nof\ttext that is\ngoing to be wrapped\nafter 20 columns."; assertEquals(expected, WordUtils.wrap(input, 20, "\n", false)); assertEquals(expected, WordUtils.wrap(input, 20, "\n", true)); // difference because of long word input = "Click here to jump to the jakarta website - http://jakarta.apache.org"; expected = "Click here to jump\nto the jakarta\nwebsite -\nhttp://jakarta.apache.org"; assertEquals(expected, WordUtils.wrap(input, 20, "\n", false)); expected = "Click here to jump\nto the jakarta\nwebsite -\nhttp://jakarta.apach\ne.org"; assertEquals(expected, WordUtils.wrap(input, 20, "\n", true)); // difference because of long word in middle input = "Click here, http://jakarta.apache.org, to jump to the jakarta website"; expected = "Click here,\nhttp://jakarta.apache.org,\nto jump to the\njakarta website"; assertEquals(expected, WordUtils.wrap(input, 20, "\n", false)); expected = "Click here,\nhttp://jakarta.apach\ne.org, to jump to\nthe jakarta website"; assertEquals(expected, WordUtils.wrap(input, 20, "\n", true)); // System.err.println(expected); // System.err.println(WordUtils.wrap(input, 20, "\n", false)); } //----------------------------------------------------------------------- public void testCapitalize_String() { assertEquals(null, WordUtils.capitalize(null)); assertEquals("", WordUtils.capitalize("")); assertEquals(" ", WordUtils.capitalize(" ")); assertEquals("I", WordUtils.capitalize("I") ); assertEquals("I", WordUtils.capitalize("i") ); assertEquals("I Am Here 123", WordUtils.capitalize("i am here 123") ); assertEquals("I Am Here 123", WordUtils.capitalize("I Am Here 123") ); assertEquals("I Am HERE 123", WordUtils.capitalize("i am HERE 123") ); assertEquals("I AM HERE 123", WordUtils.capitalize("I AM HERE 123") ); } public void testCapitalizeWithDelimiters_String() { assertEquals(null, WordUtils.capitalize(null, null)); assertEquals("", WordUtils.capitalize("", new char[0])); assertEquals(" ", WordUtils.capitalize(" ", new char[0])); char[] chars = new char[] { '-', '+', ' ', '@' }; assertEquals("I", WordUtils.capitalize("I", chars) ); assertEquals("I", WordUtils.capitalize("i", chars) ); assertEquals("I-Am Here+123", WordUtils.capitalize("i-am here+123", chars) ); assertEquals("I Am+Here-123", WordUtils.capitalize("I Am+Here-123", chars) ); assertEquals("I+Am-HERE 123", WordUtils.capitalize("i+am-HERE 123", chars) ); assertEquals("I-AM HERE+123", WordUtils.capitalize("I-AM HERE+123", chars) ); chars = new char[] {'.'}; assertEquals("I aM.Fine", WordUtils.capitalize("i aM.fine", chars) ); assertEquals("I Am.fine", WordUtils.capitalize("i am.fine", null) ); } public void testCapitalizeFully_String() { assertEquals(null, WordUtils.capitalizeFully(null)); assertEquals("", WordUtils.capitalizeFully("")); assertEquals(" ", WordUtils.capitalizeFully(" ")); assertEquals("I", WordUtils.capitalizeFully("I") ); assertEquals("I", WordUtils.capitalizeFully("i") ); assertEquals("I Am Here 123", WordUtils.capitalizeFully("i am here 123") ); assertEquals("I Am Here 123", WordUtils.capitalizeFully("I Am Here 123") ); assertEquals("I Am Here 123", WordUtils.capitalizeFully("i am HERE 123") ); assertEquals("I Am Here 123", WordUtils.capitalizeFully("I AM HERE 123") ); } public void testCapitalizeFullyWithDelimiters_String() { assertEquals(null, WordUtils.capitalizeFully(null, null)); assertEquals("", WordUtils.capitalizeFully("", new char[0])); assertEquals(" ", WordUtils.capitalizeFully(" ", new char[0])); char[] chars = new char[] { '-', '+', ' ', '@' }; assertEquals("I", WordUtils.capitalizeFully("I", chars) ); assertEquals("I", WordUtils.capitalizeFully("i", chars) ); assertEquals("I-Am Here+123", WordUtils.capitalizeFully("i-am here+123", chars) ); assertEquals("I Am+Here-123", WordUtils.capitalizeFully("I Am+Here-123", chars) ); assertEquals("I+Am-Here 123", WordUtils.capitalizeFully("i+am-HERE 123", chars) ); assertEquals("I-Am Here+123", WordUtils.capitalizeFully("I-AM HERE+123", chars) ); chars = new char[] {'.'}; assertEquals("I am.Fine", WordUtils.capitalizeFully("i aM.fine", chars) ); assertEquals("I Am.fine", WordUtils.capitalizeFully("i am.fine", null) ); } public void testUncapitalize_String() { assertEquals(null, WordUtils.uncapitalize(null)); assertEquals("", WordUtils.uncapitalize("")); assertEquals(" ", WordUtils.uncapitalize(" ")); assertEquals("i", WordUtils.uncapitalize("I") ); assertEquals("i", WordUtils.uncapitalize("i") ); assertEquals("i am here 123", WordUtils.uncapitalize("i am here 123") ); assertEquals("i am here 123", WordUtils.uncapitalize("I Am Here 123") ); assertEquals("i am hERE 123", WordUtils.uncapitalize("i am HERE 123") ); assertEquals("i aM hERE 123", WordUtils.uncapitalize("I AM HERE 123") ); } public void testUncapitalizeWithDelimiters_String() { assertEquals(null, WordUtils.uncapitalize(null, null)); assertEquals("", WordUtils.uncapitalize("", new char[0])); assertEquals(" ", WordUtils.uncapitalize(" ", new char[0])); char[] chars = new char[] { '-', '+', ' ', '@' }; assertEquals("i", WordUtils.uncapitalize("I", chars) ); assertEquals("i", WordUtils.uncapitalize("i", chars) ); assertEquals("i am-here+123", WordUtils.uncapitalize("i am-here+123", chars) ); assertEquals("i+am here-123", WordUtils.uncapitalize("I+Am Here-123", chars) ); assertEquals("i-am+hERE 123", WordUtils.uncapitalize("i-am+HERE 123", chars) ); assertEquals("i aM-hERE+123", WordUtils.uncapitalize("I AM-HERE+123", chars) ); chars = new char[] {'.'}; assertEquals("i AM.fINE", WordUtils.uncapitalize("I AM.FINE", chars) ); assertEquals("i aM.FINE", WordUtils.uncapitalize("I AM.FINE", null) ); } //----------------------------------------------------------------------- public void testInitials_String() { assertEquals(null, WordUtils.initials(null)); assertEquals("", WordUtils.initials("")); assertEquals("", WordUtils.initials(" ")); assertEquals("I", WordUtils.initials("I")); assertEquals("i", WordUtils.initials("i")); assertEquals("BJL", WordUtils.initials("Ben John Lee")); assertEquals("BJ", WordUtils.initials("Ben J.Lee")); assertEquals("BJ.L", WordUtils.initials(" Ben John . Lee")); assertEquals("iah1", WordUtils.initials("i am here 123")); } // ----------------------------------------------------------------------- public void testInitials_String_charArray() { char[] array = null; assertEquals(null, WordUtils.initials(null, array)); assertEquals("", WordUtils.initials("", array)); assertEquals("", WordUtils.initials(" ", array)); assertEquals("I", WordUtils.initials("I", array)); assertEquals("i", WordUtils.initials("i", array)); assertEquals("S", WordUtils.initials("SJC", array)); assertEquals("BJL", WordUtils.initials("Ben John Lee", array)); assertEquals("BJ", WordUtils.initials("Ben J.Lee", array)); assertEquals("BJ.L", WordUtils.initials(" Ben John . Lee", array)); assertEquals("KO", WordUtils.initials("Kay O'Murphy", array)); assertEquals("iah1", WordUtils.initials("i am here 123", array)); array = new char[0]; assertEquals(null, WordUtils.initials(null, array)); assertEquals("", WordUtils.initials("", array)); assertEquals("", WordUtils.initials(" ", array)); assertEquals("", WordUtils.initials("I", array)); assertEquals("", WordUtils.initials("i", array)); assertEquals("", WordUtils.initials("SJC", array)); assertEquals("", WordUtils.initials("Ben John Lee", array)); assertEquals("", WordUtils.initials("Ben J.Lee", array)); assertEquals("", WordUtils.initials(" Ben John . Lee", array)); assertEquals("", WordUtils.initials("Kay O'Murphy", array)); assertEquals("", WordUtils.initials("i am here 123", array)); array = " ".toCharArray(); assertEquals(null, WordUtils.initials(null, array)); assertEquals("", WordUtils.initials("", array)); assertEquals("", WordUtils.initials(" ", array)); assertEquals("I", WordUtils.initials("I", array)); assertEquals("i", WordUtils.initials("i", array)); assertEquals("S", WordUtils.initials("SJC", array)); assertEquals("BJL", WordUtils.initials("Ben John Lee", array)); assertEquals("BJ", WordUtils.initials("Ben J.Lee", array)); assertEquals("BJ.L", WordUtils.initials(" Ben John . Lee", array)); assertEquals("KO", WordUtils.initials("Kay O'Murphy", array)); assertEquals("iah1", WordUtils.initials("i am here 123", array)); array = " .".toCharArray(); assertEquals(null, WordUtils.initials(null, array)); assertEquals("", WordUtils.initials("", array)); assertEquals("", WordUtils.initials(" ", array)); assertEquals("I", WordUtils.initials("I", array)); assertEquals("i", WordUtils.initials("i", array)); assertEquals("S", WordUtils.initials("SJC", array)); assertEquals("BJL", WordUtils.initials("Ben John Lee", array)); assertEquals("BJL", WordUtils.initials("Ben J.Lee", array)); assertEquals("BJL", WordUtils.initials(" Ben John . Lee", array)); assertEquals("KO", WordUtils.initials("Kay O'Murphy", array)); assertEquals("iah1", WordUtils.initials("i am here 123", array)); array = " .'".toCharArray(); assertEquals(null, WordUtils.initials(null, array)); assertEquals("", WordUtils.initials("", array)); assertEquals("", WordUtils.initials(" ", array)); assertEquals("I", WordUtils.initials("I", array)); assertEquals("i", WordUtils.initials("i", array)); assertEquals("S", WordUtils.initials("SJC", array)); assertEquals("BJL", WordUtils.initials("Ben John Lee", array)); assertEquals("BJL", WordUtils.initials("Ben J.Lee", array)); assertEquals("BJL", WordUtils.initials(" Ben John . Lee", array)); assertEquals("KOM", WordUtils.initials("Kay O'Murphy", array)); assertEquals("iah1", WordUtils.initials("i am here 123", array)); array = "SIJo1".toCharArray(); assertEquals(null, WordUtils.initials(null, array)); assertEquals("", WordUtils.initials("", array)); assertEquals(" ", WordUtils.initials(" ", array)); assertEquals("", WordUtils.initials("I", array)); assertEquals("i", WordUtils.initials("i", array)); assertEquals("C", WordUtils.initials("SJC", array)); assertEquals("Bh", WordUtils.initials("Ben John Lee", array)); assertEquals("B.", WordUtils.initials("Ben J.Lee", array)); assertEquals(" h", WordUtils.initials(" Ben John . Lee", array)); assertEquals("K", WordUtils.initials("Kay O'Murphy", array)); assertEquals("i2", WordUtils.initials("i am here 123", array)); } // ----------------------------------------------------------------------- public void testSwapCase_String() { assertEquals(null, WordUtils.swapCase(null)); assertEquals("", WordUtils.swapCase("")); assertEquals(" ", WordUtils.swapCase(" ")); assertEquals("i", WordUtils.swapCase("I") ); assertEquals("I", WordUtils.swapCase("i") ); assertEquals("I AM HERE 123", WordUtils.swapCase("i am here 123") ); assertEquals("i aM hERE 123", WordUtils.swapCase("I Am Here 123") ); assertEquals("I AM here 123", WordUtils.swapCase("i am HERE 123") ); assertEquals("i am here 123", WordUtils.swapCase("I AM HERE 123") ); String test = "This String contains a TitleCase character: \u01C8"; String expect = "tHIS sTRING CONTAINS A tITLEcASE CHARACTER: \u01C9"; assertEquals(expect, WordUtils.swapCase(test)); } // ----------------------------------------------------------------------- public void testAbbreviate() { // check null and empty are returned respectively assertNull(WordUtils.abbreviate(null, 1,-1,"")); assertEquals(StringUtils.EMPTY, WordUtils.abbreviate("", 1,-1,"")); // test upper limit assertEquals("01234", WordUtils.abbreviate("0123456789", 0,5,"")); assertEquals("01234", WordUtils.abbreviate("0123456789", 5, 2,"")); assertEquals("012", WordUtils.abbreviate("012 3456789", 2, 5,"")); assertEquals("012 3", WordUtils.abbreviate("012 3456789", 5, 2,"")); assertEquals("0123456789", WordUtils.abbreviate("0123456789", 0,-1,"")); // test upper limit + append string assertEquals("01234-", WordUtils.abbreviate("0123456789", 0,5,"-")); assertEquals("01234-", WordUtils.abbreviate("0123456789", 5, 2,"-")); assertEquals("012", WordUtils.abbreviate("012 3456789", 2, 5, null)); assertEquals("012 3", WordUtils.abbreviate("012 3456789", 5, 2,"")); assertEquals("0123456789", WordUtils.abbreviate("0123456789", 0,-1,"")); // test lower value assertEquals("012", WordUtils.abbreviate("012 3456789", 0,5, null)); assertEquals("01234", WordUtils.abbreviate("01234 56789", 5, 10, null)); assertEquals("01 23 45 67", WordUtils.abbreviate("01 23 45 67 89", 9, -1, null)); assertEquals("01 23 45 6", WordUtils.abbreviate("01 23 45 67 89", 9, 10, null)); assertEquals("0123456789", WordUtils.abbreviate("0123456789", 15, 20, null)); // test lower value + append assertEquals("012", WordUtils.abbreviate("012 3456789", 0,5, null)); assertEquals("01234-", WordUtils.abbreviate("01234 56789", 5, 10, "-")); assertEquals("01 23 45 67abc", WordUtils.abbreviate("01 23 45 67 89", 9, -1, "abc")); assertEquals("01 23 45 6", WordUtils.abbreviate("01 23 45 67 89", 9, 10, "")); // others assertEquals("", WordUtils.abbreviate("0123456790", 0,0,"")); assertEquals("", WordUtils.abbreviate(" 0123456790", 0,-1,"")); } } apitalize("i am-here+123", chars) ); assertEquals("i+am here-123", WordUtils.uncapitalize("I+Am Here-123", chars) ); assertEquals("i-am+hERE 123", WordUtils.uncapitalize("i-am+HERE 123", chars) ); assertEquals("i aM-hERE+123", WordUtils.uncapitalize("I AM-HERE+123", chars) ); chars = new char[] {'.'}; assertEquals("i AM.fINE", WordUtils.uncapitalize("I AM.FINE", chars) ); assertEquals("i aM.FINE", WordUtils.uncapitalize("I AM.FINE", null) ); } //----------------------------------------------------------------------- public void testInitials_String() { assertEquals(null, WordUtils.initials(null)); assertEquals("", WordUtils.initials("")); assertEquals("", WordUtils.initials(" ")); assertEquals("I", WordUtils.initials("I")); assertEquals("i", WordUtils.initials("i")); assertEquals("BJL", WordUtils.initials("Ben John Lee")); assertEquals("BJ", WordUtils.initials("Ben J.Lee")); assertEquals("BJ.L", WordUtils.initials(" Ben John . Lee")); assertEquals("iah1", WordUtils.initials("i am here 123")); } // ----------------------------------------------------------------------- public void testInitials_String_charArray() { char[] array = null; assertEquals(null, WordUtils.initials(null, array)); assertEquals("", WordUtils.initials("", array)); assertEquals("", WordUtils.initials(" ", array)); assertEquals("I", WordUtils.initials("I", array)); assertEquals("i", WordUtils.initials("i", array)); assertEquals("S", WordUtils.initials("SJC", array)); assertEquals("BJL", WordUtils.initials("Ben John Lee", array)); assertEquals("BJ", WordUtils.initials("Ben J.Lee", array)); assertEquals("BJ.L", WordUtils.initials(" Ben John . Lee", array)); assertEquals("KO", WordUtils.initials("Kay O'Murphy", array)); assertEquals("iah1", WordUtils.initials("i am here 123", array)); array = new char[0]; assertEquals(null, WordUtils.initials(null, array)); assertEquals("", WordUtils.initials("", array)); assertEquals("", WordUtils.initials(" ", array)); assertEquals("", WordUtils.initials("I", array)); assertEquals("", WordUtils.initials("i", array)); assertEquals("", WordUtils.initials("SJC", array)); assertEquals("", WordUtils.initials("Ben John Lee", array)); assertEquals("", WordUtils.initials("Ben J.Lee", array)); assertEquals("", WordUtils.initials(" Ben John . Lee", array)); assertEquals("", WordUtils.initials("Kay O'Murphy", array)); assertEquals("", WordUtils.initials("i am here 123", array)); array = " ".toCharArray(); assertEquals(null, WordUtils.initials(null, array)); assertEquals("", WordUtils.initials("", array)); assertEquals("", WordUtils.initials(" ", array)); assertEquals("I", WordUtils.initials("I", array)); assertEquals("i", WordUtils.initials("i", array)); assertEquals("S", WordUtils.initials("SJC", array)); assertEquals("BJL", WordUtils.initials("Ben John Lee", array)); assertEquals("BJ", WordUtils.initials("Ben J.Lee", array)); assertEquals("BJ.L", WordUtils.initials(" Ben John . Lee", array)); assertEquals("KO", WordUtils.initials("Kay O'Murphy", array)); assertEquals("iah1", WordUtils.initials("i am here 123", array)); array = " .".toCharArray(); assertEquals(null, WordUtils.initials(null, array)); assertEquals("", WordUtils.initials("", array)); assertEquals("", WordUtils.initials(" ", array)); assertEquals("I", WordUtils.initials("I", array)); assertEquals("i", WordUtils.initials("i", array)); assertEquals("S", WordUtils.initials("SJC", array)); assertEquals("BJL", WordUtils.initials("Ben John Lee", array)); assertEquals("BJL", WordUtils.initials("Ben J.Lee", array)); assertEquals("BJL", WordUtils.initials(" Ben John . Lee", array)); assertEquals("KO", WordUtils.initials("Kay O'Murphy", array)); assertEquals("iah1", WordUtils.initials("i am here 123", array)); array = " .'".toCharArray(); assertEquals(null, WordUtils.initials(null, array)); assertEquals("", WordUtils.initials("", array)); assertEquals("", WordUtils.initials(" ", array)); assertEquals("I", WordUtils.initials("I", array)); assertEquals("i", WordUtils.initials("i", array)); assertEquals("S", WordUtils.initials("SJC", array)); assertEquals("BJL", WordUtils.initials("Ben John Lee", array)); assertEquals("BJL", WordUtils.initials("Ben J.Lee", array)); assertEquals("BJL", WordUtils.initials(" Ben John . Lee", array)); assertEquals("KOM", WordUtils.initials("Kay O'Murphy", array)); assertEquals("iah1", WordUtils.initials("i am here 123", array)); array = "SIJo1".toCharArray(); assertEquals(null, WordUtils.initials(null, array)); assertEquals("", WordUtils.initials("", array)); assertEquals(" ", WordUtils.initials(" ", array)); assertEquals("", WordUtils.initials("I", array)); assertEquals("i", WordUtils.initials("i", array)); assertEquals("C", WordUtils.initials("SJC", array)); assertEquals("Bh", WordUtils.initials("Ben John Lee", array)); assertEquals("B.", WordUtils.initials("Ben J.Lee", array)); assertEquals(" h", WordUtils.initials(" Ben John . Lee", array)); assertEquals("K", WordUtils.initials("Kay O'Murphy", array)); assertEquals("i2", WordUtils.initials("i am here 123", array)); } // ----------------------------------------------------------------------- public void testSwapCase_String() { assertEquals(null, WordUtils.swapCase(null)); assertEquals("", Word