Codebase list libcommons-lang3-java / upstream/3.11+git20210825.1.3586d1a
Import upstream version 3.11+git20210825.1.3586d1a Debian Janitor 2 years ago
243 changed file(s) with 21876 addition(s) and 18961 deletion(s). Raw diff Collapse all Expand all
0 # Licensed to the Apache Software Foundation (ASF) under one or more
1 # contributor license agreements. See the NOTICE file distributed with
2 # this work for additional information regarding copyright ownership.
3 # The ASF licenses this file to You under the Apache License, Version 2.0
4 # (the "License"); you may not use this file except in compliance with
5 # the License. You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 version: 2
16 updates:
17 - package-ecosystem: "maven"
18 directory: "/"
19 schedule:
20 interval: "daily"
21 - package-ecosystem: "github-actions"
22 directory: "/"
23 schedule:
24 interval: "daily"
1414
1515 name: Java CI
1616
17 on: [push]
17 on: [push, pull_request]
1818
1919 jobs:
2020 build:
2121
2222 runs-on: ubuntu-latest
23 continue-on-error: ${{ matrix.experimental }}
2324 strategy:
2425 matrix:
25 java: [ 8, 11, 12, 13, 14 ]
26
26 #
27 # Allow Java 16 to fail to allow Java 8 and 11 to run until we know what's wrong on Java 16.
28 # java: [ 8, 11, 16 ]
29 java: [ 8, 11 ]
30 experimental: [false]
31 include:
32 - java: 16
33 experimental: true
34 - java: 17-ea
35 experimental: true
2736 steps:
28 - uses: actions/checkout@v1
37 - uses: actions/checkout@v2.3.4
38 - uses: actions/cache@v2.1.6
39 with:
40 path: ~/.m2/repository
41 key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }}
42 restore-keys: |
43 ${{ runner.os }}-maven-
2944 - name: Set up JDK ${{ matrix.java }}
30 uses: actions/setup-java@v1
45 uses: actions/setup-java@v2
3146 with:
47 distribution: 'adopt'
3248 java-version: ${{ matrix.java }}
3349 - name: Build with Maven
34 run: mvn -V apache-rat:check spotbugs:check javadoc:javadoc -Ddoclint=all package --file pom.xml
50 run: mvn -V -Ddoclint=all --file pom.xml --no-transfer-progress
1313 # limitations under the License.
1414
1515 language: java
16
1617 cache:
1718 directories:
1819 - $HOME/.m2
20
1921 jdk:
2022 - openjdk8
2123 - openjdk11
22 - openjdk14
24 - openjdk16
2325 - openjdk-ea
26
2427 matrix:
25 include:
26 - os: linux-ppc64le
27 jdk: openjdk8
2828 allow_failures:
2929 - jdk: openjdk-ea
30
3031 script:
31 - mvn
32 - mvn -V --no-transfer-progress
33
3234 after_success:
33 - mvn clean test jacoco:report coveralls:report -Ptravis-jacoco javadoc:javadoc -Ddoclint=all
35 - mvn -V --no-transfer-progress clean test jacoco:report coveralls:report -Ptravis-jacoco javadoc:javadoc -Ddoclint=all
0 <!---
1 Licensed to the Apache Software Foundation (ASF) under one or more
2 contributor license agreements. See the NOTICE file distributed with
3 this work for additional information regarding copyright ownership.
4 The ASF licenses this file to You under the Apache License, Version 2.0
5 (the "License"); you may not use this file except in compliance with
6 the License. You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 -->
16 The Apache code of conduct page is [https://www.apache.org/foundation/policies/conduct.html](https://www.apache.org/foundation/policies/conduct.html).
00 Apache Commons Lang
1 Copyright 2001-2020 The Apache Software Foundation
1 Copyright 2001-2021 The Apache Software Foundation
22
33 This product includes software developed at
44 The Apache Software Foundation (https://www.apache.org/).
4242 Apache Commons Lang
4343 ===================
4444
45 [![Build Status](https://travis-ci.org/apache/commons-lang.svg)](https://travis-ci.org/apache/commons-lang)
45 [![Travis-CI Status](https://travis-ci.org/apache/commons-lang.svg)](https://travis-ci.org/apache/commons-lang)
46 [![GitHub Actions Status](https://github.com/apache/commons-lang/workflows/Java%20CI/badge.svg)](https://github.com/apache/commons-lang/actions)
4647 [![Coverage Status](https://coveralls.io/repos/apache/commons-lang/badge.svg)](https://coveralls.io/r/apache/commons-lang)
4748 [![Maven Central](https://maven-badges.herokuapp.com/maven-central/org.apache.commons/commons-lang3/badge.svg)](https://maven-badges.herokuapp.com/maven-central/org.apache.commons/commons-lang3/)
48 [![Javadocs](https://javadoc.io/badge/org.apache.commons/commons-lang3/3.11.svg)](https://javadoc.io/doc/org.apache.commons/commons-lang3/3.11)
49 [![Javadocs](https://javadoc.io/badge/org.apache.commons/commons-lang3/3.12.0.svg)](https://javadoc.io/doc/org.apache.commons/commons-lang3/3.12.0)
4950
5051 Apache Commons Lang, a package of Java utility classes for the
5152 classes that are in java.lang's hierarchy, or are considered to be so
6869 <dependency>
6970 <groupId>org.apache.commons</groupId>
7071 <artifactId>commons-lang3</artifactId>
71 <version>3.11</version>
72 <version>3.12.0</version>
7273 </dependency>
7374 ```
7475
0 Apache Commons Lang
1 Version 3.12.0
2 Release Notes
3
4 INTRODUCTION:
5
6 This document contains the release notes for the 3.12.0 version of Apache Commons Lang.
7 Commons Lang is a set of utility functions and reusable components that should be of use in any
8 Java environment.
9
10 Lang 3.9 and onwards now targets Java 8, making use of features that arrived with Java 8.
11
12 For the advice on upgrading from 2.x to 3.x, see the following page:
13
14 https://commons.apache.org/lang/article3_0.html
15
16 Apache Commons Lang, a package of Java utility classes for the
17 classes that are in java.lang's hierarchy, or are considered to be so
18 standard as to justify existence in java.lang.
19
20 New features and bug fixes.
21
22 Changes in this version include:
23
24 New features:
25 o Add BooleanUtils.booleanValues(). Thanks to Gary Gregory.
26 o Add BooleanUtils.primitiveValues(). Thanks to Gary Gregory.
27 o LANG-1535: Add StringUtils.containsAnyIgnoreCase(CharSequence, CharSequence...). Thanks to Gary Gregory, Isira Seneviratne.
28 o LANG-1359: Add StopWatch.getStopTime(). Thanks to Gary Gregory, Keegan Witt.
29 o More test coverage for CharSequenceUtils. #631. Thanks to Edgar Asatryan.
30 o Add fluent-style ArraySorter. Thanks to Gary Gregory.
31 o Add and use LocaleUtils.toLocale(Locale) to avoid NPEs. Thanks to Gary Gregory.
32 o Add FailableShortSupplier, handy for JDBC APIs. Thanks to Gary Gregory.
33 o Add JavaVersion.JAVA_17. Thanks to Gary Gregory.
34 o LANG-1636: Add missing boolean[] join method #686. Thanks to .
35 o Add StringUtils.substringBefore(String, int). Thanks to Gary Gregory.
36 o Add Range.INTEGER. Thanks to Gary Gregory.
37 o Add DurationUtils. Thanks to Gary Gregory.
38 o Introduce the use of @Nonnull, and @Nullable, and the Objects class as a helper tool.
39 o Add and use true and false String constants #714. Thanks to Arturo Bernal, Gary Gregory.
40 o Add and use ObjectUtils.requireNonEmpty() #716. Thanks to Arturo Bernal, Gary Gregory.
41
42 Fixed Bugs:
43 o LANG-1592: Correct implementation of RandomUtils.nextLong(long, long) Thanks to Huang Pingcai, Alex Herbert.
44 o LANG-1600: Restore handling of collections for non-JSON ToStringStyle #610. Thanks to Michael F.
45 o ContextedException Javadoc add missing semicolon #581. Thanks to iamchao1129.
46 o LANG-1608: Resolve JUnit pioneer transitive dependencies using JUnit BOM. Thanks to Edgar Asatryan.
47 o NumberUtilsTest - incorrect types in min/max tests #634. Thanks to HubertWo, Gary Gregory.
48 o LANG-1579: Improve StringUtils.stripAccents conversion of remaining accents. Thanks to XenoAmess.
49 o LANG-1606: StringUtils.countMatches - clarify Javadoc. Thanks to Rustem Galiev.
50 o LANG-1591: Remove redundant argument from substring call. Thanks to bhawna94.
51 o LANG-1613: BigDecimal is created when you pass it the min and max values, #642. Thanks to Arturo Bernal, Gary Gregory.
52 o LANG-1541: ArrayUtils.contains() and indexOf() fail to handle Double.NaN #647. Thanks to Arturo Bernal, Gary Gregory.
53 o LANG-1615: ArrayUtils contains() and indexOf() fail to handle Float.NaN # #561. Thanks to Arturo Bernal, Gary Gregory.
54 o Fix potential NPE in TypeUtils.isAssignable(Type, ParameterizedType, Map, Type>). Thanks to Gary Gregory.
55 o LANG-1420: TypeUtils.isAssignable returns wrong result for GenericArrayType and ParameterizedType, #643. Thanks to Gordon Fraser, Rostislav Krasny, Arturo Bernal, Gary Gregory.
56 o LANG-1612: testGetAllFields and testGetFieldsWithAnnotation sometimes fail. Thanks to XinT, Gary Gregory.
57 o Fix Javadoc for SystemUtils.isJavaVersionAtMost() #638. Thanks to John R. D'Orazio.
58 o LANG-1610: Fix StringUtils.unwrap throws StringIndexOutOfBoundsException #636. Thanks to Tony Liang.
59 o Fix formatting of isAnyBlank() and isAnyEmpty(). #513. Thanks to Isira Seneviratne.
60 o LANG-1618: TypeUtils. containsTypeVariables does not support GenericArrayType #661. Thanks to Arturo Bernal.
61 o LANG-1622: Javadoc of some methods incorrectly refers to another method, #667, #668. #670. Thanks to Kanak Sony, anomen-s.
62 o LANG-1620: Refine StringUtils.lastIndexOfIgnoreCase #664. Thanks to Arturo Bernal.
63 o LANG-1619: Refine StringUtils.abbreviate #663. Thanks to Arturo Bernal.
64 o LANG-1584: Refine StringUtils.isNumericSpace #573. Thanks to Arturo Bernal.
65 o LANG-1580: Refine StringUtils.deleteWhitespace #569. Thanks to Arturo Bernal.
66 o LANG-1626: Correction in Javadoc of some methods. #673 Thanks to Kanak Sony.
67 o LANG-1628: Javadoc for RandomStringUtils.random() letters, numbers parameters is wrong. Thanks to Jarkko Rantavuori.
68 o Correct markup in Javadoc for unbalanced braces #679. Thanks to Felix Schumacher.
69 o LANG-1544: MethodUtils.invokeMethod NullPointerException in case of null in args list #680. Thanks to Peter Nagy, Michael Buck, Gary Gregory.
70 o LANG-1637: Fix 2 digit week year formatting #688. Thanks to Uri Gonen, Gary Gregory, Michael Osipov.
71 o Fix broken Javadoc links to commons-text #712. Thanks to Chris Smowton.
72 o Add and use ThreadUtils.sleep(Duration). Thanks to Gary Gregory.
73 o Add and use ThreadUtils.join(Thread, Duration). Thanks to Gary Gregory.
74 o Add ObjectUtils.wait(Duration). Thanks to Gary Gregory.
75
76 Changes:
77 o LANG-1596: ArrayUtils.toPrimitive(Object) does not support boolean and other types #607. Thanks to Richard Eckart de Castilho.
78 o Enable Dependabot #587. Thanks to Gary Gregory.
79 o Bump junit-jupiter from 5.6.2 to 5.7.0.
80 o Bump spotbugs from 4.1.2 to 4.2.1, #627, #671, #708. Thanks to chtompki, Dependabot.
81 o Bump spotbugs-maven-plugin from 4.0.0 to 4.2.0, #593, #596, #609, #623, #632, #692. Thanks to Dependabot.
82 o Bump biz.aQute.bndlib from 5.1.1 to 5.3.0 #592, #628, #715. Thanks to Dependabot.
83 o Bump junit-pioneer from 0.6.0 to 1.1.0, #589, #597, #600, #624, #625, #662. Thanks to Dependabot.
84 o Bump checkstyle from 8.34 to 8.40, #594, #614, #637, #665, #706. Thanks to Dependabot.
85 o Bump actions/checkout from v2.3.1 to v2.3.4 #601, #639. Thanks to Dependabot.
86 o Bump actions/setup-java from v1.4.0 to v1.4.2 #612. Thanks to Dependabot.
87 o Update commons.jacoco.version 0.8.5 to 0.8.6 (Fixes Java 15 builds). Thanks to Gary Gregory.
88 o Update maven-surefire-plugin 2.22.2 -> 3.0.0-M5. Thanks to Gary Gregory.
89 o Bump maven-pmd-plugin from 3.13.0 to 3.14.0 #660. Thanks to Dependabot.
90 o Bump jmh.version from 1.21 to 1.27 #674. Thanks to Dependabot.
91 o Update commons.japicmp.version 0.14.3 -> 0.15.2. Thanks to Gary Gregory.
92 o Processor.java: check enum equality with == instead of .equals() method #690. Thanks to Ali K. Nouri.
93 o Bump junit-pioneer from 1.1.0 to 1.3.0 #702. Thanks to Dependabot.
94 o Bump maven-checkstyle-plugin from 3.1.1 to 3.1.2 #705. Thanks to Dependabot.
95 o Bump actions/cache from v2 to v2.1.4 #710. Thanks to Dependabot.
96 o Bump junit-bom from 5.7.0 to 5.7.1 #707. Thanks to Dependabot.
97 o Minor Improvements #701. Thanks to Arturo Bernal.
98 o Minor Improvement: Add final variable.try to make the code read-only #700. Thanks to Arturo Bernal.
99 o Minor Improvement: Remove redundant initializer #699. Thanks to Arturo Bernal.
100 o Use own validator ObjectUtils.anyNull to check null String input #718. Thanks to Arturo Bernal.
101
102
103 Historical list of changes: https://commons.apache.org/proper/commons-lang/changes-report.html
104
105 For complete information on Apache Commons Lang, including instructions on how to submit bug reports,
106 patches, or suggestions for improvement, see the Apache Apache Commons Lang website:
107
108 https://commons.apache.org/proper/commons-lang/
109
110 Download page: https://commons.apache.org/proper/commons-lang/download_lang.cgi
111
112 Have fun!
113 -Apache Commons Team
114
115 =============================================================================
116
0117 Apache Commons Lang
1118 Version 3.11
2119 Release Notes
0 <!---
1 Licensed to the Apache Software Foundation (ASF) under one or more
2 contributor license agreements. See the NOTICE file distributed with
3 this work for additional information regarding copyright ownership.
4 The ASF licenses this file to You under the Apache License, Version 2.0
5 (the "License"); you may not use this file except in compliance with
6 the License. You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 -->
16 The Apache Commons security page is [https://commons.apache.org/security.html](https://commons.apache.org/security.html).
2121 <parent>
2222 <groupId>org.apache.commons</groupId>
2323 <artifactId>commons-parent</artifactId>
24 <version>51</version>
24 <version>52</version>
2525 </parent>
2626 <modelVersion>4.0.0</modelVersion>
2727 <artifactId>commons-lang3</artifactId>
28 <version>3.11</version>
28 <version>3.13.0-SNAPSHOT</version>
2929 <name>Apache Commons Lang</name>
3030
3131 <inceptionYear>2001</inceptionYear>
4646 <connection>scm:git:http://gitbox.apache.org/repos/asf/commons-lang.git</connection>
4747 <developerConnection>scm:git:https://gitbox.apache.org/repos/asf/commons-lang.git</developerConnection>
4848 <url>https://gitbox.apache.org/repos/asf?p=commons-lang.git</url>
49 <tag>commons-lang-3.11</tag>
49 <tag>commons-lang-3.12.0</tag>
5050 </scm>
5151
5252 <developers>
9898 </roles>
9999 </developer>
100100 <developer>
101 <name>Gary D. Gregory</name>
102101 <id>ggregory</id>
103 <email>ggregory@apache.org</email>
104 <timezone>-5</timezone>
105 <roles>
106 <role>Java Developer</role>
107 </roles>
102 <name>Gary Gregory</name>
103 <email>ggregory at apache.org</email>
104 <url>https://www.garygregory.com</url>
105 <organization>The Apache Software Foundation</organization>
106 <organizationUrl>https://www.apache.org/</organizationUrl>
107 <roles>
108 <role>PMC Member</role>
109 </roles>
110 <timezone>America/New_York</timezone>
111 <properties>
112 <picUrl>https://people.apache.org/~ggregory/img/garydgregory80.png</picUrl>
113 </properties>
108114 </developer>
109115 <developer>
110116 <name>Fredrik Westermarck</name>
511517 <name>Jin Xu</name>
512518 </contributor>
513519 </contributors>
520
521 <dependencyManagement>
522 <dependencies>
523 <dependency>
524 <groupId>org.junit</groupId>
525 <artifactId>junit-bom</artifactId>
526 <version>5.7.2</version>
527 <type>pom</type>
528 <scope>import</scope>
529 </dependency>
530 </dependencies>
531 </dependencyManagement>
514532
515533 <!-- Lang should depend on very little -->
516534 <dependencies>
518536 <dependency>
519537 <groupId>org.junit.jupiter</groupId>
520538 <artifactId>junit-jupiter</artifactId>
521 <version>5.6.2</version>
522539 <scope>test</scope>
523540 </dependency>
524541 <dependency>
525542 <groupId>org.junit-pioneer</groupId>
526543 <artifactId>junit-pioneer</artifactId>
527 <version>0.6.0</version>
544 <version>1.4.2</version>
528545 <scope>test</scope>
529546 </dependency>
530547 <dependency>
537554 <dependency>
538555 <groupId>org.easymock</groupId>
539556 <artifactId>easymock</artifactId>
540 <version>4.2</version>
557 <version>4.3</version>
541558 <scope>test</scope>
542559 </dependency>
543560
554571 <version>${jmh.version}</version>
555572 <scope>test</scope>
556573 </dependency>
557
574 <dependency>
575 <groupId>com.google.code.findbugs</groupId>
576 <artifactId>jsr305</artifactId>
577 <version>3.0.2</version>
578 <scope>test</scope>
579 </dependency>
558580 </dependencies>
559581
560582 <distributionManagement>
586608 <commons.packageId>lang3</commons.packageId>
587609 <commons.module.name>org.apache.commons.lang3</commons.module.name>
588610 <!-- Current 3.x release series -->
589 <commons.release.version>3.11</commons.release.version>
611 <commons.release.version>3.13.0</commons.release.version>
590612 <commons.release.desc>(Java 8+)</commons.release.desc>
591613 <!-- Previous 2.x release series -->
592614 <commons.release.2.version>2.6</commons.release.2.version>
601623 <commons.scmPubCheckoutDirectory>site-content</commons.scmPubCheckoutDirectory>
602624 <commons.encoding>utf-8</commons.encoding>
603625
604 <checkstyle.plugin.version>3.1.1</checkstyle.plugin.version>
605 <checkstyle.version>8.34</checkstyle.version>
626 <checkstyle.plugin.version>3.1.2</checkstyle.plugin.version>
627 <checkstyle.version>8.44</checkstyle.version>
606628 <checkstyle.configdir>src/site/resources/checkstyle</checkstyle.configdir>
607629
608 <spotbugs.plugin.version>4.0.0</spotbugs.plugin.version>
609 <spotbugs.impl.version>4.0.6</spotbugs.impl.version>
630 <spotbugs.plugin.version>4.3.0</spotbugs.plugin.version>
631 <spotbugs.impl.version>4.2.3</spotbugs.impl.version>
610632 <japicmp.skip>false</japicmp.skip>
611633 <clirr.skip>true</clirr.skip>
612634
613635 <!-- JMH Benchmark related properties, version, target compiler and name of the benchmarking uber jar. -->
614 <jmh.version>1.21</jmh.version>
636 <jmh.version>1.27</jmh.version>
615637 <uberjar.name>benchmarks</uberjar.name>
616638
617 <commons.jacoco.version>0.8.5</commons.jacoco.version>
639 <commons.jacoco.version>0.8.7</commons.jacoco.version>
618640 <commons.surefire.version>3.0.0-M5</commons.surefire.version>
619 <commons.javadoc.version>3.2.0</commons.javadoc.version>
620
621 <!-- never generate report if there are binary incompatible changes -->
622 <commons.japicmp.breakBuildOnBinaryIncompatibleModifications>true</commons.japicmp.breakBuildOnBinaryIncompatibleModifications>
623 <commons.japicmp.version>0.14.3</commons.japicmp.version>
641 <commons.javadoc.version>3.3.0</commons.javadoc.version>
642 <commons.japicmp.version>0.15.3</commons.japicmp.version>
624643
625644 <!-- Commons Release Plugin -->
626 <commons.bc.version>3.10</commons.bc.version>
627 <commons.rc.version>RC2</commons.rc.version>
645 <commons.bc.version>3.12.0</commons.bc.version>
646 <commons.rc.version>RC1</commons.rc.version>
628647 <commons.release.isDistModule>true</commons.release.isDistModule>
629648 <commons.distSvnStagingUrl>scm:svn:https://dist.apache.org/repos/dist/dev/commons/lang</commons.distSvnStagingUrl>
630649 <commons.releaseManagerName>Gary Gregory</commons.releaseManagerName>
633652
634653
635654 <build>
636 <defaultGoal>clean verify apache-rat:check checkstyle:check japicmp:cmp spotbugs:check javadoc:javadoc</defaultGoal>
655 <defaultGoal>clean package apache-rat:check checkstyle:check japicmp:cmp spotbugs:check javadoc:javadoc</defaultGoal>
637656 <pluginManagement>
638657 <plugins>
639658 <plugin>
647666 <exclude>src/site/resources/release-notes/RELEASE-NOTES-*.txt</exclude>
648667 <exclude>src/test/resources/lang-708-input.txt</exclude>
649668 </excludes>
650 </configuration>
651 </plugin>
652 <!-- override skip property of parent pom -->
653 <plugin>
654 <groupId>com.github.siom79.japicmp</groupId>
655 <artifactId>japicmp-maven-plugin</artifactId>
656 <configuration>
657 <skip>false</skip>
658669 </configuration>
659670 </plugin>
660671 </plugins>
691702 <plugin>
692703 <groupId>org.apache.maven.plugins</groupId>
693704 <artifactId>maven-surefire-plugin</artifactId>
705 <version>${commons.surefire.version}</version>
694706 <executions>
695707 <execution>
696708 <id>plain</id>
781793 <dependency>
782794 <groupId>biz.aQute.bnd</groupId>
783795 <artifactId>biz.aQute.bndlib</artifactId>
784 <version>5.1.1</version>
796 <version>5.3.0</version>
785797 </dependency>
786798 </dependencies>
787799 </plugin>
817829 </plugin>
818830 <plugin>
819831 <artifactId>maven-pmd-plugin</artifactId>
820 <version>3.13.0</version>
832 <version>3.14.0</version>
821833 <configuration>
822834 <targetJdk>${maven.compiler.target}</targetJdk>
823835 </configuration>
922934 </activation>
923935 <properties>
924936 <!-- LANG-1265: allow tests to access private fields/methods of java.base classes via reflection -->
925 <argLine>-Xmx512m --add-opens java.base/java.lang.reflect=ALL-UNNAMED --add-opens java.base/java.lang=ALL-UNNAMED</argLine>
937 <!-- LANG-1667: allow tests to access private fields/methods of java.base/java.util such as ArrayList via reflection -->
938 <argLine>-Xmx512m --add-opens java.base/java.lang.reflect=ALL-UNNAMED --add-opens java.base/java.lang=ALL-UNNAMED --add-opens java.base/java.util=ALL-UNNAMED</argLine>
926939 <!-- coverall version 4.3.0 does not work with java 9, see https://github.com/trautonen/coveralls-maven-plugin/issues/112 -->
927940 <coveralls.skip>true</coveralls.skip>
928941 </properties>
936949 <!-- jacoco does not work with java 13 yet -->
937950 <jacoco.skip>true</jacoco.skip>
938951 </properties>
952 </profile>
953 <profile>
954 <id>java15</id>
955 <activation>
956 <!-- This is ONLY activated for Java 15 -->
957 <jdk>15</jdk>
958 </activation>
959 <build>
960 <plugins>
961 <plugin>
962 <groupId>org.apache.maven.plugins</groupId>
963 <artifactId>maven-surefire-plugin</artifactId>
964 <configuration>
965 <excludes>
966 <exclude>org/apache/commons/lang3/time/Java15BugFastDateParserTest.java</exclude>
967 </excludes>
968 </configuration>
969 </plugin>
970 </plugins>
971 </build>
939972 </profile>
940973
941974 <profile>
2121 put here to instruct findbugs it must ignore them.
2222 -->
2323 <FindBugsFilter>
24
25 <!-- https://github.com/spotbugs/spotbugs/issues/1504 -->
26 <Match>
27 <Class name="org.apache.commons.lang3.ArrayUtils" />
28 <Method name="shuffle" />
29 <Bug pattern="DMI_RANDOM_USED_ONLY_ONCE" />
30 </Match>
31
32 <!-- https://github.com/spotbugs/spotbugs/issues/1504 -->
33 <Match>
34 <Class name="org.apache.commons.lang3.RandomStringUtils" />
35 <Method name="random" />
36 <Bug pattern="DMI_RANDOM_USED_ONLY_ONCE" />
37 </Match>
2438
2539 <Match>
2640 <Class name="org.apache.commons.lang3.ArrayUtils" />
152166 <Method name="compare" />
153167 <Bug pattern="RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE" />
154168 </Match>
169
170 <!-- Reason: requireNonNull is supposed to take a nullable parameter,
171 whatever Spotbugs thinks of it. -->
172 <Match>
173 <Class name="org.apache.commons.lang3.function.Objects" />
174 <Method name="requireNonNull" />
175 <Bug pattern="NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE" />
176 </Match>
155177 </FindBugsFilter>
1919 This file is also used by the maven-changes-plugin to generate the release notes.
2020 Useful ways of finding items to add to this file are:
2121
22 1. Add items when you fix a bug or add a feature (this makes the
22 1. Add items when you fix a bug or add a feature (this makes the
2323 release process easy :-).
2424
2525 2. Do a JIRA search for tickets closed since the previous release.
3131
3232 mvn changes:announcement-generate -Prelease-notes [-Dchanges.version=nnn]
3333
34 then tweak the formatting if necessary
34 then tweak the formatting if necessary
3535 and commit
3636
3737 The <action> type attribute can be add,update,fix,remove.
3838 -->
39
4039
4140 <document>
4241 <properties>
4443 </properties>
4544 <body>
4645
47 <release version="3.11" date="2020-07-12" description="New features and bug fixes.">
46 <release version="3.13.0" date="2021-MM-DD" description="New features and bug fixes (Java 8).">
47 <!-- FIX -->
48 <action issue="LANG-1645" type="fix" dev="aherbert" due-to="Alex Herbert">NumberUtils.createNumber() to recognize hex integers prefixed with +.</action>
49 <action issue="LANG-1646" type="fix" dev="aherbert" due-to="Alex Herbert">NumberUtils.createNumber() to return requested floating point type for zero.</action>
50 <action type="fix" dev="ggregory" due-to="SpotBugs, Gary Gregory">DMI: Random object created and used only once (DMI_RANDOM_USED_ONLY_ONCE); Better multi-threaded behavior.</action>
51 <action issue="LANG-1646" type="fix" dev="aherbert" due-to="Arturo Bernal">Redundant Collection operation. Use Collections.emptyIterator() #738.</action>
52 <action type="fix" dev="ggregory" due-to="Gary Gregory">Make Streams.stream(Collection) null-safe.</action>
53 <action issue="LANG-1667" type="fix" dev="ggregory" due-to="Andrew Thomas">Allow tests to access java.util classes such as ArrayList in Java 16 #788.</action>
54 <action issue="LANG-1669" type="fix" dev="ggregory" due-to="Andrew Thomas">OpenJDK 16 Day Period Parsing #791.</action>
55 <action issue="LANG-1663" type="fix" dev="ggregory" due-to="Andrew Thomas">Update documentation to list correct exception for null array parameters #785.</action>
56 <action type="fix" dev="ggregory" due-to="Thunderforge">Fixing reversed Javadoc descriptions in StopWatch #781.</action>
57 <!-- ADD -->
58 <action type="add" dev="ggregory" due-to="Gary Gregory">Add EnumUtils.getEnumSystemProperty(...).</action>
59 <action type="add" dev="ggregory" due-to="Gary Gregory">Add TriConsumer.</action>
60 <action type="add" dev="ggregory" due-to="Gary Gregory">Add and use EnumUtils.getFirstEnumIgnoreCase(Class, String, Function, E).</action>
61 <action type="add" dev="ggregory" due-to="Gary Gregory">Add and use Suppliers.</action>
62 <action type="add" dev="ggregory" due-to="Gary Gregory">Add and use ArrayUtils.getComponentType(T[]).</action>
63 <action type="add" dev="ggregory" due-to="Gary Gregory">Add and use ClassUtils.getComponentType(Class&gt;T[]>).</action>
64 <action type="add" dev="ggregory" due-to="Gary Gregory">Add and use ObjectUtils.getClass(T).</action>
65 <action type="add" dev="ggregory" due-to="Gary Gregory">Add and use ArrayUtils.newInstance(Class&gt;T>, int).</action>
66 <action type="add" dev="ggregory" due-to="Gary Gregory">Add and use null-safe Streams.of(T...).</action>
67 <action type="add" dev="ggregory" due-to="Gary Gregory">Add ClassUtils.comparator().</action>
68 <action type="add" dev="ggregory" due-to="Gary Gregory">Add and use ThreadUtils.sleepQuietly(long).</action>
69 <action type="add" dev="ggregory" due-to="Gary Gregory">Add and use ArrayUtils.setAll(T[], IntFunction).</action>
70 <action type="add" dev="ggregory" due-to="Gary Gregory">Add and use ArrayUtils.setAll(T[], Supplier).</action>
71 <action type="add" dev="ggregory" due-to="Gary Gregory">Add BooleanConsumer.</action>
72 <!-- UPDATE -->
73 <action type="update" dev="ggregory" due-to="Dependabot, Gary Gregory">Bump spotbugs-maven-plugin from 4.2.0 to 4.2.3 #735.</action>
74 <action type="update" dev="ggregory" due-to="Dependabot, XenoAmess">Bump Bump actions/cache from v2.1.4 to v2.1.6 #742, #752, #764.</action>
75 <action type="update" dev="ggregory" due-to="Gary Gregory">Bump actions/setup-java from v1.4.3 to v2.</action>
76 <action type="update" dev="ggregory" due-to="Dependabot">Bump spotbugs-maven-plugin from 4.2.2 to 4.3.0.</action>
77 <action type="update" dev="ggregory" due-to="Dependabot">Bump spotbugs from 4.2.2 to 4.2.3 #744.</action>
78 <action type="update" dev="ggregory" due-to="Dependabot, Gary Gregory">Bump checkstyle from 8.41 to 8.44 #739, #768.</action>
79 <action type="update" dev="ggregory" due-to="Dependabot">Bump easymock from 4.2 to 4.3 #746.</action>
80 <action type="update" dev="ggregory" due-to="Gary Gregory">commons.jacoco.version 0.8.6 -> 0.8.7.</action>
81 <action type="update" dev="ggregory" due-to="Gary Gregory">commons.japicmp.version 0.15.2 -> 0.15.3.</action>
82 <action type="update" dev="ggregory" due-to="Dependabot">Bump junit-pioneer from 1.3.8 to 1.4.2 #749, #767.</action>
83 <action type="update" dev="ggregory" due-to="Dependabot">Bump junit-bom from 5.7.1 to 5.7.2 #761.</action>
84 <action type="update" dev="ggregory" due-to="Dependabot">Bump commons.javadoc.version from 3.2.0 to 3.3.0.</action>
85 </release>
86
87 <release version="3.12.0" date="2021-02-26" description="New features and bug fixes (Java 8).">
88 <!-- FIX -->
89 <action issue="LANG-1592" type="fix" dev="aherbert" due-to="Huang Pingcai, Alex Herbert">Correct implementation of RandomUtils.nextLong(long, long)</action>
90 <action issue="LANG-1600" type="fix" dev="ggregory" due-to="Michael F">Restore handling of collections for non-JSON ToStringStyle #610.</action>
91 <action type="fix" dev="ggregory" due-to="iamchao1129">ContextedException Javadoc add missing semicolon #581.</action>
92 <action issue="LANG-1608" type="fix" dev="aherbert" due-to="Edgar Asatryan">Resolve JUnit pioneer transitive dependencies using JUnit BOM.</action>
93 <action type="fix" dev="aherbert" due-to="HubertWo, Gary Gregory">NumberUtilsTest - incorrect types in min/max tests #634.</action>
94 <action issue="LANG-1579" type="fix" dev="aherbert" due-to="XenoAmess">Improve StringUtils.stripAccents conversion of remaining accents.</action>
95 <action issue="LANG-1606" type="fix" dev="sebb" due-to="Rustem Galiev">StringUtils.countMatches - clarify Javadoc.</action>
96 <action issue="LANG-1591" type="fix" dev="kinow" due-to="bhawna94">Remove redundant argument from substring call.</action>
97 <action issue="LANG-1613" type="fix" dev="ggregory" due-to="Arturo Bernal, Gary Gregory">BigDecimal is created when you pass it the min and max values, #642.</action>
98 <action issue="LANG-1541" type="fix" dev="ggregory" due-to="Arturo Bernal, Gary Gregory">ArrayUtils.contains() and indexOf() fail to handle Double.NaN #647.</action>
99 <action issue="LANG-1615" type="fix" dev="ggregory" due-to="Arturo Bernal, Gary Gregory">ArrayUtils contains() and indexOf() fail to handle Float.NaN # #561.</action>
100 <action type="fix" dev="ggregory" due-to="Gary Gregory">Fix potential NPE in TypeUtils.isAssignable(Type, ParameterizedType, Map, Type>).</action>
101 <action issue="LANG-1420" type="fix" dev="ggregory" due-to="Gordon Fraser, Rostislav Krasny, Arturo Bernal, Gary Gregory">TypeUtils.isAssignable returns wrong result for GenericArrayType and ParameterizedType, #643.</action>
102 <action issue="LANG-1612" type="fix" dev="ggregory" due-to="XinT, Gary Gregory">testGetAllFields and testGetFieldsWithAnnotation sometimes fail.</action>
103 <action type="fix" dev="ggregory" due-to="John R. D'Orazio">Fix Javadoc for SystemUtils.isJavaVersionAtMost() #638.</action>
104 <action issue="LANG-1610" type="fix" dev="ggregory" due-to="Tony Liang">Fix StringUtils.unwrap throws StringIndexOutOfBoundsException #636.</action>
105 <action type="fix" dev="ggregory" due-to="Isira Seneviratne">Fix formatting of isAnyBlank() and isAnyEmpty(). #513.</action>
106 <action issue="LANG-1618" type="fix" dev="ggregory" due-to="Arturo Bernal">TypeUtils. containsTypeVariables does not support GenericArrayType #661.</action>
107 <action issue="LANG-1622" type="fix" dev="ggregory" due-to="Kanak Sony, anomen-s">Javadoc of some methods incorrectly refers to another method, #667, #668. #670.</action>
108 <action issue="LANG-1620" type="fix" dev="ggregory" due-to="Arturo Bernal">Refine StringUtils.lastIndexOfIgnoreCase #664.</action>
109 <action issue="LANG-1619" type="fix" dev="ggregory" due-to="Arturo Bernal">Refine StringUtils.abbreviate #663.</action>
110 <action issue="LANG-1584" type="fix" dev="ggregory" due-to="Arturo Bernal">Refine StringUtils.isNumericSpace #573.</action>
111 <action issue="LANG-1580" type="fix" dev="ggregory" due-to="Arturo Bernal">Refine StringUtils.deleteWhitespace #569.</action>
112 <action issue="LANG-1626" type="fix" dev="ggregory" due-to="Kanak Sony">Correction in Javadoc of some methods. #673</action>
113 <action issue="LANG-1628" type="fix" dev="kinow" due-to="Jarkko Rantavuori">Javadoc for RandomStringUtils.random() letters, numbers parameters is wrong.</action>
114 <action type="fix" dev="ggregory" due-to="Felix Schumacher">Correct markup in Javadoc for unbalanced braces #679.</action>
115 <action issue="LANG-1544" type="fix" dev="kinow" due-to="Peter Nagy, Michael Buck, Gary Gregory">MethodUtils.invokeMethod NullPointerException in case of null in args list #680.</action>
116 <action issue="LANG-1637" type="fix" dev="ggregory" due-to="Uri Gonen, Gary Gregory, Michael Osipov">Fix 2 digit week year formatting #688.</action>
117 <action type="fix" dev="ggregory" due-to="Chris Smowton">Fix broken Javadoc links to commons-text #712.</action>
118 <action type="fix" dev="ggregory" due-to="Gary Gregory">Add and use ThreadUtils.sleep(Duration).</action>
119 <action type="fix" dev="ggregory" due-to="Gary Gregory">Add and use ThreadUtils.join(Thread, Duration).</action>
120 <action type="fix" dev="ggregory" due-to="Gary Gregory">Add ObjectUtils.wait(Duration).</action>
121 <!-- ADD -->
122 <action type="add" dev="ggregory" due-to="Gary Gregory">Add BooleanUtils.booleanValues().</action>
123 <action type="add" dev="ggregory" due-to="Gary Gregory">Add BooleanUtils.primitiveValues().</action>
124 <action issue="LANG-1535" type="add" dev="ggregory" due-to="Gary Gregory, Isira Seneviratne">Add StringUtils.containsAnyIgnoreCase(CharSequence, CharSequence...).</action>
125 <action issue="LANG-1359" type="add" dev="ggregory" due-to="Gary Gregory, Keegan Witt">Add StopWatch.getStopTime().</action>
126 <action type="add" dev="ggregory" due-to="Edgar Asatryan">More test coverage for CharSequenceUtils. #631.</action>
127 <action issue="LANG-1596" type="update" dev="aherbert" due-to="Richard Eckart de Castilho">ArrayUtils.toPrimitive(Object) does not support boolean and other types #607.</action>
128 <action type="add" dev="ggregory" due-to="Gary Gregory">Add fluent-style ArraySorter.</action>
129 <action type="add" dev="ggregory" due-to="Gary Gregory">Add and use LocaleUtils.toLocale(Locale) to avoid NPEs.</action>
130 <action type="add" dev="ggregory" due-to="Gary Gregory">Add FailableShortSupplier, handy for JDBC APIs.</action>
131 <action type="add" dev="ggregory" due-to="Gary Gregory">Add JavaVersion.JAVA_17.</action>
132 <action issue="LANG-1636" type="add" dev="ggregory" due-to="">Add missing boolean[] join method #686.</action>
133 <action type="add" dev="ggregory" due-to="Gary Gregory">Add StringUtils.substringBefore(String, int).</action>
134 <action type="add" dev="ggregory" due-to="Gary Gregory">Add Range.INTEGER.</action>
135 <action type="add" dev="ggregory" due-to="Gary Gregory">Add DurationUtils.</action>
136 <action type="add" dev="jochen">Introduce the use of @Nonnull, and @Nullable, and the Objects class as a helper tool.</action>
137 <action type="add" dev="ggregory" due-to="Arturo Bernal, Gary Gregory">Add and use true and false String constants #714.</action>
138 <action type="add" dev="ggregory" due-to="Arturo Bernal, Gary Gregory">Add and use ObjectUtils.requireNonEmpty() #716.</action>
139 <!-- UPDATE -->
140 <action type="update" dev="ggregory" due-to="Gary Gregory">Enable Dependabot #587.</action>
141 <action type="update" dev="chtompki">Bump junit-jupiter from 5.6.2 to 5.7.0.</action>
142 <action type="update" dev="chtompki" due-to="chtompki, Dependabot">Bump spotbugs from 4.1.2 to 4.2.2, #627, #671, #708, #726.</action>
143 <action type="update" dev="ggregory" due-to="Dependabot">Bump spotbugs-maven-plugin from 4.0.0 to 4.2.0, #593, #596, #609, #623, #632, #692.</action>
144 <action type="update" dev="ggregory" due-to="Dependabot">Bump biz.aQute.bndlib from 5.1.1 to 5.3.0 #592, #628, #715.</action>
145 <action type="update" dev="ggregory" due-to="Dependabot">Bump junit-pioneer from 0.6.0 to 1.1.0, #589, #597, #600, #624, #625, #662.</action>
146 <action type="update" dev="ggregory" due-to="Dependabot">Bump checkstyle from 8.34 to 8.41, #594, #614, #637, #665, #706, #722.</action>
147 <action type="update" dev="ggregory" due-to="Dependabot">Bump actions/checkout from v2.3.1 to v2.3.4 #601, #639.</action>
148 <action type="update" dev="ggregory" due-to="Dependabot">Bump actions/setup-java from v1.4.0 to v1.4.2 #612.</action>
149 <action type="update" dev="ggregory" due-to="Gary Gregory">Update commons.jacoco.version 0.8.5 to 0.8.6 (Fixes Java 15 builds).</action>
150 <action type="update" dev="ggregory" due-to="Gary Gregory">Update maven-surefire-plugin 2.22.2 -> 3.0.0-M5.</action>
151 <action type="update" dev="ggregory" due-to="Dependabot">Bump maven-pmd-plugin from 3.13.0 to 3.14.0 #660.</action>
152 <action type="update" dev="kinow" due-to="Dependabot">Bump jmh.version from 1.21 to 1.27 #674.</action>
153 <action type="update" dev="ggregory" due-to="Gary Gregory">Update commons.japicmp.version 0.14.3 -> 0.15.2.</action>
154 <action type="update" dev="ggregory" due-to="Ali K. Nouri">Processor.java: check enum equality with == instead of .equals() method #690.</action>
155 <action type="update" dev="ggregory" due-to="Dependabot">Bump junit-pioneer from 1.1.0 to 1.3.8, #702, #721.</action>
156 <action type="update" dev="ggregory" due-to="Dependabot">Bump maven-checkstyle-plugin from 3.1.1 to 3.1.2 #705.</action>
157 <action type="update" dev="ggregory" due-to="Dependabot">Bump actions/cache from v2 to v2.1.4 #710.</action>
158 <action type="update" dev="ggregory" due-to="Dependabot">Bump junit-bom from 5.7.0 to 5.7.1 #707.</action>
159 <action type="update" dev="ggregory" due-to="Arturo Bernal">Minor Improvements #701.</action>
160 <action type="update" dev="ggregory" due-to="Arturo Bernal">Minor Improvement: Add final variable.try to make the code read-only #700.</action>
161 <action type="update" dev="ggregory" due-to="Arturo Bernal">Minor Improvement: Remove redundant initializer #699.</action>
162 <action type="update" dev="ggregory" due-to="Arturo Bernal">Use own validator ObjectUtils.anyNull to check null String input #718.</action>
163 </release>
164 <release version="3.11" date="2020-07-12" description="New features and bug fixes (Java 8).">
48165 <action type="update" dev="chtompki" due-to="Jin Xu">Refine test output for FastDateParserTest</action>
49166 <action issue="LANG-1549" type="update" dev="chtompki" due-to="Jin Xu">CharSequenceUtils.lastIndexOf : remake it</action>
50167 <action type="update" dev="kinow" due-to="XenoAmess">remove encoding and docEncoding and use inherited values from commons-parent</action>
175292 <action issue="LANG-1422" type="add" dev="ggregory">Add null-safe StringUtils.valueOf(char[]) to delegate to String.valueOf(char[])</action>
176293 <action issue="LANG-1427" type="add" dev="ggregory">Add API org.apache.commons.lang3.SystemUtils.isJavaVersionAtMost(JavaVersion)</action>
177294 <action issue="LANG-1436" type="update" dev="aherbert">Consolidate the StringUtils equals and equalsIgnoreCase Javadoc and implementation</action>
178 <action type="update" dev="ggregory" due-to="Andrei Troie aft90">(doc) Fix javadoc for 'startIndex' parameter of StringUtils.join() methods. GitHub PR #412.</action>
295 <action type="update" dev="ggregory" due-to="Andrei Troie aft90">(doc) Fix javadoc for 'startIndex' parameter of StringUtils.join() methods. GitHub PR #412.</action>
179296 </release>
180297
181298 <release version="3.8.1" date="2018-09-19" description="This release is a bugfix for Restoring Bundle-SymbolicName in the MANIFEST.mf file.">
200317 <action issue="LANG-1352" type="add" dev="pschumacher" due-to="Ruslan Sibgatullin">EnumUtils.getEnumIgnoreCase and isValidEnumIgnoreCase methods added</action>
201318 <action issue="LANG-1372" type="add" dev="pschumacher" due-to="Sérgio Ozaki">Add ToStringSummary annotation</action>
202319 <action issue="LANG-1356" type="add" dev="pschumacher" due-to="Yathos UG">Add bypass option for classes to recursive and reflective EqualsBuilder</action>
203 <action issue="LANG-1391" type="add" dev="ggregory" due-to="Sauro Matulli, Oleg Chubaryov">Improve Javadoc for StringUtils.isAnyEmpty(null)</action>
204 <action issue="LANG-1393" type="add" dev="ggregory" due-to="Gary Gregory">Add API SystemUtils.String getEnvironmentVariable(final String name, final String defaultValue)</action>
205 <action issue="LANG-1394" type="add" dev="ggregory" due-to="Sebb, Gary Gregory">org.apache.commons.lang3.SystemUtils should not write to System.err.</action>
320 <action issue="LANG-1391" type="add" dev="ggregory" due-to="Sauro Matulli, Oleg Chubaryov">Improve Javadoc for StringUtils.isAnyEmpty(null)</action>
321 <action issue="LANG-1393" type="add" dev="ggregory" due-to="Gary Gregory">Add API SystemUtils.String getEnvironmentVariable(final String name, final String defaultValue)</action>
322 <action issue="LANG-1394" type="add" dev="ggregory" due-to="Sebb, Gary Gregory">org.apache.commons.lang3.SystemUtils should not write to System.err.</action>
206323 <action issue="LANG-1238" type="add" dev="ggregory" due-to="Christopher Cordeiro, Gary Gregory, Bruno P. Kinoshita, Oleg Chubaryov">Add RegexUtils class instead of overloading methods in StringUtils that take a regex to take precompiled Pattern.</action>
207324 <action issue="LANG-1390" type="add" dev="ggregory" due-to="Jochen Schalanda">StringUtils.join() with support for List&lt;?> with configurable start/end indices.</action>
208325 <action issue="LANG-1392" type="add" dev="pschumacher" due-to="Jeff Nelson">Methods for getting first non empty or non blank value</action>
137137
138138 ${project.url}
139139
140 Download page: ${project.url}download_csv.cgi
140 Download page: ${project.url}download_lang.cgi
141141
142142 Have fun!
143143 -Apache Commons Team
9999 public AnnotationUtils() {
100100 }
101101
102 //-----------------------------------------------------------------------
103102 /**
104103 * <p>Checks if two annotations are equal using the criteria for equality
105104 * presented in the {@link Annotation#equals(Object)} API docs.</p>
1717
1818 import java.util.HashMap;
1919 import java.util.Map;
20 import java.util.stream.Stream;
2120
2221 import org.apache.commons.lang3.arch.Processor;
22 import org.apache.commons.lang3.stream.Streams;
2323
2424 /**
2525 * An utility class for the os.arch System Property. The class defines methods for
100100 * @throws IllegalStateException If the key already exists.
101101 */
102102 private static void addProcessors(final Processor processor, final String... keys) {
103 Stream.of(keys).forEach(e -> addProcessor(e, processor));
103 Streams.of(keys).forEach(e -> addProcessor(e, processor));
104104 }
105105
106106 /**
0 /*
1 * Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package org.apache.commons.lang3;
17
18 import java.util.Arrays;
19 import java.util.Comparator;
20
21 /**
22 * Sorts and returns arrays in the fluent style.
23 *
24 * @since 3.12.0
25 */
26 public class ArraySorter {
27
28 /**
29 * Sorts and returns the given array.
30 *
31 * @param array the array to sort.
32 * @return the given array.
33 * @see Arrays#sort(byte[])
34 */
35 public static byte[] sort(final byte[] array) {
36 Arrays.sort(array);
37 return array;
38 }
39
40 /**
41 * Sorts and returns the given array.
42 *
43 * @param array the array to sort.
44 * @return the given array.
45 * @see Arrays#sort(char[])
46 */
47 public static char[] sort(final char[] array) {
48 Arrays.sort(array);
49 return array;
50 }
51
52 /**
53 * Sorts and returns the given array.
54 *
55 * @param array the array to sort.
56 * @return the given array.
57 * @see Arrays#sort(double[])
58 */
59 public static double[] sort(final double[] array) {
60 Arrays.sort(array);
61 return array;
62 }
63
64 /**
65 * Sorts and returns the given array.
66 *
67 * @param array the array to sort.
68 * @return the given array.
69 * @see Arrays#sort(float[])
70 */
71 public static float[] sort(final float[] array) {
72 Arrays.sort(array);
73 return array;
74 }
75
76 /**
77 * Sorts and returns the given array.
78 *
79 * @param array the array to sort.
80 * @return the given array.
81 * @see Arrays#sort(int[])
82 */
83 public static int[] sort(final int[] array) {
84 Arrays.sort(array);
85 return array;
86 }
87
88 /**
89 * Sorts and returns the given array.
90 *
91 * @param array the array to sort.
92 * @return the given array.
93 * @see Arrays#sort(long[])
94 */
95 public static long[] sort(final long[] array) {
96 Arrays.sort(array);
97 return array;
98 }
99
100 /**
101 * Sorts and returns the given array.
102 *
103 * @param array the array to sort.
104 * @return the given array.
105 * @see Arrays#sort(short[])
106 */
107 public static short[] sort(final short[] array) {
108 Arrays.sort(array);
109 return array;
110 }
111
112 /**
113 * Sorts and returns the given array.
114 *
115 * @param <T> the array type.
116 * @param array the array to sort.
117 * @return the given array.
118 * @see Arrays#sort(Object[])
119 */
120 public static <T> T[] sort(final T[] array) {
121 Arrays.sort(array);
122 return array;
123 }
124
125 /**
126 * Sorts and returns the given array.
127 *
128 * @param <T> the array type.
129 * @param array the array to sort.
130 * @param comparator the comparator to determine the order of the array. A {@code null} value uses the elements'
131 * {@link Comparable natural ordering}.
132 * @return the given array.
133 * @see Arrays#sort(Object[])
134 */
135 public static <T> T[] sort(final T[] array, final Comparator<? super T> comparator) {
136 Arrays.sort(array, comparator);
137 return array;
138 }
139
140 }
2525 import java.util.HashMap;
2626 import java.util.Map;
2727 import java.util.Random;
28 import java.util.concurrent.ThreadLocalRandom;
29 import java.util.function.IntFunction;
30 import java.util.function.Supplier;
2831
2932 import org.apache.commons.lang3.builder.EqualsBuilder;
3033 import org.apache.commons.lang3.builder.HashCodeBuilder;
3437 import org.apache.commons.lang3.mutable.MutableInt;
3538
3639 /**
37 * <p>Operations on arrays, primitive arrays (like {@code int[]}) and
40 * Operations on arrays, primitive arrays (like {@code int[]}) and
3841 * primitive wrapper arrays (like {@code Integer[]}).
39 *
40 * <p>This class tries to handle {@code null} input gracefully.
42 * <p>
43 * This class tries to handle {@code null} input gracefully.
4144 * An exception will not be thrown for a {@code null}
4245 * array input. However, an Object array that contains a {@code null}
4346 * element may throw an exception. Each method documents its behavior.
44 *
45 * <p>#ThreadSafe#
47 * </p>
48 * <p>
49 * #ThreadSafe#
50 * </p>
4651 * @since 2.0
4752 */
4853 public class ArrayUtils {
5055 /**
5156 * An empty immutable {@code boolean} array.
5257 */
53 public static final boolean[] EMPTY_BOOLEAN_ARRAY = new boolean[0];
58 public static final boolean[] EMPTY_BOOLEAN_ARRAY = {};
5459
5560 /**
5661 * An empty immutable {@code Boolean} array.
5762 */
58 public static final Boolean[] EMPTY_BOOLEAN_OBJECT_ARRAY = new Boolean[0];
63 public static final Boolean[] EMPTY_BOOLEAN_OBJECT_ARRAY = {};
5964
6065 /**
6166 * An empty immutable {@code byte} array.
6267 */
63 public static final byte[] EMPTY_BYTE_ARRAY = new byte[0];
68 public static final byte[] EMPTY_BYTE_ARRAY = {};
6469
6570 /**
6671 * An empty immutable {@code Byte} array.
6772 */
68 public static final Byte[] EMPTY_BYTE_OBJECT_ARRAY = new Byte[0];
73 public static final Byte[] EMPTY_BYTE_OBJECT_ARRAY = {};
6974
7075 /**
7176 * An empty immutable {@code char} array.
7277 */
73 public static final char[] EMPTY_CHAR_ARRAY = new char[0];
78 public static final char[] EMPTY_CHAR_ARRAY = {};
7479
7580 /**
7681 * An empty immutable {@code Character} array.
7782 */
78 public static final Character[] EMPTY_CHARACTER_OBJECT_ARRAY = new Character[0];
83 public static final Character[] EMPTY_CHARACTER_OBJECT_ARRAY = {};
7984
8085 /**
8186 * An empty immutable {@code Class} array.
8590 /**
8691 * An empty immutable {@code double} array.
8792 */
88 public static final double[] EMPTY_DOUBLE_ARRAY = new double[0];
93 public static final double[] EMPTY_DOUBLE_ARRAY = {};
8994
9095 /**
9196 * An empty immutable {@code Double} array.
9297 */
93 public static final Double[] EMPTY_DOUBLE_OBJECT_ARRAY = new Double[0];
98 public static final Double[] EMPTY_DOUBLE_OBJECT_ARRAY = {};
9499
95100 /**
96101 * An empty immutable {@code Field} array.
97102 *
98103 * @since 3.10
99104 */
100 public static final Field[] EMPTY_FIELD_ARRAY = new Field[0];
105 public static final Field[] EMPTY_FIELD_ARRAY = {};
101106
102107 /**
103108 * An empty immutable {@code float} array.
104109 */
105 public static final float[] EMPTY_FLOAT_ARRAY = new float[0];
110 public static final float[] EMPTY_FLOAT_ARRAY = {};
106111
107112 /**
108113 * An empty immutable {@code Float} array.
109114 */
110 public static final Float[] EMPTY_FLOAT_OBJECT_ARRAY = new Float[0];
115 public static final Float[] EMPTY_FLOAT_OBJECT_ARRAY = {};
111116
112117 /**
113118 * An empty immutable {@code int} array.
114119 */
115 public static final int[] EMPTY_INT_ARRAY = new int[0];
120 public static final int[] EMPTY_INT_ARRAY = {};
116121
117122 /**
118123 * An empty immutable {@code Integer} array.
119124 */
120 public static final Integer[] EMPTY_INTEGER_OBJECT_ARRAY = new Integer[0];
125 public static final Integer[] EMPTY_INTEGER_OBJECT_ARRAY = {};
121126
122127 /**
123128 * An empty immutable {@code long} array.
124129 */
125 public static final long[] EMPTY_LONG_ARRAY = new long[0];
130 public static final long[] EMPTY_LONG_ARRAY = {};
126131
127132 /**
128133 * An empty immutable {@code Long} array.
129134 */
130 public static final Long[] EMPTY_LONG_OBJECT_ARRAY = new Long[0];
135 public static final Long[] EMPTY_LONG_OBJECT_ARRAY = {};
131136
132137 /**
133138 * An empty immutable {@code Method} array.
134139 *
135140 * @since 3.10
136141 */
137 public static final Method[] EMPTY_METHOD_ARRAY = new Method[0];
142 public static final Method[] EMPTY_METHOD_ARRAY = {};
138143
139144 /**
140145 * An empty immutable {@code Object} array.
141146 */
142 public static final Object[] EMPTY_OBJECT_ARRAY = new Object[0];
147 public static final Object[] EMPTY_OBJECT_ARRAY = {};
143148
144149 /**
145150 * An empty immutable {@code short} array.
146151 */
147 public static final short[] EMPTY_SHORT_ARRAY = new short[0];
152 public static final short[] EMPTY_SHORT_ARRAY = {};
148153
149154 /**
150155 * An empty immutable {@code Short} array.
151156 */
152 public static final Short[] EMPTY_SHORT_OBJECT_ARRAY = new Short[0];
157 public static final Short[] EMPTY_SHORT_OBJECT_ARRAY = {};
153158
154159 /**
155160 * An empty immutable {@code String} array.
156161 */
157 public static final String[] EMPTY_STRING_ARRAY = new String[0];
162 public static final String[] EMPTY_STRING_ARRAY = {};
158163
159164 /**
160165 * An empty immutable {@code Throwable} array.
161166 *
162167 * @since 3.10
163168 */
164 public static final Throwable[] EMPTY_THROWABLE_ARRAY = new Throwable[0];
169 public static final Throwable[] EMPTY_THROWABLE_ARRAY = {};
165170
166171 /**
167172 * An empty immutable {@code Type} array.
168173 *
169174 * @since 3.10
170175 */
171 public static final Type[] EMPTY_TYPE_ARRAY = new Type[0];
176 public static final Type[] EMPTY_TYPE_ARRAY = {};
172177
173178 /**
174179 * The index value when an element is not found in a list or array: {@code -1}.
178183 public static final int INDEX_NOT_FOUND = -1;
179184
180185 /**
181 * <p>Copies the given array and adds the given element at the end of the new array.
182 *
183 * <p>The new array contains the same elements of the input
186 * Copies the given array and adds the given element at the end of the new array.
187 * <p>
188 * The new array contains the same elements of the input
184189 * array plus the given element in the last position. The component type of
185190 * the new array is the same as that of the input array.
186 *
187 * <p>If the input array is {@code null}, a new one element array is returned
188 * whose component type is the same as the element.
189 *
191 * </p>
192 * <p>
193 * If the input array is {@code null}, a new one element array is returned
194 * whose component type is the same as the element.
195 * </p>
190196 * <pre>
191197 * ArrayUtils.add(null, true) = [true]
192198 * ArrayUtils.add([true], false) = [true, false]
205211 }
206212
207213 /**
208 * <p>Inserts the specified element at the specified position in the array.
214 * Inserts the specified element at the specified position in the array.
209215 * Shifts the element currently at that position (if any) and any subsequent
210216 * elements to the right (adds one to their indices).
211 *
212 * <p>This method returns a new array with the same elements of the input
217 * <p>
218 * This method returns a new array with the same elements of the input
213219 * array plus the given element on the specified position. The component
214220 * type of the returned array is always the same as that of the input
215221 * array.
216 *
217 * <p>If the input array is {@code null}, a new one element array is returned
218 * whose component type is the same as the element.
219 *
222 * </p>
223 * <p>
224 * If the input array is {@code null}, a new one element array is returned
225 * whose component type is the same as the element.
226 * </p>
220227 * <pre>
221228 * ArrayUtils.add(null, 0, true) = [true]
222229 * ArrayUtils.add([true], 0, false) = [false, true]
239246 }
240247
241248 /**
242 * <p>Copies the given array and adds the given element at the end of the new array.
243 *
244 * <p>The new array contains the same elements of the input
249 * Copies the given array and adds the given element at the end of the new array.
250 * <p>
251 * The new array contains the same elements of the input
245252 * array plus the given element in the last position. The component type of
246253 * the new array is the same as that of the input array.
247 *
248 * <p>If the input array is {@code null}, a new one element array is returned
249 * whose component type is the same as the element.
250 *
254 * </p>
255 * <p>
256 * If the input array is {@code null}, a new one element array is returned
257 * whose component type is the same as the element.
258 * </p>
251259 * <pre>
252260 * ArrayUtils.add(null, 0) = [0]
253261 * ArrayUtils.add([1], 0) = [1, 0]
266274 }
267275
268276 /**
269 * <p>Inserts the specified element at the specified position in the array.
277 * Inserts the specified element at the specified position in the array.
270278 * Shifts the element currently at that position (if any) and any subsequent
271279 * elements to the right (adds one to their indices).
272 *
273 * <p>This method returns a new array with the same elements of the input
280 * <p>
281 * This method returns a new array with the same elements of the input
274282 * array plus the given element on the specified position. The component
275283 * type of the returned array is always the same as that of the input
276284 * array.
277 *
278 * <p>If the input array is {@code null}, a new one element array is returned
279 * whose component type is the same as the element.
280 *
285 * </p>
286 * <p>
287 * If the input array is {@code null}, a new one element array is returned
288 * whose component type is the same as the element.
289 * </p>
281290 * <pre>
282291 * ArrayUtils.add([1], 0, 2) = [2, 1]
283292 * ArrayUtils.add([2, 6], 2, 3) = [2, 6, 3]
301310 }
302311
303312 /**
304 * <p>Copies the given array and adds the given element at the end of the new array.
305 *
306 * <p>The new array contains the same elements of the input
313 * Copies the given array and adds the given element at the end of the new array.
314 * <p>
315 * The new array contains the same elements of the input
307316 * array plus the given element in the last position. The component type of
308317 * the new array is the same as that of the input array.
309 *
310 * <p>If the input array is {@code null}, a new one element array is returned
311 * whose component type is the same as the element.
312 *
318 * </p>
319 * <p>
320 * If the input array is {@code null}, a new one element array is returned
321 * whose component type is the same as the element.
322 * </p>
313323 * <pre>
314324 * ArrayUtils.add(null, '0') = ['0']
315325 * ArrayUtils.add(['1'], '0') = ['1', '0']
328338 }
329339
330340 /**
331 * <p>Inserts the specified element at the specified position in the array.
341 * Inserts the specified element at the specified position in the array.
332342 * Shifts the element currently at that position (if any) and any subsequent
333343 * elements to the right (adds one to their indices).
334 *
335 * <p>This method returns a new array with the same elements of the input
344 * <p>
345 * This method returns a new array with the same elements of the input
336346 * array plus the given element on the specified position. The component
337347 * type of the returned array is always the same as that of the input
338348 * array.
339 *
340 * <p>If the input array is {@code null}, a new one element array is returned
341 * whose component type is the same as the element.
342 *
349 * </p>
350 * <p>
351 * If the input array is {@code null}, a new one element array is returned
352 * whose component type is the same as the element.
353 * </p>
343354 * <pre>
344355 * ArrayUtils.add(null, 0, 'a') = ['a']
345356 * ArrayUtils.add(['a'], 0, 'b') = ['b', 'a']
364375 }
365376
366377 /**
367 * <p>Copies the given array and adds the given element at the end of the new array.
368 *
369 * <p>The new array contains the same elements of the input
378 * Copies the given array and adds the given element at the end of the new array.
379 *
380 * <p>
381 * The new array contains the same elements of the input
370382 * array plus the given element in the last position. The component type of
371383 * the new array is the same as that of the input array.
372 *
373 * <p>If the input array is {@code null}, a new one element array is returned
374 * whose component type is the same as the element.
375 *
384 * </p>
385 * <p>
386 * If the input array is {@code null}, a new one element array is returned
387 * whose component type is the same as the element.
388 * </p>
376389 * <pre>
377390 * ArrayUtils.add(null, 0) = [0]
378391 * ArrayUtils.add([1], 0) = [1, 0]
391404 }
392405
393406 /**
394 * <p>Inserts the specified element at the specified position in the array.
407 * Inserts the specified element at the specified position in the array.
395408 * Shifts the element currently at that position (if any) and any subsequent
396409 * elements to the right (adds one to their indices).
397 *
398 * <p>This method returns a new array with the same elements of the input
410 * <p>
411 * This method returns a new array with the same elements of the input
399412 * array plus the given element on the specified position. The component
400413 * type of the returned array is always the same as that of the input
401414 * array.
402 *
403 * <p>If the input array is {@code null}, a new one element array is returned
404 * whose component type is the same as the element.
405 *
415 * </p>
416 * <p>
417 * If the input array is {@code null}, a new one element array is returned
418 * whose component type is the same as the element.
419 * </p>
406420 * <pre>
407421 * ArrayUtils.add([1.1], 0, 2.2) = [2.2, 1.1]
408422 * ArrayUtils.add([2.3, 6.4], 2, 10.5) = [2.3, 6.4, 10.5]
426440 }
427441
428442 /**
429 * <p>Copies the given array and adds the given element at the end of the new array.
430 *
431 * <p>The new array contains the same elements of the input
443 * Copies the given array and adds the given element at the end of the new array.
444 * <p>
445 * The new array contains the same elements of the input
432446 * array plus the given element in the last position. The component type of
433447 * the new array is the same as that of the input array.
434 *
435 * <p>If the input array is {@code null}, a new one element array is returned
436 * whose component type is the same as the element.
437 *
448 * </p>
449 * <p>
450 * If the input array is {@code null}, a new one element array is returned
451 * whose component type is the same as the element.
452 * </p>
438453 * <pre>
439454 * ArrayUtils.add(null, 0) = [0]
440455 * ArrayUtils.add([1], 0) = [1, 0]
453468 }
454469
455470 /**
456 * <p>Inserts the specified element at the specified position in the array.
471 * Inserts the specified element at the specified position in the array.
457472 * Shifts the element currently at that position (if any) and any subsequent
458473 * elements to the right (adds one to their indices).
459 *
460 * <p>This method returns a new array with the same elements of the input
474 * <p>
475 * This method returns a new array with the same elements of the input
461476 * array plus the given element on the specified position. The component
462477 * type of the returned array is always the same as that of the input
463478 * array.
464 *
465 * <p>If the input array is {@code null}, a new one element array is returned
466 * whose component type is the same as the element.
467 *
479 * </p>
480 * <p>
481 * If the input array is {@code null}, a new one element array is returned
482 * whose component type is the same as the element.
483 * </p>
468484 * <pre>
469485 * ArrayUtils.add([1.1f], 0, 2.2f) = [2.2f, 1.1f]
470486 * ArrayUtils.add([2.3f, 6.4f], 2, 10.5f) = [2.3f, 6.4f, 10.5f]
488504 }
489505
490506 /**
491 * <p>Copies the given array and adds the given element at the end of the new array.
492 *
493 * <p>The new array contains the same elements of the input
507 * Copies the given array and adds the given element at the end of the new array.
508 * <p>
509 * The new array contains the same elements of the input
494510 * array plus the given element in the last position. The component type of
495511 * the new array is the same as that of the input array.
496 *
497 * <p>If the input array is {@code null}, a new one element array is returned
498 * whose component type is the same as the element.
499 *
512 * </p>
513 * <p>
514 * If the input array is {@code null}, a new one element array is returned
515 * whose component type is the same as the element.
516 * </p>
500517 * <pre>
501518 * ArrayUtils.add(null, 0) = [0]
502519 * ArrayUtils.add([1], 0) = [1, 0]
515532 }
516533
517534 /**
518 * <p>Inserts the specified element at the specified position in the array.
535 * Inserts the specified element at the specified position in the array.
519536 * Shifts the element currently at that position (if any) and any subsequent
520537 * elements to the right (adds one to their indices).
521 *
522 * <p>This method returns a new array with the same elements of the input
538 * <p>
539 * This method returns a new array with the same elements of the input
523540 * array plus the given element on the specified position. The component
524541 * type of the returned array is always the same as that of the input
525542 * array.
526 *
527 * <p>If the input array is {@code null}, a new one element array is returned
528 * whose component type is the same as the element.
529 *
543 * </p>
544 * <p>
545 * If the input array is {@code null}, a new one element array is returned
546 * whose component type is the same as the element.
547 * </p>
530548 * <pre>
531549 * ArrayUtils.add([1], 0, 2) = [2, 1]
532550 * ArrayUtils.add([2, 6], 2, 10) = [2, 6, 10]
550568 }
551569
552570 /**
553 * <p>Inserts the specified element at the specified position in the array.
571 * Inserts the specified element at the specified position in the array.
554572 * Shifts the element currently at that position (if any) and any subsequent
555573 * elements to the right (adds one to their indices).
556 *
557 * <p>This method returns a new array with the same elements of the input
574 * <p>
575 * This method returns a new array with the same elements of the input
558576 * array plus the given element on the specified position. The component
559577 * type of the returned array is always the same as that of the input
560578 * array.
561 *
562 * <p>If the input array is {@code null}, a new one element array is returned
563 * whose component type is the same as the element.
564 *
579 * </p>
580 * <p>
581 * If the input array is {@code null}, a new one element array is returned
582 * whose component type is the same as the element.
583 * </p>
565584 * <pre>
566585 * ArrayUtils.add([1L], 0, 2L) = [2L, 1L]
567586 * ArrayUtils.add([2L, 6L], 2, 10L) = [2L, 6L, 10L]
585604 }
586605
587606 /**
588 * <p>Copies the given array and adds the given element at the end of the new array.
589 *
590 * <p>The new array contains the same elements of the input
607 * Copies the given array and adds the given element at the end of the new array.
608 * <p>
609 * The new array contains the same elements of the input
591610 * array plus the given element in the last position. The component type of
592611 * the new array is the same as that of the input array.
593 *
594 * <p>If the input array is {@code null}, a new one element array is returned
595 * whose component type is the same as the element.
596 *
612 * </p>
613 * <p>
614 * If the input array is {@code null}, a new one element array is returned
615 * whose component type is the same as the element.
616 * </p>
597617 * <pre>
598618 * ArrayUtils.add(null, 0) = [0]
599619 * ArrayUtils.add([1], 0) = [1, 0]
645665 }
646666
647667 /**
648 * <p>Inserts the specified element at the specified position in the array.
668 * Inserts the specified element at the specified position in the array.
649669 * Shifts the element currently at that position (if any) and any subsequent
650670 * elements to the right (adds one to their indices).
651 *
652 * <p>This method returns a new array with the same elements of the input
671 * <p>
672 * This method returns a new array with the same elements of the input
653673 * array plus the given element on the specified position. The component
654674 * type of the returned array is always the same as that of the input
655675 * array.
656 *
657 * <p>If the input array is {@code null}, a new one element array is returned
658 * whose component type is the same as the element.
659 *
676 * </p>
677 * <p>
678 * If the input array is {@code null}, a new one element array is returned
679 * whose component type is the same as the element.
680 * </p>
660681 * <pre>
661682 * ArrayUtils.add([1], 0, 2) = [2, 1]
662683 * ArrayUtils.add([2, 6], 2, 10) = [2, 6, 10]
680701 }
681702
682703 /**
683 * <p>Copies the given array and adds the given element at the end of the new array.
684 *
685 * <p>The new array contains the same elements of the input
704 * Copies the given array and adds the given element at the end of the new array.
705 * <p>
706 * The new array contains the same elements of the input
686707 * array plus the given element in the last position. The component type of
687708 * the new array is the same as that of the input array.
688 *
689 * <p>If the input array is {@code null}, a new one element array is returned
690 * whose component type is the same as the element.
691 *
709 * </p>
710 * <p>
711 * If the input array is {@code null}, a new one element array is returned
712 * whose component type is the same as the element.
713 * </p>
692714 * <pre>
693715 * ArrayUtils.add(null, 0) = [0]
694716 * ArrayUtils.add([1], 0) = [1, 0]
706728 return newArray;
707729 }
708730
709
710 /**
711 * <p>Inserts the specified element at the specified position in the array.
731 /**
732 * Inserts the specified element at the specified position in the array.
712733 * Shifts the element currently at that position (if any) and any subsequent
713734 * elements to the right (adds one to their indices).
714 *
715 * <p>This method returns a new array with the same elements of the input
735 * <p>
736 * This method returns a new array with the same elements of the input
716737 * array plus the given element on the specified position. The component
717738 * type of the returned array is always the same as that of the input
718739 * array.
719 *
720 * <p>If the input array is {@code null}, a new one element array is returned
721 * whose component type is the same as the element.
722 *
740 * </p>
741 * <p>
742 * If the input array is {@code null}, a new one element array is returned
743 * whose component type is the same as the element.
744 * </p>
723745 * <pre>
724746 * ArrayUtils.add(null, 0, null) = IllegalArgumentException
725747 * ArrayUtils.add(null, 0, "a") = ["a"]
741763 */
742764 @Deprecated
743765 public static <T> T[] add(final T[] array, final int index, final T element) {
744 Class<?> clss = null;
766 Class<T> clss = null;
745767 if (array != null) {
746 clss = array.getClass().getComponentType();
768 clss = getComponentType(array);
747769 } else if (element != null) {
748 clss = element.getClass();
770 clss = ObjectUtils.getClass(element);
749771 } else {
750772 throw new IllegalArgumentException("Array and element cannot both be null");
751773 }
752 @SuppressWarnings("unchecked") // the add method creates an array of type clss, which is type T
753 final T[] newArray = (T[]) add(array, index, element, clss);
754 return newArray;
755 }
756
757 /**
758 * <p>Copies the given array and adds the given element at the end of the new array.
759 *
760 * <p>The new array contains the same elements of the input
774 return (T[]) add(array, index, element, clss);
775 }
776
777
778 /**
779 * Copies the given array and adds the given element at the end of the new array.
780 * <p>
781 * The new array contains the same elements of the input
761782 * array plus the given element in the last position. The component type of
762783 * the new array is the same as that of the input array.
763 *
764 * <p>If the input array is {@code null}, a new one element array is returned
765 * whose component type is the same as the element, unless the element itself is null,
766 * in which case the return type is Object[]
767 *
784 * </p>
785 * <p>
786 * If the input array is {@code null}, a new one element array is returned
787 * whose component type is the same as the element, unless the element itself is null,
788 * in which case the return type is Object[]
789 * </p>
768790 * <pre>
769791 * ArrayUtils.add(null, null) = IllegalArgumentException
770792 * ArrayUtils.add(null, "a") = ["a"]
784806 * @throws IllegalArgumentException if both arguments are null
785807 */
786808 public static <T> T[] add(final T[] array, final T element) {
787 Class<?> type;
809 final Class<?> type;
788810 if (array != null) {
789811 type = array.getClass().getComponentType();
790812 } else if (element != null) {
800822 }
801823
802824 /**
803 * <p>Adds all the elements of the given arrays into a new array.
804 * <p>The new array contains all of the element of {@code array1} followed
825 * Adds all the elements of the given arrays into a new array.
826 * <p>
827 * The new array contains all of the element of {@code array1} followed
805828 * by all of the elements {@code array2}. When an array is returned, it is always
806829 * a new array.
807 *
830 * </p>
808831 * <pre>
809832 * ArrayUtils.addAll(array1, null) = cloned copy of array1
810833 * ArrayUtils.addAll(null, array2) = cloned copy of array2
819842 public static boolean[] addAll(final boolean[] array1, final boolean... array2) {
820843 if (array1 == null) {
821844 return clone(array2);
822 } else if (array2 == null) {
845 }
846 if (array2 == null) {
823847 return clone(array1);
824848 }
825849 final boolean[] joinedArray = new boolean[array1.length + array2.length];
829853 }
830854
831855 /**
832 * <p>Adds all the elements of the given arrays into a new array.
833 * <p>The new array contains all of the element of {@code array1} followed
856 * Adds all the elements of the given arrays into a new array.
857 * <p>
858 * The new array contains all of the element of {@code array1} followed
834859 * by all of the elements {@code array2}. When an array is returned, it is always
835860 * a new array.
836 *
861 * </p>
837862 * <pre>
838863 * ArrayUtils.addAll(array1, null) = cloned copy of array1
839864 * ArrayUtils.addAll(null, array2) = cloned copy of array2
848873 public static byte[] addAll(final byte[] array1, final byte... array2) {
849874 if (array1 == null) {
850875 return clone(array2);
851 } else if (array2 == null) {
876 }
877 if (array2 == null) {
852878 return clone(array1);
853879 }
854880 final byte[] joinedArray = new byte[array1.length + array2.length];
858884 }
859885
860886 /**
861 * <p>Adds all the elements of the given arrays into a new array.
862 * <p>The new array contains all of the element of {@code array1} followed
887 * Adds all the elements of the given arrays into a new array.
888 * <p>
889 * The new array contains all of the element of {@code array1} followed
863890 * by all of the elements {@code array2}. When an array is returned, it is always
864891 * a new array.
865 *
892 * </p>
866893 * <pre>
867894 * ArrayUtils.addAll(array1, null) = cloned copy of array1
868895 * ArrayUtils.addAll(null, array2) = cloned copy of array2
877904 public static char[] addAll(final char[] array1, final char... array2) {
878905 if (array1 == null) {
879906 return clone(array2);
880 } else if (array2 == null) {
907 }
908 if (array2 == null) {
881909 return clone(array1);
882910 }
883911 final char[] joinedArray = new char[array1.length + array2.length];
887915 }
888916
889917 /**
890 * <p>Adds all the elements of the given arrays into a new array.
891 * <p>The new array contains all of the element of {@code array1} followed
918 * Adds all the elements of the given arrays into a new array.
919 * <p>
920 * The new array contains all of the element of {@code array1} followed
892921 * by all of the elements {@code array2}. When an array is returned, it is always
893922 * a new array.
894 *
923 * </p>
895924 * <pre>
896925 * ArrayUtils.addAll(array1, null) = cloned copy of array1
897926 * ArrayUtils.addAll(null, array2) = cloned copy of array2
906935 public static double[] addAll(final double[] array1, final double... array2) {
907936 if (array1 == null) {
908937 return clone(array2);
909 } else if (array2 == null) {
938 }
939 if (array2 == null) {
910940 return clone(array1);
911941 }
912942 final double[] joinedArray = new double[array1.length + array2.length];
916946 }
917947
918948 /**
919 * <p>Adds all the elements of the given arrays into a new array.
920 * <p>The new array contains all of the element of {@code array1} followed
949 * Adds all the elements of the given arrays into a new array.
950 * <p>
951 * The new array contains all of the element of {@code array1} followed
921952 * by all of the elements {@code array2}. When an array is returned, it is always
922953 * a new array.
923 *
954 * </p>
924955 * <pre>
925956 * ArrayUtils.addAll(array1, null) = cloned copy of array1
926957 * ArrayUtils.addAll(null, array2) = cloned copy of array2
935966 public static float[] addAll(final float[] array1, final float... array2) {
936967 if (array1 == null) {
937968 return clone(array2);
938 } else if (array2 == null) {
969 }
970 if (array2 == null) {
939971 return clone(array1);
940972 }
941973 final float[] joinedArray = new float[array1.length + array2.length];
945977 }
946978
947979 /**
948 * <p>Adds all the elements of the given arrays into a new array.
949 * <p>The new array contains all of the element of {@code array1} followed
980 * Adds all the elements of the given arrays into a new array.
981 * <p>
982 * The new array contains all of the element of {@code array1} followed
950983 * by all of the elements {@code array2}. When an array is returned, it is always
951984 * a new array.
952 *
985 * </p>
953986 * <pre>
954987 * ArrayUtils.addAll(array1, null) = cloned copy of array1
955988 * ArrayUtils.addAll(null, array2) = cloned copy of array2
964997 public static int[] addAll(final int[] array1, final int... array2) {
965998 if (array1 == null) {
966999 return clone(array2);
967 } else if (array2 == null) {
1000 }
1001 if (array2 == null) {
9681002 return clone(array1);
9691003 }
9701004 final int[] joinedArray = new int[array1.length + array2.length];
9741008 }
9751009
9761010 /**
977 * <p>Adds all the elements of the given arrays into a new array.
978 * <p>The new array contains all of the element of {@code array1} followed
1011 * Adds all the elements of the given arrays into a new array.
1012 * <p>
1013 * The new array contains all of the element of {@code array1} followed
9791014 * by all of the elements {@code array2}. When an array is returned, it is always
9801015 * a new array.
981 *
1016 * </p>
9821017 * <pre>
9831018 * ArrayUtils.addAll(array1, null) = cloned copy of array1
9841019 * ArrayUtils.addAll(null, array2) = cloned copy of array2
9931028 public static long[] addAll(final long[] array1, final long... array2) {
9941029 if (array1 == null) {
9951030 return clone(array2);
996 } else if (array2 == null) {
1031 }
1032 if (array2 == null) {
9971033 return clone(array1);
9981034 }
9991035 final long[] joinedArray = new long[array1.length + array2.length];
10031039 }
10041040
10051041 /**
1006 * <p>Adds all the elements of the given arrays into a new array.
1007 * <p>The new array contains all of the element of {@code array1} followed
1042 * Adds all the elements of the given arrays into a new array.
1043 * <p>
1044 * The new array contains all of the element of {@code array1} followed
10081045 * by all of the elements {@code array2}. When an array is returned, it is always
10091046 * a new array.
1010 *
1047 * </p>
10111048 * <pre>
10121049 * ArrayUtils.addAll(array1, null) = cloned copy of array1
10131050 * ArrayUtils.addAll(null, array2) = cloned copy of array2
10221059 public static short[] addAll(final short[] array1, final short... array2) {
10231060 if (array1 == null) {
10241061 return clone(array2);
1025 } else if (array2 == null) {
1062 }
1063 if (array2 == null) {
10261064 return clone(array1);
10271065 }
10281066 final short[] joinedArray = new short[array1.length + array2.length];
10321070 }
10331071
10341072 /**
1035 * <p>Adds all the elements of the given arrays into a new array.
1036 * <p>The new array contains all of the element of {@code array1} followed
1073 * Adds all the elements of the given arrays into a new array.
1074 * <p>
1075 * The new array contains all of the element of {@code array1} followed
10371076 * by all of the elements {@code array2}. When an array is returned, it is always
10381077 * a new array.
1039 *
1078 * </p>
10401079 * <pre>
10411080 * ArrayUtils.addAll(null, null) = null
10421081 * ArrayUtils.addAll(array1, null) = cloned copy of array1
10581097 public static <T> T[] addAll(final T[] array1, @SuppressWarnings("unchecked") final T... array2) {
10591098 if (array1 == null) {
10601099 return clone(array2);
1061 } else if (array2 == null) {
1100 }
1101 if (array2 == null) {
10621102 return clone(array1);
10631103 }
1064 final Class<?> type1 = array1.getClass().getComponentType();
1065 @SuppressWarnings("unchecked") // OK, because array is of type T
1066 final T[] joinedArray = (T[]) Array.newInstance(type1, array1.length + array2.length);
1104 final Class<T> type1 = getComponentType(array1);
1105 final T[] joinedArray = newInstance(type1, array1.length + array2.length);
10671106 System.arraycopy(array1, 0, joinedArray, 0, array1.length);
10681107 try {
10691108 System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);
10861125
10871126 /**
10881127 * Copies the given array and adds the given element at the beginning of the new array.
1089 *
10901128 * <p>
10911129 * The new array contains the same elements of the input array plus the given element in the first position. The
10921130 * component type of the new array is the same as that of the input array.
10931131 * </p>
1094 *
10951132 * <p>
10961133 * If the input array is {@code null}, a new one element array is returned whose component type is the same as the
10971134 * element.
10981135 * </p>
1099 *
11001136 * <pre>
1101 * ArrayUtils.add(null, true) = [true]
1102 * ArrayUtils.add([true], false) = [false, true]
1103 * ArrayUtils.add([true, false], true) = [true, true, false]
1137 * ArrayUtils.addFirst(null, true) = [true]
1138 * ArrayUtils.addFirst([true], false) = [false, true]
1139 * ArrayUtils.addFirst([true, false], true) = [true, true, false]
11041140 * </pre>
11051141 *
11061142 * @param array the array to "add" the element to, may be {@code null}.
11151151
11161152 /**
11171153 * Copies the given array and adds the given element at the beginning of the new array.
1118 *
11191154 * <p>
11201155 * The new array contains the same elements of the input array plus the given element in the first position. The
11211156 * component type of the new array is the same as that of the input array.
11221157 * </p>
1123 *
11241158 * <p>
11251159 * If the input array is {@code null}, a new one element array is returned whose component type is the same as the
11261160 * element.
11271161 * </p>
1128 *
11291162 * <pre>
1130 * ArrayUtils.add(null, 1) = [1]
1131 * ArrayUtils.add([1], 0) = [0, 1]
1132 * ArrayUtils.add([1, 0], 1) = [1, 1, 0]
1163 * ArrayUtils.addFirst(null, 1) = [1]
1164 * ArrayUtils.addFirst([1], 0) = [0, 1]
1165 * ArrayUtils.addFirst([1, 0], 1) = [1, 1, 0]
11331166 * </pre>
11341167 *
11351168 * @param array the array to "add" the element to, may be {@code null}.
11441177
11451178 /**
11461179 * Copies the given array and adds the given element at the beginning of the new array.
1147 *
11481180 * <p>
11491181 * The new array contains the same elements of the input array plus the given element in the first position. The
11501182 * component type of the new array is the same as that of the input array.
11511183 * </p>
1152 *
11531184 * <p>
11541185 * If the input array is {@code null}, a new one element array is returned whose component type is the same as the
11551186 * element.
11561187 * </p>
1157 *
11581188 * <pre>
1159 * ArrayUtils.add(null, '1') = ['1']
1160 * ArrayUtils.add(['1'], '0') = ['0', '1']
1161 * ArrayUtils.add(['1', '0'], '1') = ['1', '1', '0']
1189 * ArrayUtils.addFirst(null, '1') = ['1']
1190 * ArrayUtils.addFirst(['1'], '0') = ['0', '1']
1191 * ArrayUtils.addFirst(['1', '0'], '1') = ['1', '1', '0']
11621192 * </pre>
11631193 *
11641194 * @param array the array to "add" the element to, may be {@code null}.
11731203
11741204 /**
11751205 * Copies the given array and adds the given element at the beginning of the new array.
1176 *
11771206 * <p>
11781207 * The new array contains the same elements of the input array plus the given element in the first position. The
11791208 * component type of the new array is the same as that of the input array.
11801209 * </p>
1181 *
11821210 * <p>
11831211 * If the input array is {@code null}, a new one element array is returned whose component type is the same as the
11841212 * element.
11851213 * </p>
1186 *
11871214 * <pre>
1188 * ArrayUtils.add(null, 1) = [1]
1189 * ArrayUtils.add([1], 0) = [0, 1]
1190 * ArrayUtils.add([1, 0], 1) = [1, 1, 0]
1215 * ArrayUtils.addFirst(null, 1) = [1]
1216 * ArrayUtils.addFirst([1], 0) = [0, 1]
1217 * ArrayUtils.addFirst([1, 0], 1) = [1, 1, 0]
11911218 * </pre>
11921219 *
11931220 * @param array the array to "add" the element to, may be {@code null}.
12021229
12031230 /**
12041231 * Copies the given array and adds the given element at the beginning of the new array.
1205 *
12061232 * <p>
12071233 * The new array contains the same elements of the input array plus the given element in the first position. The
12081234 * component type of the new array is the same as that of the input array.
12091235 * </p>
1210 *
12111236 * <p>
12121237 * If the input array is {@code null}, a new one element array is returned whose component type is the same as the
12131238 * element.
12141239 * </p>
1215 *
12161240 * <pre>
1217 * ArrayUtils.add(null, 1) = [1]
1218 * ArrayUtils.add([1], 0) = [0, 1]
1219 * ArrayUtils.add([1, 0], 1) = [1, 1, 0]
1241 * ArrayUtils.addFirst(null, 1) = [1]
1242 * ArrayUtils.addFirst([1], 0) = [0, 1]
1243 * ArrayUtils.addFirst([1, 0], 1) = [1, 1, 0]
12201244 * </pre>
12211245 *
12221246 * @param array the array to "add" the element to, may be {@code null}.
12311255
12321256 /**
12331257 * Copies the given array and adds the given element at the beginning of the new array.
1234 *
12351258 * <p>
12361259 * The new array contains the same elements of the input array plus the given element in the first position. The
12371260 * component type of the new array is the same as that of the input array.
12381261 * </p>
1239 *
12401262 * <p>
12411263 * If the input array is {@code null}, a new one element array is returned whose component type is the same as the
12421264 * element.
12431265 * </p>
1244 *
12451266 * <pre>
1246 * ArrayUtils.add(null, 1) = [1]
1247 * ArrayUtils.add([1], 0) = [0, 1]
1248 * ArrayUtils.add([1, 0], 1) = [1, 1, 0]
1267 * ArrayUtils.addFirst(null, 1) = [1]
1268 * ArrayUtils.addFirst([1], 0) = [0, 1]
1269 * ArrayUtils.addFirst([1, 0], 1) = [1, 1, 0]
12491270 * </pre>
12501271 *
12511272 * @param array the array to "add" the element to, may be {@code null}.
12601281
12611282 /**
12621283 * Copies the given array and adds the given element at the beginning of the new array.
1263 *
12641284 * <p>
12651285 * The new array contains the same elements of the input array plus the given element in the first position. The
12661286 * component type of the new array is the same as that of the input array.
12671287 * </p>
1268 *
12691288 * <p>
12701289 * If the input array is {@code null}, a new one element array is returned whose component type is the same as the
12711290 * element.
12721291 * </p>
1273 *
12741292 * <pre>
1275 * ArrayUtils.add(null, 1) = [1]
1276 * ArrayUtils.add([1], 0) = [0, 1]
1277 * ArrayUtils.add([1, 0], 1) = [1, 1, 0]
1293 * ArrayUtils.addFirst(null, 1) = [1]
1294 * ArrayUtils.addFirst([1], 0) = [0, 1]
1295 * ArrayUtils.addFirst([1, 0], 1) = [1, 1, 0]
12781296 * </pre>
12791297 *
12801298 * @param array the array to "add" the element to, may be {@code null}.
12891307
12901308 /**
12911309 * Copies the given array and adds the given element at the beginning of the new array.
1292 *
12931310 * <p>
12941311 * The new array contains the same elements of the input array plus the given element in the first position. The
12951312 * component type of the new array is the same as that of the input array.
12961313 * </p>
1297 *
12981314 * <p>
12991315 * If the input array is {@code null}, a new one element array is returned whose component type is the same as the
13001316 * element.
13011317 * </p>
1302 *
13031318 * <pre>
1304 * ArrayUtils.add(null, 1) = [1]
1305 * ArrayUtils.add([1], 0) = [0, 1]
1306 * ArrayUtils.add([1, 0], 1) = [1, 1, 0]
1319 * ArrayUtils.addFirst(null, 1) = [1]
1320 * ArrayUtils.addFirst([1], 0) = [0, 1]
1321 * ArrayUtils.addFirst([1, 0], 1) = [1, 1, 0]
13071322 * </pre>
13081323 *
13091324 * @param array the array to "add" the element to, may be {@code null}.
13181333
13191334 /**
13201335 * Copies the given array and adds the given element at the beginning of the new array.
1321 *
13221336 * <p>
13231337 * The new array contains the same elements of the input array plus the given element in the first positioaddFirstaddFirstaddFirstn. The
13241338 * component type of the new array is the same as that of the input array.
13251339 * </p>
1326 *
13271340 * <p>
13281341 * If the input array is {@code null}, a new one element array is returned whose component type is the same as the
13291342 * element, unless the element itself is null, in which case the return type is Object[]
13301343 * </p>
1331 *
13321344 * <pre>
1333 * ArrayUtils.add(null, null) = IllegalArgumentException
1334 * ArrayUtils.add(null, "a") = ["a"]
1335 * ArrayUtils.add(["a"], null) = [null, "a"]
1336 * ArrayUtils.add(["a"], "b") = ["b", "a"]
1337 * ArrayUtils.add(["a", "b"], "c") = ["c", "a", "b"]
1345 * ArrayUtils.addFirst(null, null) = IllegalArgumentException
1346 * ArrayUtils.addFirst(null, "a") = ["a"]
1347 * ArrayUtils.addFirst(["a"], null) = [null, "a"]
1348 * ArrayUtils.addFirst(["a"], "b") = ["b", "a"]
1349 * ArrayUtils.addFirst(["a", "b"], "c") = ["c", "a", "b"]
13381350 * </pre>
13391351 *
13401352 * @param <T> the component type of the array
13511363 }
13521364
13531365 /**
1354 * <p>Clones an array returning a typecast result and handling
1366 * Clones an array returning a typecast result and handling
13551367 * {@code null}.
1356 *
1357 * <p>This method returns {@code null} for a {@code null} input array.
1368 * <p>
1369 * This method returns {@code null} for a {@code null} input array.
1370 * </p>
13581371 *
13591372 * @param array the array to clone, may be {@code null}
13601373 * @return the cloned array, {@code null} if {@code null} input
13671380 }
13681381
13691382 /**
1370 * <p>Clones an array returning a typecast result and handling
1383 * Clones an array returning a typecast result and handling
13711384 * {@code null}.
1372 *
1373 * <p>This method returns {@code null} for a {@code null} input array.
1385 * <p>
1386 * This method returns {@code null} for a {@code null} input array.
1387 * </p>
13741388 *
13751389 * @param array the array to clone, may be {@code null}
13761390 * @return the cloned array, {@code null} if {@code null} input
13831397 }
13841398
13851399 /**
1386 * <p>Clones an array returning a typecast result and handling
1400 * Clones an array returning a typecast result and handling
13871401 * {@code null}.
1388 *
1389 * <p>This method returns {@code null} for a {@code null} input array.
1402 * <p>
1403 * This method returns {@code null} for a {@code null} input array.
1404 * </p>
13901405 *
13911406 * @param array the array to clone, may be {@code null}
13921407 * @return the cloned array, {@code null} if {@code null} input
13991414 }
14001415
14011416 /**
1402 * <p>Clones an array returning a typecast result and handling
1417 * Clones an array returning a typecast result and handling
14031418 * {@code null}.
1404 *
1405 * <p>This method returns {@code null} for a {@code null} input array.
1419 * <p>
1420 * This method returns {@code null} for a {@code null} input array.
1421 * </p>
14061422 *
14071423 * @param array the array to clone, may be {@code null}
14081424 * @return the cloned array, {@code null} if {@code null} input
14151431 }
14161432
14171433 /**
1418 * <p>Clones an array returning a typecast result and handling
1434 * Clones an array returning a typecast result and handling
14191435 * {@code null}.
1420 *
1421 * <p>This method returns {@code null} for a {@code null} input array.
1436 * <p>
1437 * This method returns {@code null} for a {@code null} input array.
1438 * </p>
14221439 *
14231440 * @param array the array to clone, may be {@code null}
14241441 * @return the cloned array, {@code null} if {@code null} input
14311448 }
14321449
14331450 /**
1434 * <p>Clones an array returning a typecast result and handling
1451 * Clones an array returning a typecast result and handling
14351452 * {@code null}.
1436 *
1437 * <p>This method returns {@code null} for a {@code null} input array.
1453 * <p>
1454 * This method returns {@code null} for a {@code null} input array.
1455 * </p>
14381456 *
14391457 * @param array the array to clone, may be {@code null}
14401458 * @return the cloned array, {@code null} if {@code null} input
14471465 }
14481466
14491467 /**
1450 * <p>Clones an array returning a typecast result and handling
1468 * Clones an array returning a typecast result and handling
14511469 * {@code null}.
1452 *
1453 * <p>This method returns {@code null} for a {@code null} input array.
1470 * <p>
1471 * This method returns {@code null} for a {@code null} input array.
1472 * </p>
14541473 *
14551474 * @param array the array to clone, may be {@code null}
14561475 * @return the cloned array, {@code null} if {@code null} input
14631482 }
14641483
14651484 /**
1466 * <p>Clones an array returning a typecast result and handling
1485 * Clones an array returning a typecast result and handling
14671486 * {@code null}.
1468 *
1469 * <p>This method returns {@code null} for a {@code null} input array.
1487 * <p>
1488 * This method returns {@code null} for a {@code null} input array.
1489 * </p>
14701490 *
14711491 * @param array the array to clone, may be {@code null}
14721492 * @return the cloned array, {@code null} if {@code null} input
14781498 return array.clone();
14791499 }
14801500
1481 // Clone
1482 //-----------------------------------------------------------------------
1483 /**
1484 * <p>Shallow clones an array returning a typecast result and handling
1501 /**
1502 * Shallow clones an array returning a typecast result and handling
14851503 * {@code null}.
1486 *
1487 * <p>The objects in the array are not cloned, thus there is no special
1504 * <p>
1505 * The objects in the array are not cloned, thus there is no special
14881506 * handling for multi-dimensional arrays.
1489 *
1490 * <p>This method returns {@code null} for a {@code null} input array.
1507 * </p>
1508 * <p>
1509 * This method returns {@code null} for a {@code null} input array.
1510 * </p>
14911511 *
14921512 * @param <T> the component type of the array
14931513 * @param array the array to shallow clone, may be {@code null}
15011521 }
15021522
15031523 /**
1504 * <p>Checks if the value is in the given array.
1505 *
1506 * <p>The method returns {@code false} if a {@code null} array is passed in.
1524 * Checks if the value is in the given array.
1525 * <p>
1526 * The method returns {@code false} if a {@code null} array is passed in.
1527 * </p>
15071528 *
15081529 * @param array the array to search through
15091530 * @param valueToFind the value to find
15141535 }
15151536
15161537 /**
1517 * <p>Checks if the value is in the given array.
1518 *
1519 * <p>The method returns {@code false} if a {@code null} array is passed in.
1538 * Checks if the value is in the given array.
1539 * <p>
1540 * The method returns {@code false} if a {@code null} array is passed in.
1541 * </p>
15201542 *
15211543 * @param array the array to search through
15221544 * @param valueToFind the value to find
15271549 }
15281550
15291551 /**
1530 * <p>Checks if the value is in the given array.
1531 *
1532 * <p>The method returns {@code false} if a {@code null} array is passed in.
1552 * Checks if the value is in the given array.
1553 * <p>
1554 * The method returns {@code false} if a {@code null} array is passed in.
1555 * </p>
15331556 *
15341557 * @param array the array to search through
15351558 * @param valueToFind the value to find
15411564 }
15421565
15431566 /**
1544 * <p>Checks if the value is in the given array.
1545 *
1546 * <p>The method returns {@code false} if a {@code null} array is passed in.
1567 * Checks if the value is in the given array.
1568 * <p>
1569 * The method returns {@code false} if a {@code null} array is passed in.
1570 * </p>
15471571 *
15481572 * @param array the array to search through
15491573 * @param valueToFind the value to find
15541578 }
15551579
15561580 /**
1557 * <p>Checks if a value falling within the given tolerance is in the
1581 * Checks if a value falling within the given tolerance is in the
15581582 * given array. If the array contains a value within the inclusive range
15591583 * defined by (value - tolerance) to (value + tolerance).
1560 *
1561 * <p>The method returns {@code false} if a {@code null} array
1584 * <p>
1585 * The method returns {@code false} if a {@code null} array
15621586 * is passed in.
1587 * </p>
15631588 *
15641589 * @param array the array to search
15651590 * @param valueToFind the value to find
15711596 }
15721597
15731598 /**
1574 * <p>Checks if the value is in the given array.
1575 *
1576 * <p>The method returns {@code false} if a {@code null} array is passed in.
1599 * Checks if the value is in the given array.
1600 * <p>
1601 * The method returns {@code false} if a {@code null} array is passed in.
1602 * </p>
15771603 *
15781604 * @param array the array to search through
15791605 * @param valueToFind the value to find
15841610 }
15851611
15861612 /**
1587 * <p>Checks if the value is in the given array.
1588 *
1589 * <p>The method returns {@code false} if a {@code null} array is passed in.
1613 * Checks if the value is in the given array.
1614 * <p>
1615 * The method returns {@code false} if a {@code null} array is passed in.
1616 * </p>
15901617 *
15911618 * @param array the array to search through
15921619 * @param valueToFind the value to find
15971624 }
15981625
15991626 /**
1600 * <p>Checks if the value is in the given array.
1601 *
1602 * <p>The method returns {@code false} if a {@code null} array is passed in.
1627 * Checks if the value is in the given array.
1628 * <p>
1629 * The method returns {@code false} if a {@code null} array is passed in.
1630 * </p>
16031631 *
16041632 * @param array the array to search through
16051633 * @param valueToFind the value to find
16101638 }
16111639
16121640 /**
1613 * <p>Checks if the object is in the given array.
1614 *
1615 * <p>The method returns {@code false} if a {@code null} array is passed in.
1641 * Checks if the object is in the given array.
1642 * <p>
1643 * The method returns {@code false} if a {@code null} array is passed in.
1644 * </p>
16161645 *
16171646 * @param array the array to search through
16181647 * @param objectToFind the object to find
16231652 }
16241653
16251654 /**
1626 * <p>Checks if the value is in the given array.
1627 *
1628 * <p>The method returns {@code false} if a {@code null} array is passed in.
1655 * Checks if the value is in the given array.
1656 * <p>
1657 * The method returns {@code false} if a {@code null} array is passed in.
1658 * </p>
16291659 *
16301660 * @param array the array to search through
16311661 * @param valueToFind the value to find
16811711 return isArrayIndexValid(array, index) ? array[index] : defaultValue;
16821712 }
16831713
1684 //-----------------------------------------------------------------------
1685 /**
1686 * <p>Returns the length of the specified array.
1714 /**
1715 * Gets an array's component type.
1716 *
1717 * @param <T> The array type.
1718 * @param array The array.
1719 * @return The component type.
1720 * @since 3.13.0
1721 */
1722 public static <T> Class<T> getComponentType(final T[] array) {
1723 return ClassUtils.getComponentType(ObjectUtils.getClass(array));
1724 }
1725
1726 /**
1727 * Returns the length of the specified array.
16871728 * This method can deal with {@code Object} arrays and with primitive arrays.
1688 *
1689 * <p>If the input array is {@code null}, {@code 0} is returned.
1690 *
1729 * <p>
1730 * If the input array is {@code null}, {@code 0} is returned.
1731 * </p>
16911732 * <pre>
16921733 * ArrayUtils.getLength(null) = 0
16931734 * ArrayUtils.getLength([]) = 0
17101751 }
17111752
17121753 /**
1713 * <p>Get a hash code for an array handling multi-dimensional arrays correctly.
1714 *
1715 * <p>Multi-dimensional primitive arrays are also handled correctly by this method.
1754 * Get a hash code for an array handling multi-dimensional arrays correctly.
1755 * <p>
1756 * Multi-dimensional primitive arrays are also handled correctly by this method.
1757 * </p>
17161758 *
17171759 * @param array the array to get a hash code for, {@code null} returns zero
17181760 * @return a hash code for the array
17231765
17241766 /**
17251767 * Finds the indices of the given value in the array.
1726 *
1727 * <p>This method returns an empty BitSet for a {@code null} input array.</p>
1768 * <p>
1769 * This method returns an empty BitSet for a {@code null} input array.
1770 * </p>
17281771 *
17291772 * @param array the array to search through for the object, may be {@code null}
17301773 * @param valueToFind the value to find
17381781
17391782 /**
17401783 * Finds the indices of the given value in the array starting at the given index.
1741 *
1742 * <p>This method returns an empty BitSet for a {@code null} input array.</p>
1743 *
1744 * <p>A negative startIndex is treated as zero. A startIndex larger than the array
1745 * length will return an empty BitSet ({@code -1}).</p>
1784 * <p>
1785 * This method returns an empty BitSet for a {@code null} input array.
1786 * </p>
1787 * <p>
1788 * A negative startIndex is treated as zero. A startIndex larger than the array
1789 * length will return an empty BitSet ({@code -1}).
1790 * </p>
17461791 *
17471792 * @param array the array to search through for the object, may be {@code null}
17481793 * @param valueToFind the value to find
22442289 return bitSet;
22452290 }
22462291
2247 // boolean IndexOf
2248 //-----------------------------------------------------------------------
2249 /**
2250 * <p>Finds the index of the given value in the array.
2251 *
2252 * <p>This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
2292 /**
2293 * Finds the index of the given value in the array.
2294 * <p>
2295 * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
2296 * </p>
22532297 *
22542298 * @param array the array to search through for the object, may be {@code null}
22552299 * @param valueToFind the value to find
22612305 }
22622306
22632307 /**
2264 * <p>Finds the index of the given value in the array starting at the given index.
2265 *
2266 * <p>This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
2267 *
2268 * <p>A negative startIndex is treated as zero. A startIndex larger than the array
2308 * Finds the index of the given value in the array starting at the given index.
2309 * <p>
2310 * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
2311 * </p>
2312 * <p>
2313 * A negative startIndex is treated as zero. A startIndex larger than the array
22692314 * length will return {@link #INDEX_NOT_FOUND} ({@code -1}).
2315 * </p>
22702316 *
22712317 * @param array the array to search through for the object, may be {@code null}
22722318 * @param valueToFind the value to find
22902336 return INDEX_NOT_FOUND;
22912337 }
22922338
2293 // byte IndexOf
2294 //-----------------------------------------------------------------------
2295 /**
2296 * <p>Finds the index of the given value in the array.
2297 *
2298 * <p>This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
2339 /**
2340 * Finds the index of the given value in the array.
2341 * <p>
2342 * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
2343 * </p>
22992344 *
23002345 * @param array the array to search through for the object, may be {@code null}
23012346 * @param valueToFind the value to find
23072352 }
23082353
23092354 /**
2310 * <p>Finds the index of the given value in the array starting at the given index.
2311 *
2312 * <p>This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
2313 *
2314 * <p>A negative startIndex is treated as zero. A startIndex larger than the array
2355 * Finds the index of the given value in the array starting at the given index.
2356 * <p>
2357 * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
2358 * </p>
2359 * <p>
2360 * A negative startIndex is treated as zero. A startIndex larger than the array
23152361 * length will return {@link #INDEX_NOT_FOUND} ({@code -1}).
2362 * </p>
23162363 *
23172364 * @param array the array to search through for the object, may be {@code null}
23182365 * @param valueToFind the value to find
23352382 return INDEX_NOT_FOUND;
23362383 }
23372384
2338 // char IndexOf
2339 //-----------------------------------------------------------------------
2340 /**
2341 * <p>Finds the index of the given value in the array.
2342 *
2343 * <p>This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
2385 /**
2386 * Finds the index of the given value in the array.
2387 * <p>
2388 * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
2389 * </p>
23442390 *
23452391 * @param array the array to search through for the object, may be {@code null}
23462392 * @param valueToFind the value to find
23532399 }
23542400
23552401 /**
2356 * <p>Finds the index of the given value in the array starting at the given index.
2357 *
2358 * <p>This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
2359 *
2360 * <p>A negative startIndex is treated as zero. A startIndex larger than the array
2402 * Finds the index of the given value in the array starting at the given index.
2403 * <p>
2404 * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
2405 * </p>
2406 * <p>
2407 * A negative startIndex is treated as zero. A startIndex larger than the array
23612408 * length will return {@link #INDEX_NOT_FOUND} ({@code -1}).
2409 * </p>
23622410 *
23632411 * @param array the array to search through for the object, may be {@code null}
23642412 * @param valueToFind the value to find
23822430 return INDEX_NOT_FOUND;
23832431 }
23842432
2385 // double IndexOf
2386 //-----------------------------------------------------------------------
2387 /**
2388 * <p>Finds the index of the given value in the array.
2389 *
2390 * <p>This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
2433 /**
2434 * Finds the index of the given value in the array.
2435 * <p>
2436 * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
2437 * </p>
23912438 *
23922439 * @param array the array to search through for the object, may be {@code null}
23932440 * @param valueToFind the value to find
23992446 }
24002447
24012448 /**
2402 * <p>Finds the index of the given value within a given tolerance in the array.
2449 * Finds the index of the given value within a given tolerance in the array.
24032450 * This method will return the index of the first value which falls between the region
24042451 * defined by valueToFind - tolerance and valueToFind + tolerance.
2405 *
2406 * <p>This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
2452 * <p>
2453 * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
2454 * </p>
24072455 *
24082456 * @param array the array to search through for the object, may be {@code null}
24092457 * @param valueToFind the value to find
24162464 }
24172465
24182466 /**
2419 * <p>Finds the index of the given value in the array starting at the given index.
2420 *
2421 * <p>This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
2422 *
2423 * <p>A negative startIndex is treated as zero. A startIndex larger than the array
2467 * Finds the index of the given value in the array starting at the given index.
2468 * <p>
2469 * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
2470 * </p>
2471 * <p>
2472 * A negative startIndex is treated as zero. A startIndex larger than the array
24242473 * length will return {@link #INDEX_NOT_FOUND} ({@code -1}).
2474 * </p>
24252475 *
24262476 * @param array the array to search through for the object, may be {@code null}
24272477 * @param valueToFind the value to find
24362486 if (startIndex < 0) {
24372487 startIndex = 0;
24382488 }
2489 final boolean searchNaN = Double.isNaN(valueToFind);
24392490 for (int i = startIndex; i < array.length; i++) {
2440 if (valueToFind == array[i]) {
2491 final double element = array[i];
2492 if (valueToFind == element || (searchNaN && Double.isNaN(element))) {
24412493 return i;
24422494 }
24432495 }
24452497 }
24462498
24472499 /**
2448 * <p>Finds the index of the given value in the array starting at the given index.
2500 * Finds the index of the given value in the array starting at the given index.
24492501 * This method will return the index of the first value which falls between the region
24502502 * defined by valueToFind - tolerance and valueToFind + tolerance.
2451 *
2452 * <p>This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
2453 *
2454 * <p>A negative startIndex is treated as zero. A startIndex larger than the array
2503 * <p>
2504 * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
2505 * </p>
2506 * <p>
2507 * A negative startIndex is treated as zero. A startIndex larger than the array
24552508 * length will return {@link #INDEX_NOT_FOUND} ({@code -1}).
2509 * </p>
24562510 *
24572511 * @param array the array to search through for the object, may be {@code null}
24582512 * @param valueToFind the value to find
24782532 return INDEX_NOT_FOUND;
24792533 }
24802534
2481 // float IndexOf
2482 //-----------------------------------------------------------------------
2483 /**
2484 * <p>Finds the index of the given value in the array.
2485 *
2486 * <p>This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
2535 /**
2536 * Finds the index of the given value in the array.
2537 * <p>
2538 * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
2539 * </p>
24872540 *
24882541 * @param array the array to search through for the object, may be {@code null}
24892542 * @param valueToFind the value to find
24952548 }
24962549
24972550 /**
2498 * <p>Finds the index of the given value in the array starting at the given index.
2499 *
2500 * <p>This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
2501 *
2502 * <p>A negative startIndex is treated as zero. A startIndex larger than the array
2551 * Finds the index of the given value in the array starting at the given index.
2552 * <p>
2553 * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
2554 * </p>
2555 * <p>
2556 * A negative startIndex is treated as zero. A startIndex larger than the array
25032557 * length will return {@link #INDEX_NOT_FOUND} ({@code -1}).
2558 * </p>
25042559 *
25052560 * @param array the array to search through for the object, may be {@code null}
25062561 * @param valueToFind the value to find
25152570 if (startIndex < 0) {
25162571 startIndex = 0;
25172572 }
2573 final boolean searchNaN = Float.isNaN(valueToFind);
25182574 for (int i = startIndex; i < array.length; i++) {
2519 if (valueToFind == array[i]) {
2575 final float element = array[i];
2576 if (valueToFind == element || (searchNaN && Float.isNaN(element))) {
25202577 return i;
25212578 }
25222579 }
25232580 return INDEX_NOT_FOUND;
25242581 }
25252582
2526 // int IndexOf
2527 //-----------------------------------------------------------------------
2528 /**
2529 * <p>Finds the index of the given value in the array.
2530 *
2531 * <p>This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
2532 *
2533 * @param array the array to search through for the object, may be {@code null}
2534 * @param valueToFind the value to find
2535 * @return the index of the value within the array,
2536 * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
2537 */
2538 public static int indexOf(final int[] array, final int valueToFind) {
2539 return indexOf(array, valueToFind, 0);
2540 }
2541
2542 /**
2543 * <p>Finds the index of the given value in the array starting at the given index.
2544 *
2545 * <p>This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
2546 *
2547 * <p>A negative startIndex is treated as zero. A startIndex larger than the array
2583 /**
2584 * Finds the index of the given value in the array.
2585 * <p>
2586 * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
2587 * </p>
2588 *
2589 * @param array the array to search through for the object, may be {@code null}
2590 * @param valueToFind the value to find
2591 * @return the index of the value within the array,
2592 * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
2593 */
2594 public static int indexOf(final int[] array, final int valueToFind) {
2595 return indexOf(array, valueToFind, 0);
2596 }
2597
2598 /**
2599 * Finds the index of the given value in the array starting at the given index.
2600 * <p>
2601 * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
2602 * </p>
2603 * <p>
2604 * A negative startIndex is treated as zero. A startIndex larger than the array
25482605 * length will return {@link #INDEX_NOT_FOUND} ({@code -1}).
2606 * </p>
25492607 *
25502608 * @param array the array to search through for the object, may be {@code null}
25512609 * @param valueToFind the value to find
25682626 return INDEX_NOT_FOUND;
25692627 }
25702628
2571 // long IndexOf
2572 //-----------------------------------------------------------------------
2573 /**
2574 * <p>Finds the index of the given value in the array.
2575 *
2576 * <p>This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
2577 *
2578 * @param array the array to search through for the object, may be {@code null}
2579 * @param valueToFind the value to find
2580 * @return the index of the value within the array,
2581 * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
2629 /**
2630 * Finds the index of the given value in the array.
2631 * <p>
2632 * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
2633 * </p>
2634 *
2635 * @param array the array to search through for the object, may be {@code null}
2636 * @param valueToFind the value to find
2637 * @return the index of the value within the array, {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null}
2638 * array input
25822639 */
25832640 public static int indexOf(final long[] array, final long valueToFind) {
25842641 return indexOf(array, valueToFind, 0);
25852642 }
25862643
25872644 /**
2588 * <p>Finds the index of the given value in the array starting at the given index.
2589 *
2590 * <p>This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
2591 *
2592 * <p>A negative startIndex is treated as zero. A startIndex larger than the array
2645 * Finds the index of the given value in the array starting at the given index.
2646 * <p>
2647 * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
2648 * </p>
2649 * <p>
2650 * A negative startIndex is treated as zero. A startIndex larger than the array
25932651 * length will return {@link #INDEX_NOT_FOUND} ({@code -1}).
2652 * </p>
25942653 *
25952654 * @param array the array to search through for the object, may be {@code null}
25962655 * @param valueToFind the value to find
26132672 return INDEX_NOT_FOUND;
26142673 }
26152674
2616 // Object IndexOf
2617 //-----------------------------------------------------------------------
2618 /**
2619 * <p>Finds the index of the given object in the array.
2620 *
2621 * <p>This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
2675 /**
2676 * Finds the index of the given object in the array.
2677 * <p>
2678 * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
2679 * </p>
26222680 *
26232681 * @param array the array to search through for the object, may be {@code null}
26242682 * @param objectToFind the object to find, may be {@code null}
26302688 }
26312689
26322690 /**
2633 * <p>Finds the index of the given object in the array starting at the given index.
2634 *
2635 * <p>This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
2636 *
2637 * <p>A negative startIndex is treated as zero. A startIndex larger than the array
2691 * Finds the index of the given object in the array starting at the given index.
2692 * <p>
2693 * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
2694 * </p>
2695 * <p>
2696 * A negative startIndex is treated as zero. A startIndex larger than the array
26382697 * length will return {@link #INDEX_NOT_FOUND} ({@code -1}).
2698 * </p>
26392699 *
26402700 * @param array the array to search through for the object, may be {@code null}
26412701 * @param objectToFind the object to find, may be {@code null}
26662726 return INDEX_NOT_FOUND;
26672727 }
26682728
2669 // short IndexOf
2670 //-----------------------------------------------------------------------
2671 /**
2672 * <p>Finds the index of the given value in the array.
2673 *
2674 * <p>This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
2729 /**
2730 * Finds the index of the given value in the array.
2731 * <p>
2732 * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
2733 * </p>
26752734 *
26762735 * @param array the array to search through for the object, may be {@code null}
26772736 * @param valueToFind the value to find
26832742 }
26842743
26852744 /**
2686 * <p>Finds the index of the given value in the array starting at the given index.
2687 *
2688 * <p>This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
2689 *
2690 * <p>A negative startIndex is treated as zero. A startIndex larger than the array
2745 * Finds the index of the given value in the array starting at the given index.
2746 * <p>
2747 * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
2748 * </p>
2749 * <p>
2750 * A negative startIndex is treated as zero. A startIndex larger than the array
26912751 * length will return {@link #INDEX_NOT_FOUND} ({@code -1}).
2752 * </p>
26922753 *
26932754 * @param array the array to search through for the object, may be {@code null}
26942755 * @param valueToFind the value to find
27122773 }
27132774
27142775 /**
2715 * <p>Inserts elements into an array at the given index (starting from zero).</p>
2776 * Inserts elements into an array at the given index (starting from zero).
27162777 *
27172778 * <p>When an array is returned, it is always a new array.</p>
27182779 *
27542815 }
27552816
27562817 /**
2757 * <p>Inserts elements into an array at the given index (starting from zero).</p>
2818 * Inserts elements into an array at the given index (starting from zero).
27582819 *
27592820 * <p>When an array is returned, it is always a new array.</p>
27602821 *
27962857 }
27972858
27982859 /**
2799 * <p>Inserts elements into an array at the given index (starting from zero).</p>
2860 * Inserts elements into an array at the given index (starting from zero).
28002861 *
28012862 * <p>When an array is returned, it is always a new array.</p>
28022863 *
28382899 }
28392900
28402901 /**
2841 * <p>Inserts elements into an array at the given index (starting from zero).</p>
2902 * Inserts elements into an array at the given index (starting from zero).
28422903 *
28432904 * <p>When an array is returned, it is always a new array.</p>
28442905 *
28802941 }
28812942
28822943 /**
2883 * <p>Inserts elements into an array at the given index (starting from zero).</p>
2944 * Inserts elements into an array at the given index (starting from zero).
28842945 *
28852946 * <p>When an array is returned, it is always a new array.</p>
28862947 *
29222983 }
29232984
29242985 /**
2925 * <p>Inserts elements into an array at the given index (starting from zero).</p>
2986 * Inserts elements into an array at the given index (starting from zero).
29262987 *
29272988 * <p>When an array is returned, it is always a new array.</p>
29282989 *
29643025 }
29653026
29663027 /**
2967 * <p>Inserts elements into an array at the given index (starting from zero).</p>
3028 * Inserts elements into an array at the given index (starting from zero).
29683029 *
29693030 * <p>When an array is returned, it is always a new array.</p>
29703031 *
30063067 }
30073068
30083069 /**
3009 * <p>Inserts elements into an array at the given index (starting from zero).</p>
3070 * Inserts elements into an array at the given index (starting from zero).
30103071 *
30113072 * <p>When an array is returned, it is always a new array.</p>
30123073 *
30483109 }
30493110
30503111 /**
3051 * <p>Inserts elements into an array at the given index (starting from zero).</p>
3112 * Inserts elements into an array at the given index (starting from zero).
30523113 *
30533114 * <p>When an array is returned, it is always a new array.</p>
30543115 *
30873148 throw new IndexOutOfBoundsException("Index: " + index + ", Length: " + array.length);
30883149 }
30893150
3090 final Class<?> type = array.getClass().getComponentType();
3091 @SuppressWarnings("unchecked") // OK, because array and values are of type T
3092 final
3093 T[] result = (T[]) Array.newInstance(type, array.length + values.length);
3151 final Class<T> type = getComponentType(array);
3152 final int length = array.length + values.length;
3153 final T[] result = newInstance(type, length);
30943154
30953155 System.arraycopy(values, 0, result, index, values.length);
30963156 if (index > 0) {
31223182 }
31233183
31243184 /**
3125 * <p>Checks if an array of primitive booleans is empty or {@code null}.
3185 * Checks if an array of primitive booleans is empty or {@code null}.
31263186 *
31273187 * @param array the array to test
31283188 * @return {@code true} if the array is empty or {@code null}
31323192 return getLength(array) == 0;
31333193 }
31343194
3135 // IndexOf search
3136 // ----------------------------------------------------------------------
3137
3138 /**
3139 * <p>Checks if an array of primitive bytes is empty or {@code null}.
3195 /**
3196 * Checks if an array of primitive bytes is empty or {@code null}.
31403197 *
31413198 * @param array the array to test
31423199 * @return {@code true} if the array is empty or {@code null}
31473204 }
31483205
31493206 /**
3150 * <p>Checks if an array of primitive chars is empty or {@code null}.
3207 * Checks if an array of primitive chars is empty or {@code null}.
31513208 *
31523209 * @param array the array to test
31533210 * @return {@code true} if the array is empty or {@code null}
31583215 }
31593216
31603217 /**
3161 * <p>Checks if an array of primitive doubles is empty or {@code null}.
3218 * Checks if an array of primitive doubles is empty or {@code null}.
31623219 *
31633220 * @param array the array to test
31643221 * @return {@code true} if the array is empty or {@code null}
31693226 }
31703227
31713228 /**
3172 * <p>Checks if an array of primitive floats is empty or {@code null}.
3229 * Checks if an array of primitive floats is empty or {@code null}.
31733230 *
31743231 * @param array the array to test
31753232 * @return {@code true} if the array is empty or {@code null}
31793236 return getLength(array) == 0;
31803237 }
31813238
3182
3183
3184 /**
3185 * <p>Checks if an array of primitive ints is empty or {@code null}.
3239 /**
3240 * Checks if an array of primitive ints is empty or {@code null}.
31863241 *
31873242 * @param array the array to test
31883243 * @return {@code true} if the array is empty or {@code null}
31933248 }
31943249
31953250 /**
3196 * <p>Checks if an array of primitive longs is empty or {@code null}.
3251 * Checks if an array of primitive longs is empty or {@code null}.
31973252 *
31983253 * @param array the array to test
31993254 * @return {@code true} if the array is empty or {@code null}
32033258 return getLength(array) == 0;
32043259 }
32053260
3206 // ----------------------------------------------------------------------
3207 /**
3208 * <p>Checks if an array of Objects is empty or {@code null}.
3261 /**
3262 * Checks if an array of Objects is empty or {@code null}.
32093263 *
32103264 * @param array the array to test
32113265 * @return {@code true} if the array is empty or {@code null}
32163270 }
32173271
32183272 /**
3219 * <p>Checks if an array of primitive shorts is empty or {@code null}.
3273 * Checks if an array of primitive shorts is empty or {@code null}.
32203274 *
32213275 * @param array the array to test
32223276 * @return {@code true} if the array is empty or {@code null}
32273281 }
32283282
32293283 /**
3230 * <p>Compares two arrays, using equals(), handling multi-dimensional arrays
3284 * Compares two arrays, using equals(), handling multi-dimensional arrays
32313285 * correctly.
3232 *
3233 * <p>Multi-dimensional primitive arrays are also handled correctly by this method.
3286 * <p>
3287 * Multi-dimensional primitive arrays are also handled correctly by this method.
3288 * </p>
32343289 *
32353290 * @param array1 the left hand array to compare, may be {@code null}
32363291 * @param array2 the right hand array to compare, may be {@code null}
32443299 }
32453300
32463301 /**
3247 * <p>Checks if an array of primitive booleans is not empty and not {@code null}.
3302 * Checks if an array of primitive booleans is not empty and not {@code null}.
32483303 *
32493304 * @param array the array to test
32503305 * @return {@code true} if the array is not empty and not {@code null}
32553310 }
32563311
32573312 /**
3258 * <p>Checks if an array of primitive bytes is not empty and not {@code null}.
3313 * Checks if an array of primitive bytes is not empty and not {@code null}.
32593314 *
32603315 * @param array the array to test
32613316 * @return {@code true} if the array is not empty and not {@code null}
32663321 }
32673322
32683323 /**
3269 * <p>Checks if an array of primitive chars is not empty and not {@code null}.
3324 * Checks if an array of primitive chars is not empty and not {@code null}.
32703325 *
32713326 * @param array the array to test
32723327 * @return {@code true} if the array is not empty and not {@code null}
32773332 }
32783333
32793334 /**
3280 * <p>Checks if an array of primitive doubles is not empty and not {@code null}.
3335 * Checks if an array of primitive doubles is not empty and not {@code null}.
32813336 *
32823337 * @param array the array to test
32833338 * @return {@code true} if the array is not empty and not {@code null}
32883343 }
32893344
32903345 /**
3291 * <p>Checks if an array of primitive floats is not empty and not {@code null}.
3346 * Checks if an array of primitive floats is not empty and not {@code null}.
32923347 *
32933348 * @param array the array to test
32943349 * @return {@code true} if the array is not empty and not {@code null}
32993354 }
33003355
33013356 /**
3302 * <p>Checks if an array of primitive ints is not empty and not {@code null}.
3357 * Checks if an array of primitive ints is not empty and not {@code null}.
33033358 *
33043359 * @param array the array to test
33053360 * @return {@code true} if the array is not empty and not {@code null}
33103365 }
33113366
33123367 /**
3313 * <p>Checks if an array of primitive longs is not empty and not {@code null}.
3368 * Checks if an array of primitive longs is not empty and not {@code null}.
33143369 *
33153370 * @param array the array to test
33163371 * @return {@code true} if the array is not empty and not {@code null}
33213376 }
33223377
33233378 /**
3324 * <p>Checks if an array of primitive shorts is not empty and not {@code null}.
3379 * Checks if an array of primitive shorts is not empty and not {@code null}.
33253380 *
33263381 * @param array the array to test
33273382 * @return {@code true} if the array is not empty and not {@code null}
33313386 return !isEmpty(array);
33323387 }
33333388
3334 // ----------------------------------------------------------------------
3335 /**
3336 * <p>Checks if an array of Objects is not empty and not {@code null}.
3389 /**
3390 * Checks if an array of Objects is not empty and not {@code null}.
33373391 *
33383392 * @param <T> the component type of the array
33393393 * @param array the array to test
33453399 }
33463400
33473401 /**
3348 * <p>Checks whether two arrays are the same length, treating
3402 * Checks whether two arrays are the same length, treating
33493403 * {@code null} arrays as length {@code 0}.
33503404 *
33513405 * @param array1 the first array, may be {@code null}
33583412 }
33593413
33603414 /**
3361 * <p>Checks whether two arrays are the same length, treating
3415 * Checks whether two arrays are the same length, treating
33623416 * {@code null} arrays as length {@code 0}.
33633417 *
33643418 * @param array1 the first array, may be {@code null}
33713425 }
33723426
33733427 /**
3374 * <p>Checks whether two arrays are the same length, treating
3428 * Checks whether two arrays are the same length, treating
33753429 * {@code null} arrays as length {@code 0}.
33763430 *
33773431 * @param array1 the first array, may be {@code null}
33843438 }
33853439
33863440 /**
3387 * <p>Checks whether two arrays are the same length, treating
3441 * Checks whether two arrays are the same length, treating
33883442 * {@code null} arrays as length {@code 0}.
33893443 *
33903444 * @param array1 the first array, may be {@code null}
33973451 }
33983452
33993453 /**
3400 * <p>Checks whether two arrays are the same length, treating
3454 * Checks whether two arrays are the same length, treating
34013455 * {@code null} arrays as length {@code 0}.
34023456 *
34033457 * @param array1 the first array, may be {@code null}
34103464 }
34113465
34123466 /**
3413 * <p>Checks whether two arrays are the same length, treating
3467 * Checks whether two arrays are the same length, treating
34143468 * {@code null} arrays as length {@code 0}.
34153469 *
34163470 * @param array1 the first array, may be {@code null}
34233477 }
34243478
34253479 /**
3426 * <p>Checks whether two arrays are the same length, treating
3480 * Checks whether two arrays are the same length, treating
34273481 * {@code null} arrays as length {@code 0}.
34283482 *
34293483 * @param array1 the first array, may be {@code null}
34353489 return getLength(array1) == getLength(array2);
34363490 }
34373491
3438
3439 /**
3440 * <p>Checks whether two arrays are the same length, treating
3492 /**
3493 * Checks whether two arrays are the same length, treating
34413494 * {@code null} arrays as length {@code 0}.
3442 *
3443 * <p>Any multi-dimensional aspects of the arrays are ignored.
3495 * <p>
3496 * Any multi-dimensional aspects of the arrays are ignored.
3497 * </p>
34443498 *
34453499 * @param array1 the first array, may be {@code null}
34463500 * @param array2 the second array, may be {@code null}
34533507 }
34543508
34553509 /**
3456 * <p>Checks whether two arrays are the same length, treating
3510 * Checks whether two arrays are the same length, treating
34573511 * {@code null} arrays as length {@code 0}.
3458 *
3459 * <p>Any multi-dimensional aspects of the arrays are ignored.
3512 * <p>
3513 * Any multi-dimensional aspects of the arrays are ignored.
3514 * </p>
34603515 *
34613516 * @param array1 the first array, may be {@code null}
34623517 * @param array2 the second array, may be {@code null}
34673522 return getLength(array1) == getLength(array2);
34683523 }
34693524
3470 /**
3471 * <p>Checks whether two arrays are the same length, treating
3525
3526 /**
3527 * Checks whether two arrays are the same length, treating
34723528 * {@code null} arrays as length {@code 0}.
34733529 *
34743530 * @param array1 the first array, may be {@code null}
34813537 }
34823538
34833539 /**
3484 * <p>Checks whether two arrays are the same type taking into account
3540 * Checks whether two arrays are the same type taking into account
34853541 * multi-dimensional arrays.
34863542 *
34873543 * @param array1 the first array, must not be {@code null}
34973553 }
34983554
34993555 /**
3500 * <p>This method checks whether the provided array is sorted according to natural ordering
3556 * This method checks whether the provided array is sorted according to natural ordering
35013557 * ({@code false} before {@code true}).
35023558 *
35033559 * @param array the array to check
35233579 }
35243580
35253581 /**
3526 * <p>This method checks whether the provided array is sorted according to natural ordering.
3582 * Checks whether the provided array is sorted according to natural ordering.
35273583 *
35283584 * @param array the array to check
35293585 * @return whether the array is sorted according to natural ordering
35483604 }
35493605
35503606 /**
3551 * <p>This method checks whether the provided array is sorted according to natural ordering.
3607 * Checks whether the provided array is sorted according to natural ordering.
35523608 *
35533609 * @param array the array to check
35543610 * @return whether the array is sorted according to natural ordering
35733629 }
35743630
35753631 /**
3576 * <p>This method checks whether the provided array is sorted according to natural ordering.
3632 * This method checks whether the provided array is sorted according to natural ordering.
35773633 *
35783634 * @param array the array to check
35793635 * @return whether the array is sorted according to natural ordering
35983654 }
35993655
36003656 /**
3601 * <p>This method checks whether the provided array is sorted according to natural ordering.
3657 * This method checks whether the provided array is sorted according to natural ordering.
36023658 *
36033659 * @param array the array to check
36043660 * @return whether the array is sorted according to natural ordering
36233679 }
36243680
36253681 /**
3626 * <p>This method checks whether the provided array is sorted according to natural ordering.
3682 * This method checks whether the provided array is sorted according to natural ordering.
36273683 *
36283684 * @param array the array to check
36293685 * @return whether the array is sorted according to natural ordering
36483704 }
36493705
36503706 /**
3651 * <p>This method checks whether the provided array is sorted according to natural ordering.
3707 * This method checks whether the provided array is sorted according to natural ordering.
36523708 *
36533709 * @param array the array to check
36543710 * @return whether the array is sorted according to natural ordering
36733729 }
36743730
36753731 /**
3676 * <p>This method checks whether the provided array is sorted according to natural ordering.
3732 * This method checks whether the provided array is sorted according to natural ordering.
36773733 *
36783734 * @param array the array to check
36793735 * @return whether the array is sorted according to natural ordering
36983754 }
36993755
37003756 /**
3701 * <p>This method checks whether the provided array is sorted according to the class's
3757 * This method checks whether the provided array is sorted according to the class's
37023758 * {@code compareTo} method.
37033759 *
37043760 * @param array the array to check
37113767 }
37123768
37133769 /**
3714 * <p>This method checks whether the provided array is sorted according to the provided {@code Comparator}.
3770 * This method checks whether the provided array is sorted according to the provided {@code Comparator}.
37153771 *
37163772 * @param array the array to check
37173773 * @param comparator the {@code Comparator} to compare over
37423798 }
37433799
37443800 /**
3745 * <p>Finds the last index of the given value within the array.
3746 *
3747 * <p>This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) if
3801 * Finds the last index of the given value within the array.
3802 * <p>
3803 * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) if
37483804 * {@code null} array input.
3805 * </p>
37493806 *
37503807 * @param array the array to traverse backwards looking for the object, may be {@code null}
37513808 * @param valueToFind the object to find
37573814 }
37583815
37593816 /**
3760 * <p>Finds the last index of the given value in the array starting at the given index.
3761 *
3762 * <p>This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
3763 *
3764 * <p>A negative startIndex will return {@link #INDEX_NOT_FOUND} ({@code -1}). A startIndex larger than
3817 * Finds the last index of the given value in the array starting at the given index.
3818 * <p>
3819 * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
3820 * </p>
3821 * <p>
3822 * A negative startIndex will return {@link #INDEX_NOT_FOUND} ({@code -1}). A startIndex larger than
37653823 * the array length will search from the end of the array.
3824 * </p>
37663825 *
37673826 * @param array the array to traverse for looking for the object, may be {@code null}
37683827 * @param valueToFind the value to find
37713830 * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
37723831 */
37733832 public static int lastIndexOf(final boolean[] array, final boolean valueToFind, int startIndex) {
3774 if (isEmpty(array)) {
3833 if (isEmpty(array) || (startIndex < 0)) {
37753834 return INDEX_NOT_FOUND;
37763835 }
3777 if (startIndex < 0) {
3778 return INDEX_NOT_FOUND;
3779 } else if (startIndex >= array.length) {
3836 if (startIndex >= array.length) {
37803837 startIndex = array.length - 1;
37813838 }
37823839 for (int i = startIndex; i >= 0; i--) {
37883845 }
37893846
37903847 /**
3791 * <p>Finds the last index of the given value within the array.
3792 *
3793 * <p>This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
3848 * Finds the last index of the given value within the array.
3849 * <p>
3850 * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
3851 * </p>
37943852 *
37953853 * @param array the array to traverse backwards looking for the object, may be {@code null}
37963854 * @param valueToFind the object to find
38023860 }
38033861
38043862 /**
3805 * <p>Finds the last index of the given value in the array starting at the given index.
3806 *
3807 * <p>This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
3808 *
3809 * <p>A negative startIndex will return {@link #INDEX_NOT_FOUND} ({@code -1}). A startIndex larger than the
3863 * Finds the last index of the given value in the array starting at the given index.
3864 * <p>
3865 * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
3866 * </p>
3867 * <p>
3868 * A negative startIndex will return {@link #INDEX_NOT_FOUND} ({@code -1}). A startIndex larger than the
38103869 * array length will search from the end of the array.
3870 * </p>
38113871 *
38123872 * @param array the array to traverse for looking for the object, may be {@code null}
38133873 * @param valueToFind the value to find
38163876 * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
38173877 */
38183878 public static int lastIndexOf(final byte[] array, final byte valueToFind, int startIndex) {
3819 if (array == null) {
3879 if ((array == null) || (startIndex < 0)) {
38203880 return INDEX_NOT_FOUND;
38213881 }
3822 if (startIndex < 0) {
3823 return INDEX_NOT_FOUND;
3824 } else if (startIndex >= array.length) {
3882 if (startIndex >= array.length) {
38253883 startIndex = array.length - 1;
38263884 }
38273885 for (int i = startIndex; i >= 0; i--) {
38333891 }
38343892
38353893 /**
3836 * <p>Finds the last index of the given value within the array.
3837 *
3838 * <p>This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
3894 * Finds the last index of the given value within the array.
3895 * <p>
3896 * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
3897 * </p>
38393898 *
38403899 * @param array the array to traverse backwards looking for the object, may be {@code null}
38413900 * @param valueToFind the object to find
38483907 }
38493908
38503909 /**
3851 * <p>Finds the last index of the given value in the array starting at the given index.
3852 *
3853 * <p>This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
3854 *
3855 * <p>A negative startIndex will return {@link #INDEX_NOT_FOUND} ({@code -1}). A startIndex larger than the
3910 * Finds the last index of the given value in the array starting at the given index.
3911 * <p>
3912 * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
3913 * </p>
3914 * <p>
3915 * A negative startIndex will return {@link #INDEX_NOT_FOUND} ({@code -1}). A startIndex larger than the
38563916 * array length will search from the end of the array.
3917 * </p>
38573918 *
38583919 * @param array the array to traverse for looking for the object, may be {@code null}
38593920 * @param valueToFind the value to find
38633924 * @since 2.1
38643925 */
38653926 public static int lastIndexOf(final char[] array, final char valueToFind, int startIndex) {
3866 if (array == null) {
3927 if ((array == null) || (startIndex < 0)) {
38673928 return INDEX_NOT_FOUND;
38683929 }
3869 if (startIndex < 0) {
3870 return INDEX_NOT_FOUND;
3871 } else if (startIndex >= array.length) {
3930 if (startIndex >= array.length) {
38723931 startIndex = array.length - 1;
38733932 }
38743933 for (int i = startIndex; i >= 0; i--) {
38803939 }
38813940
38823941 /**
3883 * <p>Finds the last index of the given value within the array.
3884 *
3885 * <p>This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
3942 * Finds the last index of the given value within the array.
3943 * <p>
3944 * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
3945 * </p>
38863946 *
38873947 * @param array the array to traverse backwards looking for the object, may be {@code null}
38883948 * @param valueToFind the object to find
38943954 }
38953955
38963956 /**
3897 * <p>Finds the last index of the given value within a given tolerance in the array.
3957 * Finds the last index of the given value within a given tolerance in the array.
38983958 * This method will return the index of the last value which falls between the region
38993959 * defined by valueToFind - tolerance and valueToFind + tolerance.
3900 *
3901 * <p>This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
3960 * <p>
3961 * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
3962 * </p>
39023963 *
39033964 * @param array the array to search through for the object, may be {@code null}
39043965 * @param valueToFind the value to find
39113972 }
39123973
39133974 /**
3914 * <p>Finds the last index of the given value in the array starting at the given index.
3915 *
3916 * <p>This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
3917 *
3918 * <p>A negative startIndex will return {@link #INDEX_NOT_FOUND} ({@code -1}). A startIndex larger than the
3975 * Finds the last index of the given value in the array starting at the given index.
3976 * <p>
3977 * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
3978 * </p>
3979 * <p>
3980 * A negative startIndex will return {@link #INDEX_NOT_FOUND} ({@code -1}). A startIndex larger than the
39193981 * array length will search from the end of the array.
3982 * </p>
39203983 *
39213984 * @param array the array to traverse for looking for the object, may be {@code null}
39223985 * @param valueToFind the value to find
39253988 * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
39263989 */
39273990 public static int lastIndexOf(final double[] array, final double valueToFind, int startIndex) {
3928 if (isEmpty(array)) {
3991 if (isEmpty(array) || (startIndex < 0)) {
39293992 return INDEX_NOT_FOUND;
39303993 }
3931 if (startIndex < 0) {
3932 return INDEX_NOT_FOUND;
3933 } else if (startIndex >= array.length) {
3994 if (startIndex >= array.length) {
39343995 startIndex = array.length - 1;
39353996 }
39363997 for (int i = startIndex; i >= 0; i--) {
39424003 }
39434004
39444005 /**
3945 * <p>Finds the last index of the given value in the array starting at the given index.
4006 * Finds the last index of the given value in the array starting at the given index.
39464007 * This method will return the index of the last value which falls between the region
39474008 * defined by valueToFind - tolerance and valueToFind + tolerance.
3948 *
3949 * <p>This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
3950 *
3951 * <p>A negative startIndex will return {@link #INDEX_NOT_FOUND} ({@code -1}). A startIndex larger than the
4009 * <p>
4010 * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
4011 * </p>
4012 * <p>
4013 * A negative startIndex will return {@link #INDEX_NOT_FOUND} ({@code -1}). A startIndex larger than the
39524014 * array length will search from the end of the array.
4015 * </p>
39534016 *
39544017 * @param array the array to traverse for looking for the object, may be {@code null}
39554018 * @param valueToFind the value to find
39594022 * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
39604023 */
39614024 public static int lastIndexOf(final double[] array, final double valueToFind, int startIndex, final double tolerance) {
3962 if (isEmpty(array)) {
4025 if (isEmpty(array) || (startIndex < 0)) {
39634026 return INDEX_NOT_FOUND;
39644027 }
3965 if (startIndex < 0) {
3966 return INDEX_NOT_FOUND;
3967 } else if (startIndex >= array.length) {
4028 if (startIndex >= array.length) {
39684029 startIndex = array.length - 1;
39694030 }
39704031 final double min = valueToFind - tolerance;
39774038 return INDEX_NOT_FOUND;
39784039 }
39794040
3980
3981 /**
3982 * <p>Finds the last index of the given value within the array.
3983 *
3984 * <p>This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
4041 /**
4042 * Finds the last index of the given value within the array.
4043 * <p>
4044 * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
4045 * </p>
39854046 *
39864047 * @param array the array to traverse backwards looking for the object, may be {@code null}
39874048 * @param valueToFind the object to find
39934054 }
39944055
39954056 /**
3996 * <p>Finds the last index of the given value in the array starting at the given index.
3997 *
3998 * <p>This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
3999 *
4000 * <p>A negative startIndex will return {@link #INDEX_NOT_FOUND} ({@code -1}). A startIndex larger than the
4057 * Finds the last index of the given value in the array starting at the given index.
4058 * <p>
4059 * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
4060 * </p>
4061 * <p>
4062 * A negative startIndex will return {@link #INDEX_NOT_FOUND} ({@code -1}). A startIndex larger than the
40014063 * array length will search from the end of the array.
4064 * </p>
40024065 *
40034066 * @param array the array to traverse for looking for the object, may be {@code null}
40044067 * @param valueToFind the value to find
40074070 * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
40084071 */
40094072 public static int lastIndexOf(final float[] array, final float valueToFind, int startIndex) {
4010 if (isEmpty(array)) {
4073 if (isEmpty(array) || (startIndex < 0)) {
40114074 return INDEX_NOT_FOUND;
40124075 }
4013 if (startIndex < 0) {
4014 return INDEX_NOT_FOUND;
4015 } else if (startIndex >= array.length) {
4076 if (startIndex >= array.length) {
40164077 startIndex = array.length - 1;
40174078 }
40184079 for (int i = startIndex; i >= 0; i--) {
40234084 return INDEX_NOT_FOUND;
40244085 }
40254086
4026 /**
4027 * <p>Finds the last index of the given value within the array.
4028 *
4029 * <p>This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
4087
4088 /**
4089 * Finds the last index of the given value within the array.
4090 * <p>
4091 * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
4092 * </p>
40304093 *
40314094 * @param array the array to traverse backwards looking for the object, may be {@code null}
40324095 * @param valueToFind the object to find
40384101 }
40394102
40404103 /**
4041 * <p>Finds the last index of the given value in the array starting at the given index.
4042 *
4043 * <p>This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
4044 *
4045 * <p>A negative startIndex will return {@link #INDEX_NOT_FOUND} ({@code -1}). A startIndex larger than the
4104 * Finds the last index of the given value in the array starting at the given index.
4105 * <p>
4106 * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
4107 * </p>
4108 * <p>
4109 * A negative startIndex will return {@link #INDEX_NOT_FOUND} ({@code -1}). A startIndex larger than the
40464110 * array length will search from the end of the array.
4111 * </p>
40474112 *
40484113 * @param array the array to traverse for looking for the object, may be {@code null}
40494114 * @param valueToFind the value to find
40524117 * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
40534118 */
40544119 public static int lastIndexOf(final int[] array, final int valueToFind, int startIndex) {
4055 if (array == null) {
4120 if ((array == null) || (startIndex < 0)) {
40564121 return INDEX_NOT_FOUND;
40574122 }
4058 if (startIndex < 0) {
4059 return INDEX_NOT_FOUND;
4060 } else if (startIndex >= array.length) {
4123 if (startIndex >= array.length) {
40614124 startIndex = array.length - 1;
40624125 }
40634126 for (int i = startIndex; i >= 0; i--) {
40694132 }
40704133
40714134 /**
4072 * <p>Finds the last index of the given value within the array.
4073 *
4074 * <p>This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
4135 * Finds the last index of the given value within the array.
4136 * <p>
4137 * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
4138 * </p>
40754139 *
40764140 * @param array the array to traverse backwards looking for the object, may be {@code null}
40774141 * @param valueToFind the object to find
40834147 }
40844148
40854149 /**
4086 * <p>Finds the last index of the given value in the array starting at the given index.
4087 *
4088 * <p>This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
4089 *
4090 * <p>A negative startIndex will return {@link #INDEX_NOT_FOUND} ({@code -1}). A startIndex larger than the
4150 * Finds the last index of the given value in the array starting at the given index.
4151 * <p>
4152 * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
4153 * </p>
4154 * <p>
4155 * A negative startIndex will return {@link #INDEX_NOT_FOUND} ({@code -1}). A startIndex larger than the
40914156 * array length will search from the end of the array.
4157 * </p>
40924158 *
40934159 * @param array the array to traverse for looking for the object, may be {@code null}
40944160 * @param valueToFind the value to find
40974163 * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
40984164 */
40994165 public static int lastIndexOf(final long[] array, final long valueToFind, int startIndex) {
4100 if (array == null) {
4166 if ((array == null) || (startIndex < 0)) {
41014167 return INDEX_NOT_FOUND;
41024168 }
4103 if (startIndex < 0) {
4104 return INDEX_NOT_FOUND;
4105 } else if (startIndex >= array.length) {
4169 if (startIndex >= array.length) {
41064170 startIndex = array.length - 1;
41074171 }
41084172 for (int i = startIndex; i >= 0; i--) {
41144178 }
41154179
41164180 /**
4117 * <p>Finds the last index of the given object within the array.
4118 *
4119 * <p>This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
4181 * Finds the last index of the given object within the array.
4182 * <p>
4183 * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
4184 * </p>
41204185 *
41214186 * @param array the array to traverse backwards looking for the object, may be {@code null}
41224187 * @param objectToFind the object to find, may be {@code null}
41284193 }
41294194
41304195 /**
4131 * <p>Finds the last index of the given object in the array starting at the given index.
4132 *
4133 * <p>This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
4134 *
4135 * <p>A negative startIndex will return {@link #INDEX_NOT_FOUND} ({@code -1}). A startIndex larger than
4196 * Finds the last index of the given object in the array starting at the given index.
4197 * <p>
4198 * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
4199 * </p>
4200 * <p>
4201 * A negative startIndex will return {@link #INDEX_NOT_FOUND} ({@code -1}). A startIndex larger than
41364202 * the array length will search from the end of the array.
4203 * </p>
41374204 *
41384205 * @param array the array to traverse for looking for the object, may be {@code null}
41394206 * @param objectToFind the object to find, may be {@code null}
41424209 * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
41434210 */
41444211 public static int lastIndexOf(final Object[] array, final Object objectToFind, int startIndex) {
4145 if (array == null) {
4212 if ((array == null) || (startIndex < 0)) {
41464213 return INDEX_NOT_FOUND;
41474214 }
4148 if (startIndex < 0) {
4149 return INDEX_NOT_FOUND;
4150 } else if (startIndex >= array.length) {
4215 if (startIndex >= array.length) {
41514216 startIndex = array.length - 1;
41524217 }
41534218 if (objectToFind == null) {
41674232 }
41684233
41694234 /**
4170 * <p>Finds the last index of the given value within the array.
4171 *
4172 * <p>This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
4235 * Finds the last index of the given value within the array.
4236 * <p>
4237 * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
4238 * </p>
41734239 *
41744240 * @param array the array to traverse backwards looking for the object, may be {@code null}
41754241 * @param valueToFind the object to find
41814247 }
41824248
41834249 /**
4184 * <p>Finds the last index of the given value in the array starting at the given index.
4185 *
4186 * <p>This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
4187 *
4188 * <p>A negative startIndex will return {@link #INDEX_NOT_FOUND} ({@code -1}). A startIndex larger than the
4250 * Finds the last index of the given value in the array starting at the given index.
4251 * <p>
4252 * This method returns {@link #INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array.
4253 * </p>
4254 * <p>
4255 * A negative startIndex will return {@link #INDEX_NOT_FOUND} ({@code -1}). A startIndex larger than the
41894256 * array length will search from the end of the array.
4257 * </p>
41904258 *
41914259 * @param array the array to traverse for looking for the object, may be {@code null}
41924260 * @param valueToFind the value to find
41954263 * {@link #INDEX_NOT_FOUND} ({@code -1}) if not found or {@code null} array input
41964264 */
41974265 public static int lastIndexOf(final short[] array, final short valueToFind, int startIndex) {
4198 if (array == null) {
4266 if ((array == null) || (startIndex < 0)) {
41994267 return INDEX_NOT_FOUND;
42004268 }
4201 if (startIndex < 0) {
4202 return INDEX_NOT_FOUND;
4203 } else if (startIndex >= array.length) {
4269 if (startIndex >= array.length) {
42044270 startIndex = array.length - 1;
42054271 }
42064272 for (int i = startIndex; i >= 0; i--) {
42124278 }
42134279
42144280 /**
4215 * <p>Defensive programming technique to change a {@code null}
4281 * Delegates to {@link Array#newInstance(Class,int)} using generics.
4282 *
4283 * @param <T> The array type.
4284 * @param componentType The array class.
4285 * @param length the array length
4286 * @return The new array.
4287 * @exception NullPointerException if the specified {@code componentType} parameter is null.
4288 * @since 3.13.0
4289 */
4290 @SuppressWarnings("unchecked") // OK, because array and values are of type T
4291 public static <T> T[] newInstance(final Class<T> componentType, final int length) {
4292 return (T[]) Array.newInstance(componentType, length);
4293 }
4294
4295 /**
4296 * Defensive programming technique to change a {@code null}
42164297 * reference to an empty one.
4217 *
4218 * <p>This method returns an empty array for a {@code null} input array.
4219 *
4220 * <p>As a memory optimizing technique an empty array passed in will be overridden with
4298 * <p>
4299 * This method returns an empty array for a {@code null} input array.
4300 * </p>
4301 * <p>
4302 * As a memory optimizing technique an empty array passed in will be overridden with
42214303 * the empty {@code public static} references in this class.
4304 * </p>
42224305 *
42234306 * @param array the array to check for {@code null} or empty
42244307 * @return the same array, {@code public static} empty array if {@code null} or empty input
42324315 }
42334316
42344317 /**
4235 * <p>Defensive programming technique to change a {@code null}
4318 * Defensive programming technique to change a {@code null}
42364319 * reference to an empty one.
4237 *
4238 * <p>This method returns an empty array for a {@code null} input array.
4239 *
4240 * <p>As a memory optimizing technique an empty array passed in will be overridden with
4320 * <p>
4321 * This method returns an empty array for a {@code null} input array.
4322 * </p>
4323 * <p>
4324 * As a memory optimizing technique an empty array passed in will be overridden with
42414325 * the empty {@code public static} references in this class.
4326 * </p>
42424327 *
42434328 * @param array the array to check for {@code null} or empty
42444329 * @return the same array, {@code public static} empty array if {@code null} or empty input
42524337 }
42534338
42544339 /**
4255 * <p>Defensive programming technique to change a {@code null}
4340 * Defensive programming technique to change a {@code null}
42564341 * reference to an empty one.
4257 *
4258 * <p>This method returns an empty array for a {@code null} input array.
4259 *
4260 * <p>As a memory optimizing technique an empty array passed in will be overridden with
4342 * <p>
4343 * This method returns an empty array for a {@code null} input array.
4344 * </p>
4345 * <p>
4346 * As a memory optimizing technique an empty array passed in will be overridden with
42614347 * the empty {@code public static} references in this class.
4348 * </p>
42624349 *
42634350 * @param array the array to check for {@code null} or empty
42644351 * @return the same array, {@code public static} empty array if {@code null} or empty input
42724359 }
42734360
42744361 /**
4275 * <p>Defensive programming technique to change a {@code null}
4362 * Defensive programming technique to change a {@code null}
42764363 * reference to an empty one.
4277 *
4278 * <p>This method returns an empty array for a {@code null} input array.
4279 *
4280 * <p>As a memory optimizing technique an empty array passed in will be overridden with
4364 * <p>
4365 * This method returns an empty array for a {@code null} input array.
4366 * </p>
4367 * <p>
4368 * As a memory optimizing technique an empty array passed in will be overridden with
42814369 * the empty {@code public static} references in this class.
4370 * </p>
42824371 *
42834372 * @param array the array to check for {@code null} or empty
42844373 * @return the same array, {@code public static} empty array if {@code null} or empty input
42924381 }
42934382
42944383 /**
4295 * <p>Defensive programming technique to change a {@code null}
4384 * Defensive programming technique to change a {@code null}
42964385 * reference to an empty one.
4297 *
4298 * <p>This method returns an empty array for a {@code null} input array.
4299 *
4300 * <p>As a memory optimizing technique an empty array passed in will be overridden with
4386 * <p>
4387 * This method returns an empty array for a {@code null} input array.
4388 * </p>
4389 * <p>
4390 * As a memory optimizing technique an empty array passed in will be overridden with
43014391 * the empty {@code public static} references in this class.
4392 * </p>
43024393 *
43034394 * @param array the array to check for {@code null} or empty
43044395 * @return the same array, {@code public static} empty array if {@code null} or empty input
43124403 }
43134404
43144405 /**
4315 * <p>Defensive programming technique to change a {@code null}
4406 * Defensive programming technique to change a {@code null}
43164407 * reference to an empty one.
4317 *
4318 * <p>This method returns an empty array for a {@code null} input array.
4319 *
4320 * <p>As a memory optimizing technique an empty array passed in will be overridden with
4408 * <p>
4409 * This method returns an empty array for a {@code null} input array.
4410 * </p>
4411 * <p>
4412 * As a memory optimizing technique an empty array passed in will be overridden with
43214413 * the empty {@code public static} references in this class.
4414 * </p>
43224415 *
43234416 * @param array the array to check for {@code null} or empty
43244417 * @return the same array, {@code public static} empty array if {@code null} or empty input
43324425 }
43334426
43344427 /**
4335 * <p>Defensive programming technique to change a {@code null}
4428 * Defensive programming technique to change a {@code null}
43364429 * reference to an empty one.
4337 *
4338 * <p>This method returns an empty array for a {@code null} input array.
4339 *
4340 * <p>As a memory optimizing technique an empty array passed in will be overridden with
4430 * <p>
4431 * This method returns an empty array for a {@code null} input array.
4432 * </p>
4433 * <p>
4434 * As a memory optimizing technique an empty array passed in will be overridden with
43414435 * the empty {@code public static} references in this class.
4436 * </p>
43424437 *
43434438 * @param array the array to check for {@code null} or empty
43444439 * @return the same array, {@code public static} empty array if {@code null} or empty input
43524447 }
43534448
43544449 /**
4355 * <p>Defensive programming technique to change a {@code null}
4450 * Defensive programming technique to change a {@code null}
43564451 * reference to an empty one.
4357 *
4358 * <p>This method returns an empty array for a {@code null} input array.
4359 *
4360 * <p>As a memory optimizing technique an empty array passed in will be overridden with
4452 * <p>
4453 * This method returns an empty array for a {@code null} input array.
4454 * </p>
4455 * <p>
4456 * As a memory optimizing technique an empty array passed in will be overridden with
43614457 * the empty {@code public static} references in this class.
4458 * </p>
43624459 *
43634460 * @param array the array to check for {@code null} or empty
43644461 * @return the same array, {@code public static} empty array if {@code null} or empty input
43724469 }
43734470
43744471 /**
4375 * <p>Defensive programming technique to change a {@code null}
4472 * Defensive programming technique to change a {@code null}
43764473 * reference to an empty one.
4377 *
4378 * <p>This method returns an empty array for a {@code null} input array.
4379 *
4380 * <p>As a memory optimizing technique an empty array passed in will be overridden with
4474 * <p>
4475 * This method returns an empty array for a {@code null} input array.
4476 * </p>
4477 * <p>
4478 * As a memory optimizing technique an empty array passed in will be overridden with
43814479 * the empty {@code public static} references in this class.
4480 * </p>
43824481 *
43834482 * @param array the array to check for {@code null} or empty
43844483 * @return the same array, {@code public static} empty array if {@code null} or empty input
43924491 }
43934492
43944493 /**
4395 * <p>Defensive programming technique to change a {@code null}
4494 * Defensive programming technique to change a {@code null}
43964495 * reference to an empty one.
4397 *
4398 * <p>This method returns an empty array for a {@code null} input array.
4399 *
4400 * <p>As a memory optimizing technique an empty array passed in will be overridden with
4496 * <p>
4497 * This method returns an empty array for a {@code null} input array.
4498 * </p>
4499 * <p>
4500 * As a memory optimizing technique an empty array passed in will be overridden with
44014501 * the empty {@code public static} references in this class.
4502 * </p>
44024503 *
44034504 * @param array the array to check for {@code null} or empty
44044505 * @return the same array, {@code public static} empty array if {@code null} or empty input
44124513 }
44134514
44144515 /**
4415 * <p>Defensive programming technique to change a {@code null}
4516 * Defensive programming technique to change a {@code null}
44164517 * reference to an empty one.
4417 *
4418 * <p>This method returns an empty array for a {@code null} input array.
4419 *
4420 * <p>As a memory optimizing technique an empty array passed in will be overridden with
4518 * <p>
4519 * This method returns an empty array for a {@code null} input array.
4520 * </p>
4521 * <p>
4522 * As a memory optimizing technique an empty array passed in will be overridden with
44214523 * the empty {@code public static} references in this class.
4524 * </p>
44224525 *
44234526 * @param array the array to check for {@code null} or empty
44244527 * @return the same array, {@code public static} empty array if {@code null} or empty input
44324535 }
44334536
44344537 /**
4435 * <p>Defensive programming technique to change a {@code null}
4538 * Defensive programming technique to change a {@code null}
44364539 * reference to an empty one.
4437 *
4438 * <p>This method returns an empty array for a {@code null} input array.
4439 *
4440 * <p>As a memory optimizing technique an empty array passed in will be overridden with
4540 * <p>
4541 * This method returns an empty array for a {@code null} input array.
4542 * </p>
4543 * <p>
4544 * As a memory optimizing technique an empty array passed in will be overridden with
44414545 * the empty {@code public static} references in this class.
4546 * </p>
44424547 *
44434548 * @param array the array to check for {@code null} or empty
44444549 * @return the same array, {@code public static} empty array if {@code null} or empty input
44514556 return array;
44524557 }
44534558
4454 // Primitive/Object array converters
4455 // ----------------------------------------------------------------------
4456
4457 /**
4458 * <p>Defensive programming technique to change a {@code null}
4559 /**
4560 * Defensive programming technique to change a {@code null}
44594561 * reference to an empty one.
4460 *
4461 * <p>This method returns an empty array for a {@code null} input array.
4462 *
4463 * <p>As a memory optimizing technique an empty array passed in will be overridden with
4562 * <p>
4563 * This method returns an empty array for a {@code null} input array.
4564 * </p>
4565 * <p>
4566 * As a memory optimizing technique an empty array passed in will be overridden with
44644567 * the empty {@code public static} references in this class.
4568 * </p>
44654569 *
44664570 * @param array the array to check for {@code null} or empty
44674571 * @return the same array, {@code public static} empty array if {@code null} or empty input
44754579 }
44764580
44774581 /**
4478 * <p>Defensive programming technique to change a {@code null}
4582 * Defensive programming technique to change a {@code null}
44794583 * reference to an empty one.
4480 *
4481 * <p>This method returns an empty array for a {@code null} input array.
4482 *
4483 * <p>As a memory optimizing technique an empty array passed in will be overridden with
4584 * <p>
4585 * This method returns an empty array for a {@code null} input array.
4586 * </p>
4587 * <p>
4588 * As a memory optimizing technique an empty array passed in will be overridden with
44844589 * the empty {@code public static} references in this class.
4590 * </p>
44854591 *
44864592 * @param array the array to check for {@code null} or empty
44874593 * @return the same array, {@code public static} empty array if {@code null} or empty input
44954601 }
44964602
44974603 /**
4498 * <p>Defensive programming technique to change a {@code null}
4604 * Defensive programming technique to change a {@code null}
44994605 * reference to an empty one.
4500 *
4501 * <p>This method returns an empty array for a {@code null} input array.
4502 *
4503 * <p>As a memory optimizing technique an empty array passed in will be overridden with
4606 * <p>
4607 * This method returns an empty array for a {@code null} input array.
4608 * </p>
4609 * <p>
4610 * As a memory optimizing technique an empty array passed in will be overridden with
45044611 * the empty {@code public static} references in this class.
4612 * </p>
45054613 *
45064614 * @param array the array to check for {@code null} or empty
45074615 * @return the same array, {@code public static} empty array if {@code null} or empty input
45154623 }
45164624
45174625 /**
4518 * <p>Defensive programming technique to change a {@code null}
4626 * Defensive programming technique to change a {@code null}
45194627 * reference to an empty one.
4520 *
4521 * <p>This method returns an empty array for a {@code null} input array.
4522 *
4523 * <p>As a memory optimizing technique an empty array passed in will be overridden with
4628 * <p>
4629 * This method returns an empty array for a {@code null} input array.
4630 * </p>
4631 * <p>
4632 * As a memory optimizing technique an empty array passed in will be overridden with
45244633 * the empty {@code public static} references in this class.
4634 * </p>
45254635 *
45264636 * @param array the array to check for {@code null} or empty
45274637 * @return the same array, {@code public static} empty array if {@code null} or empty input
45354645 }
45364646
45374647 /**
4538 * <p>Defensive programming technique to change a {@code null}
4648 * Defensive programming technique to change a {@code null}
45394649 * reference to an empty one.
4540 *
4541 * <p>This method returns an empty array for a {@code null} input array.
4542 *
4543 * <p>As a memory optimizing technique an empty array passed in will be overridden with
4650 * <p>
4651 * This method returns an empty array for a {@code null} input array.
4652 * </p>
4653 * <p>
4654 * As a memory optimizing technique an empty array passed in will be overridden with
45444655 * the empty {@code public static} references in this class.
4656 * </p>
45454657 *
45464658 * @param array the array to check for {@code null} or empty
45474659 * @return the same array, {@code public static} empty array if {@code null} or empty input
45554667 }
45564668
45574669 /**
4558 * <p>Defensive programming technique to change a {@code null}
4670 * Defensive programming technique to change a {@code null}
45594671 * reference to an empty one.
4560 *
4561 * <p>This method returns an empty array for a {@code null} input array.
4562 *
4563 * <p>As a memory optimizing technique an empty array passed in will be overridden with
4672 * <p>
4673 * This method returns an empty array for a {@code null} input array.
4674 * </p>
4675 * <p>
4676 * As a memory optimizing technique an empty array passed in will be overridden with
45644677 * the empty {@code public static} references in this class.
4678 * </p>
45654679 *
45664680 * @param array the array to check for {@code null} or empty
45674681 * @return the same array, {@code public static} empty array if {@code null} or empty input
45754689 }
45764690
45774691 /**
4578 * <p>Defensive programming technique to change a {@code null}
4692 * Defensive programming technique to change a {@code null}
45794693 * reference to an empty one.
4580 *
4581 * <p>This method returns an empty array for a {@code null} input array.
4582 *
4583 * <p>As a memory optimizing technique an empty array passed in will be overridden with
4694 * <p>
4695 * This method returns an empty array for a {@code null} input array.
4696 * </p>
4697 * <p>
4698 * As a memory optimizing technique an empty array passed in will be overridden with
45844699 * the empty {@code public static} references in this class.
4700 * </p>
45854701 *
45864702 * @param array the array to check for {@code null} or empty
45874703 * @return the same array, {@code public static} empty array if {@code null} or empty input
45944710 return array;
45954711 }
45964712
4597 // nullToEmpty
4598 //-----------------------------------------------------------------------
4599 /**
4600 * <p>Defensive programming technique to change a {@code null}
4713 /**
4714 * Defensive programming technique to change a {@code null}
46014715 * reference to an empty one.
4602 *
4603 * <p>This method returns an empty array for a {@code null} input array.
4716 * <p>
4717 * This method returns an empty array for a {@code null} input array.
4718 * </p>
46044719 *
46054720 * @param array the array to check for {@code null} or empty
46064721 * @param type the class representation of the desired array
46204735 return array;
46214736 }
46224737
4623 /**
4624 * <p>Removes the element at the specified position from the specified array.
4738 private static ThreadLocalRandom random() {
4739 return ThreadLocalRandom.current();
4740 }
4741
4742 /**
4743 * Removes the element at the specified position from the specified array.
46254744 * All subsequent elements are shifted to the left (subtracts one from
46264745 * their indices).
4627 *
4628 * <p>This method returns a new array with the same elements of the input
4746 * <p>
4747 * This method returns a new array with the same elements of the input
46294748 * array except the element on the specified position. The component
46304749 * type of the returned array is always the same as that of the input
46314750 * array.
4632 *
4633 * <p>If the input array is {@code null}, an IndexOutOfBoundsException
4751 * </p>
4752 * <p>
4753 * If the input array is {@code null}, an IndexOutOfBoundsException
46344754 * will be thrown, because in that case no valid index can be specified.
4635 *
4755 * </p>
46364756 * <pre>
46374757 * ArrayUtils.remove([true], 0) = []
46384758 * ArrayUtils.remove([true, false], 0) = [false]
46534773 }
46544774
46554775 /**
4656 * <p>Removes the element at the specified position from the specified array.
4776 * Removes the element at the specified position from the specified array.
46574777 * All subsequent elements are shifted to the left (subtracts one from
46584778 * their indices).
4659 *
4660 * <p>This method returns a new array with the same elements of the input
4779 * <p>
4780 * This method returns a new array with the same elements of the input
46614781 * array except the element on the specified position. The component
46624782 * type of the returned array is always the same as that of the input
46634783 * array.
4664 *
4665 * <p>If the input array is {@code null}, an IndexOutOfBoundsException
4784 * </p>
4785 * <p>
4786 * If the input array is {@code null}, an IndexOutOfBoundsException
46664787 * will be thrown, because in that case no valid index can be specified.
4667 *
4788 * </p>
46684789 * <pre>
46694790 * ArrayUtils.remove([1], 0) = []
46704791 * ArrayUtils.remove([1, 0], 0) = [0]
46854806 }
46864807
46874808 /**
4688 * <p>Removes the element at the specified position from the specified array.
4809 * Removes the element at the specified position from the specified array.
46894810 * All subsequent elements are shifted to the left (subtracts one from
46904811 * their indices).
4691 *
4692 * <p>This method returns a new array with the same elements of the input
4812 * <p>
4813 * This method returns a new array with the same elements of the input
46934814 * array except the element on the specified position. The component
46944815 * type of the returned array is always the same as that of the input
46954816 * array.
4696 *
4697 * <p>If the input array is {@code null}, an IndexOutOfBoundsException
4817 * </p>
4818 * <p>
4819 * If the input array is {@code null}, an IndexOutOfBoundsException
46984820 * will be thrown, because in that case no valid index can be specified.
4699 *
4821 * </p>
47004822 * <pre>
47014823 * ArrayUtils.remove(['a'], 0) = []
47024824 * ArrayUtils.remove(['a', 'b'], 0) = ['b']
47174839 }
47184840
47194841 /**
4720 * <p>Removes the element at the specified position from the specified array.
4842 * Removes the element at the specified position from the specified array.
47214843 * All subsequent elements are shifted to the left (subtracts one from
47224844 * their indices).
4723 *
4724 * <p>This method returns a new array with the same elements of the input
4845 * <p>
4846 * This method returns a new array with the same elements of the input
47254847 * array except the element on the specified position. The component
47264848 * type of the returned array is always the same as that of the input
47274849 * array.
4728 *
4729 * <p>If the input array is {@code null}, an IndexOutOfBoundsException
4850 * </p>
4851 * <p>
4852 * If the input array is {@code null}, an IndexOutOfBoundsException
47304853 * will be thrown, because in that case no valid index can be specified.
4731 *
4854 * </p>
47324855 * <pre>
47334856 * ArrayUtils.remove([1.1], 0) = []
47344857 * ArrayUtils.remove([2.5, 6.0], 0) = [6.0]
47494872 }
47504873
47514874 /**
4752 * <p>Removes the element at the specified position from the specified array.
4875 * Removes the element at the specified position from the specified array.
47534876 * All subsequent elements are shifted to the left (subtracts one from
47544877 * their indices).
4755 *
4756 * <p>This method returns a new array with the same elements of the input
4878 * <p>
4879 * This method returns a new array with the same elements of the input
47574880 * array except the element on the specified position. The component
47584881 * type of the returned array is always the same as that of the input
47594882 * array.
4760 *
4761 * <p>If the input array is {@code null}, an IndexOutOfBoundsException
4883 * </p>
4884 * <p>
4885 * If the input array is {@code null}, an IndexOutOfBoundsException
47624886 * will be thrown, because in that case no valid index can be specified.
4763 *
4887 * </p>
47644888 * <pre>
47654889 * ArrayUtils.remove([1.1], 0) = []
47664890 * ArrayUtils.remove([2.5, 6.0], 0) = [6.0]
47814905 }
47824906
47834907 /**
4784 * <p>Removes the element at the specified position from the specified array.
4908 * Removes the element at the specified position from the specified array.
47854909 * All subsequent elements are shifted to the left (subtracts one from
47864910 * their indices).
4787 *
4788 * <p>This method returns a new array with the same elements of the input
4911 * <p>
4912 * This method returns a new array with the same elements of the input
47894913 * array except the element on the specified position. The component
47904914 * type of the returned array is always the same as that of the input
47914915 * array.
4792 *
4793 * <p>If the input array is {@code null}, an IndexOutOfBoundsException
4916 * </p>
4917 * <p>
4918 * If the input array is {@code null}, an IndexOutOfBoundsException
47944919 * will be thrown, because in that case no valid index can be specified.
4795 *
4920 * </p>
47964921 * <pre>
47974922 * ArrayUtils.remove([1], 0) = []
47984923 * ArrayUtils.remove([2, 6], 0) = [6]
48134938 }
48144939
48154940 /**
4816 * <p>Removes the element at the specified position from the specified array.
4941 * Removes the element at the specified position from the specified array.
48174942 * All subsequent elements are shifted to the left (subtracts one from
48184943 * their indices).
4819 *
4820 * <p>This method returns a new array with the same elements of the input
4944 * <p>
4945 * This method returns a new array with the same elements of the input
48214946 * array except the element on the specified position. The component
48224947 * type of the returned array is always the same as that of the input
48234948 * array.
4824 *
4825 * <p>If the input array is {@code null}, an IndexOutOfBoundsException
4949 * </p>
4950 * <p>
4951 * If the input array is {@code null}, an IndexOutOfBoundsException
48264952 * will be thrown, because in that case no valid index can be specified.
4827 *
4953 * </p>
48284954 * <pre>
48294955 * ArrayUtils.remove([1], 0) = []
48304956 * ArrayUtils.remove([2, 6], 0) = [6]
48454971 }
48464972
48474973 /**
4848 * <p>Removes the element at the specified position from the specified array.
4974 * Removes the element at the specified position from the specified array.
48494975 * All subsequent elements are shifted to the left (subtracts one from
48504976 * their indices).
4851 *
4852 * <p>This method returns a new array with the same elements of the input
4977 * <p>
4978 * This method returns a new array with the same elements of the input
48534979 * array except the element on the specified position. The component
48544980 * type of the returned array is always the same as that of the input
48554981 * array.
4856 *
4857 * <p>If the input array is {@code null}, an IndexOutOfBoundsException
4982 * </p>
4983 * <p>
4984 * If the input array is {@code null}, an IndexOutOfBoundsException
48584985 * will be thrown, because in that case no valid index can be specified.
4986 * </p>
48594987 *
48604988 * @param array the array to remove the element from, may not be {@code null}
48614989 * @param index the position of the element to be removed
48815009 }
48825010
48835011 /**
4884 * <p>Removes the element at the specified position from the specified array.
5012 * Removes the element at the specified position from the specified array.
48855013 * All subsequent elements are shifted to the left (subtracts one from
48865014 * their indices).
4887 *
4888 * <p>This method returns a new array with the same elements of the input
5015 * <p>
5016 * This method returns a new array with the same elements of the input
48895017 * array except the element on the specified position. The component
48905018 * type of the returned array is always the same as that of the input
48915019 * array.
4892 *
4893 * <p>If the input array is {@code null}, an IndexOutOfBoundsException
5020 * </p>
5021 * <p>
5022 * If the input array is {@code null}, an IndexOutOfBoundsException
48945023 * will be thrown, because in that case no valid index can be specified.
4895 *
5024 * </p>
48965025 * <pre>
48975026 * ArrayUtils.remove([1], 0) = []
48985027 * ArrayUtils.remove([2, 6], 0) = [6]
49135042 }
49145043
49155044 /**
4916 * <p>Removes the element at the specified position from the specified array.
5045 * Removes the element at the specified position from the specified array.
49175046 * All subsequent elements are shifted to the left (subtracts one from
49185047 * their indices).
4919 *
4920 * <p>This method returns a new array with the same elements of the input
5048 * <p>
5049 * This method returns a new array with the same elements of the input
49215050 * array except the element on the specified position. The component
49225051 * type of the returned array is always the same as that of the input
49235052 * array.
4924 *
4925 * <p>If the input array is {@code null}, an IndexOutOfBoundsException
5053 * </p>
5054 * <p>
5055 * If the input array is {@code null}, an IndexOutOfBoundsException
49265056 * will be thrown, because in that case no valid index can be specified.
4927 *
5057 * </p>
49285058 * <pre>
49295059 * ArrayUtils.remove(["a"], 0) = []
49305060 * ArrayUtils.remove(["a", "b"], 0) = ["b"]
49475077 }
49485078
49495079 /**
4950 * <p>Removes the elements at the specified positions from the specified array.
5080 * Removes the elements at the specified positions from the specified array.
49515081 * All remaining elements are shifted to the left.
4952 *
4953 * <p>This method returns a new array with the same elements of the input
5082 * <p>
5083 * This method returns a new array with the same elements of the input
49545084 * array except those at the specified positions. The component
49555085 * type of the returned array is always the same as that of the input
49565086 * array.
4957 *
4958 * <p>If the input array is {@code null}, an IndexOutOfBoundsException
5087 * </p>
5088 * <p>
5089 * If the input array is {@code null}, an IndexOutOfBoundsException
49595090 * will be thrown, because in that case no valid index can be specified.
4960 *
5091 * </p>
49615092 * <pre>
49625093 * ArrayUtils.removeAll([true, false, true], 0, 2) = [false]
49635094 * ArrayUtils.removeAll([true, false, true], 1, 2) = [true]
49765107 }
49775108
49785109 /**
4979 * <p>Removes the elements at the specified positions from the specified array.
5110 * Removes the elements at the specified positions from the specified array.
49805111 * All remaining elements are shifted to the left.
4981 *
4982 * <p>This method returns a new array with the same elements of the input
5112 * <p>
5113 * This method returns a new array with the same elements of the input
49835114 * array except those at the specified positions. The component
49845115 * type of the returned array is always the same as that of the input
49855116 * array.
4986 *
4987 * <p>If the input array is {@code null}, an IndexOutOfBoundsException
5117 * </p>
5118 * <p>
5119 * If the input array is {@code null}, an IndexOutOfBoundsException
49885120 * will be thrown, because in that case no valid index can be specified.
4989 *
5121 * </p>
49905122 * <pre>
49915123 * ArrayUtils.removeAll([1], 0) = []
49925124 * ArrayUtils.removeAll([2, 6], 0) = [6]
50095141 }
50105142
50115143 /**
5012 * <p>Removes the elements at the specified positions from the specified array.
5144 * Removes the elements at the specified positions from the specified array.
50135145 * All remaining elements are shifted to the left.
5014 *
5015 * <p>This method returns a new array with the same elements of the input
5146 * <p>
5147 * This method returns a new array with the same elements of the input
50165148 * array except those at the specified positions. The component
50175149 * type of the returned array is always the same as that of the input
50185150 * array.
5019 *
5020 * <p>If the input array is {@code null}, an IndexOutOfBoundsException
5151 * </p>
5152 * <p>
5153 * If the input array is {@code null}, an IndexOutOfBoundsException
50215154 * will be thrown, because in that case no valid index can be specified.
5022 *
5155 * </p>
50235156 * <pre>
50245157 * ArrayUtils.removeAll([1], 0) = []
50255158 * ArrayUtils.removeAll([2, 6], 0) = [6]
50425175 }
50435176
50445177 /**
5045 * <p>Removes the elements at the specified positions from the specified array.
5178 * Removes the elements at the specified positions from the specified array.
50465179 * All remaining elements are shifted to the left.
5047 *
5048 * <p>This method returns a new array with the same elements of the input
5180 * <p>
5181 * This method returns a new array with the same elements of the input
50495182 * array except those at the specified positions. The component
50505183 * type of the returned array is always the same as that of the input
50515184 * array.
5052 *
5053 * <p>If the input array is {@code null}, an IndexOutOfBoundsException
5185 * </p>
5186 * <p>
5187 * If the input array is {@code null}, an IndexOutOfBoundsException
50545188 * will be thrown, because in that case no valid index can be specified.
5055 *
5189 * </p>
50565190 * <pre>
50575191 * ArrayUtils.removeAll([1], 0) = []
50585192 * ArrayUtils.removeAll([2, 6], 0) = [6]
50755209 }
50765210
50775211 /**
5078 * <p>Removes the elements at the specified positions from the specified array.
5212 * Removes the elements at the specified positions from the specified array.
50795213 * All remaining elements are shifted to the left.
5080 *
5081 * <p>This method returns a new array with the same elements of the input
5214 * <p>
5215 * This method returns a new array with the same elements of the input
50825216 * array except those at the specified positions. The component
50835217 * type of the returned array is always the same as that of the input
50845218 * array.
5085 *
5086 * <p>If the input array is {@code null}, an IndexOutOfBoundsException
5219 * </p>
5220 * <p>
5221 * If the input array is {@code null}, an IndexOutOfBoundsException
50875222 * will be thrown, because in that case no valid index can be specified.
5088 *
5223 * </p>
50895224 * <pre>
50905225 * ArrayUtils.removeAll([1], 0) = []
50915226 * ArrayUtils.removeAll([2, 6], 0) = [6]
51085243 }
51095244
51105245 /**
5111 * <p>Removes the elements at the specified positions from the specified array.
5246 * Removes the elements at the specified positions from the specified array.
51125247 * All remaining elements are shifted to the left.
5113 *
5114 * <p>This method returns a new array with the same elements of the input
5248 * <p>
5249 * This method returns a new array with the same elements of the input
51155250 * array except those at the specified positions. The component
51165251 * type of the returned array is always the same as that of the input
51175252 * array.
5118 *
5119 * <p>If the input array is {@code null}, an IndexOutOfBoundsException
5253 * </p>
5254 * <p>
5255 * If the input array is {@code null}, an IndexOutOfBoundsException
51205256 * will be thrown, because in that case no valid index can be specified.
5121 *
5257 * </p>
51225258 * <pre>
51235259 * ArrayUtils.removeAll([1], 0) = []
51245260 * ArrayUtils.removeAll([2, 6], 0) = [6]
51415277 }
51425278
51435279 /**
5144 * <p>Removes the elements at the specified positions from the specified array.
5280 * Removes the elements at the specified positions from the specified array.
51455281 * All remaining elements are shifted to the left.
5146 *
5147 * <p>This method returns a new array with the same elements of the input
5282 * <p>
5283 * This method returns a new array with the same elements of the input
51485284 * array except those at the specified positions. The component
51495285 * type of the returned array is always the same as that of the input
51505286 * array.
5151 *
5152 * <p>If the input array is {@code null}, an IndexOutOfBoundsException
5287 * </p>
5288 * <p>
5289 * If the input array is {@code null}, an IndexOutOfBoundsException
51535290 * will be thrown, because in that case no valid index can be specified.
5154 *
5291 * </p>
51555292 * <pre>
51565293 * ArrayUtils.removeAll([1], 0) = []
51575294 * ArrayUtils.removeAll([2, 6], 0) = [6]
52175354
52185355 /**
52195356 * Removes multiple array elements specified by index.
5357 *
52205358 * @param array source
52215359 * @param indices to remove
52225360 * @return new array of same type minus elements specified by unique values of {@code indices}
52265364 static Object removeAll(final Object array, final int... indices) {
52275365 final int length = getLength(array);
52285366 int diff = 0; // number of distinct indexes, i.e. number of entries that will be removed
5229 final int[] clonedIndices = clone(indices);
5230 Arrays.sort(clonedIndices);
5367 final int[] clonedIndices = ArraySorter.sort(clone(indices));
52315368
52325369 // identify length of result array
52335370 if (isNotEmpty(clonedIndices)) {
52695406 }
52705407
52715408 /**
5272 * <p>Removes the elements at the specified positions from the specified array.
5409 * Removes the elements at the specified positions from the specified array.
52735410 * All remaining elements are shifted to the left.
5274 *
5275 * <p>This method returns a new array with the same elements of the input
5411 * <p>
5412 * This method returns a new array with the same elements of the input
52765413 * array except those at the specified positions. The component
52775414 * type of the returned array is always the same as that of the input
52785415 * array.
5279 *
5280 * <p>If the input array is {@code null}, an IndexOutOfBoundsException
5416 * </p>
5417 * <p>
5418 * If the input array is {@code null}, an IndexOutOfBoundsException
52815419 * will be thrown, because in that case no valid index can be specified.
5282 *
5420 * </p>
52835421 * <pre>
52845422 * ArrayUtils.removeAll([1], 0) = []
52855423 * ArrayUtils.removeAll([2, 6], 0) = [6]
53025440 }
53035441
53045442 /**
5305 * <p>Removes the elements at the specified positions from the specified array.
5443 * Removes the elements at the specified positions from the specified array.
53065444 * All remaining elements are shifted to the left.
5307 *
5308 * <p>This method returns a new array with the same elements of the input
5445 * <p>
5446 * This method returns a new array with the same elements of the input
53095447 * array except those at the specified positions. The component
53105448 * type of the returned array is always the same as that of the input
53115449 * array.
5312 *
5313 * <p>If the input array is {@code null}, an IndexOutOfBoundsException
5450 * </p>
5451 * <p>
5452 * If the input array is {@code null}, an IndexOutOfBoundsException
53145453 * will be thrown, because in that case no valid index can be specified.
5315 *
5454 * </p>
53165455 * <pre>
53175456 * ArrayUtils.removeAll(["a", "b", "c"], 0, 2) = ["b"]
53185457 * ArrayUtils.removeAll(["a", "b", "c"], 1, 2) = ["a"]
53345473
53355474 /**
53365475 * Removes the occurrences of the specified element from the specified boolean array.
5337 *
53385476 * <p>
53395477 * All subsequent elements are shifted to the left (subtracts one from their indices).
53405478 * If the array doesn't contains such an element, no elements are removed from the array.
53555493
53565494 /**
53575495 * Removes the occurrences of the specified element from the specified byte array.
5358 *
53595496 * <p>
53605497 * All subsequent elements are shifted to the left (subtracts one from their indices).
53615498 * If the array doesn't contains such an element, no elements are removed from the array.
53765513
53775514 /**
53785515 * Removes the occurrences of the specified element from the specified char array.
5379 *
53805516 * <p>
53815517 * All subsequent elements are shifted to the left (subtracts one from their indices).
53825518 * If the array doesn't contains such an element, no elements are removed from the array.
53975533
53985534 /**
53995535 * Removes the occurrences of the specified element from the specified double array.
5400 *
54015536 * <p>
54025537 * All subsequent elements are shifted to the left (subtracts one from their indices).
54035538 * If the array doesn't contains such an element, no elements are removed from the array.
54185553
54195554 /**
54205555 * Removes the occurrences of the specified element from the specified float array.
5421 *
54225556 * <p>
54235557 * All subsequent elements are shifted to the left (subtracts one from their indices).
54245558 * If the array doesn't contains such an element, no elements are removed from the array.
54395573
54405574 /**
54415575 * Removes the occurrences of the specified element from the specified int array.
5442 *
54435576 * <p>
54445577 * All subsequent elements are shifted to the left (subtracts one from their indices).
54455578 * If the array doesn't contains such an element, no elements are removed from the array.
54605593
54615594 /**
54625595 * Removes the occurrences of the specified element from the specified long array.
5463 *
54645596 * <p>
54655597 * All subsequent elements are shifted to the left (subtracts one from their indices).
54665598 * If the array doesn't contains such an element, no elements are removed from the array.
54815613
54825614 /**
54835615 * Removes the occurrences of the specified element from the specified short array.
5484 *
54855616 * <p>
54865617 * All subsequent elements are shifted to the left (subtracts one from their indices).
54875618 * If the array doesn't contains such an element, no elements are removed from the array.
55025633
55035634 /**
55045635 * Removes the occurrences of the specified element from the specified array.
5505 *
55065636 * <p>
55075637 * All subsequent elements are shifted to the left (subtracts one from their indices).
55085638 * If the array doesn't contains such an element, no elements are removed from the array.
55245654
55255655 /**
55265656 * Removes the occurrences of the specified element from the specified boolean array.
5527 *
55285657 * <p>
55295658 * All subsequent elements are shifted to the left (subtracts one from their indices).
55305659 * If the array doesn't contains such an element, no elements are removed from the array.
55435672
55445673 /**
55455674 * Removes the occurrences of the specified element from the specified byte array.
5546 *
55475675 * <p>
55485676 * All subsequent elements are shifted to the left (subtracts one from their indices).
55495677 * If the array doesn't contains such an element, no elements are removed from the array.
55625690
55635691 /**
55645692 * Removes the occurrences of the specified element from the specified char array.
5565 *
55665693 * <p>
55675694 * All subsequent elements are shifted to the left (subtracts one from their indices).
55685695 * If the array doesn't contains such an element, no elements are removed from the array.
55815708
55825709 /**
55835710 * Removes the occurrences of the specified element from the specified double array.
5584 *
55855711 * <p>
55865712 * All subsequent elements are shifted to the left (subtracts one from their indices).
55875713 * If the array doesn't contains such an element, no elements are removed from the array.
56005726
56015727 /**
56025728 * Removes the occurrences of the specified element from the specified float array.
5603 *
56045729 * <p>
56055730 * All subsequent elements are shifted to the left (subtracts one from their indices).
56065731 * If the array doesn't contains such an element, no elements are removed from the array.
56195744
56205745 /**
56215746 * Removes the occurrences of the specified element from the specified int array.
5622 *
56235747 * <p>
56245748 * All subsequent elements are shifted to the left (subtracts one from their indices).
56255749 * If the array doesn't contains such an element, no elements are removed from the array.
56385762
56395763 /**
56405764 * Removes the occurrences of the specified element from the specified long array.
5641 *
56425765 * <p>
56435766 * All subsequent elements are shifted to the left (subtracts one from their indices).
56445767 * If the array doesn't contains such an element, no elements are removed from the array.
56575780
56585781 /**
56595782 * Removes the occurrences of the specified element from the specified short array.
5660 *
56615783 * <p>
56625784 * All subsequent elements are shifted to the left (subtracts one from their indices).
56635785 * If the array doesn't contains such an element, no elements are removed from the array.
56765798
56775799 /**
56785800 * Removes the occurrences of the specified element from the specified array.
5679 *
56805801 * <p>
56815802 * All subsequent elements are shifted to the left (subtracts one from their indices).
56825803 * If the array doesn't contains such an element, no elements are removed from the array.
56955816 }
56965817
56975818 /**
5698 * <p>Removes the first occurrence of the specified element from the
5819 * Removes the first occurrence of the specified element from the
56995820 * specified array. All subsequent elements are shifted to the left
57005821 * (subtracts one from their indices). If the array doesn't contains
57015822 * such an element, no elements are removed from the array.
5702 *
5703 * <p>This method returns a new array with the same elements of the input
5823 * <p>
5824 * This method returns a new array with the same elements of the input
57045825 * array except the first occurrence of the specified element. The component
57055826 * type of the returned array is always the same as that of the input
57065827 * array.
5707 *
5828 * </p>
57085829 * <pre>
57095830 * ArrayUtils.removeElement(null, true) = null
57105831 * ArrayUtils.removeElement([], true) = []
57285849 }
57295850
57305851 /**
5731 * <p>Removes the first occurrence of the specified element from the
5852 * Removes the first occurrence of the specified element from the
57325853 * specified array. All subsequent elements are shifted to the left
57335854 * (subtracts one from their indices). If the array doesn't contains
57345855 * such an element, no elements are removed from the array.
5735 *
5736 * <p>This method returns a new array with the same elements of the input
5856 * <p>
5857 * This method returns a new array with the same elements of the input
57375858 * array except the first occurrence of the specified element. The component
57385859 * type of the returned array is always the same as that of the input
57395860 * array.
5740 *
5861 * </p>
57415862 * <pre>
57425863 * ArrayUtils.removeElement(null, 1) = null
57435864 * ArrayUtils.removeElement([], 1) = []
57615882 }
57625883
57635884 /**
5764 * <p>Removes the first occurrence of the specified element from the
5885 * Removes the first occurrence of the specified element from the
57655886 * specified array. All subsequent elements are shifted to the left
57665887 * (subtracts one from their indices). If the array doesn't contains
57675888 * such an element, no elements are removed from the array.
5768 *
5769 * <p>This method returns a new array with the same elements of the input
5889 * <p>
5890 * This method returns a new array with the same elements of the input
57705891 * array except the first occurrence of the specified element. The component
57715892 * type of the returned array is always the same as that of the input
57725893 * array.
5773 *
5894 * </p>
57745895 * <pre>
57755896 * ArrayUtils.removeElement(null, 'a') = null
57765897 * ArrayUtils.removeElement([], 'a') = []
57945915 }
57955916
57965917 /**
5797 * <p>Removes the first occurrence of the specified element from the
5918 * Removes the first occurrence of the specified element from the
57985919 * specified array. All subsequent elements are shifted to the left
57995920 * (subtracts one from their indices). If the array doesn't contains
58005921 * such an element, no elements are removed from the array.
5801 *
5802 * <p>This method returns a new array with the same elements of the input
5922 * <p>
5923 * This method returns a new array with the same elements of the input
58035924 * array except the first occurrence of the specified element. The component
58045925 * type of the returned array is always the same as that of the input
58055926 * array.
5806 *
5927 * </p>
58075928 * <pre>
58085929 * ArrayUtils.removeElement(null, 1.1) = null
58095930 * ArrayUtils.removeElement([], 1.1) = []
58275948 }
58285949
58295950 /**
5830 * <p>Removes the first occurrence of the specified element from the
5951 * Removes the first occurrence of the specified element from the
58315952 * specified array. All subsequent elements are shifted to the left
58325953 * (subtracts one from their indices). If the array doesn't contains
58335954 * such an element, no elements are removed from the array.
5834 *
5835 * <p>This method returns a new array with the same elements of the input
5955 * <p>
5956 * This method returns a new array with the same elements of the input
58365957 * array except the first occurrence of the specified element. The component
58375958 * type of the returned array is always the same as that of the input
58385959 * array.
5839 *
5960 * </p>
58405961 * <pre>
58415962 * ArrayUtils.removeElement(null, 1.1) = null
58425963 * ArrayUtils.removeElement([], 1.1) = []
58605981 }
58615982
58625983 /**
5863 * <p>Removes the first occurrence of the specified element from the
5984 * Removes the first occurrence of the specified element from the
58645985 * specified array. All subsequent elements are shifted to the left
58655986 * (subtracts one from their indices). If the array doesn't contains
58665987 * such an element, no elements are removed from the array.
5867 *
5868 * <p>This method returns a new array with the same elements of the input
5988 * <p>
5989 * This method returns a new array with the same elements of the input
58695990 * array except the first occurrence of the specified element. The component
58705991 * type of the returned array is always the same as that of the input
58715992 * array.
5872 *
5993 * </p>
58735994 * <pre>
58745995 * ArrayUtils.removeElement(null, 1) = null
58755996 * ArrayUtils.removeElement([], 1) = []
58936014 }
58946015
58956016 /**
5896 * <p>Removes the first occurrence of the specified element from the
6017 * Removes the first occurrence of the specified element from the
58976018 * specified array. All subsequent elements are shifted to the left
58986019 * (subtracts one from their indices). If the array doesn't contains
58996020 * such an element, no elements are removed from the array.
5900 *
5901 * <p>This method returns a new array with the same elements of the input
6021 * <p>
6022 * This method returns a new array with the same elements of the input
59026023 * array except the first occurrence of the specified element. The component
59036024 * type of the returned array is always the same as that of the input
59046025 * array.
5905 *
6026 * </p>
59066027 * <pre>
59076028 * ArrayUtils.removeElement(null, 1) = null
59086029 * ArrayUtils.removeElement([], 1) = []
59266047 }
59276048
59286049 /**
5929 * <p>Removes the first occurrence of the specified element from the
6050 * Removes the first occurrence of the specified element from the
59306051 * specified array. All subsequent elements are shifted to the left
59316052 * (subtracts one from their indices). If the array doesn't contains
59326053 * such an element, no elements are removed from the array.
5933 *
5934 * <p>This method returns a new array with the same elements of the input
6054 * <p>
6055 * This method returns a new array with the same elements of the input
59356056 * array except the first occurrence of the specified element. The component
59366057 * type of the returned array is always the same as that of the input
59376058 * array.
5938 *
6059 * </p>
59396060 * <pre>
59406061 * ArrayUtils.removeElement(null, 1) = null
59416062 * ArrayUtils.removeElement([], 1) = []
59596080 }
59606081
59616082 /**
5962 * <p>Removes the first occurrence of the specified element from the
6083 * Removes the first occurrence of the specified element from the
59636084 * specified array. All subsequent elements are shifted to the left
59646085 * (subtracts one from their indices). If the array doesn't contains
59656086 * such an element, no elements are removed from the array.
5966 *
5967 * <p>This method returns a new array with the same elements of the input
6087 * <p>
6088 * This method returns a new array with the same elements of the input
59686089 * array except the first occurrence of the specified element. The component
59696090 * type of the returned array is always the same as that of the input
59706091 * array.
5971 *
6092 * </p>
59726093 * <pre>
59736094 * ArrayUtils.removeElement(null, "a") = null
59746095 * ArrayUtils.removeElement([], "a") = []
59936114 }
59946115
59956116 /**
5996 * <p>Removes occurrences of specified elements, in specified quantities,
6117 * Removes occurrences of specified elements, in specified quantities,
59976118 * from the specified array. All subsequent elements are shifted left.
59986119 * For any element-to-be-removed specified in greater quantities than
59996120 * contained in the original array, no change occurs beyond the
60006121 * removal of the existing matching items.
6001 *
6002 * <p>This method returns a new array with the same elements of the input
6122 * <p>
6123 * This method returns a new array with the same elements of the input
60036124 * array except for the earliest-encountered occurrences of the specified
60046125 * elements. The component type of the returned array is always the same
60056126 * as that of the input array.
6006 *
6127 * </p>
60076128 * <pre>
60086129 * ArrayUtils.removeElements(null, true, false) = null
60096130 * ArrayUtils.removeElements([], true, false) = []
60486169 }
60496170
60506171 /**
6051 * <p>Removes occurrences of specified elements, in specified quantities,
6172 * Removes occurrences of specified elements, in specified quantities,
60526173 * from the specified array. All subsequent elements are shifted left.
60536174 * For any element-to-be-removed specified in greater quantities than
60546175 * contained in the original array, no change occurs beyond the
60556176 * removal of the existing matching items.
6056 *
6057 * <p>This method returns a new array with the same elements of the input
6177 * <p>
6178 * This method returns a new array with the same elements of the input
60586179 * array except for the earliest-encountered occurrences of the specified
60596180 * elements. The component type of the returned array is always the same
60606181 * as that of the input array.
6061 *
6182 * </p>
60626183 * <pre>
60636184 * ArrayUtils.removeElements(null, 1, 2) = null
60646185 * ArrayUtils.removeElements([], 1, 2) = []
61036224 }
61046225
61056226 /**
6106 * <p>Removes occurrences of specified elements, in specified quantities,
6227 * Removes occurrences of specified elements, in specified quantities,
61076228 * from the specified array. All subsequent elements are shifted left.
61086229 * For any element-to-be-removed specified in greater quantities than
61096230 * contained in the original array, no change occurs beyond the
61106231 * removal of the existing matching items.
6111 *
6112 * <p>This method returns a new array with the same elements of the input
6232 * <p>
6233 * This method returns a new array with the same elements of the input
61136234 * array except for the earliest-encountered occurrences of the specified
61146235 * elements. The component type of the returned array is always the same
61156236 * as that of the input array.
6116 *
6237 * </p>
61176238 * <pre>
61186239 * ArrayUtils.removeElements(null, 1, 2) = null
61196240 * ArrayUtils.removeElements([], 1, 2) = []
61586279 }
61596280
61606281 /**
6161 * <p>Removes occurrences of specified elements, in specified quantities,
6282 * Removes occurrences of specified elements, in specified quantities,
61626283 * from the specified array. All subsequent elements are shifted left.
61636284 * For any element-to-be-removed specified in greater quantities than
61646285 * contained in the original array, no change occurs beyond the
61656286 * removal of the existing matching items.
6166 *
6167 * <p>This method returns a new array with the same elements of the input
6287 * <p>
6288 * This method returns a new array with the same elements of the input
61686289 * array except for the earliest-encountered occurrences of the specified
61696290 * elements. The component type of the returned array is always the same
61706291 * as that of the input array.
6171 *
6292 * </p>
61726293 * <pre>
61736294 * ArrayUtils.removeElements(null, 1, 2) = null
61746295 * ArrayUtils.removeElements([], 1, 2) = []
62136334 }
62146335
62156336 /**
6216 * <p>Removes occurrences of specified elements, in specified quantities,
6337 * Removes occurrences of specified elements, in specified quantities,
62176338 * from the specified array. All subsequent elements are shifted left.
62186339 * For any element-to-be-removed specified in greater quantities than
62196340 * contained in the original array, no change occurs beyond the
62206341 * removal of the existing matching items.
6221 *
6222 * <p>This method returns a new array with the same elements of the input
6342 * <p>
6343 * This method returns a new array with the same elements of the input
62236344 * array except for the earliest-encountered occurrences of the specified
62246345 * elements. The component type of the returned array is always the same
62256346 * as that of the input array.
6226 *
6347 * </p>
62276348 * <pre>
62286349 * ArrayUtils.removeElements(null, 1, 2) = null
62296350 * ArrayUtils.removeElements([], 1, 2) = []
62686389 }
62696390
62706391 /**
6271 * <p>Removes occurrences of specified elements, in specified quantities,
6392 * Removes occurrences of specified elements, in specified quantities,
62726393 * from the specified array. All subsequent elements are shifted left.
62736394 * For any element-to-be-removed specified in greater quantities than
62746395 * contained in the original array, no change occurs beyond the
62756396 * removal of the existing matching items.
6276 *
6277 * <p>This method returns a new array with the same elements of the input
6397 * <p>
6398 * This method returns a new array with the same elements of the input
62786399 * array except for the earliest-encountered occurrences of the specified
62796400 * elements. The component type of the returned array is always the same
62806401 * as that of the input array.
6281 *
6402 * </p>
62826403 * <pre>
62836404 * ArrayUtils.removeElements(null, 1, 2) = null
62846405 * ArrayUtils.removeElements([], 1, 2) = []
63236444 }
63246445
63256446 /**
6326 * <p>Removes occurrences of specified elements, in specified quantities,
6447 * Removes occurrences of specified elements, in specified quantities,
63276448 * from the specified array. All subsequent elements are shifted left.
63286449 * For any element-to-be-removed specified in greater quantities than
63296450 * contained in the original array, no change occurs beyond the
63306451 * removal of the existing matching items.
6331 *
6332 * <p>This method returns a new array with the same elements of the input
6452 * <p>
6453 * This method returns a new array with the same elements of the input
63336454 * array except for the earliest-encountered occurrences of the specified
63346455 * elements. The component type of the returned array is always the same
63356456 * as that of the input array.
6336 *
6457 * </p>
63376458 * <pre>
63386459 * ArrayUtils.removeElements(null, 1, 2) = null
63396460 * ArrayUtils.removeElements([], 1, 2) = []
63786499 }
63796500
63806501 /**
6381 * <p>Removes occurrences of specified elements, in specified quantities,
6502 * Removes occurrences of specified elements, in specified quantities,
63826503 * from the specified array. All subsequent elements are shifted left.
63836504 * For any element-to-be-removed specified in greater quantities than
63846505 * contained in the original array, no change occurs beyond the
63856506 * removal of the existing matching items.
6386 *
6387 * <p>This method returns a new array with the same elements of the input
6507 * <p>
6508 * This method returns a new array with the same elements of the input
63886509 * array except for the earliest-encountered occurrences of the specified
63896510 * elements. The component type of the returned array is always the same
63906511 * as that of the input array.
6391 *
6512 * </p>
63926513 * <pre>
63936514 * ArrayUtils.removeElements(null, 1, 2) = null
63946515 * ArrayUtils.removeElements([], 1, 2) = []
64336554 }
64346555
64356556 /**
6436 * <p>Removes occurrences of specified elements, in specified quantities,
6557 * Removes occurrences of specified elements, in specified quantities,
64376558 * from the specified array. All subsequent elements are shifted left.
64386559 * For any element-to-be-removed specified in greater quantities than
64396560 * contained in the original array, no change occurs beyond the
64406561 * removal of the existing matching items.
6441 *
6442 * <p>This method returns a new array with the same elements of the input
6562 * <p>
6563 * This method returns a new array with the same elements of the input
64436564 * array except for the earliest-encountered occurrences of the specified
64446565 * elements. The component type of the returned array is always the same
64456566 * as that of the input array.
6446 *
6567 * </p>
64476568 * <pre>
64486569 * ArrayUtils.removeElements(null, "a", "b") = null
64496570 * ArrayUtils.removeElements([], "a", "b") = []
64916612 }
64926613
64936614 /**
6494 * <p>Reverses the order of the given array.
6495 *
6496 * <p>This method does nothing for a {@code null} input array.
6615 * Reverses the order of the given array.
6616 * <p>
6617 * This method does nothing for a {@code null} input array.
6618 * </p>
64976619 *
64986620 * @param array the array to reverse, may be {@code null}
64996621 */
65056627 }
65066628
65076629 /**
6508 * <p>
65096630 * Reverses the order of the given array in the given range.
6510 *
65116631 * <p>
65126632 * This method does nothing for a {@code null} input array.
6633 * </p>
65136634 *
65146635 * @param array
65156636 * the array to reverse, may be {@code null}
65386659 }
65396660
65406661 /**
6541 * <p>Reverses the order of the given array.
6542 *
6543 * <p>This method does nothing for a {@code null} input array.
6662 * Reverses the order of the given array.
6663 * <p>
6664 * This method does nothing for a {@code null} input array.
6665 * </p>
65446666 *
65456667 * @param array the array to reverse, may be {@code null}
65466668 */
65526674 }
65536675
65546676 /**
6555 * <p>
65566677 * Reverses the order of the given array in the given range.
6557 *
65586678 * <p>
65596679 * This method does nothing for a {@code null} input array.
6680 * </p>
65606681 *
65616682 * @param array
65626683 * the array to reverse, may be {@code null}
65856706 }
65866707
65876708 /**
6588 * <p>Reverses the order of the given array.
6589 *
6590 * <p>This method does nothing for a {@code null} input array.
6709 * Reverses the order of the given array.
6710 * <p>
6711 * This method does nothing for a {@code null} input array.
6712 * </p>
65916713 *
65926714 * @param array the array to reverse, may be {@code null}
65936715 */
65996721 }
66006722
66016723 /**
6602 * <p>
66036724 * Reverses the order of the given array in the given range.
6604 *
66056725 * <p>
66066726 * This method does nothing for a {@code null} input array.
6727 * </p>
66076728 *
66086729 * @param array
66096730 * the array to reverse, may be {@code null}
66326753 }
66336754
66346755 /**
6635 * <p>Reverses the order of the given array.
6636 *
6637 * <p>This method does nothing for a {@code null} input array.
6756 * Reverses the order of the given array.
6757 * <p>
6758 * This method does nothing for a {@code null} input array.
6759 * </p>
66386760 *
66396761 * @param array the array to reverse, may be {@code null}
66406762 */
66466768 }
66476769
66486770 /**
6649 * <p>
66506771 * Reverses the order of the given array in the given range.
6651 *
66526772 * <p>
66536773 * This method does nothing for a {@code null} input array.
6774 * </p>
66546775 *
66556776 * @param array
66566777 * the array to reverse, may be {@code null}
66796800 }
66806801
66816802 /**
6682 * <p>Reverses the order of the given array.
6683 *
6684 * <p>This method does nothing for a {@code null} input array.
6803 * Reverses the order of the given array.
6804 * <p>
6805 * This method does nothing for a {@code null} input array.
6806 * </p>
66856807 *
66866808 * @param array the array to reverse, may be {@code null}
66876809 */
66936815 }
66946816
66956817 /**
6696 * <p>
66976818 * Reverses the order of the given array in the given range.
6698 *
66996819 * <p>
67006820 * This method does nothing for a {@code null} input array.
6821 * </p>
67016822 *
67026823 * @param array
67036824 * the array to reverse, may be {@code null}
67266847 }
67276848
67286849 /**
6729 * <p>Reverses the order of the given array.
6730 *
6731 * <p>This method does nothing for a {@code null} input array.
6850 * Reverses the order of the given array.
6851 * <p>
6852 * This method does nothing for a {@code null} input array.
6853 * </p>
67326854 *
67336855 * @param array the array to reverse, may be {@code null}
67346856 */
67406862 }
67416863
67426864 /**
6743 * <p>
67446865 * Reverses the order of the given array in the given range.
6745 *
67466866 * <p>
67476867 * This method does nothing for a {@code null} input array.
6868 * </p>
67486869 *
67496870 * @param array
67506871 * the array to reverse, may be {@code null}
67736894 }
67746895
67756896 /**
6776 * <p>Reverses the order of the given array.
6777 *
6778 * <p>This method does nothing for a {@code null} input array.
6897 * Reverses the order of the given array.
6898 * <p>
6899 * This method does nothing for a {@code null} input array.
6900 * </p>
67796901 *
67806902 * @param array the array to reverse, may be {@code null}
67816903 */
67876909 }
67886910
67896911 /**
6790 * <p>
67916912 * Reverses the order of the given array in the given range.
6792 *
67936913 * <p>
67946914 * This method does nothing for a {@code null} input array.
6915 * </p>
67956916 *
67966917 * @param array
67976918 * the array to reverse, may be {@code null}
68196940 }
68206941 }
68216942
6822 // Reverse
6823 //-----------------------------------------------------------------------
6824 /**
6825 * <p>Reverses the order of the given array.
6826 *
6827 * <p>There is no special handling for multi-dimensional arrays.
6828 *
6829 * <p>This method does nothing for a {@code null} input array.
6943 /**
6944 * Reverses the order of the given array.
6945 * <p>
6946 * There is no special handling for multi-dimensional arrays.
6947 * </p>
6948 * <p>
6949 * This method does nothing for a {@code null} input array.
6950 * </p>
68306951 *
68316952 * @param array the array to reverse, may be {@code null}
68326953 */
68386959 }
68396960
68406961 /**
6841 * <p>
68426962 * Reverses the order of the given array in the given range.
6843 *
68446963 * <p>
68456964 * This method does nothing for a {@code null} input array.
6965 * </p>
68466966 *
68476967 * @param array
68486968 * the array to reverse, may be {@code null}
68716991 }
68726992
68736993 /**
6874 * <p>Reverses the order of the given array.
6875 *
6876 * <p>This method does nothing for a {@code null} input array.
6994 * Reverses the order of the given array.
6995 * <p>
6996 * This method does nothing for a {@code null} input array.
6997 * </p>
68776998 *
68786999 * @param array the array to reverse, may be {@code null}
68797000 */
68857006 }
68867007
68877008 /**
6888 * <p>
68897009 * Reverses the order of the given array in the given range.
6890 *
68917010 * <p>
68927011 * This method does nothing for a {@code null} input array.
7012 * </p>
68937013 *
68947014 * @param array
68957015 * the array to reverse, may be {@code null}
69157035 j--;
69167036 i++;
69177037 }
7038 }
7039
7040 /**
7041 * Sets all elements of the specified array, using the provided generator supplier to compute each element.
7042 * <p>
7043 * If the generator supplier throws an exception, it is relayed to the caller and the array is left in an indeterminate
7044 * state.
7045 * </p>
7046 *
7047 * @param <T> type of elements of the array.
7048 * @param array array to be initialized.
7049 * @param generator a function accepting an index and producing the desired value for that position.
7050 * @return the input array
7051 * @since 3.13.0
7052 */
7053 public static <T> T[] setAll(T[] array, IntFunction<? extends T> generator) {
7054 if (array != null && generator != null) {
7055 Arrays.setAll(array, generator);
7056 }
7057 return array;
7058 }
7059
7060 /**
7061 * Sets all elements of the specified array, using the provided generator supplier to compute each element.
7062 * <p>
7063 * If the generator supplier throws an exception, it is relayed to the caller and the array is left in an indeterminate
7064 * state.
7065 * </p>
7066 *
7067 * @param <T> type of elements of the array.
7068 * @param array array to be initialized.
7069 * @param generator a function accepting an index and producing the desired value for that position.
7070 * @return the input array
7071 * @since 3.13.0
7072 */
7073 public static <T> T[] setAll(T[] array, final Supplier<? extends T> generator) {
7074 if (array != null && generator != null) {
7075 for (int i = 0; i < array.length; i++) {
7076 array[i] = generator.get();
7077 }
7078 }
7079 return array;
69187080 }
69197081
69207082 /**
69567118 * @since 3.5
69577119 */
69587120 public static void shift(final boolean[] array, int startIndexInclusive, int endIndexExclusive, int offset) {
6959 if (array == null) {
6960 return;
6961 }
6962 if (startIndexInclusive >= array.length - 1 || endIndexExclusive <= 0) {
7121 if ((array == null) || startIndexInclusive >= array.length - 1 || endIndexExclusive <= 0) {
69637122 return;
69647123 }
69657124 if (startIndexInclusive < 0) {
70357194 * @since 3.5
70367195 */
70377196 public static void shift(final byte[] array, int startIndexInclusive, int endIndexExclusive, int offset) {
7038 if (array == null) {
7039 return;
7040 }
7041 if (startIndexInclusive >= array.length - 1 || endIndexExclusive <= 0) {
7197 if ((array == null) || startIndexInclusive >= array.length - 1 || endIndexExclusive <= 0) {
70427198 return;
70437199 }
70447200 if (startIndexInclusive < 0) {
71147270 * @since 3.5
71157271 */
71167272 public static void shift(final char[] array, int startIndexInclusive, int endIndexExclusive, int offset) {
7117 if (array == null) {
7118 return;
7119 }
7120 if (startIndexInclusive >= array.length - 1 || endIndexExclusive <= 0) {
7273 if ((array == null) || startIndexInclusive >= array.length - 1 || endIndexExclusive <= 0) {
71217274 return;
71227275 }
71237276 if (startIndexInclusive < 0) {
71937346 * @since 3.5
71947347 */
71957348 public static void shift(final double[] array, int startIndexInclusive, int endIndexExclusive, int offset) {
7196 if (array == null) {
7197 return;
7198 }
7199 if (startIndexInclusive >= array.length - 1 || endIndexExclusive <= 0) {
7349 if ((array == null) || startIndexInclusive >= array.length - 1 || endIndexExclusive <= 0) {
72007350 return;
72017351 }
72027352 if (startIndexInclusive < 0) {
72727422 * @since 3.5
72737423 */
72747424 public static void shift(final float[] array, int startIndexInclusive, int endIndexExclusive, int offset) {
7275 if (array == null) {
7276 return;
7277 }
7278 if (startIndexInclusive >= array.length - 1 || endIndexExclusive <= 0) {
7425 if ((array == null) || startIndexInclusive >= array.length - 1 || endIndexExclusive <= 0) {
72797426 return;
72807427 }
72817428 if (startIndexInclusive < 0) {
73517498 * @since 3.5
73527499 */
73537500 public static void shift(final int[] array, int startIndexInclusive, int endIndexExclusive, int offset) {
7354 if (array == null) {
7355 return;
7356 }
7357 if (startIndexInclusive >= array.length - 1 || endIndexExclusive <= 0) {
7501 if ((array == null) || startIndexInclusive >= array.length - 1 || endIndexExclusive <= 0) {
73587502 return;
73597503 }
73607504 if (startIndexInclusive < 0) {
74307574 * @since 3.5
74317575 */
74327576 public static void shift(final long[] array, int startIndexInclusive, int endIndexExclusive, int offset) {
7433 if (array == null) {
7434 return;
7435 }
7436 if (startIndexInclusive >= array.length - 1 || endIndexExclusive <= 0) {
7577 if ((array == null) || startIndexInclusive >= array.length - 1 || endIndexExclusive <= 0) {
74377578 return;
74387579 }
74397580 if (startIndexInclusive < 0) {
74707611 }
74717612 }
74727613
7473 // Shift
7474 //-----------------------------------------------------------------------
74757614 /**
74767615 * Shifts the order of the given array.
74777616 *
75117650 * @since 3.5
75127651 */
75137652 public static void shift(final Object[] array, int startIndexInclusive, int endIndexExclusive, int offset) {
7514 if (array == null) {
7515 return;
7516 }
7517 if (startIndexInclusive >= array.length - 1 || endIndexExclusive <= 0) {
7653 if (array == null || startIndexInclusive >= array.length - 1 || endIndexExclusive <= 0) {
75187654 return;
75197655 }
75207656 if (startIndexInclusive < 0) {
75907726 * @since 3.5
75917727 */
75927728 public static void shift(final short[] array, int startIndexInclusive, int endIndexExclusive, int offset) {
7593 if (array == null) {
7594 return;
7595 }
7596 if (startIndexInclusive >= array.length - 1 || endIndexExclusive <= 0) {
7729 if ((array == null) || startIndexInclusive >= array.length - 1 || endIndexExclusive <= 0) {
75977730 return;
75987731 }
75997732 if (startIndexInclusive < 0) {
76387771 * @since 3.6
76397772 */
76407773 public static void shuffle(final boolean[] array) {
7641 shuffle(array, new Random());
7774 shuffle(array, random());
76427775 }
76437776
76447777 /**
76637796 * @since 3.6
76647797 */
76657798 public static void shuffle(final byte[] array) {
7666 shuffle(array, new Random());
7799 shuffle(array, random());
76677800 }
76687801
76697802 /**
76887821 * @since 3.6
76897822 */
76907823 public static void shuffle(final char[] array) {
7691 shuffle(array, new Random());
7824 shuffle(array, random());
76927825 }
76937826
76947827 /**
77137846 * @since 3.6
77147847 */
77157848 public static void shuffle(final double[] array) {
7716 shuffle(array, new Random());
7849 shuffle(array, random());
77177850 }
77187851
77197852 /**
77387871 * @since 3.6
77397872 */
77407873 public static void shuffle(final float[] array) {
7741 shuffle(array, new Random());
7874 shuffle(array, random());
77427875 }
77437876
77447877 /**
77637896 * @since 3.6
77647897 */
77657898 public static void shuffle(final int[] array) {
7766 shuffle(array, new Random());
7899 shuffle(array, random());
77677900 }
77687901
77697902 /**
77887921 * @since 3.6
77897922 */
77907923 public static void shuffle(final long[] array) {
7791 shuffle(array, new Random());
7924 shuffle(array, random());
77927925 }
77937926
77947927 /**
78137946 * @since 3.6
78147947 */
78157948 public static void shuffle(final Object[] array) {
7816 shuffle(array, new Random());
7949 shuffle(array, random());
78177950 }
78187951
78197952 /**
78387971 * @since 3.6
78397972 */
78407973 public static void shuffle(final short[] array) {
7841 shuffle(array, new Random());
7974 shuffle(array, random());
78427975 }
78437976
78447977 /**
78567989 }
78577990
78587991 /**
7859 * <p>Produces a new {@code boolean} array containing the elements
7992 * Produces a new {@code boolean} array containing the elements
78607993 * between the start and end indices.
7861 *
7862 * <p>The start index is inclusive, the end index exclusive.
7994 * <p>
7995 * The start index is inclusive, the end index exclusive.
78637996 * Null array input produces null output.
7997 * </p>
78647998 *
78657999 * @param array the array
78668000 * @param startIndexInclusive the starting index. Undervalue (&lt;0)
78968030 }
78978031
78988032 /**
7899 * <p>Produces a new {@code byte} array containing the elements
8033 * Produces a new {@code byte} array containing the elements
79008034 * between the start and end indices.
7901 *
7902 * <p>The start index is inclusive, the end index exclusive.
8035 * <p>
8036 * The start index is inclusive, the end index exclusive.
79038037 * Null array input produces null output.
8038 * </p>
79048039 *
79058040 * @param array the array
79068041 * @param startIndexInclusive the starting index. Undervalue (&lt;0)
79368071 }
79378072
79388073 /**
7939 * <p>Produces a new {@code char} array containing the elements
8074 * Produces a new {@code char} array containing the elements
79408075 * between the start and end indices.
7941 *
7942 * <p>The start index is inclusive, the end index exclusive.
8076 * <p>
8077 * The start index is inclusive, the end index exclusive.
79438078 * Null array input produces null output.
8079 * </p>
79448080 *
79458081 * @param array the array
79468082 * @param startIndexInclusive the starting index. Undervalue (&lt;0)
79768112 }
79778113
79788114 /**
7979 * <p>Produces a new {@code double} array containing the elements
8115 * Produces a new {@code double} array containing the elements
79808116 * between the start and end indices.
7981 *
7982 * <p>The start index is inclusive, the end index exclusive.
8117 * <p>
8118 * The start index is inclusive, the end index exclusive.
79838119 * Null array input produces null output.
8120 * </p>
79848121 *
79858122 * @param array the array
79868123 * @param startIndexInclusive the starting index. Undervalue (&lt;0)
80168153 }
80178154
80188155 /**
8019 * <p>Produces a new {@code float} array containing the elements
8156 * Produces a new {@code float} array containing the elements
80208157 * between the start and end indices.
8021 *
8022 * <p>The start index is inclusive, the end index exclusive.
8158 * <p>
8159 * The start index is inclusive, the end index exclusive.
80238160 * Null array input produces null output.
8161 * </p>
80248162 *
80258163 * @param array the array
80268164 * @param startIndexInclusive the starting index. Undervalue (&lt;0)
80568194 }
80578195
80588196 /**
8059 * <p>Produces a new {@code int} array containing the elements
8197 * Produces a new {@code int} array containing the elements
80608198 * between the start and end indices.
8061 *
8062 * <p>The start index is inclusive, the end index exclusive.
8199 * <p>
8200 * The start index is inclusive, the end index exclusive.
80638201 * Null array input produces null output.
8202 * </p>
80648203 *
80658204 * @param array the array
80668205 * @param startIndexInclusive the starting index. Undervalue (&lt;0)
80968235 }
80978236
80988237 /**
8099 * <p>Produces a new {@code long} array containing the elements
8238 * Produces a new {@code long} array containing the elements
81008239 * between the start and end indices.
8101 *
8102 * <p>The start index is inclusive, the end index exclusive.
8240 * <p>
8241 * The start index is inclusive, the end index exclusive.
81038242 * Null array input produces null output.
8243 * </p>
81048244 *
81058245 * @param array the array
81068246 * @param startIndexInclusive the starting index. Undervalue (&lt;0)
81368276 }
81378277
81388278 /**
8139 * <p>Produces a new {@code short} array containing the elements
8279 * Produces a new {@code short} array containing the elements
81408280 * between the start and end indices.
8141 *
8142 * <p>The start index is inclusive, the end index exclusive.
8281 * <p>
8282 * The start index is inclusive, the end index exclusive.
81438283 * Null array input produces null output.
8284 * </p>
81448285 *
81458286 * @param array the array
81468287 * @param startIndexInclusive the starting index. Undervalue (&lt;0)
81758316 return subarray;
81768317 }
81778318
8178 // Subarrays
8179 //-----------------------------------------------------------------------
8180 /**
8181 * <p>Produces a new array containing the elements between
8319 /**
8320 * Produces a new array containing the elements between
81828321 * the start and end indices.
8183 *
8184 * <p>The start index is inclusive, the end index exclusive.
8322 * <p>
8323 * The start index is inclusive, the end index exclusive.
81858324 * Null array input produces null output.
8186 *
8187 * <p>The component type of the subarray is always the same as
8325 * </p>
8326 * <p>
8327 * The component type of the subarray is always the same as
81888328 * that of the input array. Thus, if the input is an array of type
81898329 * {@code Date}, the following usage is envisaged:
8190 *
8330 * </p>
81918331 * <pre>
81928332 * Date[] someDates = (Date[]) ArrayUtils.subarray(allDates, 2, 5);
81938333 * </pre>
82178357 endIndexExclusive = array.length;
82188358 }
82198359 final int newSize = endIndexExclusive - startIndexInclusive;
8220 final Class<?> type = array.getClass().getComponentType();
8360 final Class<T> type = getComponentType(array);
82218361 if (newSize <= 0) {
8222 @SuppressWarnings("unchecked") // OK, because array is of type T
8223 final T[] emptyArray = (T[]) Array.newInstance(type, 0);
8224 return emptyArray;
8225 }
8226 @SuppressWarnings("unchecked") // OK, because array is of type T
8227 final
8228 T[] subarray = (T[]) Array.newInstance(type, newSize);
8362 return newInstance(type, 0);
8363 }
8364 final T[] subarray = newInstance(type, newSize);
82298365 System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);
82308366 return subarray;
82318367 }
82588394 swap(array, offset1, offset2, 1);
82598395 }
82608396
8397
82618398 /**
82628399 * Swaps a series of elements in the given boolean array.
82638400 *
83008437 }
83018438 }
83028439
8303
83048440 /**
83058441 * Swaps two elements in the given byte array.
83068442 *
87238859 }
87248860 }
87258861
8726 // Swap
8727 //-----------------------------------------------------------------------
87288862 /**
87298863 * Swaps two elements in the given array.
87308864 *
88248958 }
88258959
88268960 /**
8827 * Swaps a series of elements in the given short array.
8828 *
8829 * <p>This method does nothing for a {@code null} or empty input array or
8830 * for overflow indices. Negative indices are promoted to 0(zero). If any
8831 * of the sub-arrays to swap falls outside of the given array, then the
8832 * swap is stopped at the end of the array and as many as possible elements
8833 * are swapped.</p>
8834 *
8835 * Examples:
8836 * <ul>
8837 * <li>ArrayUtils.swap([1, 2, 3, 4], 0, 2, 1) -&gt; [3, 2, 1, 4]</li>
8838 * <li>ArrayUtils.swap([1, 2, 3, 4], 0, 0, 1) -&gt; [1, 2, 3, 4]</li>
8839 * <li>ArrayUtils.swap([1, 2, 3, 4], 2, 0, 2) -&gt; [3, 4, 1, 2]</li>
8840 * <li>ArrayUtils.swap([1, 2, 3, 4], -3, 2, 2) -&gt; [3, 4, 1, 2]</li>
8841 * <li>ArrayUtils.swap([1, 2, 3, 4], 0, 3, 3) -&gt; [4, 2, 3, 1]</li>
8842 * </ul>
8843 *
8844 * @param array the array to swap, may be {@code null}
8845 * @param offset1 the index of the first element in the series to swap
8846 * @param offset2 the index of the second element in the series to swap
8847 * @param len the number of elements to swap starting with the given indices
8848 * @since 3.5
8849 */
8850 public static void swap(final short[] array, int offset1, int offset2, int len) {
8851 if (isEmpty(array) || offset1 >= array.length || offset2 >= array.length) {
8852 return;
8853 }
8854 if (offset1 < 0) {
8855 offset1 = 0;
8856 }
8857 if (offset2 < 0) {
8858 offset2 = 0;
8859 }
8860 if (offset1 == offset2) {
8861 return;
8862 }
8863 len = Math.min(Math.min(len, array.length - offset1), array.length - offset2);
8864 for (int i = 0; i < len; i++, offset1++, offset2++) {
8865 final short aux = array[offset1];
8866 array[offset1] = array[offset2];
8867 array[offset2] = aux;
8868 }
8869 }
8870
8871 // Generic array
8872 //-----------------------------------------------------------------------
8873 /**
8874 * <p>Create a type-safe generic array.
8875 *
8876 * <p>The Java language does not allow an array to be created from a generic type:
8877 *
8961 * Swaps a series of elements in the given short array.
8962 *
8963 * <p>This method does nothing for a {@code null} or empty input array or
8964 * for overflow indices. Negative indices are promoted to 0(zero). If any
8965 * of the sub-arrays to swap falls outside of the given array, then the
8966 * swap is stopped at the end of the array and as many as possible elements
8967 * are swapped.</p>
8968 *
8969 * Examples:
8970 * <ul>
8971 * <li>ArrayUtils.swap([1, 2, 3, 4], 0, 2, 1) -&gt; [3, 2, 1, 4]</li>
8972 * <li>ArrayUtils.swap([1, 2, 3, 4], 0, 0, 1) -&gt; [1, 2, 3, 4]</li>
8973 * <li>ArrayUtils.swap([1, 2, 3, 4], 2, 0, 2) -&gt; [3, 4, 1, 2]</li>
8974 * <li>ArrayUtils.swap([1, 2, 3, 4], -3, 2, 2) -&gt; [3, 4, 1, 2]</li>
8975 * <li>ArrayUtils.swap([1, 2, 3, 4], 0, 3, 3) -&gt; [4, 2, 3, 1]</li>
8976 * </ul>
8977 *
8978 * @param array the array to swap, may be {@code null}
8979 * @param offset1 the index of the first element in the series to swap
8980 * @param offset2 the index of the second element in the series to swap
8981 * @param len the number of elements to swap starting with the given indices
8982 * @since 3.5
8983 */
8984 public static void swap(final short[] array, int offset1, int offset2, int len) {
8985 if (isEmpty(array) || offset1 >= array.length || offset2 >= array.length) {
8986 return;
8987 }
8988 if (offset1 < 0) {
8989 offset1 = 0;
8990 }
8991 if (offset2 < 0) {
8992 offset2 = 0;
8993 }
8994 if (offset1 == offset2) {
8995 return;
8996 }
8997 len = Math.min(Math.min(len, array.length - offset1), array.length - offset2);
8998 for (int i = 0; i < len; i++, offset1++, offset2++) {
8999 final short aux = array[offset1];
9000 array[offset1] = array[offset2];
9001 array[offset2] = aux;
9002 }
9003 }
9004
9005 /**
9006 * Create a type-safe generic array.
9007 * <p>
9008 * The Java language does not allow an array to be created from a generic type:
9009 * </p>
88789010 * <pre>
88799011 public static &lt;T&gt; T[] createAnArray(int size) {
88809012 return new T[size]; // compiler error here
88839015 return (T[]) new Object[size]; // ClassCastException at runtime
88849016 }
88859017 * </pre>
8886 *
8887 * <p>Therefore new arrays of generic types can be created with this method.
9018 * <p>
9019 * Therefore new arrays of generic types can be created with this method.
88889020 * For example, an array of Strings can be created:
8889 *
9021 * </p>
88909022 * <pre>
88919023 String[] array = ArrayUtils.toArray("1", "2");
88929024 String[] emptyArray = ArrayUtils.&lt;String&gt;toArray();
88939025 * </pre>
8894 *
8895 * <p>The method is typically used in scenarios, where the caller itself uses generic types
9026 * <p>
9027 * The method is typically used in scenarios, where the caller itself uses generic types
88969028 * that have to be combined into an array.
8897 *
8898 * <p>Note, this method makes only sense to provide arguments of the same type so that the
9029 * </p>
9030 * <p>
9031 * Note, this method makes only sense to provide arguments of the same type so that the
88999032 * compiler can deduce the type of the array itself. While it is possible to select the
89009033 * type explicitly like in
89019034 * {@code Number[] array = ArrayUtils.&lt;Number&gt;toArray(Integer.valueOf(42), Double.valueOf(Math.PI))},
89029035 * there is no real advantage when compared to
89039036 * {@code new Number[] {Integer.valueOf(42), Double.valueOf(Math.PI)}}.
9037 * </p>
89049038 *
89059039 * @param <T> the array's element type
89069040 * @param items the varargs array items, null allowed
89119045 return items;
89129046 }
89139047
8914 // To map
8915 //-----------------------------------------------------------------------
8916 /**
8917 * <p>Converts the given array into a {@link java.util.Map}. Each element of the array
9048 /**
9049 * Converts the given array into a {@link java.util.Map}. Each element of the array
89189050 * must be either a {@link java.util.Map.Entry} or an Array, containing at least two
89199051 * elements, where the first element is used as key and the second as
89209052 * value.
8921 *
8922 * <p>This method can be used to initialize:
9053 * <p>
9054 * This method can be used to initialize:
9055 * </p>
89239056 * <pre>
89249057 * // Create a Map mapping colors.
89259058 * Map colorMap = ArrayUtils.toMap(new String[][] {
89279060 * {"GREEN", "#00FF00"},
89289061 * {"BLUE", "#0000FF"}});
89299062 * </pre>
8930 *
8931 * <p>This method returns {@code null} for a {@code null} input array.
9063 * <p>
9064 * This method returns {@code null} for a {@code null} input array.
9065 * </p>
89329066 *
89339067 * @param array an array whose elements are either a {@link java.util.Map.Entry} or
89349068 * an Array containing at least two elements, may be {@code null}
89669100 }
89679101
89689102 /**
8969 * <p>Converts an array of primitive booleans to objects.
8970 *
8971 * <p>This method returns {@code null} for a {@code null} input array.
9103 * Converts an array of primitive booleans to objects.
9104 *
9105 * <p>This method returns {@code null} for a {@code null} input array.</p>
89729106 *
89739107 * @param array a {@code boolean} array
89749108 * @return a {@code Boolean} array, {@code null} if null array input
89769110 public static Boolean[] toObject(final boolean[] array) {
89779111 if (array == null) {
89789112 return null;
8979 } else if (array.length == 0) {
9113 }
9114 if (array.length == 0) {
89809115 return EMPTY_BOOLEAN_OBJECT_ARRAY;
89819116 }
89829117 final Boolean[] result = new Boolean[array.length];
8983 for (int i = 0; i < array.length; i++) {
8984 result[i] = (array[i] ? Boolean.TRUE : Boolean.FALSE);
8985 }
8986 return result;
8987 }
8988
8989 /**
8990 * <p>Converts an array of primitive bytes to objects.
8991 *
8992 * <p>This method returns {@code null} for a {@code null} input array.
9118 return setAll(result, i -> array[i] ? Boolean.TRUE : Boolean.FALSE);
9119 }
9120
9121 /**
9122 * Converts an array of primitive bytes to objects.
9123 *
9124 * <p>This method returns {@code null} for a {@code null} input array.</p>
89939125 *
89949126 * @param array a {@code byte} array
89959127 * @return a {@code Byte} array, {@code null} if null array input
89979129 public static Byte[] toObject(final byte[] array) {
89989130 if (array == null) {
89999131 return null;
9000 } else if (array.length == 0) {
9132 }
9133 if (array.length == 0) {
90019134 return EMPTY_BYTE_OBJECT_ARRAY;
90029135 }
9003 final Byte[] result = new Byte[array.length];
9004 for (int i = 0; i < array.length; i++) {
9005 result[i] = Byte.valueOf(array[i]);
9006 }
9007 return result;
9008 }
9009
9010 /**
9011 * <p>Converts an array of primitive chars to objects.
9012 *
9013 * <p>This method returns {@code null} for a {@code null} input array.
9136 return setAll(new Byte[array.length], i -> Byte.valueOf(array[i]));
9137 }
9138
9139 /**
9140 * Converts an array of primitive chars to objects.
9141 *
9142 * <p>This method returns {@code null} for a {@code null} input array.</p>
90149143 *
90159144 * @param array a {@code char} array
90169145 * @return a {@code Character} array, {@code null} if null array input
90189147 public static Character[] toObject(final char[] array) {
90199148 if (array == null) {
90209149 return null;
9021 } else if (array.length == 0) {
9150 }
9151 if (array.length == 0) {
90229152 return EMPTY_CHARACTER_OBJECT_ARRAY;
90239153 }
9024 final Character[] result = new Character[array.length];
9025 for (int i = 0; i < array.length; i++) {
9026 result[i] = Character.valueOf(array[i]);
9027 }
9028 return result;
9154 return setAll(new Character[array.length], i -> Character.valueOf(array[i]));
90299155 }
90309156
90319157 /**
9032 * <p>Converts an array of primitive doubles to objects.
9033 *
9034 * <p>This method returns {@code null} for a {@code null} input array.
9158 * Converts an array of primitive doubles to objects.
9159 *
9160 * <p>This method returns {@code null} for a {@code null} input array.</p>
90359161 *
90369162 * @param array a {@code double} array
90379163 * @return a {@code Double} array, {@code null} if null array input
90399165 public static Double[] toObject(final double[] array) {
90409166 if (array == null) {
90419167 return null;
9042 } else if (array.length == 0) {
9168 }
9169 if (array.length == 0) {
90439170 return EMPTY_DOUBLE_OBJECT_ARRAY;
90449171 }
9045 final Double[] result = new Double[array.length];
9046 for (int i = 0; i < array.length; i++) {
9047 result[i] = Double.valueOf(array[i]);
9048 }
9049 return result;
9050 }
9051
9052 /**
9053 * <p>Converts an array of primitive floats to objects.
9054 *
9055 * <p>This method returns {@code null} for a {@code null} input array.
9172 return setAll(new Double[array.length], i -> Double.valueOf(array[i]));
9173 }
9174
9175 /**
9176 * Converts an array of primitive floats to objects.
9177 *
9178 * <p>This method returns {@code null} for a {@code null} input array.</p>
90569179 *
90579180 * @param array a {@code float} array
90589181 * @return a {@code Float} array, {@code null} if null array input
90609183 public static Float[] toObject(final float[] array) {
90619184 if (array == null) {
90629185 return null;
9063 } else if (array.length == 0) {
9186 }
9187 if (array.length == 0) {
90649188 return EMPTY_FLOAT_OBJECT_ARRAY;
90659189 }
9066 final Float[] result = new Float[array.length];
9067 for (int i = 0; i < array.length; i++) {
9068 result[i] = Float.valueOf(array[i]);
9069 }
9070 return result;
9071 }
9072
9073 /**
9074 * <p>Converts an array of primitive ints to objects.
9075 *
9076 * <p>This method returns {@code null} for a {@code null} input array.
9190 return setAll(new Float[array.length], i -> Float.valueOf(array[i]));
9191 }
9192
9193 /**
9194 * Converts an array of primitive ints to objects.
9195 *
9196 * <p>This method returns {@code null} for a {@code null} input array.</p>
90779197 *
90789198 * @param array an {@code int} array
90799199 * @return an {@code Integer} array, {@code null} if null array input
90819201 public static Integer[] toObject(final int[] array) {
90829202 if (array == null) {
90839203 return null;
9084 } else if (array.length == 0) {
9204 }
9205 if (array.length == 0) {
90859206 return EMPTY_INTEGER_OBJECT_ARRAY;
90869207 }
9087 final Integer[] result = new Integer[array.length];
9088 for (int i = 0; i < array.length; i++) {
9089 result[i] = Integer.valueOf(array[i]);
9090 }
9091 return result;
9092 }
9093
9094 /**
9095 * <p>Converts an array of primitive longs to objects.
9096 *
9097 * <p>This method returns {@code null} for a {@code null} input array.
9208 return setAll(new Integer[array.length], i -> Integer.valueOf(array[i]));
9209 }
9210
9211 /**
9212 * Converts an array of primitive longs to objects.
9213 *
9214 * <p>This method returns {@code null} for a {@code null} input array.</p>
90989215 *
90999216 * @param array a {@code long} array
91009217 * @return a {@code Long} array, {@code null} if null array input
91029219 public static Long[] toObject(final long[] array) {
91039220 if (array == null) {
91049221 return null;
9105 } else if (array.length == 0) {
9222 }
9223 if (array.length == 0) {
91069224 return EMPTY_LONG_OBJECT_ARRAY;
91079225 }
9108 final Long[] result = new Long[array.length];
9109 for (int i = 0; i < array.length; i++) {
9110 result[i] = Long.valueOf(array[i]);
9111 }
9112 return result;
9113 }
9114
9115 /**
9116 * <p>Converts an array of primitive shorts to objects.
9117 *
9118 * <p>This method returns {@code null} for a {@code null} input array.
9226 return setAll(new Long[array.length], i -> Long.valueOf(array[i]));
9227 }
9228
9229 /**
9230 * Converts an array of primitive shorts to objects.
9231 *
9232 * <p>This method returns {@code null} for a {@code null} input array.</p>
91199233 *
91209234 * @param array a {@code short} array
91219235 * @return a {@code Short} array, {@code null} if null array input
91239237 public static Short[] toObject(final short[] array) {
91249238 if (array == null) {
91259239 return null;
9126 } else if (array.length == 0) {
9240 }
9241 if (array.length == 0) {
91279242 return EMPTY_SHORT_OBJECT_ARRAY;
91289243 }
9129 final Short[] result = new Short[array.length];
9130 for (int i = 0; i < array.length; i++) {
9131 result[i] = Short.valueOf(array[i]);
9132 }
9133 return result;
9134 }
9135
9136 // Boolean array converters
9137 // ----------------------------------------------------------------------
9138 /**
9139 * <p>Converts an array of object Booleans to primitives.
9140 *
9141 * <p>This method returns {@code null} for a {@code null} input array.
9244 return setAll(new Short[array.length], i -> Short.valueOf(array[i]));
9245 }
9246
9247 /**
9248 * Converts an array of object Booleans to primitives.
9249 * <p>
9250 * This method returns {@code null} for a {@code null} input array.
9251 * </p>
91429252 *
91439253 * @param array a {@code Boolean} array, may be {@code null}
91449254 * @return a {@code boolean} array, {@code null} if null array input
91479257 public static boolean[] toPrimitive(final Boolean[] array) {
91489258 if (array == null) {
91499259 return null;
9150 } else if (array.length == 0) {
9260 }
9261 if (array.length == 0) {
91519262 return EMPTY_BOOLEAN_ARRAY;
91529263 }
91539264 final boolean[] result = new boolean[array.length];
91589269 }
91599270
91609271 /**
9161 * <p>Converts an array of object Booleans to primitives handling {@code null}.
9162 *
9163 * <p>This method returns {@code null} for a {@code null} input array.
9272 * Converts an array of object Booleans to primitives handling {@code null}.
9273 * <p>
9274 * This method returns {@code null} for a {@code null} input array.
9275 * </p>
91649276 *
91659277 * @param array a {@code Boolean} array, may be {@code null}
91669278 * @param valueForNull the value to insert if {@code null} found
91699281 public static boolean[] toPrimitive(final Boolean[] array, final boolean valueForNull) {
91709282 if (array == null) {
91719283 return null;
9172 } else if (array.length == 0) {
9284 }
9285 if (array.length == 0) {
91739286 return EMPTY_BOOLEAN_ARRAY;
91749287 }
91759288 final boolean[] result = new boolean[array.length];
91809293 return result;
91819294 }
91829295
9183 // Byte array converters
9184 // ----------------------------------------------------------------------
9185 /**
9186 * <p>Converts an array of object Bytes to primitives.
9187 *
9188 * <p>This method returns {@code null} for a {@code null} input array.
9296 /**
9297 * Converts an array of object Bytes to primitives.
9298 * <p>
9299 * This method returns {@code null} for a {@code null} input array.
9300 * </p>
91899301 *
91909302 * @param array a {@code Byte} array, may be {@code null}
91919303 * @return a {@code byte} array, {@code null} if null array input
91949306 public static byte[] toPrimitive(final Byte[] array) {
91959307 if (array == null) {
91969308 return null;
9197 } else if (array.length == 0) {
9309 }
9310 if (array.length == 0) {
91989311 return EMPTY_BYTE_ARRAY;
91999312 }
92009313 final byte[] result = new byte[array.length];
92059318 }
92069319
92079320 /**
9208 * <p>Converts an array of object Bytes to primitives handling {@code null}.
9209 *
9210 * <p>This method returns {@code null} for a {@code null} input array.
9321 * Converts an array of object Bytes to primitives handling {@code null}.
9322 * <p>
9323 * This method returns {@code null} for a {@code null} input array.
9324 * </p>
92119325 *
92129326 * @param array a {@code Byte} array, may be {@code null}
92139327 * @param valueForNull the value to insert if {@code null} found
92169330 public static byte[] toPrimitive(final Byte[] array, final byte valueForNull) {
92179331 if (array == null) {
92189332 return null;
9219 } else if (array.length == 0) {
9333 }
9334 if (array.length == 0) {
92209335 return EMPTY_BYTE_ARRAY;
92219336 }
92229337 final byte[] result = new byte[array.length];
92279342 return result;
92289343 }
92299344
9230 // Character array converters
9231 // ----------------------------------------------------------------------
9232 /**
9233 * <p>Converts an array of object Characters to primitives.
9234 *
9235 * <p>This method returns {@code null} for a {@code null} input array.
9345 /**
9346 * Converts an array of object Characters to primitives.
9347 * <p>
9348 * This method returns {@code null} for a {@code null} input array.
9349 * </p>
92369350 *
92379351 * @param array a {@code Character} array, may be {@code null}
92389352 * @return a {@code char} array, {@code null} if null array input
92419355 public static char[] toPrimitive(final Character[] array) {
92429356 if (array == null) {
92439357 return null;
9244 } else if (array.length == 0) {
9358 }
9359 if (array.length == 0) {
92459360 return EMPTY_CHAR_ARRAY;
92469361 }
92479362 final char[] result = new char[array.length];
92529367 }
92539368
92549369 /**
9255 * <p>Converts an array of object Character to primitives handling {@code null}.
9256 *
9257 * <p>This method returns {@code null} for a {@code null} input array.
9370 * Converts an array of object Character to primitives handling {@code null}.
9371 * <p>
9372 * This method returns {@code null} for a {@code null} input array.
9373 * </p>
92589374 *
92599375 * @param array a {@code Character} array, may be {@code null}
92609376 * @param valueForNull the value to insert if {@code null} found
92639379 public static char[] toPrimitive(final Character[] array, final char valueForNull) {
92649380 if (array == null) {
92659381 return null;
9266 } else if (array.length == 0) {
9382 }
9383 if (array.length == 0) {
92679384 return EMPTY_CHAR_ARRAY;
92689385 }
92699386 final char[] result = new char[array.length];
92749391 return result;
92759392 }
92769393
9277 // Double array converters
9278 // ----------------------------------------------------------------------
9279 /**
9280 * <p>Converts an array of object Doubles to primitives.
9281 *
9282 * <p>This method returns {@code null} for a {@code null} input array.
9394 /**
9395 * Converts an array of object Doubles to primitives.
9396 * <p>
9397 * This method returns {@code null} for a {@code null} input array.
9398 * </p>
92839399 *
92849400 * @param array a {@code Double} array, may be {@code null}
92859401 * @return a {@code double} array, {@code null} if null array input
92889404 public static double[] toPrimitive(final Double[] array) {
92899405 if (array == null) {
92909406 return null;
9291 } else if (array.length == 0) {
9407 }
9408 if (array.length == 0) {
92929409 return EMPTY_DOUBLE_ARRAY;
92939410 }
92949411 final double[] result = new double[array.length];
92999416 }
93009417
93019418 /**
9302 * <p>Converts an array of object Doubles to primitives handling {@code null}.
9303 *
9304 * <p>This method returns {@code null} for a {@code null} input array.
9419 * Converts an array of object Doubles to primitives handling {@code null}.
9420 * <p>
9421 * This method returns {@code null} for a {@code null} input array.
9422 * </p>
93059423 *
93069424 * @param array a {@code Double} array, may be {@code null}
93079425 * @param valueForNull the value to insert if {@code null} found
93109428 public static double[] toPrimitive(final Double[] array, final double valueForNull) {
93119429 if (array == null) {
93129430 return null;
9313 } else if (array.length == 0) {
9431 }
9432 if (array.length == 0) {
93149433 return EMPTY_DOUBLE_ARRAY;
93159434 }
93169435 final double[] result = new double[array.length];
93219440 return result;
93229441 }
93239442
9324 // Float array converters
9325 // ----------------------------------------------------------------------
9326 /**
9327 * <p>Converts an array of object Floats to primitives.
9328 *
9329 * <p>This method returns {@code null} for a {@code null} input array.
9443 /**
9444 * Converts an array of object Floats to primitives.
9445 * <p>
9446 * This method returns {@code null} for a {@code null} input array.
9447 * </p>
93309448 *
93319449 * @param array a {@code Float} array, may be {@code null}
93329450 * @return a {@code float} array, {@code null} if null array input
93359453 public static float[] toPrimitive(final Float[] array) {
93369454 if (array == null) {
93379455 return null;
9338 } else if (array.length == 0) {
9456 }
9457 if (array.length == 0) {
93399458 return EMPTY_FLOAT_ARRAY;
93409459 }
93419460 final float[] result = new float[array.length];
93469465 }
93479466
93489467 /**
9349 * <p>Converts an array of object Floats to primitives handling {@code null}.
9350 *
9351 * <p>This method returns {@code null} for a {@code null} input array.
9468 * Converts an array of object Floats to primitives handling {@code null}.
9469 * <p>
9470 * This method returns {@code null} for a {@code null} input array.
9471 * </p>
93529472 *
93539473 * @param array a {@code Float} array, may be {@code null}
93549474 * @param valueForNull the value to insert if {@code null} found
93579477 public static float[] toPrimitive(final Float[] array, final float valueForNull) {
93589478 if (array == null) {
93599479 return null;
9360 } else if (array.length == 0) {
9480 }
9481 if (array.length == 0) {
93619482 return EMPTY_FLOAT_ARRAY;
93629483 }
93639484 final float[] result = new float[array.length];
93689489 return result;
93699490 }
93709491
9371 // Int array converters
9372 // ----------------------------------------------------------------------
9373 /**
9374 * <p>Converts an array of object Integers to primitives.
9375 *
9376 * <p>This method returns {@code null} for a {@code null} input array.
9492 /**
9493 * Converts an array of object Integers to primitives.
9494 * <p>
9495 * This method returns {@code null} for a {@code null} input array.
9496 * </p>
93779497 *
93789498 * @param array a {@code Integer} array, may be {@code null}
93799499 * @return an {@code int} array, {@code null} if null array input
93829502 public static int[] toPrimitive(final Integer[] array) {
93839503 if (array == null) {
93849504 return null;
9385 } else if (array.length == 0) {
9505 }
9506 if (array.length == 0) {
93869507 return EMPTY_INT_ARRAY;
93879508 }
93889509 final int[] result = new int[array.length];
93939514 }
93949515
93959516 /**
9396 * <p>Converts an array of object Integer to primitives handling {@code null}.
9397 *
9398 * <p>This method returns {@code null} for a {@code null} input array.
9517 * Converts an array of object Integer to primitives handling {@code null}.
9518 * <p>
9519 * This method returns {@code null} for a {@code null} input array.
9520 * </p>
93999521 *
94009522 * @param array a {@code Integer} array, may be {@code null}
94019523 * @param valueForNull the value to insert if {@code null} found
94049526 public static int[] toPrimitive(final Integer[] array, final int valueForNull) {
94059527 if (array == null) {
94069528 return null;
9407 } else if (array.length == 0) {
9529 }
9530 if (array.length == 0) {
94089531 return EMPTY_INT_ARRAY;
94099532 }
94109533 final int[] result = new int[array.length];
94159538 return result;
94169539 }
94179540
9418 // Long array converters
9419 // ----------------------------------------------------------------------
9420 /**
9421 * <p>Converts an array of object Longs to primitives.
9422 *
9423 * <p>This method returns {@code null} for a {@code null} input array.
9541 /**
9542 * Converts an array of object Longs to primitives.
9543 * <p>
9544 * This method returns {@code null} for a {@code null} input array.
9545 * </p>
94249546 *
94259547 * @param array a {@code Long} array, may be {@code null}
94269548 * @return a {@code long} array, {@code null} if null array input
94299551 public static long[] toPrimitive(final Long[] array) {
94309552 if (array == null) {
94319553 return null;
9432 } else if (array.length == 0) {
9554 }
9555 if (array.length == 0) {
94339556 return EMPTY_LONG_ARRAY;
94349557 }
94359558 final long[] result = new long[array.length];
94409563 }
94419564
94429565 /**
9443 * <p>Converts an array of object Long to primitives handling {@code null}.
9444 *
9445 * <p>This method returns {@code null} for a {@code null} input array.
9566 * Converts an array of object Long to primitives handling {@code null}.
9567 * <p>
9568 * This method returns {@code null} for a {@code null} input array.
9569 * </p>
94469570 *
94479571 * @param array a {@code Long} array, may be {@code null}
94489572 * @param valueForNull the value to insert if {@code null} found
94519575 public static long[] toPrimitive(final Long[] array, final long valueForNull) {
94529576 if (array == null) {
94539577 return null;
9454 } else if (array.length == 0) {
9578 }
9579 if (array.length == 0) {
94559580 return EMPTY_LONG_ARRAY;
94569581 }
94579582 final long[] result = new long[array.length];
94639588 }
94649589
94659590 /**
9466 * <p>Create an array of primitive type from an array of wrapper types.
9467 *
9468 * <p>This method returns {@code null} for a {@code null} input array.
9591 * Create an array of primitive type from an array of wrapper types.
9592 * <p>
9593 * This method returns {@code null} for a {@code null} input array.
9594 * </p>
94699595 *
94709596 * @param array an array of wrapper object
94719597 * @return an array of the corresponding primitive type, or the original array
94779603 }
94789604 final Class<?> ct = array.getClass().getComponentType();
94799605 final Class<?> pt = ClassUtils.wrapperToPrimitive(ct);
9606 if (Boolean.TYPE.equals(pt)) {
9607 return toPrimitive((Boolean[]) array);
9608 }
9609 if (Character.TYPE.equals(pt)) {
9610 return toPrimitive((Character[]) array);
9611 }
9612 if (Byte.TYPE.equals(pt)) {
9613 return toPrimitive((Byte[]) array);
9614 }
94809615 if (Integer.TYPE.equals(pt)) {
94819616 return toPrimitive((Integer[]) array);
94829617 }
94959630 return array;
94969631 }
94979632
9498 // Short array converters
9499 // ----------------------------------------------------------------------
9500 /**
9501 * <p>Converts an array of object Shorts to primitives.
9502 *
9503 * <p>This method returns {@code null} for a {@code null} input array.
9633 /**
9634 * Converts an array of object Shorts to primitives.
9635 * <p>
9636 * This method returns {@code null} for a {@code null} input array.
9637 * </p>
95049638 *
95059639 * @param array a {@code Short} array, may be {@code null}
95069640 * @return a {@code byte} array, {@code null} if null array input
95099643 public static short[] toPrimitive(final Short[] array) {
95109644 if (array == null) {
95119645 return null;
9512 } else if (array.length == 0) {
9646 }
9647 if (array.length == 0) {
95139648 return EMPTY_SHORT_ARRAY;
95149649 }
95159650 final short[] result = new short[array.length];
95209655 }
95219656
95229657 /**
9523 * <p>Converts an array of object Short to primitives handling {@code null}.
9524 *
9525 * <p>This method returns {@code null} for a {@code null} input array.
9658 * Converts an array of object Short to primitives handling {@code null}.
9659 * <p>
9660 * This method returns {@code null} for a {@code null} input array.
9661 * </p>
95269662 *
95279663 * @param array a {@code Short} array, may be {@code null}
95289664 * @param valueForNull the value to insert if {@code null} found
95319667 public static short[] toPrimitive(final Short[] array, final short valueForNull) {
95329668 if (array == null) {
95339669 return null;
9534 } else if (array.length == 0) {
9670 }
9671 if (array.length == 0) {
95359672 return EMPTY_SHORT_ARRAY;
95369673 }
95379674 final short[] result = new short[array.length];
95429679 return result;
95439680 }
95449681
9545 // Basic methods handling multi-dimensional arrays
9546 //-----------------------------------------------------------------------
9547 /**
9548 * <p>Outputs an array as a String, treating {@code null} as an empty array.
9549 *
9550 * <p>Multi-dimensional arrays are handled correctly, including
9682 /**
9683 * Outputs an array as a String, treating {@code null} as an empty array.
9684 * <p>
9685 * Multi-dimensional arrays are handled correctly, including
95519686 * multi-dimensional primitive arrays.
9552 *
9553 * <p>The format is that of Java source code, for example {@code {a,b}}.
9687 * </p>
9688 * <p>
9689 * The format is that of Java source code, for example {@code {a,b}}.
9690 * </p>
95549691 *
95559692 * @param array the array to get a toString for, may be {@code null}
95569693 * @return a String representation of the array, '{}' if null array input
95609697 }
95619698
95629699 /**
9563 * <p>Outputs an array as a String handling {@code null}s.
9564 *
9565 * <p>Multi-dimensional arrays are handled correctly, including
9700 * Outputs an array as a String handling {@code null}s.
9701 * <p>
9702 * Multi-dimensional arrays are handled correctly, including
95669703 * multi-dimensional primitive arrays.
9567 *
9568 * <p>The format is that of Java source code, for example {@code {a,b}}.
9704 * </p>
9705 * <p>
9706 * The format is that of Java source code, for example {@code {a,b}}.
9707 * </p>
95699708 *
95709709 * @param array the array to get a toString for, may be {@code null}
95719710 * @param stringIfNull the String to return if the array is {@code null}
95799718 }
95809719
95819720 /**
9582 * <p>Returns an array containing the string representation of each element in the argument array.</p>
9583 *
9584 * <p>This method returns {@code null} for a {@code null} input array.</p>
9721 * Returns an array containing the string representation of each element in the argument array.
9722 * <p>
9723 * This method returns {@code null} for a {@code null} input array.
9724 * </p>
95859725 *
95869726 * @param array the {@code Object[]} to be processed, may be null
95879727 * @return {@code String[]} of the same size as the source with its element's string representation,
95929732 public static String[] toStringArray(final Object[] array) {
95939733 if (array == null) {
95949734 return null;
9595 } else if (array.length == 0) {
9735 }
9736 if (array.length == 0) {
95969737 return EMPTY_STRING_ARRAY;
95979738 }
95989739
96059746 }
96069747
96079748 /**
9608 * <p>Returns an array containing the string representation of each element in the argument
9609 * array handling {@code null} elements.</p>
9610 *
9611 * <p>This method returns {@code null} for a {@code null} input array.</p>
9749 * Returns an array containing the string representation of each element in the argument
9750 * array handling {@code null} elements.
9751 * <p>
9752 * This method returns {@code null} for a {@code null} input array.
9753 * </p>
96129754 *
96139755 * @param array the Object[] to be processed, may be null
96149756 * @param valueForNullElements the value to insert if {@code null} is found
96189760 public static String[] toStringArray(final Object[] array, final String valueForNullElements) {
96199761 if (null == array) {
96209762 return null;
9621 } else if (array.length == 0) {
9763 }
9764 if (array.length == 0) {
96229765 return EMPTY_STRING_ARRAY;
96239766 }
96249767
96329775 }
96339776
96349777 /**
9635 * <p>ArrayUtils instances should NOT be constructed in standard programming.
9778 * ArrayUtils instances should NOT be constructed in standard programming.
96369779 * Instead, the class should be used as {@code ArrayUtils.clone(new int[] {2})}.
9637 *
9638 * <p>This constructor is public to permit tools that require a JavaBean instance
9780 * <p>
9781 * This constructor is public to permit tools that require a JavaBean instance
96399782 * to operate.
9783 * </p>
96409784 */
96419785 public ArrayUtils() {
9642 super();
96439786 }
96449787 }
2828 * @since 2.0
2929 */
3030 public class BooleanUtils {
31
32 /**
33 * <p>{@code BooleanUtils} instances should NOT be constructed in standard programming.
34 * Instead, the class should be used as {@code BooleanUtils.negate(true);}.</p>
35 *
36 * <p>This constructor is public to permit tools that require a JavaBean instance
37 * to operate.</p>
38 */
39 public BooleanUtils() {
40 super();
41 }
42
43 // Boolean utilities
44 //--------------------------------------------------------------------------
31 /**
32 * The false String {@code "false"}.
33 *
34 * @since 3.12.0
35 */
36 public static final String FALSE = "false";
37
38 /**
39 * The no String {@code "no"}.
40 *
41 * @since 3.12.0
42 */
43 public static final String NO = "no";
44
45 /**
46 * The off String {@code "off"}.
47 *
48 * @since 3.12.0
49 */
50 public static final String OFF = "off";
51
52 /**
53 * The on String {@code "on"}.
54 *
55 * @since 3.12.0
56 */
57 public static final String ON = "on";
58
59 /**
60 * The true String {@code "true"}.
61 *
62 * @since 3.12.0
63 */
64 public static final String TRUE = "true";
65
66 /**
67 * The yes String {@code "yes"}.
68 *
69 * @since 3.12.0
70 */
71 public static final String YES = "yes";
72
73 /**
74 * <p>Performs an 'and' operation on a set of booleans.</p>
75 *
76 * <pre>
77 * BooleanUtils.and(true, true) = true
78 * BooleanUtils.and(false, false) = false
79 * BooleanUtils.and(true, false) = false
80 * BooleanUtils.and(true, true, false) = false
81 * BooleanUtils.and(true, true, true) = true
82 * </pre>
83 *
84 * @param array an array of {@code boolean}s
85 * @return the result of the logical 'and' operation. That is {@code false}
86 * if any of the parameters is {@code false} and {@code true} otherwise.
87 * @throws NullPointerException if {@code array} is {@code null}
88 * @throws IllegalArgumentException if {@code array} is empty.
89 * @since 3.0.1
90 */
91 public static boolean and(final boolean... array) {
92 ObjectUtils.requireNonEmpty(array, "array");
93 for (final boolean element : array) {
94 if (!element) {
95 return false;
96 }
97 }
98 return true;
99 }
100
101 /**
102 * <p>Performs an 'and' operation on an array of Booleans.</p>
103 *
104 * <pre>
105 * BooleanUtils.and(Boolean.TRUE, Boolean.TRUE) = Boolean.TRUE
106 * BooleanUtils.and(Boolean.FALSE, Boolean.FALSE) = Boolean.FALSE
107 * BooleanUtils.and(Boolean.TRUE, Boolean.FALSE) = Boolean.FALSE
108 * BooleanUtils.and(Boolean.TRUE, Boolean.TRUE, Boolean.TRUE) = Boolean.TRUE
109 * BooleanUtils.and(Boolean.FALSE, Boolean.FALSE, Boolean.TRUE) = Boolean.FALSE
110 * BooleanUtils.and(Boolean.TRUE, Boolean.FALSE, Boolean.TRUE) = Boolean.FALSE
111 * </pre>
112 *
113 * @param array an array of {@code Boolean}s
114 * @return the result of the logical 'and' operation. That is {@code false}
115 * if any of the parameters is {@code false} and {@code true} otherwise.
116 * @throws NullPointerException if {@code array} is {@code null}
117 * @throws IllegalArgumentException if {@code array} is empty.
118 * @throws IllegalArgumentException if {@code array} contains a {@code null}
119 * @since 3.0.1
120 */
121 public static Boolean and(final Boolean... array) {
122 ObjectUtils.requireNonEmpty(array, "array");
123 try {
124 final boolean[] primitive = ArrayUtils.toPrimitive(array);
125 return and(primitive) ? Boolean.TRUE : Boolean.FALSE;
126 } catch (final NullPointerException ex) {
127 throw new IllegalArgumentException("The array must not contain any null elements");
128 }
129 }
130
131 /**
132 * Returns a new array of possible values (like an enum would).
133 * @return a new array of possible values (like an enum would).
134 * @since 3.12.0
135 */
136 public static Boolean[] booleanValues() {
137 return new Boolean[] {Boolean.FALSE, Boolean.TRUE};
138 }
139
140 /**
141 * <p>Compares two {@code boolean} values. This is the same functionality as provided in Java 7.</p>
142 *
143 * @param x the first {@code boolean} to compare
144 * @param y the second {@code boolean} to compare
145 * @return the value {@code 0} if {@code x == y};
146 * a value less than {@code 0} if {@code !x && y}; and
147 * a value greater than {@code 0} if {@code x && !y}
148 * @since 3.4
149 */
150 public static int compare(final boolean x, final boolean y) {
151 if (x == y) {
152 return 0;
153 }
154 return x ? 1 : -1;
155 }
156
157 /**
158 * <p>Checks if a {@code Boolean} value is {@code false},
159 * handling {@code null} by returning {@code false}.</p>
160 *
161 * <pre>
162 * BooleanUtils.isFalse(Boolean.TRUE) = false
163 * BooleanUtils.isFalse(Boolean.FALSE) = true
164 * BooleanUtils.isFalse(null) = false
165 * </pre>
166 *
167 * @param bool the boolean to check, null returns {@code false}
168 * @return {@code true} only if the input is non-{@code null} and {@code false}
169 * @since 2.1
170 */
171 public static boolean isFalse(final Boolean bool) {
172 return Boolean.FALSE.equals(bool);
173 }
174
175 /**
176 * <p>Checks if a {@code Boolean} value is <i>not</i> {@code false},
177 * handling {@code null} by returning {@code true}.</p>
178 *
179 * <pre>
180 * BooleanUtils.isNotFalse(Boolean.TRUE) = true
181 * BooleanUtils.isNotFalse(Boolean.FALSE) = false
182 * BooleanUtils.isNotFalse(null) = true
183 * </pre>
184 *
185 * @param bool the boolean to check, null returns {@code true}
186 * @return {@code true} if the input is {@code null} or {@code true}
187 * @since 2.3
188 */
189 public static boolean isNotFalse(final Boolean bool) {
190 return !isFalse(bool);
191 }
192
193 /**
194 * <p>Checks if a {@code Boolean} value is <i>not</i> {@code true},
195 * handling {@code null} by returning {@code true}.</p>
196 *
197 * <pre>
198 * BooleanUtils.isNotTrue(Boolean.TRUE) = false
199 * BooleanUtils.isNotTrue(Boolean.FALSE) = true
200 * BooleanUtils.isNotTrue(null) = true
201 * </pre>
202 *
203 * @param bool the boolean to check, null returns {@code true}
204 * @return {@code true} if the input is null or false
205 * @since 2.3
206 */
207 public static boolean isNotTrue(final Boolean bool) {
208 return !isTrue(bool);
209 }
210
211 /**
212 * <p>Checks if a {@code Boolean} value is {@code true},
213 * handling {@code null} by returning {@code false}.</p>
214 *
215 * <pre>
216 * BooleanUtils.isTrue(Boolean.TRUE) = true
217 * BooleanUtils.isTrue(Boolean.FALSE) = false
218 * BooleanUtils.isTrue(null) = false
219 * </pre>
220 *
221 * @param bool the boolean to check, {@code null} returns {@code false}
222 * @return {@code true} only if the input is non-null and true
223 * @since 2.1
224 */
225 public static boolean isTrue(final Boolean bool) {
226 return Boolean.TRUE.equals(bool);
227 }
228
45229 /**
46230 * <p>Negates the specified boolean.</p>
47231 *
65249 }
66250 return bool.booleanValue() ? Boolean.FALSE : Boolean.TRUE;
67251 }
68
69 // boolean Boolean methods
70 //-----------------------------------------------------------------------
71 /**
72 * <p>Checks if a {@code Boolean} value is {@code true},
73 * handling {@code null} by returning {@code false}.</p>
74 *
75 * <pre>
76 * BooleanUtils.isTrue(Boolean.TRUE) = true
77 * BooleanUtils.isTrue(Boolean.FALSE) = false
78 * BooleanUtils.isTrue(null) = false
79 * </pre>
80 *
81 * @param bool the boolean to check, {@code null} returns {@code false}
82 * @return {@code true} only if the input is non-null and true
83 * @since 2.1
84 */
85 public static boolean isTrue(final Boolean bool) {
86 return Boolean.TRUE.equals(bool);
87 }
88
89 /**
90 * <p>Checks if a {@code Boolean} value is <i>not</i> {@code true},
91 * handling {@code null} by returning {@code true}.</p>
92 *
93 * <pre>
94 * BooleanUtils.isNotTrue(Boolean.TRUE) = false
95 * BooleanUtils.isNotTrue(Boolean.FALSE) = true
96 * BooleanUtils.isNotTrue(null) = true
97 * </pre>
98 *
99 * @param bool the boolean to check, null returns {@code true}
100 * @return {@code true} if the input is null or false
101 * @since 2.3
102 */
103 public static boolean isNotTrue(final Boolean bool) {
104 return !isTrue(bool);
105 }
106
107 /**
108 * <p>Checks if a {@code Boolean} value is {@code false},
109 * handling {@code null} by returning {@code false}.</p>
110 *
111 * <pre>
112 * BooleanUtils.isFalse(Boolean.TRUE) = false
113 * BooleanUtils.isFalse(Boolean.FALSE) = true
114 * BooleanUtils.isFalse(null) = false
115 * </pre>
116 *
117 * @param bool the boolean to check, null returns {@code false}
118 * @return {@code true} only if the input is non-{@code null} and {@code false}
119 * @since 2.1
120 */
121 public static boolean isFalse(final Boolean bool) {
122 return Boolean.FALSE.equals(bool);
123 }
124
125 /**
126 * <p>Checks if a {@code Boolean} value is <i>not</i> {@code false},
127 * handling {@code null} by returning {@code true}.</p>
128 *
129 * <pre>
130 * BooleanUtils.isNotFalse(Boolean.TRUE) = true
131 * BooleanUtils.isNotFalse(Boolean.FALSE) = false
132 * BooleanUtils.isNotFalse(null) = true
133 * </pre>
134 *
135 * @param bool the boolean to check, null returns {@code true}
136 * @return {@code true} if the input is {@code null} or {@code true}
137 * @since 2.3
138 */
139 public static boolean isNotFalse(final Boolean bool) {
140 return !isFalse(bool);
141 }
142
143 //-----------------------------------------------------------------------
252 /**
253 * <p>Performs an 'or' operation on a set of booleans.</p>
254 *
255 * <pre>
256 * BooleanUtils.or(true, true) = true
257 * BooleanUtils.or(false, false) = false
258 * BooleanUtils.or(true, false) = true
259 * BooleanUtils.or(true, true, false) = true
260 * BooleanUtils.or(true, true, true) = true
261 * BooleanUtils.or(false, false, false) = false
262 * </pre>
263 *
264 * @param array an array of {@code boolean}s
265 * @return {@code true} if any of the arguments is {@code true}, and it returns {@code false} otherwise.
266 * @throws NullPointerException if {@code array} is {@code null}
267 * @throws IllegalArgumentException if {@code array} is empty.
268 * @since 3.0.1
269 */
270 public static boolean or(final boolean... array) {
271 ObjectUtils.requireNonEmpty(array, "array");
272 for (final boolean element : array) {
273 if (element) {
274 return true;
275 }
276 }
277 return false;
278 }
279
280 /**
281 * <p>Performs an 'or' operation on an array of Booleans.</p>
282 *
283 * <pre>
284 * BooleanUtils.or(Boolean.TRUE, Boolean.TRUE) = Boolean.TRUE
285 * BooleanUtils.or(Boolean.FALSE, Boolean.FALSE) = Boolean.FALSE
286 * BooleanUtils.or(Boolean.TRUE, Boolean.FALSE) = Boolean.TRUE
287 * BooleanUtils.or(Boolean.TRUE, Boolean.TRUE, Boolean.TRUE) = Boolean.TRUE
288 * BooleanUtils.or(Boolean.FALSE, Boolean.FALSE, Boolean.TRUE) = Boolean.TRUE
289 * BooleanUtils.or(Boolean.TRUE, Boolean.FALSE, Boolean.TRUE) = Boolean.TRUE
290 * BooleanUtils.or(Boolean.FALSE, Boolean.FALSE, Boolean.FALSE) = Boolean.FALSE
291 * </pre>
292 *
293 * @param array an array of {@code Boolean}s
294 * @return {@code true} if any of the arguments is {@code true}, and it returns {@code false} otherwise.
295 * @throws NullPointerException if {@code array} is {@code null}
296 * @throws IllegalArgumentException if {@code array} is empty.
297 * @throws IllegalArgumentException if {@code array} contains a {@code null}
298 * @since 3.0.1
299 */
300 public static Boolean or(final Boolean... array) {
301 ObjectUtils.requireNonEmpty(array, "array");
302 try {
303 final boolean[] primitive = ArrayUtils.toPrimitive(array);
304 return or(primitive) ? Boolean.TRUE : Boolean.FALSE;
305 } catch (final NullPointerException ex) {
306 throw new IllegalArgumentException("The array must not contain any null elements");
307 }
308 }
309
310 /**
311 * Returns a new array of possible values (like an enum would).
312 * @return a new array of possible values (like an enum would).
313 * @since 3.12.0
314 */
315 public static boolean[] primitiveValues() {
316 return new boolean[] {false, true};
317 }
318
144319 /**
145320 * <p>Converts a Boolean to a boolean handling {@code null}
146321 * by returning {@code false}.</p>
156331 */
157332 public static boolean toBoolean(final Boolean bool) {
158333 return bool != null && bool.booleanValue();
334 }
335
336 /**
337 * <p>Converts an int to a boolean using the convention that {@code zero}
338 * is {@code false}, everything else is {@code true}.</p>
339 *
340 * <pre>
341 * BooleanUtils.toBoolean(0) = false
342 * BooleanUtils.toBoolean(1) = true
343 * BooleanUtils.toBoolean(2) = true
344 * </pre>
345 *
346 * @param value the int to convert
347 * @return {@code true} if non-zero, {@code false}
348 * if zero
349 */
350 public static boolean toBoolean(final int value) {
351 return value != 0;
352 }
353
354 /**
355 * <p>Converts an int to a boolean specifying the conversion values.</p>
356 *
357 * <p>If the {@code trueValue} and {@code falseValue} are the same number then
358 * the return value will be {@code true} in case {@code value} matches it.</p>
359 *
360 * <pre>
361 * BooleanUtils.toBoolean(0, 1, 0) = false
362 * BooleanUtils.toBoolean(1, 1, 0) = true
363 * BooleanUtils.toBoolean(1, 1, 1) = true
364 * BooleanUtils.toBoolean(2, 1, 2) = false
365 * BooleanUtils.toBoolean(2, 2, 0) = true
366 * </pre>
367 *
368 * @param value the {@code Integer} to convert
369 * @param trueValue the value to match for {@code true}
370 * @param falseValue the value to match for {@code false}
371 * @return {@code true} or {@code false}
372 * @throws IllegalArgumentException if {@code value} does not match neither
373 * {@code trueValue} no {@code falseValue}
374 */
375 public static boolean toBoolean(final int value, final int trueValue, final int falseValue) {
376 if (value == trueValue) {
377 return true;
378 }
379 if (value == falseValue) {
380 return false;
381 }
382 throw new IllegalArgumentException("The Integer did not match either specified value");
383 }
384
385 /**
386 * <p>Converts an Integer to a boolean specifying the conversion values.</p>
387 *
388 * <pre>
389 * BooleanUtils.toBoolean(Integer.valueOf(0), Integer.valueOf(1), Integer.valueOf(0)) = false
390 * BooleanUtils.toBoolean(Integer.valueOf(1), Integer.valueOf(1), Integer.valueOf(0)) = true
391 * BooleanUtils.toBoolean(Integer.valueOf(2), Integer.valueOf(1), Integer.valueOf(2)) = false
392 * BooleanUtils.toBoolean(Integer.valueOf(2), Integer.valueOf(2), Integer.valueOf(0)) = true
393 * BooleanUtils.toBoolean(null, null, Integer.valueOf(0)) = true
394 * </pre>
395 *
396 * @param value the Integer to convert
397 * @param trueValue the value to match for {@code true}, may be {@code null}
398 * @param falseValue the value to match for {@code false}, may be {@code null}
399 * @return {@code true} or {@code false}
400 * @throws IllegalArgumentException if no match
401 */
402 public static boolean toBoolean(final Integer value, final Integer trueValue, final Integer falseValue) {
403 if (value == null) {
404 if (trueValue == null) {
405 return true;
406 }
407 if (falseValue == null) {
408 return false;
409 }
410 } else if (value.equals(trueValue)) {
411 return true;
412 } else if (value.equals(falseValue)) {
413 return false;
414 }
415 throw new IllegalArgumentException("The Integer did not match either specified value");
416 }
417
418 /**
419 * <p>Converts a String to a boolean (optimised for performance).</p>
420 *
421 * <p>{@code 'true'}, {@code 'on'}, {@code 'y'}, {@code 't'} or {@code 'yes'}
422 * (case insensitive) will return {@code true}. Otherwise,
423 * {@code false} is returned.</p>
424 *
425 * <p>This method performs 4 times faster (JDK1.4) than
426 * {@code Boolean.valueOf(String)}. However, this method accepts
427 * 'on' and 'yes', 't', 'y' as true values.
428 *
429 * <pre>
430 * BooleanUtils.toBoolean(null) = false
431 * BooleanUtils.toBoolean("true") = true
432 * BooleanUtils.toBoolean("TRUE") = true
433 * BooleanUtils.toBoolean("tRUe") = true
434 * BooleanUtils.toBoolean("on") = true
435 * BooleanUtils.toBoolean("yes") = true
436 * BooleanUtils.toBoolean("false") = false
437 * BooleanUtils.toBoolean("x gti") = false
438 * BooleanUtils.toBoolean("y") = true
439 * BooleanUtils.toBoolean("n") = false
440 * BooleanUtils.toBoolean("t") = true
441 * BooleanUtils.toBoolean("f") = false
442 * </pre>
443 *
444 * @param str the String to check
445 * @return the boolean value of the string, {@code false} if no match or the String is null
446 */
447 public static boolean toBoolean(final String str) {
448 return toBooleanObject(str) == Boolean.TRUE;
449 }
450
451 /**
452 * <p>Converts a String to a Boolean throwing an exception if no match found.</p>
453 *
454 * <pre>
455 * BooleanUtils.toBoolean("true", "true", "false") = true
456 * BooleanUtils.toBoolean("false", "true", "false") = false
457 * </pre>
458 *
459 * @param str the String to check
460 * @param trueString the String to match for {@code true} (case sensitive), may be {@code null}
461 * @param falseString the String to match for {@code false} (case sensitive), may be {@code null}
462 * @return the boolean value of the string
463 * @throws IllegalArgumentException if the String doesn't match
464 */
465 public static boolean toBoolean(final String str, final String trueString, final String falseString) {
466 if (str == trueString) {
467 return true;
468 }
469 if (str == falseString) {
470 return false;
471 }
472 if (str != null) {
473 if (str.equals(trueString)) {
474 return true;
475 }
476 if (str.equals(falseString)) {
477 return false;
478 }
479 }
480 throw new IllegalArgumentException("The String did not match either specified value");
159481 }
160482
161483 /**
181503 return bool.booleanValue();
182504 }
183505
184 // Integer to Boolean methods
185 //-----------------------------------------------------------------------
186 /**
187 * <p>Converts an int to a boolean using the convention that {@code zero}
188 * is {@code false}, everything else is {@code true}.</p>
189 *
190 * <pre>
191 * BooleanUtils.toBoolean(0) = false
192 * BooleanUtils.toBoolean(1) = true
193 * BooleanUtils.toBoolean(2) = true
194 * </pre>
195 *
196 * @param value the int to convert
197 * @return {@code true} if non-zero, {@code false}
198 * if zero
199 */
200 public static boolean toBoolean(final int value) {
201 return value != 0;
202 }
203
204506 /**
205507 * <p>Converts an int to a Boolean using the convention that {@code zero}
206508 * is {@code false}, everything else is {@code true}.</p>
217519 */
218520 public static Boolean toBooleanObject(final int value) {
219521 return value == 0 ? Boolean.FALSE : Boolean.TRUE;
220 }
221
222 /**
223 * <p>Converts an Integer to a Boolean using the convention that {@code zero}
224 * is {@code false}, every other numeric value is {@code true}.</p>
225 *
226 * <p>{@code null} will be converted to {@code null}.</p>
227 *
228 * <p>NOTE: This method may return {@code null} and may throw a {@code NullPointerException}
229 * if unboxed to a {@code boolean}.</p>
230 *
231 * <pre>
232 * BooleanUtils.toBoolean(Integer.valueOf(0)) = Boolean.FALSE
233 * BooleanUtils.toBoolean(Integer.valueOf(1)) = Boolean.TRUE
234 * BooleanUtils.toBoolean(Integer.valueOf(null)) = null
235 * </pre>
236 *
237 * @param value the Integer to convert
238 * @return Boolean.TRUE if non-zero, Boolean.FALSE if zero,
239 * {@code null} if {@code null} input
240 */
241 public static Boolean toBooleanObject(final Integer value) {
242 if (value == null) {
243 return null;
244 }
245 return value.intValue() == 0 ? Boolean.FALSE : Boolean.TRUE;
246 }
247
248 /**
249 * <p>Converts an int to a boolean specifying the conversion values.</p>
250 *
251 * <p>If the {@code trueValue} and {@code falseValue} are the same number then
252 * the return value will be {@code true} in case {@code value} matches it.</p>
253 *
254 * <pre>
255 * BooleanUtils.toBoolean(0, 1, 0) = false
256 * BooleanUtils.toBoolean(1, 1, 0) = true
257 * BooleanUtils.toBoolean(1, 1, 1) = true
258 * BooleanUtils.toBoolean(2, 1, 2) = false
259 * BooleanUtils.toBoolean(2, 2, 0) = true
260 * </pre>
261 *
262 * @param value the {@code Integer} to convert
263 * @param trueValue the value to match for {@code true}
264 * @param falseValue the value to match for {@code false}
265 * @return {@code true} or {@code false}
266 * @throws IllegalArgumentException if {@code value} does not match neither
267 * {@code trueValue} no {@code falseValue}
268 */
269 public static boolean toBoolean(final int value, final int trueValue, final int falseValue) {
270 if (value == trueValue) {
271 return true;
272 }
273 if (value == falseValue) {
274 return false;
275 }
276 throw new IllegalArgumentException("The Integer did not match either specified value");
277 }
278
279 /**
280 * <p>Converts an Integer to a boolean specifying the conversion values.</p>
281 *
282 * <pre>
283 * BooleanUtils.toBoolean(Integer.valueOf(0), Integer.valueOf(1), Integer.valueOf(0)) = false
284 * BooleanUtils.toBoolean(Integer.valueOf(1), Integer.valueOf(1), Integer.valueOf(0)) = true
285 * BooleanUtils.toBoolean(Integer.valueOf(2), Integer.valueOf(1), Integer.valueOf(2)) = false
286 * BooleanUtils.toBoolean(Integer.valueOf(2), Integer.valueOf(2), Integer.valueOf(0)) = true
287 * BooleanUtils.toBoolean(null, null, Integer.valueOf(0)) = true
288 * </pre>
289 *
290 * @param value the Integer to convert
291 * @param trueValue the value to match for {@code true}, may be {@code null}
292 * @param falseValue the value to match for {@code false}, may be {@code null}
293 * @return {@code true} or {@code false}
294 * @throws IllegalArgumentException if no match
295 */
296 public static boolean toBoolean(final Integer value, final Integer trueValue, final Integer falseValue) {
297 if (value == null) {
298 if (trueValue == null) {
299 return true;
300 }
301 if (falseValue == null) {
302 return false;
303 }
304 } else if (value.equals(trueValue)) {
305 return true;
306 } else if (value.equals(falseValue)) {
307 return false;
308 }
309 throw new IllegalArgumentException("The Integer did not match either specified value");
310522 }
311523
312524 /**
348560 }
349561
350562 /**
563 * <p>Converts an Integer to a Boolean using the convention that {@code zero}
564 * is {@code false}, every other numeric value is {@code true}.</p>
565 *
566 * <p>{@code null} will be converted to {@code null}.</p>
567 *
568 * <p>NOTE: This method may return {@code null} and may throw a {@code NullPointerException}
569 * if unboxed to a {@code boolean}.</p>
570 *
571 * <pre>
572 * BooleanUtils.toBooleanObject(Integer.valueOf(0)) = Boolean.FALSE
573 * BooleanUtils.toBooleanObject(Integer.valueOf(1)) = Boolean.TRUE
574 * BooleanUtils.toBooleanObject(Integer.valueOf(null)) = null
575 * </pre>
576 *
577 * @param value the Integer to convert
578 * @return Boolean.TRUE if non-zero, Boolean.FALSE if zero,
579 * {@code null} if {@code null} input
580 */
581 public static Boolean toBooleanObject(final Integer value) {
582 if (value == null) {
583 return null;
584 }
585 return value.intValue() == 0 ? Boolean.FALSE : Boolean.TRUE;
586 }
587
588 /**
351589 * <p>Converts an Integer to a Boolean specifying the conversion values.</p>
352590 *
353591 * <p>NOTE: This method may return {@code null} and may throw a {@code NullPointerException}
393631 throw new IllegalArgumentException("The Integer did not match any specified value");
394632 }
395633
396 // Boolean to Integer methods
397 //-----------------------------------------------------------------------
398 /**
399 * <p>Converts a boolean to an int using the convention that
400 * {@code true} is {@code 1} and {@code false} is {@code 0}.</p>
401 *
402 * <pre>
403 * BooleanUtils.toInteger(true) = 1
404 * BooleanUtils.toInteger(false) = 0
405 * </pre>
406 *
407 * @param bool the boolean to convert
408 * @return one if {@code true}, zero if {@code false}
409 */
410 public static int toInteger(final boolean bool) {
411 return bool ? 1 : 0;
412 }
413
414 /**
415 * <p>Converts a boolean to an Integer using the convention that
416 * {@code true} is {@code 1} and {@code false} is {@code 0}.</p>
417 *
418 * <pre>
419 * BooleanUtils.toIntegerObject(true) = Integer.valueOf(1)
420 * BooleanUtils.toIntegerObject(false) = Integer.valueOf(0)
421 * </pre>
422 *
423 * @param bool the boolean to convert
424 * @return one if {@code true}, zero if {@code false}
425 */
426 public static Integer toIntegerObject(final boolean bool) {
427 return bool ? NumberUtils.INTEGER_ONE : NumberUtils.INTEGER_ZERO;
428 }
429
430 /**
431 * <p>Converts a Boolean to a Integer using the convention that
432 * {@code zero} is {@code false}.</p>
433 *
434 * <p>{@code null} will be converted to {@code null}.</p>
435 *
436 * <pre>
437 * BooleanUtils.toIntegerObject(Boolean.TRUE) = Integer.valueOf(1)
438 * BooleanUtils.toIntegerObject(Boolean.FALSE) = Integer.valueOf(0)
439 * </pre>
440 *
441 * @param bool the Boolean to convert
442 * @return one if Boolean.TRUE, zero if Boolean.FALSE, {@code null} if {@code null}
443 */
444 public static Integer toIntegerObject(final Boolean bool) {
445 if (bool == null) {
446 return null;
447 }
448 return bool.booleanValue() ? NumberUtils.INTEGER_ONE : NumberUtils.INTEGER_ZERO;
449 }
450
451 /**
452 * <p>Converts a boolean to an int specifying the conversion values.</p>
453 *
454 * <pre>
455 * BooleanUtils.toInteger(true, 1, 0) = 1
456 * BooleanUtils.toInteger(false, 1, 0) = 0
457 * </pre>
458 *
459 * @param bool the to convert
460 * @param trueValue the value to return if {@code true}
461 * @param falseValue the value to return if {@code false}
462 * @return the appropriate value
463 */
464 public static int toInteger(final boolean bool, final int trueValue, final int falseValue) {
465 return bool ? trueValue : falseValue;
466 }
467
468 /**
469 * <p>Converts a Boolean to an int specifying the conversion values.</p>
470 *
471 * <pre>
472 * BooleanUtils.toInteger(Boolean.TRUE, 1, 0, 2) = 1
473 * BooleanUtils.toInteger(Boolean.FALSE, 1, 0, 2) = 0
474 * BooleanUtils.toInteger(null, 1, 0, 2) = 2
475 * </pre>
476 *
477 * @param bool the Boolean to convert
478 * @param trueValue the value to return if {@code true}
479 * @param falseValue the value to return if {@code false}
480 * @param nullValue the value to return if {@code null}
481 * @return the appropriate value
482 */
483 public static int toInteger(final Boolean bool, final int trueValue, final int falseValue, final int nullValue) {
484 if (bool == null) {
485 return nullValue;
486 }
487 return bool.booleanValue() ? trueValue : falseValue;
488 }
489
490 /**
491 * <p>Converts a boolean to an Integer specifying the conversion values.</p>
492 *
493 * <pre>
494 * BooleanUtils.toIntegerObject(true, Integer.valueOf(1), Integer.valueOf(0)) = Integer.valueOf(1)
495 * BooleanUtils.toIntegerObject(false, Integer.valueOf(1), Integer.valueOf(0)) = Integer.valueOf(0)
496 * </pre>
497 *
498 * @param bool the to convert
499 * @param trueValue the value to return if {@code true}, may be {@code null}
500 * @param falseValue the value to return if {@code false}, may be {@code null}
501 * @return the appropriate value
502 */
503 public static Integer toIntegerObject(final boolean bool, final Integer trueValue, final Integer falseValue) {
504 return bool ? trueValue : falseValue;
505 }
506
507 /**
508 * <p>Converts a Boolean to an Integer specifying the conversion values.</p>
509 *
510 * <pre>
511 * BooleanUtils.toIntegerObject(Boolean.TRUE, Integer.valueOf(1), Integer.valueOf(0), Integer.valueOf(2)) = Integer.valueOf(1)
512 * BooleanUtils.toIntegerObject(Boolean.FALSE, Integer.valueOf(1), Integer.valueOf(0), Integer.valueOf(2)) = Integer.valueOf(0)
513 * BooleanUtils.toIntegerObject(null, Integer.valueOf(1), Integer.valueOf(0), Integer.valueOf(2)) = Integer.valueOf(2)
514 * </pre>
515 *
516 * @param bool the Boolean to convert
517 * @param trueValue the value to return if {@code true}, may be {@code null}
518 * @param falseValue the value to return if {@code false}, may be {@code null}
519 * @param nullValue the value to return if {@code null}, may be {@code null}
520 * @return the appropriate value
521 */
522 public static Integer toIntegerObject(final Boolean bool, final Integer trueValue, final Integer falseValue, final Integer nullValue) {
523 if (bool == null) {
524 return nullValue;
525 }
526 return bool.booleanValue() ? trueValue : falseValue;
527 }
528
529 // String to Boolean methods
530 //-----------------------------------------------------------------------
531634 /**
532635 * <p>Converts a String to a Boolean.</p>
533636 *
572675 // Optimisation provides same performance as before for interned 'true'.
573676 // Similar performance for null, 'false', and other strings not length 2/3/4.
574677 // 'true'/'TRUE' match 4 times slower, 'tRUE'/'True' 7 times slower.
575 if (str == "true") {
678 if (str == TRUE) {
576679 return Boolean.TRUE;
577680 }
578681 if (str == null) {
705808 throw new IllegalArgumentException("The String did not match any specified value");
706809 }
707810
708 // String to boolean methods
709 //-----------------------------------------------------------------------
710 /**
711 * <p>Converts a String to a boolean (optimised for performance).</p>
712 *
713 * <p>{@code 'true'}, {@code 'on'}, {@code 'y'}, {@code 't'} or {@code 'yes'}
714 * (case insensitive) will return {@code true}. Otherwise,
715 * {@code false} is returned.</p>
716 *
717 * <p>This method performs 4 times faster (JDK1.4) than
718 * {@code Boolean.valueOf(String)}. However, this method accepts
719 * 'on' and 'yes', 't', 'y' as true values.
720 *
721 * <pre>
722 * BooleanUtils.toBoolean(null) = false
723 * BooleanUtils.toBoolean("true") = true
724 * BooleanUtils.toBoolean("TRUE") = true
725 * BooleanUtils.toBoolean("tRUe") = true
726 * BooleanUtils.toBoolean("on") = true
727 * BooleanUtils.toBoolean("yes") = true
728 * BooleanUtils.toBoolean("false") = false
729 * BooleanUtils.toBoolean("x gti") = false
730 * BooleanUtils.toBooleanObject("y") = true
731 * BooleanUtils.toBooleanObject("n") = false
732 * BooleanUtils.toBooleanObject("t") = true
733 * BooleanUtils.toBooleanObject("f") = false
734 * </pre>
735 *
736 * @param str the String to check
737 * @return the boolean value of the string, {@code false} if no match or the String is null
738 */
739 public static boolean toBoolean(final String str) {
740 return toBooleanObject(str) == Boolean.TRUE;
741 }
742
743 /**
744 * <p>Converts a String to a Boolean throwing an exception if no match found.</p>
745 *
746 * <pre>
747 * BooleanUtils.toBoolean("true", "true", "false") = true
748 * BooleanUtils.toBoolean("false", "true", "false") = false
749 * </pre>
750 *
751 * @param str the String to check
752 * @param trueString the String to match for {@code true} (case sensitive), may be {@code null}
753 * @param falseString the String to match for {@code false} (case sensitive), may be {@code null}
754 * @return the boolean value of the string
755 * @throws IllegalArgumentException if the String doesn't match
756 */
757 public static boolean toBoolean(final String str, final String trueString, final String falseString) {
758 if (str == trueString) {
759 return true;
760 } else if (str == falseString) {
761 return false;
762 } else if (str != null) {
763 if (str.equals(trueString)) {
764 return true;
765 } else if (str.equals(falseString)) {
766 return false;
767 }
768 }
769 throw new IllegalArgumentException("The String did not match either specified value");
770 }
771
772 // Boolean to String methods
773 //-----------------------------------------------------------------------
774 /**
775 * <p>Converts a Boolean to a String returning {@code 'true'},
776 * {@code 'false'}, or {@code null}.</p>
777 *
778 * <pre>
779 * BooleanUtils.toStringTrueFalse(Boolean.TRUE) = "true"
780 * BooleanUtils.toStringTrueFalse(Boolean.FALSE) = "false"
781 * BooleanUtils.toStringTrueFalse(null) = null;
811 /**
812 * <p>Converts a boolean to an int using the convention that
813 * {@code true} is {@code 1} and {@code false} is {@code 0}.</p>
814 *
815 * <pre>
816 * BooleanUtils.toInteger(true) = 1
817 * BooleanUtils.toInteger(false) = 0
818 * </pre>
819 *
820 * @param bool the boolean to convert
821 * @return one if {@code true}, zero if {@code false}
822 */
823 public static int toInteger(final boolean bool) {
824 return bool ? 1 : 0;
825 }
826
827 /**
828 * <p>Converts a boolean to an int specifying the conversion values.</p>
829 *
830 * <pre>
831 * BooleanUtils.toInteger(true, 1, 0) = 1
832 * BooleanUtils.toInteger(false, 1, 0) = 0
833 * </pre>
834 *
835 * @param bool the to convert
836 * @param trueValue the value to return if {@code true}
837 * @param falseValue the value to return if {@code false}
838 * @return the appropriate value
839 */
840 public static int toInteger(final boolean bool, final int trueValue, final int falseValue) {
841 return bool ? trueValue : falseValue;
842 }
843
844 /**
845 * <p>Converts a Boolean to an int specifying the conversion values.</p>
846 *
847 * <pre>
848 * BooleanUtils.toInteger(Boolean.TRUE, 1, 0, 2) = 1
849 * BooleanUtils.toInteger(Boolean.FALSE, 1, 0, 2) = 0
850 * BooleanUtils.toInteger(null, 1, 0, 2) = 2
851 * </pre>
852 *
853 * @param bool the Boolean to convert
854 * @param trueValue the value to return if {@code true}
855 * @param falseValue the value to return if {@code false}
856 * @param nullValue the value to return if {@code null}
857 * @return the appropriate value
858 */
859 public static int toInteger(final Boolean bool, final int trueValue, final int falseValue, final int nullValue) {
860 if (bool == null) {
861 return nullValue;
862 }
863 return bool.booleanValue() ? trueValue : falseValue;
864 }
865
866 /**
867 * <p>Converts a boolean to an Integer using the convention that
868 * {@code true} is {@code 1} and {@code false} is {@code 0}.</p>
869 *
870 * <pre>
871 * BooleanUtils.toIntegerObject(true) = Integer.valueOf(1)
872 * BooleanUtils.toIntegerObject(false) = Integer.valueOf(0)
873 * </pre>
874 *
875 * @param bool the boolean to convert
876 * @return one if {@code true}, zero if {@code false}
877 */
878 public static Integer toIntegerObject(final boolean bool) {
879 return bool ? NumberUtils.INTEGER_ONE : NumberUtils.INTEGER_ZERO;
880 }
881
882 /**
883 * <p>Converts a boolean to an Integer specifying the conversion values.</p>
884 *
885 * <pre>
886 * BooleanUtils.toIntegerObject(true, Integer.valueOf(1), Integer.valueOf(0)) = Integer.valueOf(1)
887 * BooleanUtils.toIntegerObject(false, Integer.valueOf(1), Integer.valueOf(0)) = Integer.valueOf(0)
888 * </pre>
889 *
890 * @param bool the to convert
891 * @param trueValue the value to return if {@code true}, may be {@code null}
892 * @param falseValue the value to return if {@code false}, may be {@code null}
893 * @return the appropriate value
894 */
895 public static Integer toIntegerObject(final boolean bool, final Integer trueValue, final Integer falseValue) {
896 return bool ? trueValue : falseValue;
897 }
898
899 /**
900 * <p>Converts a Boolean to a Integer using the convention that
901 * {@code zero} is {@code false}.</p>
902 *
903 * <p>{@code null} will be converted to {@code null}.</p>
904 *
905 * <pre>
906 * BooleanUtils.toIntegerObject(Boolean.TRUE) = Integer.valueOf(1)
907 * BooleanUtils.toIntegerObject(Boolean.FALSE) = Integer.valueOf(0)
908 * </pre>
909 *
910 * @param bool the Boolean to convert
911 * @return one if Boolean.TRUE, zero if Boolean.FALSE, {@code null} if {@code null}
912 */
913 public static Integer toIntegerObject(final Boolean bool) {
914 if (bool == null) {
915 return null;
916 }
917 return bool.booleanValue() ? NumberUtils.INTEGER_ONE : NumberUtils.INTEGER_ZERO;
918 }
919
920 /**
921 * <p>Converts a Boolean to an Integer specifying the conversion values.</p>
922 *
923 * <pre>
924 * BooleanUtils.toIntegerObject(Boolean.TRUE, Integer.valueOf(1), Integer.valueOf(0), Integer.valueOf(2)) = Integer.valueOf(1)
925 * BooleanUtils.toIntegerObject(Boolean.FALSE, Integer.valueOf(1), Integer.valueOf(0), Integer.valueOf(2)) = Integer.valueOf(0)
926 * BooleanUtils.toIntegerObject(null, Integer.valueOf(1), Integer.valueOf(0), Integer.valueOf(2)) = Integer.valueOf(2)
927 * </pre>
928 *
929 * @param bool the Boolean to convert
930 * @param trueValue the value to return if {@code true}, may be {@code null}
931 * @param falseValue the value to return if {@code false}, may be {@code null}
932 * @param nullValue the value to return if {@code null}, may be {@code null}
933 * @return the appropriate value
934 */
935 public static Integer toIntegerObject(final Boolean bool, final Integer trueValue, final Integer falseValue, final Integer nullValue) {
936 if (bool == null) {
937 return nullValue;
938 }
939 return bool.booleanValue() ? trueValue : falseValue;
940 }
941
942 /**
943 * <p>Converts a boolean to a String returning one of the input Strings.</p>
944 *
945 * <pre>
946 * BooleanUtils.toString(true, "true", "false") = "true"
947 * BooleanUtils.toString(false, "true", "false") = "false"
782948 * </pre>
783949 *
784950 * @param bool the Boolean to check
785 * @return {@code 'true'}, {@code 'false'}, or {@code null}
786 */
787 public static String toStringTrueFalse(final Boolean bool) {
788 return toString(bool, "true", "false", null);
789 }
790
791 /**
792 * <p>Converts a Boolean to a String returning {@code 'on'},
793 * {@code 'off'}, or {@code null}.</p>
794 *
795 * <pre>
796 * BooleanUtils.toStringOnOff(Boolean.TRUE) = "on"
797 * BooleanUtils.toStringOnOff(Boolean.FALSE) = "off"
798 * BooleanUtils.toStringOnOff(null) = null;
799 * </pre>
800 *
801 * @param bool the Boolean to check
802 * @return {@code 'on'}, {@code 'off'}, or {@code null}
803 */
804 public static String toStringOnOff(final Boolean bool) {
805 return toString(bool, "on", "off", null);
806 }
807
808 /**
809 * <p>Converts a Boolean to a String returning {@code 'yes'},
810 * {@code 'no'}, or {@code null}.</p>
811 *
812 * <pre>
813 * BooleanUtils.toStringYesNo(Boolean.TRUE) = "yes"
814 * BooleanUtils.toStringYesNo(Boolean.FALSE) = "no"
815 * BooleanUtils.toStringYesNo(null) = null;
816 * </pre>
817 *
818 * @param bool the Boolean to check
819 * @return {@code 'yes'}, {@code 'no'}, or {@code null}
820 */
821 public static String toStringYesNo(final Boolean bool) {
822 return toString(bool, "yes", "no", null);
951 * @param trueString the String to return if {@code true}, may be {@code null}
952 * @param falseString the String to return if {@code false}, may be {@code null}
953 * @return one of the two input Strings
954 */
955 public static String toString(final boolean bool, final String trueString, final String falseString) {
956 return bool ? trueString : falseString;
823957 }
824958
825959 /**
844978 return bool.booleanValue() ? trueString : falseString;
845979 }
846980
847 // boolean to String methods
848 //-----------------------------------------------------------------------
981 /**
982 * <p>Converts a boolean to a String returning {@code 'on'}
983 * or {@code 'off'}.</p>
984 *
985 * <pre>
986 * BooleanUtils.toStringOnOff(true) = "on"
987 * BooleanUtils.toStringOnOff(false) = "off"
988 * </pre>
989 *
990 * @param bool the Boolean to check
991 * @return {@code 'on'}, {@code 'off'}, or {@code null}
992 */
993 public static String toStringOnOff(final boolean bool) {
994 return toString(bool, ON, OFF);
995 }
996
997 /**
998 * <p>Converts a Boolean to a String returning {@code 'on'},
999 * {@code 'off'}, or {@code null}.</p>
1000 *
1001 * <pre>
1002 * BooleanUtils.toStringOnOff(Boolean.TRUE) = "on"
1003 * BooleanUtils.toStringOnOff(Boolean.FALSE) = "off"
1004 * BooleanUtils.toStringOnOff(null) = null;
1005 * </pre>
1006 *
1007 * @param bool the Boolean to check
1008 * @return {@code 'on'}, {@code 'off'}, or {@code null}
1009 */
1010 public static String toStringOnOff(final Boolean bool) {
1011 return toString(bool, ON, OFF, null);
1012 }
1013
8491014 /**
8501015 * <p>Converts a boolean to a String returning {@code 'true'}
8511016 * or {@code 'false'}.</p>
8591024 * @return {@code 'true'}, {@code 'false'}, or {@code null}
8601025 */
8611026 public static String toStringTrueFalse(final boolean bool) {
862 return toString(bool, "true", "false");
863 }
864
865 /**
866 * <p>Converts a boolean to a String returning {@code 'on'}
867 * or {@code 'off'}.</p>
868 *
869 * <pre>
870 * BooleanUtils.toStringOnOff(true) = "on"
871 * BooleanUtils.toStringOnOff(false) = "off"
1027 return toString(bool, TRUE, FALSE);
1028 }
1029
1030 /**
1031 * <p>Converts a Boolean to a String returning {@code 'true'},
1032 * {@code 'false'}, or {@code null}.</p>
1033 *
1034 * <pre>
1035 * BooleanUtils.toStringTrueFalse(Boolean.TRUE) = "true"
1036 * BooleanUtils.toStringTrueFalse(Boolean.FALSE) = "false"
1037 * BooleanUtils.toStringTrueFalse(null) = null;
8721038 * </pre>
8731039 *
8741040 * @param bool the Boolean to check
875 * @return {@code 'on'}, {@code 'off'}, or {@code null}
876 */
877 public static String toStringOnOff(final boolean bool) {
878 return toString(bool, "on", "off");
1041 * @return {@code 'true'}, {@code 'false'}, or {@code null}
1042 */
1043 public static String toStringTrueFalse(final Boolean bool) {
1044 return toString(bool, TRUE, FALSE, null);
8791045 }
8801046
8811047 /**
8911057 * @return {@code 'yes'}, {@code 'no'}, or {@code null}
8921058 */
8931059 public static String toStringYesNo(final boolean bool) {
894 return toString(bool, "yes", "no");
895 }
896
897 /**
898 * <p>Converts a boolean to a String returning one of the input Strings.</p>
899 *
900 * <pre>
901 * BooleanUtils.toString(true, "true", "false") = "true"
902 * BooleanUtils.toString(false, "true", "false") = "false"
1060 return toString(bool, YES, NO);
1061 }
1062
1063 /**
1064 * <p>Converts a Boolean to a String returning {@code 'yes'},
1065 * {@code 'no'}, or {@code null}.</p>
1066 *
1067 * <pre>
1068 * BooleanUtils.toStringYesNo(Boolean.TRUE) = "yes"
1069 * BooleanUtils.toStringYesNo(Boolean.FALSE) = "no"
1070 * BooleanUtils.toStringYesNo(null) = null;
9031071 * </pre>
9041072 *
9051073 * @param bool the Boolean to check
906 * @param trueString the String to return if {@code true}, may be {@code null}
907 * @param falseString the String to return if {@code false}, may be {@code null}
908 * @return one of the two input Strings
909 */
910 public static String toString(final boolean bool, final String trueString, final String falseString) {
911 return bool ? trueString : falseString;
912 }
913
914 // logical operations
915 // ----------------------------------------------------------------------
916 /**
917 * <p>Performs an 'and' operation on a set of booleans.</p>
918 *
919 * <pre>
920 * BooleanUtils.and(true, true) = true
921 * BooleanUtils.and(false, false) = false
922 * BooleanUtils.and(true, false) = false
923 * BooleanUtils.and(true, true, false) = false
924 * BooleanUtils.and(true, true, true) = true
925 * </pre>
926 *
927 * @param array an array of {@code boolean}s
928 * @return the result of the logical 'and' operation. That is {@code false}
929 * if any of the parameters is {@code false} and {@code true} otherwise.
930 * @throws IllegalArgumentException if {@code array} is {@code null}
931 * @throws IllegalArgumentException if {@code array} is empty.
932 * @since 3.0.1
933 */
934 public static boolean and(final boolean... array) {
935 // Validates input
936 if (array == null) {
937 throw new IllegalArgumentException("The Array must not be null");
938 }
939 if (array.length == 0) {
940 throw new IllegalArgumentException("Array is empty");
941 }
942 for (final boolean element : array) {
943 if (!element) {
944 return false;
945 }
946 }
947 return true;
948 }
949
950 /**
951 * <p>Performs an 'and' operation on an array of Booleans.</p>
952 *
953 * <pre>
954 * BooleanUtils.and(Boolean.TRUE, Boolean.TRUE) = Boolean.TRUE
955 * BooleanUtils.and(Boolean.FALSE, Boolean.FALSE) = Boolean.FALSE
956 * BooleanUtils.and(Boolean.TRUE, Boolean.FALSE) = Boolean.FALSE
957 * BooleanUtils.and(Boolean.TRUE, Boolean.TRUE, Boolean.TRUE) = Boolean.TRUE
958 * BooleanUtils.and(Boolean.FALSE, Boolean.FALSE, Boolean.TRUE) = Boolean.FALSE
959 * BooleanUtils.and(Boolean.TRUE, Boolean.FALSE, Boolean.TRUE) = Boolean.FALSE
960 * </pre>
961 *
962 * @param array an array of {@code Boolean}s
963 * @return the result of the logical 'and' operation. That is {@code false}
964 * if any of the parameters is {@code false} and {@code true} otherwise.
965 * @throws IllegalArgumentException if {@code array} is {@code null}
966 * @throws IllegalArgumentException if {@code array} is empty.
967 * @throws IllegalArgumentException if {@code array} contains a {@code null}
968 * @since 3.0.1
969 */
970 public static Boolean and(final Boolean... array) {
971 if (array == null) {
972 throw new IllegalArgumentException("The Array must not be null");
973 }
974 if (array.length == 0) {
975 throw new IllegalArgumentException("Array is empty");
976 }
977 try {
978 final boolean[] primitive = ArrayUtils.toPrimitive(array);
979 return and(primitive) ? Boolean.TRUE : Boolean.FALSE;
980 } catch (final NullPointerException ex) {
981 throw new IllegalArgumentException("The array must not contain any null elements");
982 }
983 }
984
985 /**
986 * <p>Performs an 'or' operation on a set of booleans.</p>
987 *
988 * <pre>
989 * BooleanUtils.or(true, true) = true
990 * BooleanUtils.or(false, false) = false
991 * BooleanUtils.or(true, false) = true
992 * BooleanUtils.or(true, true, false) = true
993 * BooleanUtils.or(true, true, true) = true
994 * BooleanUtils.or(false, false, false) = false
995 * </pre>
996 *
997 * @param array an array of {@code boolean}s
998 * @return {@code true} if any of the arguments is {@code true}, and it returns {@code false} otherwise.
999 * @throws IllegalArgumentException if {@code array} is {@code null}
1000 * @throws IllegalArgumentException if {@code array} is empty.
1001 * @since 3.0.1
1002 */
1003 public static boolean or(final boolean... array) {
1004 if (array == null) {
1005 throw new IllegalArgumentException("The Array must not be null");
1006 }
1007 if (array.length == 0) {
1008 throw new IllegalArgumentException("Array is empty");
1009 }
1010 for (final boolean element : array) {
1011 if (element) {
1012 return true;
1013 }
1014 }
1015 return false;
1016 }
1017
1018 /**
1019 * <p>Performs an 'or' operation on an array of Booleans.</p>
1020 *
1021 * <pre>
1022 * BooleanUtils.or(Boolean.TRUE, Boolean.TRUE) = Boolean.TRUE
1023 * BooleanUtils.or(Boolean.FALSE, Boolean.FALSE) = Boolean.FALSE
1024 * BooleanUtils.or(Boolean.TRUE, Boolean.FALSE) = Boolean.TRUE
1025 * BooleanUtils.or(Boolean.TRUE, Boolean.TRUE, Boolean.TRUE) = Boolean.TRUE
1026 * BooleanUtils.or(Boolean.FALSE, Boolean.FALSE, Boolean.TRUE) = Boolean.TRUE
1027 * BooleanUtils.or(Boolean.TRUE, Boolean.FALSE, Boolean.TRUE) = Boolean.TRUE
1028 * BooleanUtils.or(Boolean.FALSE, Boolean.FALSE, Boolean.FALSE) = Boolean.FALSE
1029 * </pre>
1030 *
1031 * @param array an array of {@code Boolean}s
1032 * @return {@code true} if any of the arguments is {@code true}, and it returns {@code false} otherwise.
1033 * @throws IllegalArgumentException if {@code array} is {@code null}
1034 * @throws IllegalArgumentException if {@code array} is empty.
1035 * @throws IllegalArgumentException if {@code array} contains a {@code null}
1036 * @since 3.0.1
1037 */
1038 public static Boolean or(final Boolean... array) {
1039 if (array == null) {
1040 throw new IllegalArgumentException("The Array must not be null");
1041 }
1042 if (array.length == 0) {
1043 throw new IllegalArgumentException("Array is empty");
1044 }
1045 try {
1046 final boolean[] primitive = ArrayUtils.toPrimitive(array);
1047 return or(primitive) ? Boolean.TRUE : Boolean.FALSE;
1048 } catch (final NullPointerException ex) {
1049 throw new IllegalArgumentException("The array must not contain any null elements");
1050 }
1074 * @return {@code 'yes'}, {@code 'no'}, or {@code null}
1075 */
1076 public static String toStringYesNo(final Boolean bool) {
1077 return toString(bool, YES, NO, null);
10511078 }
10521079
10531080 /**
10611088 *
10621089 * @param array an array of {@code boolean}s
10631090 * @return the result of the xor operations
1064 * @throws IllegalArgumentException if {@code array} is {@code null}
1091 * @throws NullPointerException if {@code array} is {@code null}
10651092 * @throws IllegalArgumentException if {@code array} is empty.
10661093 */
10671094 public static boolean xor(final boolean... array) {
1068 if (array == null) {
1069 throw new IllegalArgumentException("The Array must not be null");
1070 }
1071 if (array.length == 0) {
1072 throw new IllegalArgumentException("Array is empty");
1073 }
1074
1095 ObjectUtils.requireNonEmpty(array, "array");
10751096 // false if the neutral element of the xor operator
10761097 boolean result = false;
10771098 for (final boolean element : array) {
10931114 *
10941115 * @param array an array of {@code Boolean}s
10951116 * @return the result of the xor operations
1096 * @throws IllegalArgumentException if {@code array} is {@code null}
1117 * @throws NullPointerException if {@code array} is {@code null}
10971118 * @throws IllegalArgumentException if {@code array} is empty.
10981119 * @throws IllegalArgumentException if {@code array} contains a {@code null}
10991120 */
11001121 public static Boolean xor(final Boolean... array) {
1101 if (array == null) {
1102 throw new IllegalArgumentException("The Array must not be null");
1103 }
1104 if (array.length == 0) {
1105 throw new IllegalArgumentException("Array is empty");
1106 }
1122 ObjectUtils.requireNonEmpty(array, "array");
11071123 try {
11081124 final boolean[] primitive = ArrayUtils.toPrimitive(array);
11091125 return xor(primitive) ? Boolean.TRUE : Boolean.FALSE;
11131129 }
11141130
11151131 /**
1116 * <p>Compares two {@code boolean} values. This is the same functionality as provided in Java 7.</p>
1117 *
1118 * @param x the first {@code boolean} to compare
1119 * @param y the second {@code boolean} to compare
1120 * @return the value {@code 0} if {@code x == y};
1121 * a value less than {@code 0} if {@code !x && y}; and
1122 * a value greater than {@code 0} if {@code x && !y}
1123 * @since 3.4
1124 */
1125 public static int compare(final boolean x, final boolean y) {
1126 if (x == y) {
1127 return 0;
1128 }
1129 return x ? 1 : -1;
1132 * <p>{@code BooleanUtils} instances should NOT be constructed in standard programming.
1133 * Instead, the class should be used as {@code BooleanUtils.negate(true);}.</p>
1134 *
1135 * <p>This constructor is public to permit tools that require a JavaBean instance
1136 * to operate.</p>
1137 */
1138 public BooleanUtils() {
11301139 }
11311140
11321141 }
4848 /** Cached toString. */
4949 private transient String iToString;
5050
51 /** Empty array. */
52 static final CharRange[] EMPTY_ARRAY = {};
53
5154 /**
5255 * <p>Constructs a {@code CharRange} over a set of characters,
5356 * optionally negating the range.</p>
6366 * @param negated true to express everything except the range
6467 */
6568 private CharRange(char start, char end, final boolean negated) {
66 super();
6769 if (start > end) {
6870 final char temp = start;
6971 start = end;
8082 *
8183 * @param ch only character in this range
8284 * @return the new CharRange object
83 * @see CharRange#CharRange(char, char, boolean)
8485 * @since 2.5
8586 */
8687 public static CharRange is(final char ch) {
9091 /**
9192 * <p>Constructs a negated {@code CharRange} over a single character.</p>
9293 *
94 * <p>A negated range includes everything except that defined by the
95 * single character.</p>
96 *
9397 * @param ch only character in this range
9498 * @return the new CharRange object
95 * @see CharRange#CharRange(char, char, boolean)
9699 * @since 2.5
97100 */
98101 public static CharRange isNot(final char ch) {
101104
102105 /**
103106 * <p>Constructs a {@code CharRange} over a set of characters.</p>
107 *
108 * <p>If start and end are in the wrong order, they are reversed.
109 * Thus {@code a-e} is the same as {@code e-a}.</p>
104110 *
105111 * @param start first character, inclusive, in this range
106112 * @param end last character, inclusive, in this range
107113 * @return the new CharRange object
108 * @see CharRange#CharRange(char, char, boolean)
109114 * @since 2.5
110115 */
111116 public static CharRange isIn(final char start, final char end) {
114119
115120 /**
116121 * <p>Constructs a negated {@code CharRange} over a set of characters.</p>
122 *
123 * <p>A negated range includes everything except that defined by the
124 * start and end characters.</p>
125 *
126 * <p>If start and end are in the wrong order, they are reversed.
127 * Thus {@code a-e} is the same as {@code e-a}.</p>
117128 *
118129 * @param start first character, inclusive, in this range
119130 * @param end last character, inclusive, in this range
120131 * @return the new CharRange object
121 * @see CharRange#CharRange(char, char, boolean)
122132 * @since 2.5
123133 */
124134 public static CharRange isNotIn(final char start, final char end) {
126136 }
127137
128138 // Accessors
129 //-----------------------------------------------------------------------
130139 /**
131140 * <p>Gets the start character for this character range.</p>
132141 *
158167 }
159168
160169 // Contains
161 //-----------------------------------------------------------------------
162170 /**
163171 * <p>Is the character specified contained in this range.</p>
164172 *
178186 * @throws IllegalArgumentException if {@code null} input
179187 */
180188 public boolean contains(final CharRange range) {
181 Validate.notNull(range, "The Range must not be null");
189 Validate.notNull(range, "range");
182190 if (negated) {
183191 if (range.negated) {
184192 return start >= range.start && end <= range.end;
192200 }
193201
194202 // Basics
195 //-----------------------------------------------------------------------
196203 /**
197204 * <p>Compares two CharRange objects, returning true if they represent
198205 * exactly the same range of characters defined in the same way.</p>
245252 }
246253
247254 // Expansions
248 //-----------------------------------------------------------------------
249255 /**
250256 * <p>Returns an iterator which can be used to walk through the characters described by this range.</p>
251257 *
2626
2727 private static final int NOT_FOUND = -1;
2828
29 /**
30 * <p>{@code CharSequenceUtils} instances should NOT be constructed in
31 * standard programming. </p>
32 *
33 * <p>This constructor is public to permit tools that require a JavaBean
34 * instance to operate.</p>
35 */
36 public CharSequenceUtils() {
37 super();
38 }
39
40 //-----------------------------------------------------------------------
41 /**
42 * <p>Returns a new {@code CharSequence} that is a subsequence of this
43 * sequence starting with the {@code char} value at the specified index.</p>
44 *
45 * <p>This provides the {@code CharSequence} equivalent to {@link String#substring(int)}.
46 * The length (in {@code char}) of the returned sequence is {@code length() - start},
47 * so if {@code start == end} then an empty sequence is returned.</p>
48 *
49 * @param cs the specified subsequence, null returns null
50 * @param start the start index, inclusive, valid
51 * @return a new subsequence, may be null
52 * @throws IndexOutOfBoundsException if {@code start} is negative or if
53 * {@code start} is greater than {@code length()}
54 */
55 public static CharSequence subSequence(final CharSequence cs, final int start) {
56 return cs == null ? null : cs.subSequence(start, cs.length());
57 }
58
59 //-----------------------------------------------------------------------
29 static final int TO_STRING_LIMIT = 16;
30
31 private static boolean checkLaterThan1(final CharSequence cs, final CharSequence searchChar, final int len2, final int start1) {
32 for (int i = 1, j = len2 - 1; i <= j; i++, j--) {
33 if (cs.charAt(start1 + i) != searchChar.charAt(i)
34 ||
35 cs.charAt(start1 + j) != searchChar.charAt(j)
36 ) {
37 return false;
38 }
39 }
40 return true;
41 }
42
43 /**
44 * Used by the indexOf(CharSequence methods) as a green implementation of indexOf.
45 *
46 * @param cs the {@code CharSequence} to be processed
47 * @param searchChar the {@code CharSequence} to be searched for
48 * @param start the start index
49 * @return the index where the search sequence was found
50 */
51 static int indexOf(final CharSequence cs, final CharSequence searchChar, final int start) {
52 if (cs instanceof String) {
53 return ((String) cs).indexOf(searchChar.toString(), start);
54 }
55 if (cs instanceof StringBuilder) {
56 return ((StringBuilder) cs).indexOf(searchChar.toString(), start);
57 }
58 if (cs instanceof StringBuffer) {
59 return ((StringBuffer) cs).indexOf(searchChar.toString(), start);
60 }
61 return cs.toString().indexOf(searchChar.toString(), start);
62 // if (cs instanceof String && searchChar instanceof String) {
63 // // TODO: Do we assume searchChar is usually relatively small;
64 // // If so then calling toString() on it is better than reverting to
65 // // the green implementation in the else block
66 // return ((String) cs).indexOf((String) searchChar, start);
67 // } else {
68 // // TODO: Implement rather than convert to String
69 // return cs.toString().indexOf(searchChar.toString(), start);
70 // }
71 }
72
6073 /**
6174 * Returns the index within {@code cs} of the first occurrence of the
6275 * specified character, starting the search at the specified index.
109122 return i;
110123 }
111124 }
125 return NOT_FOUND;
112126 }
113127 //supplementary characters (LANG1300)
114128 if (searchChar <= Character.MAX_CODE_POINT) {
125139 }
126140
127141 /**
128 * Used by the indexOf(CharSequence methods) as a green implementation of indexOf.
142 * Used by the lastIndexOf(CharSequence methods) as a green implementation of lastIndexOf
129143 *
130144 * @param cs the {@code CharSequence} to be processed
131 * @param searchChar the {@code CharSequence} to be searched for
145 * @param searchChar the {@code CharSequence} to find
132146 * @param start the start index
133147 * @return the index where the search sequence was found
134148 */
135 static int indexOf(final CharSequence cs, final CharSequence searchChar, final int start) {
136 if (cs instanceof String) {
137 return ((String) cs).indexOf(searchChar.toString(), start);
138 } else if (cs instanceof StringBuilder) {
139 return ((StringBuilder) cs).indexOf(searchChar.toString(), start);
140 } else if (cs instanceof StringBuffer) {
141 return ((StringBuffer) cs).indexOf(searchChar.toString(), start);
142 }
143 return cs.toString().indexOf(searchChar.toString(), start);
144 // if (cs instanceof String && searchChar instanceof String) {
145 // // TODO: Do we assume searchChar is usually relatively small;
146 // // If so then calling toString() on it is better than reverting to
147 // // the green implementation in the else block
148 // return ((String) cs).indexOf((String) searchChar, start);
149 // } else {
150 // // TODO: Implement rather than convert to String
151 // return cs.toString().indexOf(searchChar.toString(), start);
152 // }
149 static int lastIndexOf(final CharSequence cs, final CharSequence searchChar, int start) {
150 if (searchChar == null || cs == null) {
151 return NOT_FOUND;
152 }
153 if (searchChar instanceof String) {
154 if (cs instanceof String) {
155 return ((String) cs).lastIndexOf((String) searchChar, start);
156 }
157 if (cs instanceof StringBuilder) {
158 return ((StringBuilder) cs).lastIndexOf((String) searchChar, start);
159 }
160 if (cs instanceof StringBuffer) {
161 return ((StringBuffer) cs).lastIndexOf((String) searchChar, start);
162 }
163 }
164
165 final int len1 = cs.length();
166 final int len2 = searchChar.length();
167
168 if (start > len1) {
169 start = len1;
170 }
171
172 if (start < 0 || len2 < 0 || len2 > len1) {
173 return NOT_FOUND;
174 }
175
176 if (len2 == 0) {
177 return start;
178 }
179
180 if (len2 <= TO_STRING_LIMIT) {
181 if (cs instanceof String) {
182 return ((String) cs).lastIndexOf(searchChar.toString(), start);
183 }
184 if (cs instanceof StringBuilder) {
185 return ((StringBuilder) cs).lastIndexOf(searchChar.toString(), start);
186 }
187 if (cs instanceof StringBuffer) {
188 return ((StringBuffer) cs).lastIndexOf(searchChar.toString(), start);
189 }
190 }
191
192 if (start + len2 > len1) {
193 start = len1 - len2;
194 }
195
196 final char char0 = searchChar.charAt(0);
197
198 int i = start;
199 while (true) {
200 while (cs.charAt(i) != char0) {
201 i--;
202 if (i < 0) {
203 return NOT_FOUND;
204 }
205 }
206 if (checkLaterThan1(cs, searchChar, len2, i)) {
207 return i;
208 }
209 i--;
210 if (i < 0) {
211 return NOT_FOUND;
212 }
213 }
153214 }
154215
155216 /**
195256 return i;
196257 }
197258 }
259 return NOT_FOUND;
198260 }
199261 //supplementary characters (LANG1300)
200262 //NOTE - we must do a forward traversal for this to avoid duplicating code points
215277 return NOT_FOUND;
216278 }
217279
218 static final int TO_STRING_LIMIT = 16;
219
220 /**
221 * Used by the lastIndexOf(CharSequence methods) as a green implementation of lastIndexOf
222 *
223 * @param cs the {@code CharSequence} to be processed
224 * @param searchChar the {@code CharSequence} to be searched for
225 * @param start the start index
226 * @return the index where the search sequence was found
227 */
228 static int lastIndexOf(final CharSequence cs, final CharSequence searchChar, int start) {
229 if (searchChar instanceof String) {
230 if (cs instanceof String) {
231 return ((String) cs).lastIndexOf((String) searchChar, start);
232 } else if (cs instanceof StringBuilder) {
233 return ((StringBuilder) cs).lastIndexOf((String) searchChar, start);
234 } else if (cs instanceof StringBuffer) {
235 return ((StringBuffer) cs).lastIndexOf((String) searchChar, start);
236 }
237 }
238
239 final int len1 = cs.length();
240 final int len2 = searchChar.length();
241
242 if (start > len1) {
243 start = len1;
244 }
245
246 if (start < 0 || len2 < 0 || len2 > len1) {
247 return -1;
248 }
249
250 if (len2 == 0) {
251 return start;
252 }
253
254 if (len2 <= TO_STRING_LIMIT) {
255 if (cs instanceof String) {
256 return ((String) cs).lastIndexOf(searchChar.toString(), start);
257 } else if (cs instanceof StringBuilder) {
258 return ((StringBuilder) cs).lastIndexOf(searchChar.toString(), start);
259 } else if (cs instanceof StringBuffer) {
260 return ((StringBuffer) cs).lastIndexOf(searchChar.toString(), start);
261 }
262 }
263
264 if (start + len2 > len1) {
265 start = len1 - len2;
266 }
267
268 final char char0 = searchChar.charAt(0);
269
270 int i = start;
271 while (true) {
272 while (cs.charAt(i) != char0) {
273 i--;
274 if (i < 0) {
275 return -1;
276 }
277 }
278 if (checkLaterThan1(cs, searchChar, len2, i)) {
279 return i;
280 }
281 i--;
282 if (i < 0) {
283 return -1;
284 }
285 }
286 }
287
288 private static boolean checkLaterThan1(final CharSequence cs, final CharSequence searchChar, final int len2, final int start1) {
289 for (int i = 1, j = len2 - 1; i <= j; i++, j--) {
290 if (cs.charAt(start1 + i) != searchChar.charAt(i)
291 ||
292 cs.charAt(start1 + j) != searchChar.charAt(j)
293 ) {
294 return false;
295 }
296 }
297 return true;
298 }
299
300 /**
301 * Converts the given CharSequence to a char[].
302 *
303 * @param source the {@code CharSequence} to be processed.
304 * @return the resulting char array, never null.
305 * @since 3.11
306 */
307 public static char[] toCharArray(final CharSequence source) {
308 final int len = StringUtils.length(source);
309 if (len == 0) {
310 return ArrayUtils.EMPTY_CHAR_ARRAY;
311 }
312 if (source instanceof String) {
313 return ((String) source).toCharArray();
314 }
315 final char[] array = new char[len];
316 for (int i = 0; i < len; i++) {
317 array[i] = source.charAt(i);
318 }
319 return array;
320 }
321
322280 /**
323281 * Green implementation of regionMatches.
324282 *
375333
376334 return true;
377335 }
336
337 /**
338 * <p>Returns a new {@code CharSequence} that is a subsequence of this
339 * sequence starting with the {@code char} value at the specified index.</p>
340 *
341 * <p>This provides the {@code CharSequence} equivalent to {@link String#substring(int)}.
342 * The length (in {@code char}) of the returned sequence is {@code length() - start},
343 * so if {@code start == end} then an empty sequence is returned.</p>
344 *
345 * @param cs the specified subsequence, null returns null
346 * @param start the start index, inclusive, valid
347 * @return a new subsequence, may be null
348 * @throws IndexOutOfBoundsException if {@code start} is negative or if
349 * {@code start} is greater than {@code length()}
350 */
351 public static CharSequence subSequence(final CharSequence cs, final int start) {
352 return cs == null ? null : cs.subSequence(start, cs.length());
353 }
354
355 /**
356 * Converts the given CharSequence to a char[].
357 *
358 * @param source the {@code CharSequence} to be processed.
359 * @return the resulting char array, never null.
360 * @since 3.11
361 */
362 public static char[] toCharArray(final CharSequence source) {
363 final int len = StringUtils.length(source);
364 if (len == 0) {
365 return ArrayUtils.EMPTY_CHAR_ARRAY;
366 }
367 if (source instanceof String) {
368 return ((String) source).toCharArray();
369 }
370 final char[] array = new char[len];
371 for (int i = 0; i < len; i++) {
372 array[i] = source.charAt(i);
373 }
374 return array;
375 }
376
377 /**
378 * <p>{@code CharSequenceUtils} instances should NOT be constructed in
379 * standard programming. </p>
380 *
381 * <p>This constructor is public to permit tools that require a JavaBean
382 * instance to operate.</p>
383 */
384 public CharSequenceUtils() {
385 }
378386 }
8989 /** The set of CharRange objects. */
9090 private final Set<CharRange> set = Collections.synchronizedSet(new HashSet<>());
9191
92 //-----------------------------------------------------------------------
9392 /**
9493 * <p>Factory method to create a new CharSet using a special syntax.</p>
9594 *
164163 return new CharSet(setStrs);
165164 }
166165
167 //-----------------------------------------------------------------------
168166 /**
169167 * <p>Constructs a new CharSet using the set syntax.
170168 * Each string is merged in with the set.</p>
173171 * @throws NullPointerException if set is {@code null}
174172 */
175173 protected CharSet(final String... set) {
176 super();
177174 for (final String s : set) {
178175 add(s);
179176 }
180177 }
181178
182 //-----------------------------------------------------------------------
183179 /**
184180 * <p>Add a set definition string to the {@code CharSet}.</p>
185181 *
214210 }
215211 }
216212
217 //-----------------------------------------------------------------------
218213 /**
219214 * <p>Gets the internal set as an array of CharRange objects.</p>
220215 *
224219 // NOTE: This is no longer public as CharRange is no longer a public class.
225220 // It may be replaced when CharSet moves to Range.
226221 /*public*/ CharRange[] getCharRanges() {
227 return set.toArray(new CharRange[0]);
228 }
229
230 //-----------------------------------------------------------------------
222 return set.toArray(CharRange.EMPTY_ARRAY);
223 }
224
231225 /**
232226 * <p>Does the {@code CharSet} contain the specified
233227 * character {@code ch}.</p>
247241 }
248242
249243 // Basics
250 //-----------------------------------------------------------------------
251244 /**
252245 * <p>Compares two {@code CharSet} objects, returning true if they represent
253246 * exactly the same set of characters defined in the same way.</p>
243243 * to operate.</p>
244244 */
245245 public CharSetUtils() {
246 super();
247246 }
248247 }
5757 public static final char NUL = '\0';
5858
5959 static {
60 for (char c = 0; c < CHAR_STRING_ARRAY.length; c++) {
61 CHAR_STRING_ARRAY[c] = String.valueOf(c);
62 }
60 ArrayUtils.setAll(CHAR_STRING_ARRAY, i -> String.valueOf((char) i));
6361 }
6462
6563 /**
7068 * to operate.</p>
7169 */
7270 public CharUtils() {
73 super();
74 }
75
76 //-----------------------------------------------------------------------
71 }
72
7773 /**
7874 * <p>Converts the character to a Character.</p>
7975 *
118114 return Character.valueOf(str.charAt(0));
119115 }
120116
121 //-----------------------------------------------------------------------
122117 /**
123118 * <p>Converts the Character to a char throwing an exception for {@code null}.</p>
124119 *
133128 * @throws NullPointerException if the Character is null
134129 */
135130 public static char toChar(final Character ch) {
136 Validate.notNull(ch, "The Character must not be null");
131 Validate.notNull(ch, "ch");
137132 return ch.charValue();
138133 }
139134
157152 return ch.charValue();
158153 }
159154
160 //-----------------------------------------------------------------------
161155 /**
162156 * <p>Converts the String to a char using the first character, throwing
163157 * an exception on empty Strings.</p>
201195 return str.charAt(0);
202196 }
203197
204 //-----------------------------------------------------------------------
205198 /**
206199 * <p>Converts the character to the Integer it represents, throwing an
207200 * exception if the character is not numeric.</p>
264257 * @throws IllegalArgumentException if the Character is not ASCII numeric
265258 */
266259 public static int toIntValue(final Character ch) {
267 Validate.notNull(ch, "The character must not be null");
260 Validate.notNull(ch, "ch");
268261 return toIntValue(ch.charValue());
269262 }
270263
291284 return toIntValue(ch.charValue(), defaultValue);
292285 }
293286
294 //-----------------------------------------------------------------------
295287 /**
296288 * <p>Converts the character to a String that contains the one character.</p>
297289 *
307299 * @return a String containing the one specified character
308300 */
309301 public static String toString(final char ch) {
310 if (ch < 128) {
302 if (ch < CHAR_STRING_ARRAY.length) {
311303 return CHAR_STRING_ARRAY[ch];
312304 }
313305 return new String(new char[] {ch});
3434 * instance to operate.</p>
3535 */
3636 public ClassPathUtils() {
37 super();
3837 }
3938
4039 /**
5453 * @throws java.lang.NullPointerException if either {@code context} or {@code resourceName} is null.
5554 */
5655 public static String toFullyQualifiedName(final Class<?> context, final String resourceName) {
57 Validate.notNull(context, "Parameter '%s' must not be null!", "context" );
58 Validate.notNull(resourceName, "Parameter '%s' must not be null!", "resourceName");
56 Validate.notNull(context, "context" );
57 Validate.notNull(resourceName, "resourceName");
5958 return toFullyQualifiedName(context.getPackage(), resourceName);
6059 }
6160
7675 * @throws java.lang.NullPointerException if either {@code context} or {@code resourceName} is null.
7776 */
7877 public static String toFullyQualifiedName(final Package context, final String resourceName) {
79 Validate.notNull(context, "Parameter '%s' must not be null!", "context" );
80 Validate.notNull(resourceName, "Parameter '%s' must not be null!", "resourceName");
78 Validate.notNull(context, "context" );
79 Validate.notNull(resourceName, "resourceName");
8180 return context.getName() + "." + resourceName;
8281 }
8382
9897 * @throws java.lang.NullPointerException if either {@code context} or {@code resourceName} is null.
9998 */
10099 public static String toFullyQualifiedPath(final Class<?> context, final String resourceName) {
101 Validate.notNull(context, "Parameter '%s' must not be null!", "context" );
102 Validate.notNull(resourceName, "Parameter '%s' must not be null!", "resourceName");
100 Validate.notNull(context, "context" );
101 Validate.notNull(resourceName, "resourceName");
103102 return toFullyQualifiedPath(context.getPackage(), resourceName);
104103 }
105104
121120 * @throws java.lang.NullPointerException if either {@code context} or {@code resourceName} is null.
122121 */
123122 public static String toFullyQualifiedPath(final Package context, final String resourceName) {
124 Validate.notNull(context, "Parameter '%s' must not be null!", "context" );
125 Validate.notNull(resourceName, "Parameter '%s' must not be null!", "resourceName");
123 Validate.notNull(context, "context" );
124 Validate.notNull(resourceName, "resourceName");
126125 return context.getName().replace('.', '/') + "/" + resourceName;
127126 }
128127
1919 import java.lang.reflect.Modifier;
2020 import java.util.ArrayList;
2121 import java.util.Collections;
22 import java.util.Comparator;
2223 import java.util.HashMap;
2324 import java.util.HashSet;
2425 import java.util.Iterator;
2526 import java.util.LinkedHashSet;
2627 import java.util.List;
2728 import java.util.Map;
29 import java.util.Objects;
2830 import java.util.Set;
31 import java.util.stream.Collectors;
2932
3033 import org.apache.commons.lang3.mutable.MutableObject;
3134
3235 /**
33 * <p>Operates on classes without using reflection.</p>
36 * <p>
37 * Operates on classes without using reflection.
38 * </p>
3439 *
35 * <p>This class handles invalid {@code null} inputs as best it can.
36 * Each method documents its behavior in more detail.</p>
40 * <p>
41 * This class handles invalid {@code null} inputs as best it can. Each method documents its behavior in more detail.
42 * </p>
3743 *
38 * <p>The notion of a {@code canonical name} includes the human
39 * readable name for the type, for example {@code int[]}. The
40 * non-canonical method variants work with the JVM names, such as
41 * {@code [I}. </p>
44 * <p>
45 * The notion of a {@code canonical name} includes the human readable name for the type, for example {@code int[]}. The
46 * non-canonical method variants work with the JVM names, such as {@code [I}.
47 * </p>
4248 *
4349 * @since 2.0
4450 */
4652
4753 /**
4854 * Inclusivity literals for {@link #hierarchy(Class, Interfaces)}.
55 *
4956 * @since 3.2
5057 */
5158 public enum Interfaces {
5764 EXCLUDE
5865 }
5966
67 private static final Comparator<Class<?>> COMPARATOR = (o1, o2) -> Objects.compare(getName(o1), getName(o2), String::compareTo);
68
6069 /**
6170 * The package separator character: {@code '&#x2e;' == {@value}}.
6271 */
8190 * Maps names of primitives to their corresponding primitive {@code Class}es.
8291 */
8392 private static final Map<String, Class<?>> namePrimitiveMap = new HashMap<>();
93
8494 static {
85 namePrimitiveMap.put("boolean", Boolean.TYPE);
86 namePrimitiveMap.put("byte", Byte.TYPE);
87 namePrimitiveMap.put("char", Character.TYPE);
88 namePrimitiveMap.put("short", Short.TYPE);
89 namePrimitiveMap.put("int", Integer.TYPE);
90 namePrimitiveMap.put("long", Long.TYPE);
91 namePrimitiveMap.put("double", Double.TYPE);
92 namePrimitiveMap.put("float", Float.TYPE);
93 namePrimitiveMap.put("void", Void.TYPE);
94 }
95
95 namePrimitiveMap.put("boolean", Boolean.TYPE);
96 namePrimitiveMap.put("byte", Byte.TYPE);
97 namePrimitiveMap.put("char", Character.TYPE);
98 namePrimitiveMap.put("short", Short.TYPE);
99 namePrimitiveMap.put("int", Integer.TYPE);
100 namePrimitiveMap.put("long", Long.TYPE);
101 namePrimitiveMap.put("double", Double.TYPE);
102 namePrimitiveMap.put("float", Float.TYPE);
103 namePrimitiveMap.put("void", Void.TYPE);
104 }
96105 /**
97106 * Maps primitive {@code Class}es to their corresponding wrapper {@code Class}.
98107 */
99108 private static final Map<Class<?>, Class<?>> primitiveWrapperMap = new HashMap<>();
109
100110 static {
101 primitiveWrapperMap.put(Boolean.TYPE, Boolean.class);
102 primitiveWrapperMap.put(Byte.TYPE, Byte.class);
103 primitiveWrapperMap.put(Character.TYPE, Character.class);
104 primitiveWrapperMap.put(Short.TYPE, Short.class);
105 primitiveWrapperMap.put(Integer.TYPE, Integer.class);
106 primitiveWrapperMap.put(Long.TYPE, Long.class);
107 primitiveWrapperMap.put(Double.TYPE, Double.class);
108 primitiveWrapperMap.put(Float.TYPE, Float.class);
109 primitiveWrapperMap.put(Void.TYPE, Void.TYPE);
110 }
111
111 primitiveWrapperMap.put(Boolean.TYPE, Boolean.class);
112 primitiveWrapperMap.put(Byte.TYPE, Byte.class);
113 primitiveWrapperMap.put(Character.TYPE, Character.class);
114 primitiveWrapperMap.put(Short.TYPE, Short.class);
115 primitiveWrapperMap.put(Integer.TYPE, Integer.class);
116 primitiveWrapperMap.put(Long.TYPE, Long.class);
117 primitiveWrapperMap.put(Double.TYPE, Double.class);
118 primitiveWrapperMap.put(Float.TYPE, Float.class);
119 primitiveWrapperMap.put(Void.TYPE, Void.TYPE);
120 }
112121 /**
113122 * Maps wrapper {@code Class}es to their corresponding primitive types.
114123 */
115124 private static final Map<Class<?>, Class<?>> wrapperPrimitiveMap = new HashMap<>();
125
116126 static {
117127 for (final Map.Entry<Class<?>, Class<?>> entry : primitiveWrapperMap.entrySet()) {
118128 final Class<?> primitiveClass = entry.getKey();
122132 }
123133 }
124134 }
125
126135 /**
127136 * Maps a primitive class name to its corresponding abbreviation used in array class names.
128137 */
132141 * Maps an abbreviation used in array class names to corresponding primitive class name.
133142 */
134143 private static final Map<String, String> reverseAbbreviationMap;
144
135145 // Feed abbreviation maps
136146 static {
137147 final Map<String, String> m = new HashMap<>();
152162 }
153163
154164 /**
155 * <p>ClassUtils instances should NOT be constructed in standard programming.
156 * Instead, the class should be used as
157 * {@code ClassUtils.getShortClassName(cls)}.</p>
158 *
159 * <p>This constructor is public to permit tools that require a JavaBean
160 * instance to operate.</p>
161 */
162 public ClassUtils() {
163 super();
164 }
165
166 // Short class name
167 // ----------------------------------------------------------------------
168 /**
169 * <p>Gets the class name of the {@code object} without the package name or names.</p>
170 *
171 * <p>The method looks up the class of the object and then converts the name of the class invoking
172 * {@link #getShortClassName(Class)} (see relevant notes there).</p>
173 *
174 * @param object the class to get the short name for, may be {@code null}
175 * @param valueIfNull the value to return if the object is {@code null}
176 * @return the class name of the object without the package name, or {@code valueIfNull}
177 * if the argument {@code object} is {@code null}
178 */
179 public static String getShortClassName(final Object object, final String valueIfNull) {
180 if (object == null) {
181 return valueIfNull;
182 }
183 return getShortClassName(object.getClass());
184 }
185
186 /**
187 * <p>Gets the class name minus the package name from a {@code Class}.</p>
188 *
189 * <p>This method simply gets the name using {@code Class.getName()} and then calls
190 * {@link #getShortClassName(Class)}. See relevant notes there.</p>
191 *
192 * @param cls the class to get the short name for.
193 * @return the class name without the package name or an empty string. If the class
194 * is an inner class then the returned value will contain the outer class
195 * or classes separated with {@code .} (dot) character.
196 */
197 public static String getShortClassName(final Class<?> cls) {
198 if (cls == null) {
199 return StringUtils.EMPTY;
200 }
201 return getShortClassName(cls.getName());
202 }
203
204 /**
205 * <p>Gets the class name minus the package name from a String.</p>
206 *
207 * <p>The string passed in is assumed to be a class name - it is not checked. The string has to be formatted the way
208 * as the JDK method {@code Class.getName()} returns it, and not the usual way as we write it, for example in import
209 * statements, or as it is formatted by {@code Class.getCanonicalName()}.</p>
210 *
211 * <p>The difference is is significant only in case of classes that are inner classes of some other
212 * classes. In this case the separator between the outer and inner class (possibly on multiple hierarchy level) has
213 * to be {@code $} (dollar sign) and not {@code .} (dot), as it is returned by {@code Class.getName()}</p>
214 *
215 * <p>Note that this method is called from the {@link #getShortClassName(Class)} method using the string
216 * returned by {@code Class.getName()}.</p>
217 *
218 * <p>Note that this method differs from {@link #getSimpleName(Class)} in that this will
219 * return, for example {@code "Map.Entry"} whilst the {@code java.lang.Class} variant will simply
220 * return {@code "Entry"}. In this example the argument {@code className} is the string
221 * {@code java.util.Map$Entry} (note the {@code $} sign.</p>
222 *
223 * @param className the className to get the short name for. It has to be formatted as returned by
224 * {@code Class.getName()} and not {@code Class.getCanonicalName()}
225 * @return the class name of the class without the package name or an empty string. If the class is
226 * an inner class then value contains the outer class or classes and the separator is replaced
227 * to be {@code .} (dot) character.
228 */
229 public static String getShortClassName(String className) {
230 if (StringUtils.isEmpty(className)) {
231 return StringUtils.EMPTY;
232 }
233
234 final StringBuilder arrayPrefix = new StringBuilder();
235
236 // Handle array encoding
237 if (className.startsWith("[")) {
238 while (className.charAt(0) == '[') {
239 className = className.substring(1);
240 arrayPrefix.append("[]");
241 }
242 // Strip Object type encoding
243 if (className.charAt(0) == 'L' && className.charAt(className.length() - 1) == ';') {
244 className = className.substring(1, className.length() - 1);
245 }
246
247 if (reverseAbbreviationMap.containsKey(className)) {
248 className = reverseAbbreviationMap.get(className);
249 }
250 }
251
252 final int lastDotIdx = className.lastIndexOf(PACKAGE_SEPARATOR_CHAR);
253 final int innerIdx = className.indexOf(
254 INNER_CLASS_SEPARATOR_CHAR, lastDotIdx == -1 ? 0 : lastDotIdx + 1);
255 String out = className.substring(lastDotIdx + 1);
256 if (innerIdx != -1) {
257 out = out.replace(INNER_CLASS_SEPARATOR_CHAR, PACKAGE_SEPARATOR_CHAR);
258 }
259 return out + arrayPrefix;
260 }
261
262 /**
263 * <p>Null-safe version of {@code cls.getSimpleName()}</p>
264 *
265 * @param cls the class for which to get the simple name; may be null
266 * @return the simple class name or the empty string in case the argument is {@code null}
267 * @since 3.0
268 * @see Class#getSimpleName()
269 */
270 public static String getSimpleName(final Class<?> cls) {
271 return getSimpleName(cls, StringUtils.EMPTY);
272 }
273
274 /**
275 * <p>Null-safe version of {@code cls.getSimpleName()}</p>
276 *
277 * @param cls the class for which to get the simple name; may be null
278 * @param valueIfNull the value to return if null
279 * @return the simple class name or {@code valueIfNull} if the
280 * argument {@code cls} is {@code null}
281 * @since 3.0
282 * @see Class#getSimpleName()
283 */
284 public static String getSimpleName(final Class<?> cls, final String valueIfNull) {
285 return cls == null ? valueIfNull : cls.getSimpleName();
286 }
287
288 /**
289 * <p>Null-safe version of {@code object.getClass().getSimpleName()}</p>
290 *
291 * <p>It is to note that this method is overloaded and in case the argument {@code object} is a
292 * {@code Class} object then the {@link #getSimpleName(Class)} will be invoked. If this is
293 * a significant possibility then the caller should check this case and call {@code
294 * getSimpleName(Class.class)} or just simply use the string literal {@code "Class"}, which
295 * is the result of the method in that case.</p>
296 *
297 * @param object the object for which to get the simple class name; may be null
298 * @return the simple class name or the empty string in case the argument is {@code null}
299 * @since 3.7
300 * @see Class#getSimpleName()
301 */
302 public static String getSimpleName(final Object object) {
303 return getSimpleName(object, StringUtils.EMPTY);
304 }
305
306 /**
307 * <p>Null-safe version of {@code object.getClass().getSimpleName()}</p>
308 *
309 * @param object the object for which to get the simple class name; may be null
310 * @param valueIfNull the value to return if {@code object} is {@code null}
311 * @return the simple class name or {@code valueIfNull} if the
312 * argument {@code object} is {@code null}
313 * @since 3.0
314 * @see Class#getSimpleName()
315 */
316 public static String getSimpleName(final Object object, final String valueIfNull) {
317 return object == null ? valueIfNull : object.getClass().getSimpleName();
318 }
319
320 /**
321 * <p>Null-safe version of {@code cls.getName()}</p>
322 *
323 * @param cls the class for which to get the class name; may be null
324 * @return the class name or the empty string in case the argument is {@code null}
325 * @since 3.7
326 * @see Class#getSimpleName()
327 */
328 public static String getName(final Class<?> cls) {
329 return getName(cls, StringUtils.EMPTY);
330 }
331
332 /**
333 * <p>Null-safe version of {@code cls.getName()}</p>
334 *
335 * @param cls the class for which to get the class name; may be null
336 * @param valueIfNull the return value if the argument {@code cls} is {@code null}
337 * @return the class name or {@code valueIfNull}
338 * @since 3.7
339 * @see Class#getName()
340 */
341 public static String getName(final Class<?> cls, final String valueIfNull) {
342 return cls == null ? valueIfNull : cls.getName();
343 }
344
345 /**
346 * <p>Null-safe version of {@code object.getClass().getName()}</p>
347 *
348 * @param object the object for which to get the class name; may be null
349 * @return the class name or the empty String
350 * @since 3.7
351 * @see Class#getSimpleName()
352 */
353 public static String getName(final Object object) {
354 return getName(object, StringUtils.EMPTY);
355 }
356
357 /**
358 * <p>Null-safe version of {@code object.getClass().getSimpleName()}</p>
359 *
360 * @param object the object for which to get the class name; may be null
361 * @param valueIfNull the value to return if {@code object} is {@code null}
362 * @return the class name or {@code valueIfNull}
363 * @since 3.0
364 * @see Class#getName()
365 */
366 public static String getName(final Object object, final String valueIfNull) {
367 return object == null ? valueIfNull : object.getClass().getName();
368 }
369
370 // Package name
371 // ----------------------------------------------------------------------
372 /**
373 * <p>Gets the package name of an {@code Object}.</p>
374 *
375 * @param object the class to get the package name for, may be null
376 * @param valueIfNull the value to return if null
377 * @return the package name of the object, or the null value
378 */
379 public static String getPackageName(final Object object, final String valueIfNull) {
380 if (object == null) {
381 return valueIfNull;
382 }
383 return getPackageName(object.getClass());
384 }
385
386 /**
387 * <p>Gets the package name of a {@code Class}.</p>
388 *
389 * @param cls the class to get the package name for, may be {@code null}.
390 * @return the package name or an empty string
391 */
392 public static String getPackageName(final Class<?> cls) {
393 if (cls == null) {
394 return StringUtils.EMPTY;
395 }
396 return getPackageName(cls.getName());
397 }
398
399 /**
400 * <p>Gets the package name from a {@code String}.</p>
401 *
402 * <p>The string passed in is assumed to be a class name - it is not checked.</p>
403 * <p>If the class is unpackaged, return an empty string.</p>
404 *
405 * @param className the className to get the package name for, may be {@code null}
406 * @return the package name or an empty string
407 */
408 public static String getPackageName(String className) {
409 if (StringUtils.isEmpty(className)) {
410 return StringUtils.EMPTY;
411 }
412
413 // Strip array encoding
414 while (className.charAt(0) == '[') {
415 className = className.substring(1);
416 }
417 // Strip Object type encoding
418 if (className.charAt(0) == 'L' && className.charAt(className.length() - 1) == ';') {
419 className = className.substring(1);
420 }
421
422 final int i = className.lastIndexOf(PACKAGE_SEPARATOR_CHAR);
423 if (i == -1) {
424 return StringUtils.EMPTY;
425 }
426 return className.substring(0, i);
427 }
428
429 // Abbreviated name
430 // ----------------------------------------------------------------------
431 /**
432 * <p>Gets the abbreviated name of a {@code Class}.</p>
433 *
434 * @param cls the class to get the abbreviated name for, may be {@code null}
435 * @param lengthHint the desired length of the abbreviated name
165 * Gets the class comparator, comparing by class name.
166 *
167 * @return the class comparator.
168 * @since 3.13.0
169 */
170 public static Comparator<Class<?>> comparator() {
171 return COMPARATOR;
172 }
173
174 /**
175 * <p>
176 * Given a {@code List} of {@code Class} objects, this method converts them into class names.
177 * </p>
178 *
179 * <p>
180 * A new {@code List} is returned. {@code null} objects will be copied into the returned list as {@code null}.
181 * </p>
182 *
183 * @param classes the classes to change
184 * @return a {@code List} of class names corresponding to the Class objects, {@code null} if null input
185 * @throws ClassCastException if {@code classes} contains a non-{@code Class} entry
186 */
187 public static List<String> convertClassesToClassNames(final List<Class<?>> classes) {
188 return classes == null ? null : classes.stream().map(e -> getName(e, null)).collect(Collectors.toList());
189 }
190
191 /**
192 * <p>
193 * Given a {@code List} of class names, this method converts them into classes.
194 * </p>
195 *
196 * <p>
197 * A new {@code List} is returned. If the class name cannot be found, {@code null} is stored in the {@code List}. If the
198 * class name in the {@code List} is {@code null}, {@code null} is stored in the output {@code List}.
199 * </p>
200 *
201 * @param classNames the classNames to change
202 * @return a {@code List} of Class objects corresponding to the class names, {@code null} if null input
203 * @throws ClassCastException if classNames contains a non String entry
204 */
205 public static List<Class<?>> convertClassNamesToClasses(final List<String> classNames) {
206 if (classNames == null) {
207 return null;
208 }
209 final List<Class<?>> classes = new ArrayList<>(classNames.size());
210 for (final String className : classNames) {
211 try {
212 classes.add(Class.forName(className));
213 } catch (final Exception ex) {
214 classes.add(null);
215 }
216 }
217 return classes;
218 }
219
220 /**
221 * <p>
222 * Gets the abbreviated name of a {@code Class}.
223 * </p>
224 *
225 * @param cls the class to get the abbreviated name for, may be {@code null}
226 * @param lengthHint the desired length of the abbreviated name
436227 * @return the abbreviated name or an empty string
437228 * @throws IllegalArgumentException if len &lt;= 0
438229 * @see #getAbbreviatedName(String, int)
439230 * @since 3.4
440231 */
441232 public static String getAbbreviatedName(final Class<?> cls, final int lengthHint) {
442 if (cls == null) {
443 return StringUtils.EMPTY;
444 }
445 return getAbbreviatedName(cls.getName(), lengthHint);
446 }
447
448 /**
449 * <p>Gets the abbreviated class name from a {@code String}.</p>
450 *
451 * <p>The string passed in is assumed to be a class name - it is not checked.</p>
452 *
453 * <p>The abbreviation algorithm will shorten the class name, usually without
454 * significant loss of meaning.</p>
455 *
456 * <p>The abbreviated class name will always include the complete package hierarchy.
457 * If enough space is available, rightmost sub-packages will be displayed in full
458 * length. The abbreviated package names will be shortened to a single character.</p>
459 * <p>Only package names are shortened, the class simple name remains untouched. (See examples.)</p>
460 * <p>The result will be longer than the desired length only if all the package names
461 * shortened to a single character plus the class simple name with the separating dots
462 * together are longer than the desired length. In other words, when the class name
463 * cannot be shortened to the desired length.</p>
464 * <p>If the class name can be shortened then
465 * the final length will be at most {@code lengthHint} characters.</p>
466 * <p>If the {@code lengthHint} is zero or negative then the method
467 * throws exception. If you want to achieve the shortest possible version then
468 * use {@code 1} as a {@code lengthHint}.</p>
233 if (cls == null) {
234 return StringUtils.EMPTY;
235 }
236 return getAbbreviatedName(cls.getName(), lengthHint);
237 }
238
239 /**
240 * <p>
241 * Gets the abbreviated class name from a {@code String}.
242 * </p>
243 *
244 * <p>
245 * The string passed in is assumed to be a class name - it is not checked.
246 * </p>
247 *
248 * <p>
249 * The abbreviation algorithm will shorten the class name, usually without significant loss of meaning.
250 * </p>
251 *
252 * <p>
253 * The abbreviated class name will always include the complete package hierarchy. If enough space is available,
254 * rightmost sub-packages will be displayed in full length. The abbreviated package names will be shortened to a single
255 * character.
256 * </p>
257 * <p>
258 * Only package names are shortened, the class simple name remains untouched. (See examples.)
259 * </p>
260 * <p>
261 * The result will be longer than the desired length only if all the package names shortened to a single character plus
262 * the class simple name with the separating dots together are longer than the desired length. In other words, when the
263 * class name cannot be shortened to the desired length.
264 * </p>
265 * <p>
266 * If the class name can be shortened then the final length will be at most {@code lengthHint} characters.
267 * </p>
268 * <p>
269 * If the {@code lengthHint} is zero or negative then the method throws exception. If you want to achieve the shortest
270 * possible version then use {@code 1} as a {@code lengthHint}.
271 * </p>
469272 *
470273 * <table>
471274 * <caption>Examples</caption>
472 * <tr><td>className</td><td>len</td><td>return</td></tr>
473 * <tr><td> null</td><td> 1</td><td>""</td></tr>
474 * <tr><td>"java.lang.String"</td><td> 5</td><td>"j.l.String"</td></tr>
475 * <tr><td>"java.lang.String"</td><td>15</td><td>"j.lang.String"</td></tr>
476 * <tr><td>"java.lang.String"</td><td>30</td><td>"java.lang.String"</td></tr>
477 * <tr><td>"org.apache.commons.lang3.ClassUtils"</td><td>18</td><td>"o.a.c.l.ClassUtils"</td></tr>
275 * <tr>
276 * <td>className</td>
277 * <td>len</td>
278 * <td>return</td>
279 * </tr>
280 * <tr>
281 * <td>null</td>
282 * <td>1</td>
283 * <td>""</td>
284 * </tr>
285 * <tr>
286 * <td>"java.lang.String"</td>
287 * <td>5</td>
288 * <td>"j.l.String"</td>
289 * </tr>
290 * <tr>
291 * <td>"java.lang.String"</td>
292 * <td>15</td>
293 * <td>"j.lang.String"</td>
294 * </tr>
295 * <tr>
296 * <td>"java.lang.String"</td>
297 * <td>30</td>
298 * <td>"java.lang.String"</td>
299 * </tr>
300 * <tr>
301 * <td>"org.apache.commons.lang3.ClassUtils"</td>
302 * <td>18</td>
303 * <td>"o.a.c.l.ClassUtils"</td>
304 * </tr>
478305 * </table>
479306 *
480307 * @param className the className to get the abbreviated name for, may be {@code null}
481 * @param lengthHint the desired length of the abbreviated name
482 * @return the abbreviated name or an empty string if the specified
483 * class name is {@code null} or empty string. The abbreviated name may be
484 * longer than the desired length if it cannot be abbreviated to the desired length.
308 * @param lengthHint the desired length of the abbreviated name
309 * @return the abbreviated name or an empty string if the specified class name is {@code null} or empty string. The
310 * abbreviated name may be longer than the desired length if it cannot be abbreviated to the desired length.
485311 * @throws IllegalArgumentException if {@code len <= 0}
486312 * @since 3.4
487313 */
506332 }
507333
508334 ++target;
509 if (useFull(runAheadTarget, source, abbreviated.length, lengthHint)
510 || target > runAheadTarget) {
335 if (useFull(runAheadTarget, source, abbreviated.length, lengthHint) || target > runAheadTarget) {
511336 target = runAheadTarget;
512337 }
513338
520345 }
521346
522347 /**
523 * <p>Decides if the part that was just copied to its destination
524 * location in the work array can be kept as it was copied or must be
525 * abbreviated. It must be kept when the part is the last one, which
526 * is the simple name of the class. In this case the {@code source}
527 * index, from where the characters are copied points one position
528 * after the last character, a.k.a. {@code source ==
529 * originalLength}</p>
530 *
531 * <p>If the part is not the last one then it can be kept
532 * unabridged if the number of the characters copied so far plus
533 * the character that are to be copied is less than or equal to the
534 * desired length.</p>
535 *
536 * @param runAheadTarget the target index (where the characters were
537 * copied to) pointing after the last character
538 * copied when the current part was copied
539 * @param source the source index (where the characters were
540 * copied from) pointing after the last
541 * character copied when the current part was
542 * copied
543 * @param originalLength the original length of the class full name,
544 * which is abbreviated
545 * @param desiredLength the desired length of the abbreviated class
546 * name
547 * @return {@code true} if it can be kept in its original length
548 * {@code false} if the current part has to be abbreviated and
549 */
550 private static boolean useFull(final int runAheadTarget,
551 final int source,
552 final int originalLength,
553 final int desiredLength) {
554 return source >= originalLength ||
555 runAheadTarget + originalLength - source <= desiredLength;
556 }
557
558 // Superclasses/Superinterfaces
559 // ----------------------------------------------------------------------
560 /**
561 * <p>Gets a {@code List} of superclasses for the given class.</p>
562 *
563 * @param cls the class to look up, may be {@code null}
564 * @return the {@code List} of superclasses in order going up from this one
565 * {@code null} if null input
348 * <p>
349 * Gets a {@code List} of all interfaces implemented by the given class and its superclasses.
350 * </p>
351 *
352 * <p>
353 * The order is determined by looking through each interface in turn as declared in the source file and following its
354 * hierarchy up. Then each superclass is considered in the same way. Later duplicates are ignored, so the order is
355 * maintained.
356 * </p>
357 *
358 * @param cls the class to look up, may be {@code null}
359 * @return the {@code List} of interfaces in order, {@code null} if null input
360 */
361 public static List<Class<?>> getAllInterfaces(final Class<?> cls) {
362 if (cls == null) {
363 return null;
364 }
365
366 final LinkedHashSet<Class<?>> interfacesFound = new LinkedHashSet<>();
367 getAllInterfaces(cls, interfacesFound);
368
369 return new ArrayList<>(interfacesFound);
370 }
371
372 /**
373 * Gets the interfaces for the specified class.
374 *
375 * @param cls the class to look up, may be {@code null}
376 * @param interfacesFound the {@code Set} of interfaces for the class
377 */
378 private static void getAllInterfaces(Class<?> cls, final HashSet<Class<?>> interfacesFound) {
379 while (cls != null) {
380 final Class<?>[] interfaces = cls.getInterfaces();
381
382 for (final Class<?> i : interfaces) {
383 if (interfacesFound.add(i)) {
384 getAllInterfaces(i, interfacesFound);
385 }
386 }
387
388 cls = cls.getSuperclass();
389 }
390 }
391
392 /**
393 * <p>
394 * Gets a {@code List} of superclasses for the given class.
395 * </p>
396 *
397 * @param cls the class to look up, may be {@code null}
398 * @return the {@code List} of superclasses in order going up from this one {@code null} if null input
566399 */
567400 public static List<Class<?>> getAllSuperclasses(final Class<?> cls) {
568401 if (cls == null) {
578411 }
579412
580413 /**
581 * <p>Gets a {@code List} of all interfaces implemented by the given
582 * class and its superclasses.</p>
583 *
584 * <p>The order is determined by looking through each interface in turn as
585 * declared in the source file and following its hierarchy up. Then each
586 * superclass is considered in the same way. Later duplicates are ignored,
587 * so the order is maintained.</p>
588 *
589 * @param cls the class to look up, may be {@code null}
590 * @return the {@code List} of interfaces in order,
591 * {@code null} if null input
592 */
593 public static List<Class<?>> getAllInterfaces(final Class<?> cls) {
594 if (cls == null) {
595 return null;
596 }
597
598 final LinkedHashSet<Class<?>> interfacesFound = new LinkedHashSet<>();
599 getAllInterfaces(cls, interfacesFound);
600
601 return new ArrayList<>(interfacesFound);
602 }
603
604 /**
605 * Gets the interfaces for the specified class.
606 *
607 * @param cls the class to look up, may be {@code null}
608 * @param interfacesFound the {@code Set} of interfaces for the class
609 */
610 private static void getAllInterfaces(Class<?> cls, final HashSet<Class<?>> interfacesFound) {
611 while (cls != null) {
612 final Class<?>[] interfaces = cls.getInterfaces();
613
614 for (final Class<?> i : interfaces) {
615 if (interfacesFound.add(i)) {
616 getAllInterfaces(i, interfacesFound);
617 }
618 }
619
620 cls = cls.getSuperclass();
621 }
622 }
623
624 // Convert list
625 // ----------------------------------------------------------------------
626 /**
627 * <p>Given a {@code List} of class names, this method converts them into classes.</p>
628 *
629 * <p>A new {@code List} is returned. If the class name cannot be found, {@code null}
630 * is stored in the {@code List}. If the class name in the {@code List} is
631 * {@code null}, {@code null} is stored in the output {@code List}.</p>
632 *
633 * @param classNames the classNames to change
634 * @return a {@code List} of Class objects corresponding to the class names,
635 * {@code null} if null input
636 * @throws ClassCastException if classNames contains a non String entry
637 */
638 public static List<Class<?>> convertClassNamesToClasses(final List<String> classNames) {
639 if (classNames == null) {
640 return null;
641 }
642 final List<Class<?>> classes = new ArrayList<>(classNames.size());
643 for (final String className : classNames) {
644 try {
645 classes.add(Class.forName(className));
646 } catch (final Exception ex) {
647 classes.add(null);
648 }
649 }
650 return classes;
651 }
652
653 /**
654 * <p>Given a {@code List} of {@code Class} objects, this method converts
655 * them into class names.</p>
656 *
657 * <p>A new {@code List} is returned. {@code null} objects will be copied into
658 * the returned list as {@code null}.</p>
659 *
660 * @param classes the classes to change
661 * @return a {@code List} of class names corresponding to the Class objects,
662 * {@code null} if null input
663 * @throws ClassCastException if {@code classes} contains a non-{@code Class} entry
664 */
665 public static List<String> convertClassesToClassNames(final List<Class<?>> classes) {
666 if (classes == null) {
667 return null;
668 }
669 final List<String> classNames = new ArrayList<>(classes.size());
670 for (final Class<?> cls : classes) {
671 if (cls == null) {
672 classNames.add(null);
673 } else {
674 classNames.add(cls.getName());
675 }
676 }
677 return classNames;
678 }
679
680 // Is assignable
681 // ----------------------------------------------------------------------
682 /**
683 * <p>Checks if an array of Classes can be assigned to another array of Classes.</p>
684 *
685 * <p>This method calls {@link #isAssignable(Class, Class) isAssignable} for each
686 * Class pair in the input arrays. It can be used to check if a set of arguments
687 * (the first parameter) are suitably compatible with a set of method parameter types
688 * (the second parameter).</p>
689 *
690 * <p>Unlike the {@link Class#isAssignableFrom(java.lang.Class)} method, this
691 * method takes into account widenings of primitive classes and
692 * {@code null}s.</p>
693 *
694 * <p>Primitive widenings allow an int to be assigned to a {@code long},
695 * {@code float} or {@code double}. This method returns the correct
696 * result for these cases.</p>
697 *
698 * <p>{@code Null} may be assigned to any reference type. This method will
699 * return {@code true} if {@code null} is passed in and the toClass is
700 * non-primitive.</p>
701 *
702 * <p>Specifically, this method tests whether the type represented by the
703 * specified {@code Class} parameter can be converted to the type
704 * represented by this {@code Class} object via an identity conversion
705 * widening primitive or widening reference conversion. See
706 * <em><a href="http://docs.oracle.com/javase/specs/">The Java Language Specification</a></em>,
707 * sections 5.1.1, 5.1.2 and 5.1.4 for details.</p>
708 *
709 * <p><strong>Since Lang 3.0,</strong> this method will default behavior for
710 * calculating assignability between primitive and wrapper types <em>corresponding
711 * to the running Java version</em>; i.e. autoboxing will be the default
712 * behavior in VMs running Java versions &gt; 1.5.</p>
713 *
714 * @param classArray the array of Classes to check, may be {@code null}
715 * @param toClassArray the array of Classes to try to assign into, may be {@code null}
716 * @return {@code true} if assignment possible
717 */
718 public static boolean isAssignable(final Class<?>[] classArray, final Class<?>... toClassArray) {
719 return isAssignable(classArray, toClassArray, true);
720 }
721
722 /**
723 * <p>Checks if an array of Classes can be assigned to another array of Classes.</p>
724 *
725 * <p>This method calls {@link #isAssignable(Class, Class) isAssignable} for each
726 * Class pair in the input arrays. It can be used to check if a set of arguments
727 * (the first parameter) are suitably compatible with a set of method parameter types
728 * (the second parameter).</p>
729 *
730 * <p>Unlike the {@link Class#isAssignableFrom(java.lang.Class)} method, this
731 * method takes into account widenings of primitive classes and
732 * {@code null}s.</p>
733 *
734 * <p>Primitive widenings allow an int to be assigned to a {@code long},
735 * {@code float} or {@code double}. This method returns the correct
736 * result for these cases.</p>
737 *
738 * <p>{@code Null} may be assigned to any reference type. This method will
739 * return {@code true} if {@code null} is passed in and the toClass is
740 * non-primitive.</p>
741 *
742 * <p>Specifically, this method tests whether the type represented by the
743 * specified {@code Class} parameter can be converted to the type
744 * represented by this {@code Class} object via an identity conversion
745 * widening primitive or widening reference conversion. See
746 * <em><a href="http://docs.oracle.com/javase/specs/">The Java Language Specification</a></em>,
747 * sections 5.1.1, 5.1.2 and 5.1.4 for details.</p>
748 *
749 * @param classArray the array of Classes to check, may be {@code null}
750 * @param toClassArray the array of Classes to try to assign into, may be {@code null}
751 * @param autoboxing whether to use implicit autoboxing/unboxing between primitives and wrappers
752 * @return {@code true} if assignment possible
753 */
754 public static boolean isAssignable(Class<?>[] classArray, Class<?>[] toClassArray, final boolean autoboxing) {
755 if (!ArrayUtils.isSameLength(classArray, toClassArray)) {
756 return false;
757 }
758 if (classArray == null) {
759 classArray = ArrayUtils.EMPTY_CLASS_ARRAY;
760 }
761 if (toClassArray == null) {
762 toClassArray = ArrayUtils.EMPTY_CLASS_ARRAY;
763 }
764 for (int i = 0; i < classArray.length; i++) {
765 if (!isAssignable(classArray[i], toClassArray[i], autoboxing)) {
766 return false;
767 }
768 }
769 return true;
770 }
771
772 /**
773 * Returns whether the given {@code type} is a primitive or primitive wrapper ({@link Boolean}, {@link Byte}, {@link Character},
774 * {@link Short}, {@link Integer}, {@link Long}, {@link Double}, {@link Float}).
775 *
776 * @param type
777 * The class to query or null.
778 * @return true if the given {@code type} is a primitive or primitive wrapper ({@link Boolean}, {@link Byte}, {@link Character},
779 * {@link Short}, {@link Integer}, {@link Long}, {@link Double}, {@link Float}).
780 * @since 3.1
781 */
782 public static boolean isPrimitiveOrWrapper(final Class<?> type) {
783 if (type == null) {
784 return false;
785 }
786 return type.isPrimitive() || isPrimitiveWrapper(type);
787 }
788
789 /**
790 * Returns whether the given {@code type} is a primitive wrapper ({@link Boolean}, {@link Byte}, {@link Character}, {@link Short},
791 * {@link Integer}, {@link Long}, {@link Double}, {@link Float}).
792 *
793 * @param type
794 * The class to query or null.
795 * @return true if the given {@code type} is a primitive wrapper ({@link Boolean}, {@link Byte}, {@link Character}, {@link Short},
796 * {@link Integer}, {@link Long}, {@link Double}, {@link Float}).
797 * @since 3.1
798 */
799 public static boolean isPrimitiveWrapper(final Class<?> type) {
800 return wrapperPrimitiveMap.containsKey(type);
801 }
802
803 /**
804 * <p>Checks if one {@code Class} can be assigned to a variable of
805 * another {@code Class}.</p>
806 *
807 * <p>Unlike the {@link Class#isAssignableFrom(java.lang.Class)} method,
808 * this method takes into account widenings of primitive classes and
809 * {@code null}s.</p>
810 *
811 * <p>Primitive widenings allow an int to be assigned to a long, float or
812 * double. This method returns the correct result for these cases.</p>
813 *
814 * <p>{@code Null} may be assigned to any reference type. This method
815 * will return {@code true} if {@code null} is passed in and the
816 * toClass is non-primitive.</p>
817 *
818 * <p>Specifically, this method tests whether the type represented by the
819 * specified {@code Class} parameter can be converted to the type
820 * represented by this {@code Class} object via an identity conversion
821 * widening primitive or widening reference conversion. See
822 * <em><a href="http://docs.oracle.com/javase/specs/">The Java Language Specification</a></em>,
823 * sections 5.1.1, 5.1.2 and 5.1.4 for details.</p>
824 *
825 * <p><strong>Since Lang 3.0,</strong> this method will default behavior for
826 * calculating assignability between primitive and wrapper types <em>corresponding
827 * to the running Java version</em>; i.e. autoboxing will be the default
828 * behavior in VMs running Java versions &gt; 1.5.</p>
829 *
830 * @param cls the Class to check, may be null
831 * @param toClass the Class to try to assign into, returns false if null
832 * @return {@code true} if assignment possible
833 */
834 public static boolean isAssignable(final Class<?> cls, final Class<?> toClass) {
835 return isAssignable(cls, toClass, true);
836 }
837
838 /**
839 * <p>Checks if one {@code Class} can be assigned to a variable of
840 * another {@code Class}.</p>
841 *
842 * <p>Unlike the {@link Class#isAssignableFrom(java.lang.Class)} method,
843 * this method takes into account widenings of primitive classes and
844 * {@code null}s.</p>
845 *
846 * <p>Primitive widenings allow an int to be assigned to a long, float or
847 * double. This method returns the correct result for these cases.</p>
848 *
849 * <p>{@code Null} may be assigned to any reference type. This method
850 * will return {@code true} if {@code null} is passed in and the
851 * toClass is non-primitive.</p>
852 *
853 * <p>Specifically, this method tests whether the type represented by the
854 * specified {@code Class} parameter can be converted to the type
855 * represented by this {@code Class} object via an identity conversion
856 * widening primitive or widening reference conversion. See
857 * <em><a href="http://docs.oracle.com/javase/specs/">The Java Language Specification</a></em>,
858 * sections 5.1.1, 5.1.2 and 5.1.4 for details.</p>
859 *
860 * @param cls the Class to check, may be null
861 * @param toClass the Class to try to assign into, returns false if null
862 * @param autoboxing whether to use implicit autoboxing/unboxing between primitives and wrappers
863 * @return {@code true} if assignment possible
864 */
865 public static boolean isAssignable(Class<?> cls, final Class<?> toClass, final boolean autoboxing) {
866 if (toClass == null) {
867 return false;
868 }
869 // have to check for null, as isAssignableFrom doesn't
870 if (cls == null) {
871 return !toClass.isPrimitive();
872 }
873 //autoboxing:
874 if (autoboxing) {
875 if (cls.isPrimitive() && !toClass.isPrimitive()) {
876 cls = primitiveToWrapper(cls);
877 if (cls == null) {
878 return false;
879 }
880 }
881 if (toClass.isPrimitive() && !cls.isPrimitive()) {
882 cls = wrapperToPrimitive(cls);
883 if (cls == null) {
884 return false;
885 }
886 }
887 }
888 if (cls.equals(toClass)) {
889 return true;
890 }
891 if (cls.isPrimitive()) {
892 if (!toClass.isPrimitive()) {
893 return false;
894 }
895 if (Integer.TYPE.equals(cls)) {
896 return Long.TYPE.equals(toClass)
897 || Float.TYPE.equals(toClass)
898 || Double.TYPE.equals(toClass);
899 }
900 if (Long.TYPE.equals(cls)) {
901 return Float.TYPE.equals(toClass)
902 || Double.TYPE.equals(toClass);
903 }
904 if (Boolean.TYPE.equals(cls)) {
905 return false;
906 }
907 if (Double.TYPE.equals(cls)) {
908 return false;
909 }
910 if (Float.TYPE.equals(cls)) {
911 return Double.TYPE.equals(toClass);
912 }
913 if (Character.TYPE.equals(cls)) {
914 return Integer.TYPE.equals(toClass)
915 || Long.TYPE.equals(toClass)
916 || Float.TYPE.equals(toClass)
917 || Double.TYPE.equals(toClass);
918 }
919 if (Short.TYPE.equals(cls)) {
920 return Integer.TYPE.equals(toClass)
921 || Long.TYPE.equals(toClass)
922 || Float.TYPE.equals(toClass)
923 || Double.TYPE.equals(toClass);
924 }
925 if (Byte.TYPE.equals(cls)) {
926 return Short.TYPE.equals(toClass)
927 || Integer.TYPE.equals(toClass)
928 || Long.TYPE.equals(toClass)
929 || Float.TYPE.equals(toClass)
930 || Double.TYPE.equals(toClass);
931 }
932 // should never get here
933 return false;
934 }
935 return toClass.isAssignableFrom(cls);
936 }
937
938 /**
939 * <p>Converts the specified primitive Class object to its corresponding
940 * wrapper Class object.</p>
941 *
942 * <p>NOTE: From v2.2, this method handles {@code Void.TYPE},
943 * returning {@code Void.TYPE}.</p>
944 *
945 * @param cls the class to convert, may be null
946 * @return the wrapper class for {@code cls} or {@code cls} if
947 * {@code cls} is not a primitive. {@code null} if null input.
948 * @since 2.1
949 */
950 public static Class<?> primitiveToWrapper(final Class<?> cls) {
951 Class<?> convertedClass = cls;
952 if (cls != null && cls.isPrimitive()) {
953 convertedClass = primitiveWrapperMap.get(cls);
954 }
955 return convertedClass;
956 }
957
958 /**
959 * <p>Converts the specified array of primitive Class objects to an array of
960 * its corresponding wrapper Class objects.</p>
961 *
962 * @param classes the class array to convert, may be null or empty
963 * @return an array which contains for each given class, the wrapper class or
964 * the original class if class is not a primitive. {@code null} if null input.
965 * Empty array if an empty array passed in.
966 * @since 2.1
967 */
968 public static Class<?>[] primitivesToWrappers(final Class<?>... classes) {
969 if (classes == null) {
970 return null;
971 }
972
973 if (classes.length == 0) {
974 return classes;
975 }
976
977 final Class<?>[] convertedClasses = new Class[classes.length];
978 for (int i = 0; i < classes.length; i++) {
979 convertedClasses[i] = primitiveToWrapper(classes[i]);
980 }
981 return convertedClasses;
982 }
983
984 /**
985 * <p>Converts the specified wrapper class to its corresponding primitive
986 * class.</p>
987 *
988 * <p>This method is the counter part of {@code primitiveToWrapper()}.
989 * If the passed in class is a wrapper class for a primitive type, this
990 * primitive type will be returned (e.g. {@code Integer.TYPE} for
991 * {@code Integer.class}). For other classes, or if the parameter is
992 * <b>null</b>, the return value is <b>null</b>.</p>
993 *
994 * @param cls the class to convert, may be <b>null</b>
995 * @return the corresponding primitive type if {@code cls} is a
996 * wrapper class, <b>null</b> otherwise
997 * @see #primitiveToWrapper(Class)
998 * @since 2.4
999 */
1000 public static Class<?> wrapperToPrimitive(final Class<?> cls) {
1001 return wrapperPrimitiveMap.get(cls);
1002 }
1003
1004 /**
1005 * <p>Converts the specified array of wrapper Class objects to an array of
1006 * its corresponding primitive Class objects.</p>
1007 *
1008 * <p>This method invokes {@code wrapperToPrimitive()} for each element
1009 * of the passed in array.</p>
1010 *
1011 * @param classes the class array to convert, may be null or empty
1012 * @return an array which contains for each given class, the primitive class or
1013 * <b>null</b> if the original class is not a wrapper class. {@code null} if null input.
1014 * Empty array if an empty array passed in.
1015 * @see #wrapperToPrimitive(Class)
1016 * @since 2.4
1017 */
1018 public static Class<?>[] wrappersToPrimitives(final Class<?>... classes) {
1019 if (classes == null) {
1020 return null;
1021 }
1022
1023 if (classes.length == 0) {
1024 return classes;
1025 }
1026
1027 final Class<?>[] convertedClasses = new Class[classes.length];
1028 for (int i = 0; i < classes.length; i++) {
1029 convertedClasses[i] = wrapperToPrimitive(classes[i]);
1030 }
1031 return convertedClasses;
1032 }
1033
1034 // Inner class
1035 // ----------------------------------------------------------------------
1036 /**
1037 * <p>Is the specified class an inner class or static nested class.</p>
1038 *
1039 * @param cls the class to check, may be null
1040 * @return {@code true} if the class is an inner or static nested class,
1041 * false if not or {@code null}
1042 */
1043 public static boolean isInnerClass(final Class<?> cls) {
1044 return cls != null && cls.getEnclosingClass() != null;
1045 }
1046
1047 // Class loading
1048 // ----------------------------------------------------------------------
1049 /**
1050 * Returns the class represented by {@code className} using the
1051 * {@code classLoader}. This implementation supports the syntaxes
1052 * "{@code java.util.Map.Entry[]}", "{@code java.util.Map$Entry[]}",
1053 * "{@code [Ljava.util.Map.Entry;}", and "{@code [Ljava.util.Map$Entry;}".
1054 *
1055 * @param classLoader the class loader to use to load the class
1056 * @param className the class name
1057 * @param initialize whether the class must be initialized
1058 * @return the class represented by {@code className} using the {@code classLoader}
1059 * @throws ClassNotFoundException if the class is not found
1060 */
1061 public static Class<?> getClass(
1062 final ClassLoader classLoader, final String className, final boolean initialize) throws ClassNotFoundException {
1063 try {
1064 Class<?> clazz;
1065 if (namePrimitiveMap.containsKey(className)) {
1066 clazz = namePrimitiveMap.get(className);
1067 } else {
1068 clazz = Class.forName(toCanonicalName(className), initialize, classLoader);
1069 }
1070 return clazz;
1071 } catch (final ClassNotFoundException ex) {
1072 // allow path separators (.) as inner class name separators
1073 final int lastDotIndex = className.lastIndexOf(PACKAGE_SEPARATOR_CHAR);
1074
1075 if (lastDotIndex != -1) {
1076 try {
1077 return getClass(classLoader, className.substring(0, lastDotIndex) +
1078 INNER_CLASS_SEPARATOR_CHAR + className.substring(lastDotIndex + 1),
1079 initialize);
1080 } catch (final ClassNotFoundException ex2) { // NOPMD
1081 // ignore exception
1082 }
1083 }
1084
1085 throw ex;
1086 }
1087 }
1088
1089 /**
1090 * Returns the (initialized) class represented by {@code className}
1091 * using the {@code classLoader}. This implementation supports
1092 * the syntaxes "{@code java.util.Map.Entry[]}",
1093 * "{@code java.util.Map$Entry[]}", "{@code [Ljava.util.Map.Entry;}",
1094 * and "{@code [Ljava.util.Map$Entry;}".
1095 *
1096 * @param classLoader the class loader to use to load the class
1097 * @param className the class name
1098 * @return the class represented by {@code className} using the {@code classLoader}
1099 * @throws ClassNotFoundException if the class is not found
1100 */
1101 public static Class<?> getClass(final ClassLoader classLoader, final String className) throws ClassNotFoundException {
1102 return getClass(classLoader, className, true);
1103 }
1104
1105 /**
1106 * Returns the (initialized) class represented by {@code className}
1107 * using the current thread's context class loader. This implementation
1108 * supports the syntaxes "{@code java.util.Map.Entry[]}",
1109 * "{@code java.util.Map$Entry[]}", "{@code [Ljava.util.Map.Entry;}",
1110 * and "{@code [Ljava.util.Map$Entry;}".
1111 *
1112 * @param className the class name
1113 * @return the class represented by {@code className} using the current thread's context class loader
1114 * @throws ClassNotFoundException if the class is not found
1115 */
1116 public static Class<?> getClass(final String className) throws ClassNotFoundException {
1117 return getClass(className, true);
1118 }
1119
1120 /**
1121 * Returns the class represented by {@code className} using the
1122 * current thread's context class loader. This implementation supports the
1123 * syntaxes "{@code java.util.Map.Entry[]}", "{@code java.util.Map$Entry[]}",
1124 * "{@code [Ljava.util.Map.Entry;}", and "{@code [Ljava.util.Map$Entry;}".
1125 *
1126 * @param className the class name
1127 * @param initialize whether the class must be initialized
1128 * @return the class represented by {@code className} using the current thread's context class loader
1129 * @throws ClassNotFoundException if the class is not found
1130 */
1131 public static Class<?> getClass(final String className, final boolean initialize) throws ClassNotFoundException {
1132 final ClassLoader contextCL = Thread.currentThread().getContextClassLoader();
1133 final ClassLoader loader = contextCL == null ? ClassUtils.class.getClassLoader() : contextCL;
1134 return getClass(loader, className, initialize);
1135 }
1136
1137 // Public method
1138 // ----------------------------------------------------------------------
1139 /**
1140 * <p>Returns the desired Method much like {@code Class.getMethod}, however
1141 * it ensures that the returned Method is from a public class or interface and not
1142 * from an anonymous inner class. This means that the Method is invokable and
1143 * doesn't fall foul of Java bug
1144 * <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4071957">4071957</a>).</p>
1145 *
1146 * <pre>
1147 * <code>Set set = Collections.unmodifiableSet(...);
1148 * Method method = ClassUtils.getPublicMethod(set.getClass(), "isEmpty", new Class[0]);
1149 * Object result = method.invoke(set, new Object[]);</code>
1150 * </pre>
1151 *
1152 * @param cls the class to check, not null
1153 * @param methodName the name of the method
1154 * @param parameterTypes the list of parameters
1155 * @return the method
1156 * @throws NullPointerException if the class is null
1157 * @throws SecurityException if a security violation occurred
1158 * @throws NoSuchMethodException if the method is not found in the given class
1159 * or if the method doesn't conform with the requirements
1160 */
1161 public static Method getPublicMethod(final Class<?> cls, final String methodName, final Class<?>... parameterTypes)
1162 throws NoSuchMethodException {
1163
1164 final Method declaredMethod = cls.getMethod(methodName, parameterTypes);
1165 if (Modifier.isPublic(declaredMethod.getDeclaringClass().getModifiers())) {
1166 return declaredMethod;
1167 }
1168
1169 final List<Class<?>> candidateClasses = new ArrayList<>();
1170 candidateClasses.addAll(getAllInterfaces(cls));
1171 candidateClasses.addAll(getAllSuperclasses(cls));
1172
1173 for (final Class<?> candidateClass : candidateClasses) {
1174 if (!Modifier.isPublic(candidateClass.getModifiers())) {
1175 continue;
1176 }
1177 Method candidateMethod;
1178 try {
1179 candidateMethod = candidateClass.getMethod(methodName, parameterTypes);
1180 } catch (final NoSuchMethodException ex) {
1181 continue;
1182 }
1183 if (Modifier.isPublic(candidateMethod.getDeclaringClass().getModifiers())) {
1184 return candidateMethod;
1185 }
1186 }
1187
1188 throw new NoSuchMethodException("Can't find a public method for " +
1189 methodName + " " + ArrayUtils.toString(parameterTypes));
1190 }
1191
1192 // ----------------------------------------------------------------------
1193 /**
1194 * Converts a class name to a JLS style class name.
1195 *
1196 * @param className the class name
1197 * @return the converted name
1198 */
1199 private static String toCanonicalName(String className) {
1200 className = StringUtils.deleteWhitespace(className);
1201 Validate.notNull(className, "className must not be null.");
1202 if (className.endsWith("[]")) {
1203 final StringBuilder classNameBuffer = new StringBuilder();
1204 while (className.endsWith("[]")) {
1205 className = className.substring(0, className.length() - 2);
1206 classNameBuffer.append("[");
1207 }
1208 final String abbreviation = abbreviationMap.get(className);
1209 if (abbreviation != null) {
1210 classNameBuffer.append(abbreviation);
1211 } else {
1212 classNameBuffer.append("L").append(className).append(";");
1213 }
1214 className = classNameBuffer.toString();
1215 }
1216 return className;
1217 }
1218
1219 /**
1220 * <p>Converts an array of {@code Object} in to an array of {@code Class} objects.
1221 * If any of these objects is null, a null element will be inserted into the array.</p>
1222 *
1223 * <p>This method returns {@code null} for a {@code null} input array.</p>
1224 *
1225 * @param array an {@code Object} array
1226 * @return a {@code Class} array, {@code null} if null array input
1227 * @since 2.4
1228 */
1229 public static Class<?>[] toClass(final Object... array) {
1230 if (array == null) {
1231 return null;
1232 } else if (array.length == 0) {
1233 return ArrayUtils.EMPTY_CLASS_ARRAY;
1234 }
1235 final Class<?>[] classes = new Class[array.length];
1236 for (int i = 0; i < array.length; i++) {
1237 classes[i] = array[i] == null ? null : array[i].getClass();
1238 }
1239 return classes;
1240 }
1241
1242 // Short canonical name
1243 // ----------------------------------------------------------------------
1244 /**
1245 * <p>Gets the canonical name minus the package name for an {@code Object}.</p>
1246 *
1247 * @param object the class to get the short name for, may be null
1248 * @param valueIfNull the value to return if null
1249 * @return the canonical name of the object without the package name, or the null value
1250 * @since 2.4
1251 */
1252 public static String getShortCanonicalName(final Object object, final String valueIfNull) {
1253 if (object == null) {
1254 return valueIfNull;
1255 }
1256 return getShortCanonicalName(object.getClass().getName());
1257 }
1258
1259 /**
1260 * <p>Gets the canonical class name for a {@code Class}.</p>
414 * <p>
415 * Gets the canonical class name for a {@code Class}.
416 * </p>
1261417 *
1262418 * @param cls the class for which to get the canonical class name; may be null
1263419 * @return the canonical name of the class, or the empty String
1269425 }
1270426
1271427 /**
1272 * <p>Gets the canonical name for a {@code Class}.</p>
428 * <p>
429 * Gets the canonical name for a {@code Class}.
430 * </p>
1273431 *
1274432 * @param cls the class for which to get the canonical class name; may be null
1275 * @param valueIfNull the return value if null
433 * @param valueIfNull the return value if null
1276434 * @return the canonical name of the class, or {@code valueIfNull}
1277435 * @since 3.7
1278436 * @see Class#getCanonicalName()
1286444 }
1287445
1288446 /**
1289 * <p>Gets the canonical name for an {@code Object}.</p>
447 * <p>
448 * Gets the canonical name for an {@code Object}.
449 * </p>
1290450 *
1291451 * @param object the object for which to get the canonical class name; may be null
1292452 * @return the canonical name of the object, or the empty String
1298458 }
1299459
1300460 /**
1301 * <p>Gets the canonical name for an {@code Object}.</p>
461 * <p>
462 * Gets the canonical name for an {@code Object}.
463 * </p>
1302464 *
1303465 * @param object the object for which to get the canonical class name; may be null
1304 * @param valueIfNull the return value if null
466 * @param valueIfNull the return value if null
1305467 * @return the canonical name of the object or {@code valueIfNull}
1306468 * @since 3.7
1307469 * @see Class#getCanonicalName()
1315477 }
1316478
1317479 /**
1318 * <p>Gets the canonical name minus the package name from a {@code Class}.</p>
1319 *
1320 * @param cls the class for which to get the short canonical class name; may be null
1321 * @return the canonical name without the package name or an empty string
1322 * @since 2.4
1323 */
1324 public static String getShortCanonicalName(final Class<?> cls) {
1325 if (cls == null) {
1326 return StringUtils.EMPTY;
1327 }
1328 return getShortCanonicalName(cls.getName());
1329 }
1330
1331 /**
1332 * <p>Gets the canonical name minus the package name from a String.</p>
1333 *
1334 * <p>The string passed in is assumed to be a class name - it is not checked.</p>
1335 *
1336 * <p>Note that this method is mainly designed to handle the arrays and primitives properly.
1337 * If the class is an inner class then the result value will not contain the outer classes.
1338 * This way the behavior of this method is different from {@link #getShortClassName(String)}.
1339 * The argument in that case is class name and not canonical name and the return value
1340 * retains the outer classes.</p>
1341 *
1342 * <p>Note that there is no way to reliably identify the part of the string representing the
1343 * package hierarchy and the part that is the outer class or classes in case of an inner class.
1344 * Trying to find the class would require reflective call and the class itself may not even be
1345 * on the class path. Relying on the fact that class names start with capital letter and packages
1346 * with lower case is heuristic.</p>
1347 *
1348 * <p>It is recommended to use {@link #getShortClassName(String)} for cases when the class
1349 * is an inner class and use this method for cases it is designed for.</p>
1350 *
1351 * <table>
1352 * <caption>Examples</caption>
1353 * <tr><td>return value</td><td>input</td></tr>
1354 * <tr><td>{@code ""}</td><td>{@code (String)null}</td></tr>
1355 * <tr><td>{@code "Map.Entry"}</td><td>{@code java.util.Map.Entry.class.getName()}</td></tr>
1356 * <tr><td>{@code "Entry"}</td><td>{@code java.util.Map.Entry.class.getCanonicalName()}</td></tr>
1357 * <tr><td>{@code "ClassUtils"}</td><td>{@code "org.apache.commons.lang3.ClassUtils"}</td></tr>
1358 * <tr><td>{@code "ClassUtils[]"}</td><td>{@code "[Lorg.apache.commons.lang3.ClassUtils;"}</td></tr>
1359 * <tr><td>{@code "ClassUtils[][]"}</td><td>{@code "[[Lorg.apache.commons.lang3.ClassUtils;"}</td></tr>
1360 * <tr><td>{@code "ClassUtils[]"}</td><td>{@code "org.apache.commons.lang3.ClassUtils[]"}</td></tr>
1361 * <tr><td>{@code "ClassUtils[][]"}</td><td>{@code "org.apache.commons.lang3.ClassUtils[][]"}</td></tr>
1362 * <tr><td>{@code "int[]"}</td><td>{@code "[I"}</td></tr>
1363 * <tr><td>{@code "int[]"}</td><td>{@code int[].class.getCanonicalName()}</td></tr>
1364 * <tr><td>{@code "int[]"}</td><td>{@code int[].class.getName()}</td></tr>
1365 * <tr><td>{@code "int[][]"}</td><td>{@code "[[I"}</td></tr>
1366 * <tr><td>{@code "int[]"}</td><td>{@code "int[]"}</td></tr>
1367 * <tr><td>{@code "int[][]"}</td><td>{@code "int[][]"}</td></tr>
1368 * </table>
1369 *
1370 * @param canonicalName the class name to get the short name for
1371 * @return the canonical name of the class without the package name or an empty string
1372 * @since 2.4
1373 */
1374 public static String getShortCanonicalName(final String canonicalName) {
1375 return getShortClassName(getCanonicalName(canonicalName));
1376 }
1377
1378 // Package name
1379 // ----------------------------------------------------------------------
1380 /**
1381 * <p>Gets the package name from the class name of an {@code Object}.</p>
1382 *
1383 * @param object the class to get the package name for, may be null
1384 * @param valueIfNull the value to return if null
1385 * @return the package name of the object, or the null value
1386 * @since 2.4
1387 */
1388 public static String getPackageCanonicalName(final Object object, final String valueIfNull) {
1389 if (object == null) {
1390 return valueIfNull;
1391 }
1392 return getPackageCanonicalName(object.getClass().getName());
1393 }
1394
1395 /**
1396 * <p>Gets the package name from the canonical name of a {@code Class}.</p>
1397 *
1398 * @param cls the class to get the package name for, may be {@code null}.
1399 * @return the package name or an empty string
1400 * @since 2.4
1401 */
1402 public static String getPackageCanonicalName(final Class<?> cls) {
1403 if (cls == null) {
1404 return StringUtils.EMPTY;
1405 }
1406 return getPackageCanonicalName(cls.getName());
1407 }
1408
1409 /**
1410 * <p>Gets the package name from the class name. </p>
1411 *
1412 * <p>The string passed in is assumed to be a class name - it is not checked.</p>
1413 * <p>If the class is in the default package, return an empty string.</p>
1414 *
1415 * @param name the name to get the package name for, may be {@code null}
1416 * @return the package name or an empty string
1417 * @since 2.4
1418 */
1419 public static String getPackageCanonicalName(final String name) {
1420 return getPackageName(getCanonicalName(name));
1421 }
1422
1423 /**
1424 * <p>Converts a given name of class into canonical format.
1425 * If name of class is not a name of array class it returns
1426 * unchanged name.</p>
1427 *
1428 * <p>The method does not change the {@code $} separators in case
1429 * the class is inner class.</p>
1430 *
1431 * <p>Example:
480 * <p>
481 * Converts a given name of class into canonical format. If name of class is not a name of array class it returns
482 * unchanged name.
483 * </p>
484 *
485 * <p>
486 * The method does not change the {@code $} separators in case the class is inner class.
487 * </p>
488 *
489 * <p>
490 * Example:
1432491 * <ul>
1433492 * <li>{@code getCanonicalName("[I") = "int[]"}</li>
1434493 * <li>{@code getCanonicalName("[Ljava.lang.String;") = "java.lang.String[]"}</li>
1454513 return className;
1455514 }
1456515 if (className.startsWith("L")) {
1457 className = className.substring(
1458 1,
1459 className.endsWith(";")
1460 ? className.length() - 1
1461 : className.length());
1462 } else {
1463 if (!className.isEmpty()) {
1464 className = reverseAbbreviationMap.get(className.substring(0, 1));
1465 }
516 className = className.substring(1, className.endsWith(";") ? className.length() - 1 : className.length());
517 } else if (!className.isEmpty()) {
518 className = reverseAbbreviationMap.get(className.substring(0, 1));
1466519 }
1467520 final StringBuilder canonicalClassNameBuffer = new StringBuilder(className);
1468521 for (int i = 0; i < dim; i++) {
1469522 canonicalClassNameBuffer.append("[]");
1470523 }
1471524 return canonicalClassNameBuffer.toString();
525 }
526
527 /**
528 * Returns the (initialized) class represented by {@code className} using the {@code classLoader}. This implementation
529 * supports the syntaxes "{@code java.util.Map.Entry[]}", "{@code java.util.Map$Entry[]}",
530 * "{@code [Ljava.util.Map.Entry;}", and "{@code [Ljava.util.Map$Entry;}".
531 *
532 * @param classLoader the class loader to use to load the class
533 * @param className the class name
534 * @return the class represented by {@code className} using the {@code classLoader}
535 * @throws ClassNotFoundException if the class is not found
536 */
537 public static Class<?> getClass(final ClassLoader classLoader, final String className) throws ClassNotFoundException {
538 return getClass(classLoader, className, true);
539 }
540
541 /**
542 * Returns the class represented by {@code className} using the {@code classLoader}. This implementation supports the
543 * syntaxes "{@code java.util.Map.Entry[]}", "{@code java.util.Map$Entry[]}", "{@code [Ljava.util.Map.Entry;}", and
544 * "{@code [Ljava.util.Map$Entry;}".
545 *
546 * @param classLoader the class loader to use to load the class
547 * @param className the class name
548 * @param initialize whether the class must be initialized
549 * @return the class represented by {@code className} using the {@code classLoader}
550 * @throws ClassNotFoundException if the class is not found
551 */
552 public static Class<?> getClass(final ClassLoader classLoader, final String className, final boolean initialize) throws ClassNotFoundException {
553 try {
554 final Class<?> clazz;
555 if (namePrimitiveMap.containsKey(className)) {
556 clazz = namePrimitiveMap.get(className);
557 } else {
558 clazz = Class.forName(toCanonicalName(className), initialize, classLoader);
559 }
560 return clazz;
561 } catch (final ClassNotFoundException ex) {
562 // allow path separators (.) as inner class name separators
563 final int lastDotIndex = className.lastIndexOf(PACKAGE_SEPARATOR_CHAR);
564
565 if (lastDotIndex != -1) {
566 try {
567 return getClass(classLoader, className.substring(0, lastDotIndex) + INNER_CLASS_SEPARATOR_CHAR + className.substring(lastDotIndex + 1),
568 initialize);
569 } catch (final ClassNotFoundException ex2) { // NOPMD
570 // ignore exception
571 }
572 }
573
574 throw ex;
575 }
576 }
577
578 /**
579 * Returns the (initialized) class represented by {@code className} using the current thread's context class loader.
580 * This implementation supports the syntaxes "{@code java.util.Map.Entry[]}", "{@code java.util.Map$Entry[]}",
581 * "{@code [Ljava.util.Map.Entry;}", and "{@code [Ljava.util.Map$Entry;}".
582 *
583 * @param className the class name
584 * @return the class represented by {@code className} using the current thread's context class loader
585 * @throws ClassNotFoundException if the class is not found
586 */
587 public static Class<?> getClass(final String className) throws ClassNotFoundException {
588 return getClass(className, true);
589 }
590
591 /**
592 * Returns the class represented by {@code className} using the current thread's context class loader. This
593 * implementation supports the syntaxes "{@code java.util.Map.Entry[]}", "{@code java.util.Map$Entry[]}",
594 * "{@code [Ljava.util.Map.Entry;}", and "{@code [Ljava.util.Map$Entry;}".
595 *
596 * @param className the class name
597 * @param initialize whether the class must be initialized
598 * @return the class represented by {@code className} using the current thread's context class loader
599 * @throws ClassNotFoundException if the class is not found
600 */
601 public static Class<?> getClass(final String className, final boolean initialize) throws ClassNotFoundException {
602 final ClassLoader contextCL = Thread.currentThread().getContextClassLoader();
603 final ClassLoader loader = contextCL == null ? ClassUtils.class.getClassLoader() : contextCL;
604 return getClass(loader, className, initialize);
605 }
606
607 /**
608 * Delegates to {@link Class#getComponentType()} using generics.
609 *
610 * @param <T> The array class type.
611 * @param cls A class or null.
612 * @return The array component type or null.
613 * @see Class#getComponentType()
614 * @since 3.13.0
615 */
616 @SuppressWarnings("unchecked")
617 public static <T> Class<T> getComponentType(final Class<T[]> cls) {
618 return cls == null ? null : (Class<T>) cls.getComponentType();
619 }
620
621 /**
622 * <p>
623 * Null-safe version of {@code cls.getName()}
624 * </p>
625 *
626 * @param cls the class for which to get the class name; may be null
627 * @return the class name or the empty string in case the argument is {@code null}
628 * @since 3.7
629 * @see Class#getSimpleName()
630 */
631 public static String getName(final Class<?> cls) {
632 return getName(cls, StringUtils.EMPTY);
633 }
634
635 /**
636 * <p>
637 * Null-safe version of {@code cls.getName()}
638 * </p>
639 *
640 * @param cls the class for which to get the class name; may be null
641 * @param valueIfNull the return value if the argument {@code cls} is {@code null}
642 * @return the class name or {@code valueIfNull}
643 * @since 3.7
644 * @see Class#getName()
645 */
646 public static String getName(final Class<?> cls, final String valueIfNull) {
647 return cls == null ? valueIfNull : cls.getName();
648 }
649
650 /**
651 * <p>
652 * Null-safe version of {@code object.getClass().getName()}
653 * </p>
654 *
655 * @param object the object for which to get the class name; may be null
656 * @return the class name or the empty String
657 * @since 3.7
658 * @see Class#getSimpleName()
659 */
660 public static String getName(final Object object) {
661 return getName(object, StringUtils.EMPTY);
662 }
663
664 /**
665 * <p>
666 * Null-safe version of {@code object.getClass().getSimpleName()}
667 * </p>
668 *
669 * @param object the object for which to get the class name; may be null
670 * @param valueIfNull the value to return if {@code object} is {@code null}
671 * @return the class name or {@code valueIfNull}
672 * @since 3.0
673 * @see Class#getName()
674 */
675 public static String getName(final Object object, final String valueIfNull) {
676 return object == null ? valueIfNull : object.getClass().getName();
677 }
678
679 /**
680 * <p>
681 * Gets the package name from the canonical name of a {@code Class}.
682 * </p>
683 *
684 * @param cls the class to get the package name for, may be {@code null}.
685 * @return the package name or an empty string
686 * @since 2.4
687 */
688 public static String getPackageCanonicalName(final Class<?> cls) {
689 if (cls == null) {
690 return StringUtils.EMPTY;
691 }
692 return getPackageCanonicalName(cls.getName());
693 }
694
695 /**
696 * <p>
697 * Gets the package name from the class name of an {@code Object}.
698 * </p>
699 *
700 * @param object the class to get the package name for, may be null
701 * @param valueIfNull the value to return if null
702 * @return the package name of the object, or the null value
703 * @since 2.4
704 */
705 public static String getPackageCanonicalName(final Object object, final String valueIfNull) {
706 if (object == null) {
707 return valueIfNull;
708 }
709 return getPackageCanonicalName(object.getClass().getName());
710 }
711
712 /**
713 * <p>
714 * Gets the package name from the class name.
715 * </p>
716 *
717 * <p>
718 * The string passed in is assumed to be a class name - it is not checked.
719 * </p>
720 * <p>
721 * If the class is in the default package, return an empty string.
722 * </p>
723 *
724 * @param name the name to get the package name for, may be {@code null}
725 * @return the package name or an empty string
726 * @since 2.4
727 */
728 public static String getPackageCanonicalName(final String name) {
729 return getPackageName(getCanonicalName(name));
730 }
731
732 /**
733 * <p>
734 * Gets the package name of a {@code Class}.
735 * </p>
736 *
737 * @param cls the class to get the package name for, may be {@code null}.
738 * @return the package name or an empty string
739 */
740 public static String getPackageName(final Class<?> cls) {
741 if (cls == null) {
742 return StringUtils.EMPTY;
743 }
744 return getPackageName(cls.getName());
745 }
746
747 // Package name
748 // ----------------------------------------------------------------------
749 /**
750 * <p>
751 * Gets the package name of an {@code Object}.
752 * </p>
753 *
754 * @param object the class to get the package name for, may be null
755 * @param valueIfNull the value to return if null
756 * @return the package name of the object, or the null value
757 */
758 public static String getPackageName(final Object object, final String valueIfNull) {
759 if (object == null) {
760 return valueIfNull;
761 }
762 return getPackageName(object.getClass());
763 }
764
765 /**
766 * <p>
767 * Gets the package name from a {@code String}.
768 * </p>
769 *
770 * <p>
771 * The string passed in is assumed to be a class name - it is not checked.
772 * </p>
773 * <p>
774 * If the class is unpackaged, return an empty string.
775 * </p>
776 *
777 * @param className the className to get the package name for, may be {@code null}
778 * @return the package name or an empty string
779 */
780 public static String getPackageName(String className) {
781 if (StringUtils.isEmpty(className)) {
782 return StringUtils.EMPTY;
783 }
784
785 // Strip array encoding
786 while (className.charAt(0) == '[') {
787 className = className.substring(1);
788 }
789 // Strip Object type encoding
790 if (className.charAt(0) == 'L' && className.charAt(className.length() - 1) == ';') {
791 className = className.substring(1);
792 }
793
794 final int i = className.lastIndexOf(PACKAGE_SEPARATOR_CHAR);
795 if (i == -1) {
796 return StringUtils.EMPTY;
797 }
798 return className.substring(0, i);
799 }
800
801 /**
802 * <p>
803 * Returns the desired Method much like {@code Class.getMethod}, however it ensures that the returned Method is from a
804 * public class or interface and not from an anonymous inner class. This means that the Method is invokable and doesn't
805 * fall foul of Java bug <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4071957">4071957</a>).
806 * </p>
807 *
808 * <pre>
809 * <code>Set set = Collections.unmodifiableSet(...);
810 * Method method = ClassUtils.getPublicMethod(set.getClass(), "isEmpty", new Class[0]);
811 * Object result = method.invoke(set, new Object[]);</code>
812 * </pre>
813 *
814 * @param cls the class to check, not null
815 * @param methodName the name of the method
816 * @param parameterTypes the list of parameters
817 * @return the method
818 * @throws NullPointerException if the class is null
819 * @throws SecurityException if a security violation occurred
820 * @throws NoSuchMethodException if the method is not found in the given class or if the method doesn't conform with the
821 * requirements
822 */
823 public static Method getPublicMethod(final Class<?> cls, final String methodName, final Class<?>... parameterTypes) throws NoSuchMethodException {
824
825 final Method declaredMethod = cls.getMethod(methodName, parameterTypes);
826 if (Modifier.isPublic(declaredMethod.getDeclaringClass().getModifiers())) {
827 return declaredMethod;
828 }
829
830 final List<Class<?>> candidateClasses = new ArrayList<>(getAllInterfaces(cls));
831 candidateClasses.addAll(getAllSuperclasses(cls));
832
833 for (final Class<?> candidateClass : candidateClasses) {
834 if (!Modifier.isPublic(candidateClass.getModifiers())) {
835 continue;
836 }
837 final Method candidateMethod;
838 try {
839 candidateMethod = candidateClass.getMethod(methodName, parameterTypes);
840 } catch (final NoSuchMethodException ex) {
841 continue;
842 }
843 if (Modifier.isPublic(candidateMethod.getDeclaringClass().getModifiers())) {
844 return candidateMethod;
845 }
846 }
847
848 throw new NoSuchMethodException("Can't find a public method for " + methodName + " " + ArrayUtils.toString(parameterTypes));
849 }
850
851 /**
852 * <p>
853 * Gets the canonical name minus the package name from a {@code Class}.
854 * </p>
855 *
856 * @param cls the class for which to get the short canonical class name; may be null
857 * @return the canonical name without the package name or an empty string
858 * @since 2.4
859 */
860 public static String getShortCanonicalName(final Class<?> cls) {
861 if (cls == null) {
862 return StringUtils.EMPTY;
863 }
864 return getShortCanonicalName(cls.getName());
865 }
866
867 /**
868 * <p>
869 * Gets the canonical name minus the package name for an {@code Object}.
870 * </p>
871 *
872 * @param object the class to get the short name for, may be null
873 * @param valueIfNull the value to return if null
874 * @return the canonical name of the object without the package name, or the null value
875 * @since 2.4
876 */
877 public static String getShortCanonicalName(final Object object, final String valueIfNull) {
878 if (object == null) {
879 return valueIfNull;
880 }
881 return getShortCanonicalName(object.getClass().getName());
882 }
883
884 /**
885 * <p>
886 * Gets the canonical name minus the package name from a String.
887 * </p>
888 *
889 * <p>
890 * The string passed in is assumed to be a class name - it is not checked.
891 * </p>
892 *
893 * <p>
894 * Note that this method is mainly designed to handle the arrays and primitives properly. If the class is an inner class
895 * then the result value will not contain the outer classes. This way the behavior of this method is different from
896 * {@link #getShortClassName(String)}. The argument in that case is class name and not canonical name and the return
897 * value retains the outer classes.
898 * </p>
899 *
900 * <p>
901 * Note that there is no way to reliably identify the part of the string representing the package hierarchy and the part
902 * that is the outer class or classes in case of an inner class. Trying to find the class would require reflective call
903 * and the class itself may not even be on the class path. Relying on the fact that class names start with capital
904 * letter and packages with lower case is heuristic.
905 * </p>
906 *
907 * <p>
908 * It is recommended to use {@link #getShortClassName(String)} for cases when the class is an inner class and use this
909 * method for cases it is designed for.
910 * </p>
911 *
912 * <table>
913 * <caption>Examples</caption>
914 * <tr>
915 * <td>return value</td>
916 * <td>input</td>
917 * </tr>
918 * <tr>
919 * <td>{@code ""}</td>
920 * <td>{@code (String)null}</td>
921 * </tr>
922 * <tr>
923 * <td>{@code "Map.Entry"}</td>
924 * <td>{@code java.util.Map.Entry.class.getName()}</td>
925 * </tr>
926 * <tr>
927 * <td>{@code "Entry"}</td>
928 * <td>{@code java.util.Map.Entry.class.getCanonicalName()}</td>
929 * </tr>
930 * <tr>
931 * <td>{@code "ClassUtils"}</td>
932 * <td>{@code "org.apache.commons.lang3.ClassUtils"}</td>
933 * </tr>
934 * <tr>
935 * <td>{@code "ClassUtils[]"}</td>
936 * <td>{@code "[Lorg.apache.commons.lang3.ClassUtils;"}</td>
937 * </tr>
938 * <tr>
939 * <td>{@code "ClassUtils[][]"}</td>
940 * <td>{@code "[[Lorg.apache.commons.lang3.ClassUtils;"}</td>
941 * </tr>
942 * <tr>
943 * <td>{@code "ClassUtils[]"}</td>
944 * <td>{@code "org.apache.commons.lang3.ClassUtils[]"}</td>
945 * </tr>
946 * <tr>
947 * <td>{@code "ClassUtils[][]"}</td>
948 * <td>{@code "org.apache.commons.lang3.ClassUtils[][]"}</td>
949 * </tr>
950 * <tr>
951 * <td>{@code "int[]"}</td>
952 * <td>{@code "[I"}</td>
953 * </tr>
954 * <tr>
955 * <td>{@code "int[]"}</td>
956 * <td>{@code int[].class.getCanonicalName()}</td>
957 * </tr>
958 * <tr>
959 * <td>{@code "int[]"}</td>
960 * <td>{@code int[].class.getName()}</td>
961 * </tr>
962 * <tr>
963 * <td>{@code "int[][]"}</td>
964 * <td>{@code "[[I"}</td>
965 * </tr>
966 * <tr>
967 * <td>{@code "int[]"}</td>
968 * <td>{@code "int[]"}</td>
969 * </tr>
970 * <tr>
971 * <td>{@code "int[][]"}</td>
972 * <td>{@code "int[][]"}</td>
973 * </tr>
974 * </table>
975 *
976 * @param canonicalName the class name to get the short name for
977 * @return the canonical name of the class without the package name or an empty string
978 * @since 2.4
979 */
980 public static String getShortCanonicalName(final String canonicalName) {
981 return getShortClassName(getCanonicalName(canonicalName));
982 }
983
984 /**
985 * <p>
986 * Gets the class name minus the package name from a {@code Class}.
987 * </p>
988 *
989 * <p>
990 * This method simply gets the name using {@code Class.getName()} and then calls {@link #getShortClassName(Class)}. See
991 * relevant notes there.
992 * </p>
993 *
994 * @param cls the class to get the short name for.
995 * @return the class name without the package name or an empty string. If the class is an inner class then the returned
996 * value will contain the outer class or classes separated with {@code .} (dot) character.
997 */
998 public static String getShortClassName(final Class<?> cls) {
999 if (cls == null) {
1000 return StringUtils.EMPTY;
1001 }
1002 return getShortClassName(cls.getName());
1003 }
1004
1005 /**
1006 * <p>
1007 * Gets the class name of the {@code object} without the package name or names.
1008 * </p>
1009 *
1010 * <p>
1011 * The method looks up the class of the object and then converts the name of the class invoking
1012 * {@link #getShortClassName(Class)} (see relevant notes there).
1013 * </p>
1014 *
1015 * @param object the class to get the short name for, may be {@code null}
1016 * @param valueIfNull the value to return if the object is {@code null}
1017 * @return the class name of the object without the package name, or {@code valueIfNull} if the argument {@code object}
1018 * is {@code null}
1019 */
1020 public static String getShortClassName(final Object object, final String valueIfNull) {
1021 if (object == null) {
1022 return valueIfNull;
1023 }
1024 return getShortClassName(object.getClass());
1025 }
1026
1027 /**
1028 * <p>
1029 * Gets the class name minus the package name from a String.
1030 * </p>
1031 *
1032 * <p>
1033 * The string passed in is assumed to be a class name - it is not checked. The string has to be formatted the way as the
1034 * JDK method {@code Class.getName()} returns it, and not the usual way as we write it, for example in import
1035 * statements, or as it is formatted by {@code Class.getCanonicalName()}.
1036 * </p>
1037 *
1038 * <p>
1039 * The difference is is significant only in case of classes that are inner classes of some other classes. In this case
1040 * the separator between the outer and inner class (possibly on multiple hierarchy level) has to be {@code $} (dollar
1041 * sign) and not {@code .} (dot), as it is returned by {@code Class.getName()}
1042 * </p>
1043 *
1044 * <p>
1045 * Note that this method is called from the {@link #getShortClassName(Class)} method using the string returned by
1046 * {@code Class.getName()}.
1047 * </p>
1048 *
1049 * <p>
1050 * Note that this method differs from {@link #getSimpleName(Class)} in that this will return, for example
1051 * {@code "Map.Entry"} whilst the {@code java.lang.Class} variant will simply return {@code "Entry"}. In this example
1052 * the argument {@code className} is the string {@code java.util.Map$Entry} (note the {@code $} sign.
1053 * </p>
1054 *
1055 * @param className the className to get the short name for. It has to be formatted as returned by
1056 * {@code Class.getName()} and not {@code Class.getCanonicalName()}
1057 * @return the class name of the class without the package name or an empty string. If the class is an inner class then
1058 * value contains the outer class or classes and the separator is replaced to be {@code .} (dot) character.
1059 */
1060 public static String getShortClassName(String className) {
1061 if (StringUtils.isEmpty(className)) {
1062 return StringUtils.EMPTY;
1063 }
1064
1065 final StringBuilder arrayPrefix = new StringBuilder();
1066
1067 // Handle array encoding
1068 if (className.startsWith("[")) {
1069 while (className.charAt(0) == '[') {
1070 className = className.substring(1);
1071 arrayPrefix.append("[]");
1072 }
1073 // Strip Object type encoding
1074 if (className.charAt(0) == 'L' && className.charAt(className.length() - 1) == ';') {
1075 className = className.substring(1, className.length() - 1);
1076 }
1077
1078 if (reverseAbbreviationMap.containsKey(className)) {
1079 className = reverseAbbreviationMap.get(className);
1080 }
1081 }
1082
1083 final int lastDotIdx = className.lastIndexOf(PACKAGE_SEPARATOR_CHAR);
1084 final int innerIdx = className.indexOf(INNER_CLASS_SEPARATOR_CHAR, lastDotIdx == -1 ? 0 : lastDotIdx + 1);
1085 String out = className.substring(lastDotIdx + 1);
1086 if (innerIdx != -1) {
1087 out = out.replace(INNER_CLASS_SEPARATOR_CHAR, PACKAGE_SEPARATOR_CHAR);
1088 }
1089 return out + arrayPrefix;
1090 }
1091
1092 /**
1093 * <p>
1094 * Null-safe version of {@code cls.getSimpleName()}
1095 * </p>
1096 *
1097 * @param cls the class for which to get the simple name; may be null
1098 * @return the simple class name or the empty string in case the argument is {@code null}
1099 * @since 3.0
1100 * @see Class#getSimpleName()
1101 */
1102 public static String getSimpleName(final Class<?> cls) {
1103 return getSimpleName(cls, StringUtils.EMPTY);
1104 }
1105
1106 /**
1107 * <p>
1108 * Null-safe version of {@code cls.getSimpleName()}
1109 * </p>
1110 *
1111 * @param cls the class for which to get the simple name; may be null
1112 * @param valueIfNull the value to return if null
1113 * @return the simple class name or {@code valueIfNull} if the argument {@code cls} is {@code null}
1114 * @since 3.0
1115 * @see Class#getSimpleName()
1116 */
1117 public static String getSimpleName(final Class<?> cls, final String valueIfNull) {
1118 return cls == null ? valueIfNull : cls.getSimpleName();
1119 }
1120
1121 /**
1122 * <p>
1123 * Null-safe version of {@code object.getClass().getSimpleName()}
1124 * </p>
1125 *
1126 * <p>
1127 * It is to note that this method is overloaded and in case the argument {@code object} is a {@code Class} object then
1128 * the {@link #getSimpleName(Class)} will be invoked. If this is a significant possibility then the caller should check
1129 * this case and call {@code
1130 * getSimpleName(Class.class)} or just simply use the string literal {@code "Class"}, which is the result of the method
1131 * in that case.
1132 * </p>
1133 *
1134 * @param object the object for which to get the simple class name; may be null
1135 * @return the simple class name or the empty string in case the argument is {@code null}
1136 * @since 3.7
1137 * @see Class#getSimpleName()
1138 */
1139 public static String getSimpleName(final Object object) {
1140 return getSimpleName(object, StringUtils.EMPTY);
1141 }
1142
1143 /**
1144 * <p>
1145 * Null-safe version of {@code object.getClass().getSimpleName()}
1146 * </p>
1147 *
1148 * @param object the object for which to get the simple class name; may be null
1149 * @param valueIfNull the value to return if {@code object} is {@code null}
1150 * @return the simple class name or {@code valueIfNull} if the argument {@code object} is {@code null}
1151 * @since 3.0
1152 * @see Class#getSimpleName()
1153 */
1154 public static String getSimpleName(final Object object, final String valueIfNull) {
1155 return object == null ? valueIfNull : object.getClass().getSimpleName();
14721156 }
14731157
14741158 /**
15231207 final Iterator<Class<?>> wrapped = classes.iterator();
15241208
15251209 return new Iterator<Class<?>>() {
1526 Iterator<Class<?>> interfaces = Collections.<Class<?>>emptySet().iterator();
1210 Iterator<Class<?>> interfaces = Collections.emptyIterator();
15271211
15281212 @Override
15291213 public boolean hasNext() {
15441228 return nextSuperclass;
15451229 }
15461230
1231 @Override
1232 public void remove() {
1233 throw new UnsupportedOperationException();
1234 }
1235
15471236 private void walkInterfaces(final Set<Class<?>> addTo, final Class<?> c) {
15481237 for (final Class<?> iface : c.getInterfaces()) {
15491238 if (!seenInterfaces.contains(iface)) {
15531242 }
15541243 }
15551244
1556 @Override
1557 public void remove() {
1558 throw new UnsupportedOperationException();
1559 }
1560
15611245 };
15621246 };
15631247 }
15641248
1249 /**
1250 * <p>
1251 * Checks if one {@code Class} can be assigned to a variable of another {@code Class}.
1252 * </p>
1253 *
1254 * <p>
1255 * Unlike the {@link Class#isAssignableFrom(java.lang.Class)} method, this method takes into account widenings of
1256 * primitive classes and {@code null}s.
1257 * </p>
1258 *
1259 * <p>
1260 * Primitive widenings allow an int to be assigned to a long, float or double. This method returns the correct result
1261 * for these cases.
1262 * </p>
1263 *
1264 * <p>
1265 * {@code Null} may be assigned to any reference type. This method will return {@code true} if {@code null} is passed in
1266 * and the toClass is non-primitive.
1267 * </p>
1268 *
1269 * <p>
1270 * Specifically, this method tests whether the type represented by the specified {@code Class} parameter can be
1271 * converted to the type represented by this {@code Class} object via an identity conversion widening primitive or
1272 * widening reference conversion. See <em><a href="http://docs.oracle.com/javase/specs/">The Java Language
1273 * Specification</a></em>, sections 5.1.1, 5.1.2 and 5.1.4 for details.
1274 * </p>
1275 *
1276 * <p>
1277 * <strong>Since Lang 3.0,</strong> this method will default behavior for calculating assignability between primitive
1278 * and wrapper types <em>corresponding to the running Java version</em>; i.e. autoboxing will be the default behavior in
1279 * VMs running Java versions &gt; 1.5.
1280 * </p>
1281 *
1282 * @param cls the Class to check, may be null
1283 * @param toClass the Class to try to assign into, returns false if null
1284 * @return {@code true} if assignment possible
1285 */
1286 public static boolean isAssignable(final Class<?> cls, final Class<?> toClass) {
1287 return isAssignable(cls, toClass, true);
1288 }
1289
1290 /**
1291 * <p>
1292 * Checks if one {@code Class} can be assigned to a variable of another {@code Class}.
1293 * </p>
1294 *
1295 * <p>
1296 * Unlike the {@link Class#isAssignableFrom(java.lang.Class)} method, this method takes into account widenings of
1297 * primitive classes and {@code null}s.
1298 * </p>
1299 *
1300 * <p>
1301 * Primitive widenings allow an int to be assigned to a long, float or double. This method returns the correct result
1302 * for these cases.
1303 * </p>
1304 *
1305 * <p>
1306 * {@code Null} may be assigned to any reference type. This method will return {@code true} if {@code null} is passed in
1307 * and the toClass is non-primitive.
1308 * </p>
1309 *
1310 * <p>
1311 * Specifically, this method tests whether the type represented by the specified {@code Class} parameter can be
1312 * converted to the type represented by this {@code Class} object via an identity conversion widening primitive or
1313 * widening reference conversion. See <em><a href="http://docs.oracle.com/javase/specs/">The Java Language
1314 * Specification</a></em>, sections 5.1.1, 5.1.2 and 5.1.4 for details.
1315 * </p>
1316 *
1317 * @param cls the Class to check, may be null
1318 * @param toClass the Class to try to assign into, returns false if null
1319 * @param autoboxing whether to use implicit autoboxing/unboxing between primitives and wrappers
1320 * @return {@code true} if assignment possible
1321 */
1322 public static boolean isAssignable(Class<?> cls, final Class<?> toClass, final boolean autoboxing) {
1323 if (toClass == null) {
1324 return false;
1325 }
1326 // have to check for null, as isAssignableFrom doesn't
1327 if (cls == null) {
1328 return !toClass.isPrimitive();
1329 }
1330 // autoboxing:
1331 if (autoboxing) {
1332 if (cls.isPrimitive() && !toClass.isPrimitive()) {
1333 cls = primitiveToWrapper(cls);
1334 if (cls == null) {
1335 return false;
1336 }
1337 }
1338 if (toClass.isPrimitive() && !cls.isPrimitive()) {
1339 cls = wrapperToPrimitive(cls);
1340 if (cls == null) {
1341 return false;
1342 }
1343 }
1344 }
1345 if (cls.equals(toClass)) {
1346 return true;
1347 }
1348 if (cls.isPrimitive()) {
1349 if (!toClass.isPrimitive()) {
1350 return false;
1351 }
1352 if (Integer.TYPE.equals(cls)) {
1353 return Long.TYPE.equals(toClass) || Float.TYPE.equals(toClass) || Double.TYPE.equals(toClass);
1354 }
1355 if (Long.TYPE.equals(cls)) {
1356 return Float.TYPE.equals(toClass) || Double.TYPE.equals(toClass);
1357 }
1358 if (Boolean.TYPE.equals(cls)) {
1359 return false;
1360 }
1361 if (Double.TYPE.equals(cls)) {
1362 return false;
1363 }
1364 if (Float.TYPE.equals(cls)) {
1365 return Double.TYPE.equals(toClass);
1366 }
1367 if (Character.TYPE.equals(cls)) {
1368 return Integer.TYPE.equals(toClass) || Long.TYPE.equals(toClass) || Float.TYPE.equals(toClass) || Double.TYPE.equals(toClass);
1369 }
1370 if (Short.TYPE.equals(cls)) {
1371 return Integer.TYPE.equals(toClass) || Long.TYPE.equals(toClass) || Float.TYPE.equals(toClass) || Double.TYPE.equals(toClass);
1372 }
1373 if (Byte.TYPE.equals(cls)) {
1374 return Short.TYPE.equals(toClass) || Integer.TYPE.equals(toClass) || Long.TYPE.equals(toClass) || Float.TYPE.equals(toClass)
1375 || Double.TYPE.equals(toClass);
1376 }
1377 // should never get here
1378 return false;
1379 }
1380 return toClass.isAssignableFrom(cls);
1381 }
1382
1383 /**
1384 * <p>
1385 * Checks if an array of Classes can be assigned to another array of Classes.
1386 * </p>
1387 *
1388 * <p>
1389 * This method calls {@link #isAssignable(Class, Class) isAssignable} for each Class pair in the input arrays. It can be
1390 * used to check if a set of arguments (the first parameter) are suitably compatible with a set of method parameter
1391 * types (the second parameter).
1392 * </p>
1393 *
1394 * <p>
1395 * Unlike the {@link Class#isAssignableFrom(java.lang.Class)} method, this method takes into account widenings of
1396 * primitive classes and {@code null}s.
1397 * </p>
1398 *
1399 * <p>
1400 * Primitive widenings allow an int to be assigned to a {@code long}, {@code float} or {@code double}. This method
1401 * returns the correct result for these cases.
1402 * </p>
1403 *
1404 * <p>
1405 * {@code Null} may be assigned to any reference type. This method will return {@code true} if {@code null} is passed in
1406 * and the toClass is non-primitive.
1407 * </p>
1408 *
1409 * <p>
1410 * Specifically, this method tests whether the type represented by the specified {@code Class} parameter can be
1411 * converted to the type represented by this {@code Class} object via an identity conversion widening primitive or
1412 * widening reference conversion. See <em><a href="http://docs.oracle.com/javase/specs/">The Java Language
1413 * Specification</a></em>, sections 5.1.1, 5.1.2 and 5.1.4 for details.
1414 * </p>
1415 *
1416 * <p>
1417 * <strong>Since Lang 3.0,</strong> this method will default behavior for calculating assignability between primitive
1418 * and wrapper types <em>corresponding to the running Java version</em>; i.e. autoboxing will be the default behavior in
1419 * VMs running Java versions &gt; 1.5.
1420 * </p>
1421 *
1422 * @param classArray the array of Classes to check, may be {@code null}
1423 * @param toClassArray the array of Classes to try to assign into, may be {@code null}
1424 * @return {@code true} if assignment possible
1425 */
1426 public static boolean isAssignable(final Class<?>[] classArray, final Class<?>... toClassArray) {
1427 return isAssignable(classArray, toClassArray, true);
1428 }
1429
1430 /**
1431 * <p>
1432 * Checks if an array of Classes can be assigned to another array of Classes.
1433 * </p>
1434 *
1435 * <p>
1436 * This method calls {@link #isAssignable(Class, Class) isAssignable} for each Class pair in the input arrays. It can be
1437 * used to check if a set of arguments (the first parameter) are suitably compatible with a set of method parameter
1438 * types (the second parameter).
1439 * </p>
1440 *
1441 * <p>
1442 * Unlike the {@link Class#isAssignableFrom(java.lang.Class)} method, this method takes into account widenings of
1443 * primitive classes and {@code null}s.
1444 * </p>
1445 *
1446 * <p>
1447 * Primitive widenings allow an int to be assigned to a {@code long}, {@code float} or {@code double}. This method
1448 * returns the correct result for these cases.
1449 * </p>
1450 *
1451 * <p>
1452 * {@code Null} may be assigned to any reference type. This method will return {@code true} if {@code null} is passed in
1453 * and the toClass is non-primitive.
1454 * </p>
1455 *
1456 * <p>
1457 * Specifically, this method tests whether the type represented by the specified {@code Class} parameter can be
1458 * converted to the type represented by this {@code Class} object via an identity conversion widening primitive or
1459 * widening reference conversion. See <em><a href="http://docs.oracle.com/javase/specs/">The Java Language
1460 * Specification</a></em>, sections 5.1.1, 5.1.2 and 5.1.4 for details.
1461 * </p>
1462 *
1463 * @param classArray the array of Classes to check, may be {@code null}
1464 * @param toClassArray the array of Classes to try to assign into, may be {@code null}
1465 * @param autoboxing whether to use implicit autoboxing/unboxing between primitives and wrappers
1466 * @return {@code true} if assignment possible
1467 */
1468 public static boolean isAssignable(Class<?>[] classArray, Class<?>[] toClassArray, final boolean autoboxing) {
1469 if (!ArrayUtils.isSameLength(classArray, toClassArray)) {
1470 return false;
1471 }
1472 if (classArray == null) {
1473 classArray = ArrayUtils.EMPTY_CLASS_ARRAY;
1474 }
1475 if (toClassArray == null) {
1476 toClassArray = ArrayUtils.EMPTY_CLASS_ARRAY;
1477 }
1478 for (int i = 0; i < classArray.length; i++) {
1479 if (!isAssignable(classArray[i], toClassArray[i], autoboxing)) {
1480 return false;
1481 }
1482 }
1483 return true;
1484 }
1485
1486 /**
1487 * <p>
1488 * Is the specified class an inner class or static nested class.
1489 * </p>
1490 *
1491 * @param cls the class to check, may be null
1492 * @return {@code true} if the class is an inner or static nested class, false if not or {@code null}
1493 */
1494 public static boolean isInnerClass(final Class<?> cls) {
1495 return cls != null && cls.getEnclosingClass() != null;
1496 }
1497
1498 /**
1499 * Returns whether the given {@code type} is a primitive or primitive wrapper ({@link Boolean}, {@link Byte},
1500 * {@link Character}, {@link Short}, {@link Integer}, {@link Long}, {@link Double}, {@link Float}).
1501 *
1502 * @param type The class to query or null.
1503 * @return true if the given {@code type} is a primitive or primitive wrapper ({@link Boolean}, {@link Byte},
1504 * {@link Character}, {@link Short}, {@link Integer}, {@link Long}, {@link Double}, {@link Float}).
1505 * @since 3.1
1506 */
1507 public static boolean isPrimitiveOrWrapper(final Class<?> type) {
1508 if (type == null) {
1509 return false;
1510 }
1511 return type.isPrimitive() || isPrimitiveWrapper(type);
1512 }
1513
1514 /**
1515 * Returns whether the given {@code type} is a primitive wrapper ({@link Boolean}, {@link Byte}, {@link Character},
1516 * {@link Short}, {@link Integer}, {@link Long}, {@link Double}, {@link Float}).
1517 *
1518 * @param type The class to query or null.
1519 * @return true if the given {@code type} is a primitive wrapper ({@link Boolean}, {@link Byte}, {@link Character},
1520 * {@link Short}, {@link Integer}, {@link Long}, {@link Double}, {@link Float}).
1521 * @since 3.1
1522 */
1523 public static boolean isPrimitiveWrapper(final Class<?> type) {
1524 return wrapperPrimitiveMap.containsKey(type);
1525 }
1526
1527 /**
1528 * <p>
1529 * Converts the specified array of primitive Class objects to an array of its corresponding wrapper Class objects.
1530 * </p>
1531 *
1532 * @param classes the class array to convert, may be null or empty
1533 * @return an array which contains for each given class, the wrapper class or the original class if class is not a
1534 * primitive. {@code null} if null input. Empty array if an empty array passed in.
1535 * @since 2.1
1536 */
1537 public static Class<?>[] primitivesToWrappers(final Class<?>... classes) {
1538 if (classes == null) {
1539 return null;
1540 }
1541
1542 if (classes.length == 0) {
1543 return classes;
1544 }
1545
1546 final Class<?>[] convertedClasses = new Class[classes.length];
1547 for (int i = 0; i < classes.length; i++) {
1548 convertedClasses[i] = primitiveToWrapper(classes[i]);
1549 }
1550 return convertedClasses;
1551 }
1552
1553 /**
1554 * <p>
1555 * Converts the specified primitive Class object to its corresponding wrapper Class object.
1556 * </p>
1557 *
1558 * <p>
1559 * NOTE: From v2.2, this method handles {@code Void.TYPE}, returning {@code Void.TYPE}.
1560 * </p>
1561 *
1562 * @param cls the class to convert, may be null
1563 * @return the wrapper class for {@code cls} or {@code cls} if {@code cls} is not a primitive. {@code null} if null
1564 * input.
1565 * @since 2.1
1566 */
1567 public static Class<?> primitiveToWrapper(final Class<?> cls) {
1568 Class<?> convertedClass = cls;
1569 if (cls != null && cls.isPrimitive()) {
1570 convertedClass = primitiveWrapperMap.get(cls);
1571 }
1572 return convertedClass;
1573 }
1574
1575 /**
1576 * Converts a class name to a JLS style class name.
1577 *
1578 * @param className the class name
1579 * @return the converted name
1580 */
1581 private static String toCanonicalName(String className) {
1582 className = StringUtils.deleteWhitespace(className);
1583 Validate.notNull(className, "className");
1584 if (className.endsWith("[]")) {
1585 final StringBuilder classNameBuffer = new StringBuilder();
1586 while (className.endsWith("[]")) {
1587 className = className.substring(0, className.length() - 2);
1588 classNameBuffer.append("[");
1589 }
1590 final String abbreviation = abbreviationMap.get(className);
1591 if (abbreviation != null) {
1592 classNameBuffer.append(abbreviation);
1593 } else {
1594 classNameBuffer.append("L").append(className).append(";");
1595 }
1596 className = classNameBuffer.toString();
1597 }
1598 return className;
1599 }
1600
1601 /**
1602 * <p>
1603 * Converts an array of {@code Object} in to an array of {@code Class} objects. If any of these objects is null, a null
1604 * element will be inserted into the array.
1605 * </p>
1606 *
1607 * <p>
1608 * This method returns {@code null} for a {@code null} input array.
1609 * </p>
1610 *
1611 * @param array an {@code Object} array
1612 * @return a {@code Class} array, {@code null} if null array input
1613 * @since 2.4
1614 */
1615 public static Class<?>[] toClass(final Object... array) {
1616 if (array == null) {
1617 return null;
1618 }
1619 if (array.length == 0) {
1620 return ArrayUtils.EMPTY_CLASS_ARRAY;
1621 }
1622 final Class<?>[] classes = new Class[array.length];
1623 for (int i = 0; i < array.length; i++) {
1624 classes[i] = array[i] == null ? null : array[i].getClass();
1625 }
1626 return classes;
1627 }
1628
1629 /**
1630 * <p>
1631 * Decides if the part that was just copied to its destination location in the work array can be kept as it was copied
1632 * or must be abbreviated. It must be kept when the part is the last one, which is the simple name of the class. In this
1633 * case the {@code source} index, from where the characters are copied points one position after the last character,
1634 * a.k.a. {@code source ==
1635 * originalLength}
1636 * </p>
1637 *
1638 * <p>
1639 * If the part is not the last one then it can be kept unabridged if the number of the characters copied so far plus the
1640 * character that are to be copied is less than or equal to the desired length.
1641 * </p>
1642 *
1643 * @param runAheadTarget the target index (where the characters were copied to) pointing after the last character copied
1644 * when the current part was copied
1645 * @param source the source index (where the characters were copied from) pointing after the last character copied when
1646 * the current part was copied
1647 * @param originalLength the original length of the class full name, which is abbreviated
1648 * @param desiredLength the desired length of the abbreviated class name
1649 * @return {@code true} if it can be kept in its original length {@code false} if the current part has to be abbreviated
1650 * and
1651 */
1652 private static boolean useFull(final int runAheadTarget, final int source, final int originalLength, final int desiredLength) {
1653 return source >= originalLength || runAheadTarget + originalLength - source <= desiredLength;
1654 }
1655
1656 /**
1657 * <p>
1658 * Converts the specified array of wrapper Class objects to an array of its corresponding primitive Class objects.
1659 * </p>
1660 *
1661 * <p>
1662 * This method invokes {@code wrapperToPrimitive()} for each element of the passed in array.
1663 * </p>
1664 *
1665 * @param classes the class array to convert, may be null or empty
1666 * @return an array which contains for each given class, the primitive class or <b>null</b> if the original class is not
1667 * a wrapper class. {@code null} if null input. Empty array if an empty array passed in.
1668 * @see #wrapperToPrimitive(Class)
1669 * @since 2.4
1670 */
1671 public static Class<?>[] wrappersToPrimitives(final Class<?>... classes) {
1672 if (classes == null) {
1673 return null;
1674 }
1675
1676 if (classes.length == 0) {
1677 return classes;
1678 }
1679
1680 final Class<?>[] convertedClasses = new Class[classes.length];
1681 for (int i = 0; i < classes.length; i++) {
1682 convertedClasses[i] = wrapperToPrimitive(classes[i]);
1683 }
1684 return convertedClasses;
1685 }
1686
1687 /**
1688 * <p>
1689 * Converts the specified wrapper class to its corresponding primitive class.
1690 * </p>
1691 *
1692 * <p>
1693 * This method is the counter part of {@code primitiveToWrapper()}. If the passed in class is a wrapper class for a
1694 * primitive type, this primitive type will be returned (e.g. {@code Integer.TYPE} for {@code Integer.class}). For other
1695 * classes, or if the parameter is <b>null</b>, the return value is <b>null</b>.
1696 * </p>
1697 *
1698 * @param cls the class to convert, may be <b>null</b>
1699 * @return the corresponding primitive type if {@code cls} is a wrapper class, <b>null</b> otherwise
1700 * @see #primitiveToWrapper(Class)
1701 * @since 2.4
1702 */
1703 public static Class<?> wrapperToPrimitive(final Class<?> cls) {
1704 return wrapperPrimitiveMap.get(cls);
1705 }
1706
1707 /**
1708 * <p>
1709 * ClassUtils instances should NOT be constructed in standard programming. Instead, the class should be used as
1710 * {@code ClassUtils.getShortClassName(cls)}.
1711 * </p>
1712 *
1713 * <p>
1714 * This constructor is public to permit tools that require a JavaBean instance to operate.
1715 * </p>
1716 */
1717 public ClassUtils() {
1718 }
1719
15651720 }
2222 import java.util.LinkedHashMap;
2323 import java.util.List;
2424 import java.util.Map;
25 import java.util.function.Function;
2526
2627 /**
2728 * <p>Utility library to provide helper methods for Java enums.</p>
3233 */
3334 public class EnumUtils {
3435
36 private static final String CANNOT_STORE_S_S_VALUES_IN_S_BITS = "Cannot store %s %s values in %s bits";
37 private static final String ENUM_CLASS_MUST_BE_DEFINED = "EnumClass must be defined.";
3538 private static final String NULL_ELEMENTS_NOT_PERMITTED = "null elements not permitted";
36 private static final String CANNOT_STORE_S_S_VALUES_IN_S_BITS = "Cannot store %s %s values in %s bits";
3739 private static final String S_DOES_NOT_SEEM_TO_BE_AN_ENUM_TYPE = "%s does not seem to be an Enum type";
38 private static final String ENUM_CLASS_MUST_BE_DEFINED = "EnumClass must be defined.";
3940
4041 /**
4142 * Validate {@code enumClass}.
251252 * @return the enum, default enum if not found
252253 * @since 3.10
253254 */
254 public static <E extends Enum<E>> E getEnumIgnoreCase(final Class<E> enumClass, final String enumName, final E defaultEnum) {
255 public static <E extends Enum<E>> E getEnumIgnoreCase(final Class<E> enumClass, final String enumName,
256 final E defaultEnum) {
257 return getFirstEnumIgnoreCase(enumClass, enumName, Enum::name, defaultEnum);
258 }
259
260 /**
261 * <p>Gets the enum for the class, returning {@code defaultEnum} if not found.</p>
262 *
263 * <p>This method differs from {@link Enum#valueOf} in that it does not throw an exception
264 * for an invalid enum name and performs case insensitive matching of the name.</p>
265 *
266 * @param <E> the type of the enumeration
267 * @param enumClass the class of the enum to query, not null
268 * @param enumName the enum name, null returns default enum
269 * @param stringFunction the function that gets the string for an enum for comparison to {@code enumName}.
270 * @param defaultEnum the default enum
271 * @return the enum, default enum if not found
272 * @since 3.13.0
273 */
274 public static <E extends Enum<E>> E getFirstEnumIgnoreCase(final Class<E> enumClass, final String enumName,
275 final Function<E, String> stringFunction, final E defaultEnum) {
255276 if (enumName == null || !enumClass.isEnum()) {
256277 return defaultEnum;
257278 }
258279 for (final E each : enumClass.getEnumConstants()) {
259 if (each.name().equalsIgnoreCase(enumName)) {
280 if (enumName.equalsIgnoreCase(stringFunction.apply(each))) {
260281 return each;
261282 }
262283 }
291312 map.put(e.name(), e);
292313 }
293314 return map;
315 }
316
317 /**
318 * <p>
319 * Gets the enum for the class in a system property, returning {@code defaultEnum} if not found.
320 * </p>
321 *
322 * <p>
323 * This method differs from {@link Enum#valueOf} in that it does not throw an exception for an invalid enum name.
324 * </p>
325 *
326 * @param <E> the type of the enumeration
327 * @param enumClass the class of the enum to query, not null
328 * @param propName the system property key for the enum name, null returns default enum
329 * @param defaultEnum the default enum
330 * @return the enum, default enum if not found
331 * @since 3.13.0
332 */
333 public static <E extends Enum<E>> E getEnumSystemProperty(final Class<E> enumClass, final String propName,
334 final E defaultEnum) {
335 return enumClass == null || propName == null ? defaultEnum
336 : getEnum(enumClass, System.getProperty(propName), defaultEnum);
294337 }
295338
296339 /**
4141 *
4242 * <pre>
4343 * {@code
44 * Consumer<java.lang.reflect.Method> consumer = (m) -> {
44 * Consumer<java.lang.reflect.Method> consumer = m -> {
4545 * try {
4646 * m.invoke(o, args);
4747 * } catch (Throwable t) {
522522 Objects.requireNonNull(throwable, "throwable");
523523 if (throwable instanceof RuntimeException) {
524524 throw (RuntimeException) throwable;
525 } else if (throwable instanceof Error) {
525 }
526 if (throwable instanceof Error) {
526527 throw (Error) throwable;
527 } else if (throwable instanceof IOException) {
528 }
529 if (throwable instanceof IOException) {
528530 throw new UncheckedIOException((IOException) throwable);
529 } else {
530 throw new UndeclaredThrowableException(throwable);
531 }
531 }
532 throw new UndeclaredThrowableException(throwable);
532533 }
533534
534535 /**
8080 JAVA_1_9(9.0f, "9"),
8181
8282 /**
83 * Java 9
83 * Java 9.
8484 *
8585 * @since 3.5
8686 */
8787 JAVA_9(9.0f, "9"),
8888
8989 /**
90 * Java 10
90 * Java 10.
9191 *
9292 * @since 3.7
9393 */
9494 JAVA_10(10.0f, "10"),
9595
9696 /**
97 * Java 11
97 * Java 11.
9898 *
9999 * @since 3.8
100100 */
101101 JAVA_11(11.0f, "11"),
102102
103103 /**
104 * Java 12
104 * Java 12.
105105 *
106106 * @since 3.9
107107 */
108108 JAVA_12(12.0f, "12"),
109109
110110 /**
111 * Java 13
111 * Java 13.
112112 *
113113 * @since 3.9
114114 */
115115 JAVA_13(13.0f, "13"),
116116
117117 /**
118 * Java 14
118 * Java 14.
119119 *
120120 * @since 3.11
121121 */
122122 JAVA_14(14.0f, "14"),
123123
124124 /**
125 * Java 15
125 * Java 15.
126126 *
127127 * @since 3.11
128128 */
129129 JAVA_15(15.0f, "15"),
130130
131131 /**
132 * Java 16
132 * Java 16.
133133 *
134134 * @since 3.11
135135 */
136136 JAVA_16(16.0f, "16"),
137
138 /**
139 * Java 17.
140 *
141 * @since 3.12.0
142 */
143 JAVA_17(17.0f, "17"),
137144
138145 /**
139146 * The most recent java version. Mainly introduced to avoid to break when a new version of Java is used.
161168 this.name = name;
162169 }
163170
164 //-----------------------------------------------------------------------
165171 /**
166172 * <p>Whether this version of Java is at least the version of Java passed in.</p>
167173 *
175181 return this.value >= requiredVersion.value;
176182 }
177183
178 //-----------------------------------------------------------------------
179184 /**
180185 * <p>Whether this version of Java is at most the version of Java passed in.</p>
181186 *
209214 * corresponding constant of this enumeration class. This method is used
210215 * internally.
211216 *
212 * @param nom the Java version as string
217 * @param versionStr the Java version as string
213218 * @return the corresponding enumeration constant or <b>null</b> if the
214219 * version is unknown
215220 */
216 static JavaVersion get(final String nom) {
217 if (nom == null) {
221 static JavaVersion get(final String versionStr) {
222 if (versionStr == null) {
218223 return null;
219 } else if ("0.9".equals(nom)) {
224 }
225 switch (versionStr) {
226 case "0.9":
220227 return JAVA_0_9;
221 } else if ("1.1".equals(nom)) {
228 case "1.1":
222229 return JAVA_1_1;
223 } else if ("1.2".equals(nom)) {
230 case "1.2":
224231 return JAVA_1_2;
225 } else if ("1.3".equals(nom)) {
232 case "1.3":
226233 return JAVA_1_3;
227 } else if ("1.4".equals(nom)) {
234 case "1.4":
228235 return JAVA_1_4;
229 } else if ("1.5".equals(nom)) {
236 case "1.5":
230237 return JAVA_1_5;
231 } else if ("1.6".equals(nom)) {
238 case "1.6":
232239 return JAVA_1_6;
233 } else if ("1.7".equals(nom)) {
240 case "1.7":
234241 return JAVA_1_7;
235 } else if ("1.8".equals(nom)) {
242 case "1.8":
236243 return JAVA_1_8;
237 } else if ("9".equals(nom)) {
244 case "9":
238245 return JAVA_9;
239 } else if ("10".equals(nom)) {
246 case "10":
240247 return JAVA_10;
241 } else if ("11".equals(nom)) {
248 case "11":
242249 return JAVA_11;
243 } else if ("12".equals(nom)) {
250 case "12":
244251 return JAVA_12;
245 } else if ("13".equals(nom)) {
252 case "13":
246253 return JAVA_13;
247 } else if ("14".equals(nom)) {
254 case "14":
248255 return JAVA_14;
249 } else if ("15".equals(nom)) {
256 case "15":
250257 return JAVA_15;
251 } else if ("16".equals(nom)) {
258 case "16":
252259 return JAVA_16;
253 }
254 final float v = toFloatVersion(nom);
255 if ((v - 1.) < 1.) { // then we need to check decimals > .9
256 final int firstComma = Math.max(nom.indexOf('.'), nom.indexOf(','));
257 final int end = Math.max(nom.length(), nom.indexOf(',', firstComma));
258 if (Float.parseFloat(nom.substring(firstComma + 1, end)) > .9f) {
260 case "17":
261 return JAVA_17;
262 default:
263 final float v = toFloatVersion(versionStr);
264 if ((v - 1.) < 1.) { // then we need to check decimals > .9
265 final int firstComma = Math.max(versionStr.indexOf('.'), versionStr.indexOf(','));
266 final int end = Math.max(versionStr.length(), versionStr.indexOf(',', firstComma));
267 if (Float.parseFloat(versionStr.substring(firstComma + 1, end)) > .9f) {
268 return JAVA_RECENT;
269 }
270 } else if (v > 10) {
259271 return JAVA_RECENT;
260272 }
261 } else if (v > 10) {
262 return JAVA_RECENT;
263 }
264 return null;
265 }
266
267 //-----------------------------------------------------------------------
273 return null;
274 }
275 }
276
268277 /**
269278 * <p>The string value is overridden to return the standard name.</p>
270279 *
298307 */
299308 private static float toFloatVersion(final String value) {
300309 final int defaultReturnValue = -1;
301 if (value.contains(".")) {
302 final String[] toParse = value.split("\\.");
303 if (toParse.length >= 2) {
304 return NumberUtils.toFloat(toParse[0] + '.' + toParse[1], defaultReturnValue);
305 }
306 } else {
310 if (!value.contains(".")) {
307311 return NumberUtils.toFloat(value, defaultReturnValue);
308312 }
313 final String[] toParse = value.split("\\.");
314 if (toParse.length >= 2) {
315 return NumberUtils.toFloat(toParse[0] + '.' + toParse[1], defaultReturnValue);
316 }
309317 return defaultReturnValue;
310318 }
311319 }
3636 */
3737 public class LocaleUtils {
3838
39 // class to avoid synchronization (Init on demand)
40 static class SyncAvoid {
41 /** Unmodifiable list of available locales. */
42 private static final List<Locale> AVAILABLE_LOCALE_LIST;
43 /** Unmodifiable set of available locales. */
44 private static final Set<Locale> AVAILABLE_LOCALE_SET;
45
46 static {
47 final List<Locale> list = new ArrayList<>(Arrays.asList(Locale.getAvailableLocales())); // extra safe
48 AVAILABLE_LOCALE_LIST = Collections.unmodifiableList(list);
49 AVAILABLE_LOCALE_SET = Collections.unmodifiableSet(new HashSet<>(list));
50 }
51 }
52
3953 /** Concurrent map of language locales by country. */
4054 private static final ConcurrentMap<String, List<Locale>> cLanguagesByCountry =
4155 new ConcurrentHashMap<>();
4559 new ConcurrentHashMap<>();
4660
4761 /**
48 * <p>{@code LocaleUtils} instances should NOT be constructed in standard programming.
49 * Instead, the class should be used as {@code LocaleUtils.toLocale("en_GB");}.</p>
50 *
51 * <p>This constructor is public to permit tools that require a JavaBean instance
52 * to operate.</p>
53 */
54 public LocaleUtils() {
55 super();
56 }
57
58 //-----------------------------------------------------------------------
59 /**
60 * <p>Converts a String to a Locale.</p>
61 *
62 * <p>This method takes the string format of a locale and creates the
63 * locale object from it.</p>
64 *
65 * <pre>
66 * LocaleUtils.toLocale("") = new Locale("", "")
67 * LocaleUtils.toLocale("en") = new Locale("en", "")
68 * LocaleUtils.toLocale("en_GB") = new Locale("en", "GB")
69 * LocaleUtils.toLocale("en_001") = new Locale("en", "001")
70 * LocaleUtils.toLocale("en_GB_xxx") = new Locale("en", "GB", "xxx") (#)
71 * </pre>
72 *
73 * <p>(#) The behavior of the JDK variant constructor changed between JDK1.3 and JDK1.4.
74 * In JDK1.3, the constructor upper cases the variant, in JDK1.4, it doesn't.
75 * Thus, the result from getVariant() may vary depending on your JDK.</p>
76 *
77 * <p>This method validates the input strictly.
78 * The language code must be lowercase.
79 * The country code must be uppercase.
80 * The separator must be an underscore.
81 * The length must be correct.
82 * </p>
83 *
84 * @param str the locale String to convert, null returns null
85 * @return a Locale, null if null input
86 * @throws IllegalArgumentException if the string is an invalid format
87 * @see Locale#forLanguageTag(String)
88 */
89 public static Locale toLocale(final String str) {
90 if (str == null) {
91 return null;
92 }
93 if (str.isEmpty()) { // LANG-941 - JDK 8 introduced an empty locale where all fields are blank
94 return new Locale(StringUtils.EMPTY, StringUtils.EMPTY);
95 }
96 if (str.contains("#")) { // LANG-879 - Cannot handle Java 7 script & extensions
97 throw new IllegalArgumentException("Invalid locale format: " + str);
98 }
99 final int len = str.length();
100 if (len < 2) {
101 throw new IllegalArgumentException("Invalid locale format: " + str);
102 }
103 final char ch0 = str.charAt(0);
104 if (ch0 == '_') {
105 if (len < 3) {
106 throw new IllegalArgumentException("Invalid locale format: " + str);
107 }
108 final char ch1 = str.charAt(1);
109 final char ch2 = str.charAt(2);
110 if (!Character.isUpperCase(ch1) || !Character.isUpperCase(ch2)) {
111 throw new IllegalArgumentException("Invalid locale format: " + str);
112 }
113 if (len == 3) {
114 return new Locale(StringUtils.EMPTY, str.substring(1, 3));
115 }
116 if (len < 5) {
117 throw new IllegalArgumentException("Invalid locale format: " + str);
118 }
119 if (str.charAt(3) != '_') {
120 throw new IllegalArgumentException("Invalid locale format: " + str);
121 }
122 return new Locale(StringUtils.EMPTY, str.substring(1, 3), str.substring(4));
123 }
124
125 return parseLocale(str);
126 }
127
128 /**
129 * Tries to parse a locale from the given String.
130 *
131 * @param str the String to parse a locale from.
132 * @return a Locale instance parsed from the given String.
133 * @throws IllegalArgumentException if the given String can not be parsed.
134 */
135 private static Locale parseLocale(final String str) {
136 if (isISO639LanguageCode(str)) {
137 return new Locale(str);
138 }
139
140 final String[] segments = str.split("_", -1);
141 final String language = segments[0];
142 if (segments.length == 2) {
143 final String country = segments[1];
144 if (isISO639LanguageCode(language) && isISO3166CountryCode(country) ||
145 isNumericAreaCode(country)) {
146 return new Locale(language, country);
147 }
148 } else if (segments.length == 3) {
149 final String country = segments[1];
150 final String variant = segments[2];
151 if (isISO639LanguageCode(language) &&
152 (country.isEmpty() || isISO3166CountryCode(country) || isNumericAreaCode(country)) &&
153 !variant.isEmpty()) {
154 return new Locale(language, country, variant);
155 }
156 }
157 throw new IllegalArgumentException("Invalid locale format: " + str);
158 }
159
160 /**
161 * Checks whether the given String is a ISO 639 compliant language code.
162 *
163 * @param str the String to check.
164 * @return true, if the given String is a ISO 639 compliant language code.
165 */
166 private static boolean isISO639LanguageCode(final String str) {
167 return StringUtils.isAllLowerCase(str) && (str.length() == 2 || str.length() == 3);
168 }
169
170 /**
171 * Checks whether the given String is a ISO 3166 alpha-2 country code.
172 *
173 * @param str the String to check
174 * @return true, is the given String is a ISO 3166 compliant country code.
175 */
176 private static boolean isISO3166CountryCode(final String str) {
177 return StringUtils.isAllUpperCase(str) && str.length() == 2;
178 }
179
180 /**
181 * Checks whether the given String is a UN M.49 numeric area code.
182 *
183 * @param str the String to check
184 * @return true, is the given String is a UN M.49 numeric area code.
185 */
186 private static boolean isNumericAreaCode(final String str) {
187 return StringUtils.isNumeric(str) && str.length() == 3;
188 }
189
190 //-----------------------------------------------------------------------
191 /**
192 * <p>Obtains the list of locales to search through when performing
193 * a locale search.</p>
194 *
195 * <pre>
196 * localeLookupList(Locale("fr", "CA", "xxx"))
197 * = [Locale("fr", "CA", "xxx"), Locale("fr", "CA"), Locale("fr")]
198 * </pre>
199 *
200 * @param locale the locale to start from
201 * @return the unmodifiable list of Locale objects, 0 being locale, not null
202 */
203 public static List<Locale> localeLookupList(final Locale locale) {
204 return localeLookupList(locale, locale);
205 }
206
207 //-----------------------------------------------------------------------
208 /**
209 * <p>Obtains the list of locales to search through when performing
210 * a locale search.</p>
211 *
212 * <pre>
213 * localeLookupList(Locale("fr", "CA", "xxx"), Locale("en"))
214 * = [Locale("fr", "CA", "xxx"), Locale("fr", "CA"), Locale("fr"), Locale("en"]
215 * </pre>
216 *
217 * <p>The result list begins with the most specific locale, then the
218 * next more general and so on, finishing with the default locale.
219 * The list will never contain the same locale twice.</p>
220 *
221 * @param locale the locale to start from, null returns empty list
222 * @param defaultLocale the default locale to use if no other is found
223 * @return the unmodifiable list of Locale objects, 0 being locale, not null
224 */
225 public static List<Locale> localeLookupList(final Locale locale, final Locale defaultLocale) {
226 final List<Locale> list = new ArrayList<>(4);
227 if (locale != null) {
228 list.add(locale);
229 if (!locale.getVariant().isEmpty()) {
230 list.add(new Locale(locale.getLanguage(), locale.getCountry()));
231 }
232 if (!locale.getCountry().isEmpty()) {
233 list.add(new Locale(locale.getLanguage(), StringUtils.EMPTY));
234 }
235 if (!list.contains(defaultLocale)) {
236 list.add(defaultLocale);
237 }
238 }
239 return Collections.unmodifiableList(list);
240 }
241
242 //-----------------------------------------------------------------------
243 /**
24462 * <p>Obtains an unmodifiable list of installed locales.</p>
24563 *
24664 * <p>This method is a wrapper around {@link Locale#getAvailableLocales()}.
25371 return SyncAvoid.AVAILABLE_LOCALE_LIST;
25472 }
25573
256 //-----------------------------------------------------------------------
25774 /**
25875 * <p>Obtains an unmodifiable set of installed locales.</p>
25976 *
26784 return SyncAvoid.AVAILABLE_LOCALE_SET;
26885 }
26986
270 //-----------------------------------------------------------------------
271 /**
272 * <p>Checks if the locale specified is in the list of available locales.</p>
273 *
274 * @param locale the Locale object to check if it is available
275 * @return true if the locale is a known locale
276 */
277 public static boolean isAvailableLocale(final Locale locale) {
278 return availableLocaleList().contains(locale);
279 }
280
281 //-----------------------------------------------------------------------
282 /**
283 * <p>Obtains the list of languages supported for a given country.</p>
284 *
285 * <p>This method takes a country code and searches to find the
286 * languages available for that country. Variant locales are removed.</p>
287 *
288 * @param countryCode the 2 letter country code, null returns empty
289 * @return an unmodifiable List of Locale objects, not null
290 */
291 public static List<Locale> languagesByCountry(final String countryCode) {
292 if (countryCode == null) {
293 return Collections.emptyList();
294 }
295 List<Locale> langs = cLanguagesByCountry.get(countryCode);
296 if (langs == null) {
297 langs = new ArrayList<>();
298 final List<Locale> locales = availableLocaleList();
299 for (final Locale locale : locales) {
300 if (countryCode.equals(locale.getCountry()) &&
301 locale.getVariant().isEmpty()) {
302 langs.add(locale);
303 }
304 }
305 langs = Collections.unmodifiableList(langs);
306 cLanguagesByCountry.putIfAbsent(countryCode, langs);
307 langs = cLanguagesByCountry.get(countryCode);
308 }
309 return langs;
310 }
311
312 //-----------------------------------------------------------------------
31387 /**
31488 * <p>Obtains the list of countries supported for a given language.</p>
31589 *
341115 return countries;
342116 }
343117
344 //-----------------------------------------------------------------------
345 // class to avoid synchronization (Init on demand)
346 static class SyncAvoid {
347 /** Unmodifiable list of available locales. */
348 private static final List<Locale> AVAILABLE_LOCALE_LIST;
349 /** Unmodifiable set of available locales. */
350 private static final Set<Locale> AVAILABLE_LOCALE_SET;
351
352 static {
353 final List<Locale> list = new ArrayList<>(Arrays.asList(Locale.getAvailableLocales())); // extra safe
354 AVAILABLE_LOCALE_LIST = Collections.unmodifiableList(list);
355 AVAILABLE_LOCALE_SET = Collections.unmodifiableSet(new HashSet<>(list));
356 }
118 /**
119 * <p>Checks if the locale specified is in the list of available locales.</p>
120 *
121 * @param locale the Locale object to check if it is available
122 * @return true if the locale is a known locale
123 */
124 public static boolean isAvailableLocale(final Locale locale) {
125 return availableLocaleList().contains(locale);
126 }
127
128 /**
129 * Checks whether the given String is a ISO 3166 alpha-2 country code.
130 *
131 * @param str the String to check
132 * @return true, is the given String is a ISO 3166 compliant country code.
133 */
134 private static boolean isISO3166CountryCode(final String str) {
135 return StringUtils.isAllUpperCase(str) && str.length() == 2;
136 }
137
138 /**
139 * Checks whether the given String is a ISO 639 compliant language code.
140 *
141 * @param str the String to check.
142 * @return true, if the given String is a ISO 639 compliant language code.
143 */
144 private static boolean isISO639LanguageCode(final String str) {
145 return StringUtils.isAllLowerCase(str) && (str.length() == 2 || str.length() == 3);
146 }
147
148 /**
149 * Checks whether the given String is a UN M.49 numeric area code.
150 *
151 * @param str the String to check
152 * @return true, is the given String is a UN M.49 numeric area code.
153 */
154 private static boolean isNumericAreaCode(final String str) {
155 return StringUtils.isNumeric(str) && str.length() == 3;
156 }
157
158 /**
159 * <p>Obtains the list of languages supported for a given country.</p>
160 *
161 * <p>This method takes a country code and searches to find the
162 * languages available for that country. Variant locales are removed.</p>
163 *
164 * @param countryCode the 2 letter country code, null returns empty
165 * @return an unmodifiable List of Locale objects, not null
166 */
167 public static List<Locale> languagesByCountry(final String countryCode) {
168 if (countryCode == null) {
169 return Collections.emptyList();
170 }
171 List<Locale> langs = cLanguagesByCountry.get(countryCode);
172 if (langs == null) {
173 langs = new ArrayList<>();
174 final List<Locale> locales = availableLocaleList();
175 for (final Locale locale : locales) {
176 if (countryCode.equals(locale.getCountry()) &&
177 locale.getVariant().isEmpty()) {
178 langs.add(locale);
179 }
180 }
181 langs = Collections.unmodifiableList(langs);
182 cLanguagesByCountry.putIfAbsent(countryCode, langs);
183 langs = cLanguagesByCountry.get(countryCode);
184 }
185 return langs;
186 }
187
188 /**
189 * <p>Obtains the list of locales to search through when performing
190 * a locale search.</p>
191 *
192 * <pre>
193 * localeLookupList(Locale("fr", "CA", "xxx"))
194 * = [Locale("fr", "CA", "xxx"), Locale("fr", "CA"), Locale("fr")]
195 * </pre>
196 *
197 * @param locale the locale to start from
198 * @return the unmodifiable list of Locale objects, 0 being locale, not null
199 */
200 public static List<Locale> localeLookupList(final Locale locale) {
201 return localeLookupList(locale, locale);
202 }
203
204 /**
205 * <p>Obtains the list of locales to search through when performing
206 * a locale search.</p>
207 *
208 * <pre>
209 * localeLookupList(Locale("fr", "CA", "xxx"), Locale("en"))
210 * = [Locale("fr", "CA", "xxx"), Locale("fr", "CA"), Locale("fr"), Locale("en"]
211 * </pre>
212 *
213 * <p>The result list begins with the most specific locale, then the
214 * next more general and so on, finishing with the default locale.
215 * The list will never contain the same locale twice.</p>
216 *
217 * @param locale the locale to start from, null returns empty list
218 * @param defaultLocale the default locale to use if no other is found
219 * @return the unmodifiable list of Locale objects, 0 being locale, not null
220 */
221 public static List<Locale> localeLookupList(final Locale locale, final Locale defaultLocale) {
222 final List<Locale> list = new ArrayList<>(4);
223 if (locale != null) {
224 list.add(locale);
225 if (!locale.getVariant().isEmpty()) {
226 list.add(new Locale(locale.getLanguage(), locale.getCountry()));
227 }
228 if (!locale.getCountry().isEmpty()) {
229 list.add(new Locale(locale.getLanguage(), StringUtils.EMPTY));
230 }
231 if (!list.contains(defaultLocale)) {
232 list.add(defaultLocale);
233 }
234 }
235 return Collections.unmodifiableList(list);
236 }
237
238 /**
239 * Tries to parse a locale from the given String.
240 *
241 * @param str the String to parse a locale from.
242 * @return a Locale instance parsed from the given String.
243 * @throws IllegalArgumentException if the given String can not be parsed.
244 */
245 private static Locale parseLocale(final String str) {
246 if (isISO639LanguageCode(str)) {
247 return new Locale(str);
248 }
249
250 final String[] segments = str.split("_", -1);
251 final String language = segments[0];
252 if (segments.length == 2) {
253 final String country = segments[1];
254 if (isISO639LanguageCode(language) && isISO3166CountryCode(country) ||
255 isNumericAreaCode(country)) {
256 return new Locale(language, country);
257 }
258 } else if (segments.length == 3) {
259 final String country = segments[1];
260 final String variant = segments[2];
261 if (isISO639LanguageCode(language) &&
262 (country.isEmpty() || isISO3166CountryCode(country) || isNumericAreaCode(country)) &&
263 !variant.isEmpty()) {
264 return new Locale(language, country, variant);
265 }
266 }
267 throw new IllegalArgumentException("Invalid locale format: " + str);
268 }
269
270 /**
271 * Returns the given locale if non-{@code null}, otherwise {@link Locale#getDefault()}.
272 *
273 * @param locale a locale or {@code null}.
274 * @return the given locale if non-{@code null}, otherwise {@link Locale#getDefault()}.
275 * @since 3.12.0
276 */
277 public static Locale toLocale(final Locale locale) {
278 return locale != null ? locale : Locale.getDefault();
279 }
280
281 /**
282 * <p>Converts a String to a Locale.</p>
283 *
284 * <p>This method takes the string format of a locale and creates the
285 * locale object from it.</p>
286 *
287 * <pre>
288 * LocaleUtils.toLocale("") = new Locale("", "")
289 * LocaleUtils.toLocale("en") = new Locale("en", "")
290 * LocaleUtils.toLocale("en_GB") = new Locale("en", "GB")
291 * LocaleUtils.toLocale("en_001") = new Locale("en", "001")
292 * LocaleUtils.toLocale("en_GB_xxx") = new Locale("en", "GB", "xxx") (#)
293 * </pre>
294 *
295 * <p>(#) The behavior of the JDK variant constructor changed between JDK1.3 and JDK1.4.
296 * In JDK1.3, the constructor upper cases the variant, in JDK1.4, it doesn't.
297 * Thus, the result from getVariant() may vary depending on your JDK.</p>
298 *
299 * <p>This method validates the input strictly.
300 * The language code must be lowercase.
301 * The country code must be uppercase.
302 * The separator must be an underscore.
303 * The length must be correct.
304 * </p>
305 *
306 * @param str the locale String to convert, null returns null
307 * @return a Locale, null if null input
308 * @throws IllegalArgumentException if the string is an invalid format
309 * @see Locale#forLanguageTag(String)
310 */
311 public static Locale toLocale(final String str) {
312 if (str == null) {
313 return null;
314 }
315 if (str.isEmpty()) { // LANG-941 - JDK 8 introduced an empty locale where all fields are blank
316 return new Locale(StringUtils.EMPTY, StringUtils.EMPTY);
317 }
318 if (str.contains("#")) { // LANG-879 - Cannot handle Java 7 script & extensions
319 throw new IllegalArgumentException("Invalid locale format: " + str);
320 }
321 final int len = str.length();
322 if (len < 2) {
323 throw new IllegalArgumentException("Invalid locale format: " + str);
324 }
325 final char ch0 = str.charAt(0);
326 if (ch0 == '_') {
327 if (len < 3) {
328 throw new IllegalArgumentException("Invalid locale format: " + str);
329 }
330 final char ch1 = str.charAt(1);
331 final char ch2 = str.charAt(2);
332 if (!Character.isUpperCase(ch1) || !Character.isUpperCase(ch2)) {
333 throw new IllegalArgumentException("Invalid locale format: " + str);
334 }
335 if (len == 3) {
336 return new Locale(StringUtils.EMPTY, str.substring(1, 3));
337 }
338 if (len < 5) {
339 throw new IllegalArgumentException("Invalid locale format: " + str);
340 }
341 if (str.charAt(3) != '_') {
342 throw new IllegalArgumentException("Invalid locale format: " + str);
343 }
344 return new Locale(StringUtils.EMPTY, str.substring(1, 3), str.substring(4));
345 }
346
347 return parseLocale(str);
348 }
349
350 /**
351 * <p>{@code LocaleUtils} instances should NOT be constructed in standard programming.
352 * Instead, the class should be used as {@code LocaleUtils.toLocale("en_GB");}.</p>
353 *
354 * <p>This constructor is public to permit tools that require a JavaBean instance
355 * to operate.</p>
356 */
357 public LocaleUtils() {
357358 }
358359
359360 }
2020 import java.lang.reflect.Array;
2121 import java.lang.reflect.InvocationTargetException;
2222 import java.lang.reflect.Method;
23 import java.time.Duration;
2324 import java.util.Collection;
2425 import java.util.Collections;
2526 import java.util.Comparator;
2627 import java.util.HashMap;
2728 import java.util.Map;
29 import java.util.Objects;
2830 import java.util.TreeSet;
2931 import java.util.function.Supplier;
3032
3133 import org.apache.commons.lang3.exception.CloneFailedException;
34 import org.apache.commons.lang3.function.Suppliers;
3235 import org.apache.commons.lang3.mutable.MutableInt;
3336 import org.apache.commons.lang3.text.StrBuilder;
37 import org.apache.commons.lang3.time.DurationUtils;
3438
3539 /**
3640 * <p>Operations on {@code Object}.</p>
4751 // because it is part of the signature of deprecated methods
4852 public class ObjectUtils {
4953
50 // Null
51 //-----------------------------------------------------------------------
5254 /**
5355 * <p>Class used as a null placeholder where {@code null}
5456 * has another meaning.</p>
7476 * Restricted constructor - singleton.
7577 */
7678 Null() {
77 super();
7879 }
7980
8081 /**
107108 public static final Null NULL = new Null();
108109
109110 /**
110 * Checks if all values in the given array are {@code null}.
111 *
112 * <p>
113 * If all the values are {@code null} or the array is {@code null}
114 * or empty, then {@code true} is returned, otherwise {@code false} is returned.
115 * </p>
116 *
117 * <pre>
118 * ObjectUtils.allNull(*) = false
119 * ObjectUtils.allNull(*, null) = false
120 * ObjectUtils.allNull(null, *) = false
121 * ObjectUtils.allNull(null, null, *, *) = false
122 * ObjectUtils.allNull(null) = true
123 * ObjectUtils.allNull(null, null) = true
124 * </pre>
125 *
126 * @param values the values to test, may be {@code null} or empty
127 * @return {@code true} if all values in the array are {@code null}s,
128 * {@code false} if there is at least one non-null value in the array.
129 * @since 3.11
130 */
131 public static boolean allNull(final Object... values) {
132 return !anyNotNull(values);
133 }
134
135 /**
136111 * Checks if all values in the array are not {@code nulls}.
137112 *
138113 * <p>
172147 }
173148
174149 /**
150 * Checks if all values in the given array are {@code null}.
151 *
152 * <p>
153 * If all the values are {@code null} or the array is {@code null}
154 * or empty, then {@code true} is returned, otherwise {@code false} is returned.
155 * </p>
156 *
157 * <pre>
158 * ObjectUtils.allNull(*) = false
159 * ObjectUtils.allNull(*, null) = false
160 * ObjectUtils.allNull(null, *) = false
161 * ObjectUtils.allNull(null, null, *, *) = false
162 * ObjectUtils.allNull(null) = true
163 * ObjectUtils.allNull(null, null) = true
164 * </pre>
165 *
166 * @param values the values to test, may be {@code null} or empty
167 * @return {@code true} if all values in the array are {@code null}s,
168 * {@code false} if there is at least one non-null value in the array.
169 * @since 3.11
170 */
171 public static boolean allNull(final Object... values) {
172 return !anyNotNull(values);
173 }
174
175 /**
176 * Checks if any value in the given array is not {@code null}.
177 *
178 * <p>
179 * If all the values are {@code null} or the array is {@code null}
180 * or empty then {@code false} is returned. Otherwise {@code true} is returned.
181 * </p>
182 *
183 * <pre>
184 * ObjectUtils.anyNotNull(*) = true
185 * ObjectUtils.anyNotNull(*, null) = true
186 * ObjectUtils.anyNotNull(null, *) = true
187 * ObjectUtils.anyNotNull(null, null, *, *) = true
188 * ObjectUtils.anyNotNull(null) = false
189 * ObjectUtils.anyNotNull(null, null) = false
190 * </pre>
191 *
192 * @param values the values to test, may be {@code null} or empty
193 * @return {@code true} if there is at least one non-null value in the array,
194 * {@code false} if all values in the array are {@code null}s.
195 * If the array is {@code null} or empty {@code false} is also returned.
196 * @since 3.5
197 */
198 public static boolean anyNotNull(final Object... values) {
199 return firstNonNull(values) != null;
200 }
201
202 /**
175203 * Checks if any value in the given array is {@code null}.
176204 *
177205 * <p>
199227 return !allNotNull(values);
200228 }
201229
202 /**
203 * Checks if any value in the given array is not {@code null}.
204 *
205 * <p>
206 * If all the values are {@code null} or the array is {@code null}
207 * or empty then {@code false} is returned. Otherwise {@code true} is returned.
208 * </p>
209 *
210 * <pre>
211 * ObjectUtils.anyNotNull(*) = true
212 * ObjectUtils.anyNotNull(*, null) = true
213 * ObjectUtils.anyNotNull(null, *) = true
214 * ObjectUtils.anyNotNull(null, null, *, *) = true
215 * ObjectUtils.anyNotNull(null) = false
216 * ObjectUtils.anyNotNull(null, null) = false
217 * </pre>
218 *
219 * @param values the values to test, may be {@code null} or empty
220 * @return {@code true} if there is at least one non-null value in the array,
221 * {@code false} if all values in the array are {@code null}s.
222 * If the array is {@code null} or empty {@code false} is also returned.
223 * @since 3.5
224 */
225 public static boolean anyNotNull(final Object... values) {
226 return firstNonNull(values) != null;
227 }
228
229 // cloning
230 //-----------------------------------------------------------------------
231230 /**
232231 * <p>Clone an object.</p>
233232 *
326325 public static <T extends Comparable<? super T>> int compare(final T c1, final T c2, final boolean nullGreater) {
327326 if (c1 == c2) {
328327 return 0;
329 } else if (c1 == null) {
328 }
329 if (c1 == null) {
330330 return nullGreater ? 1 : -1;
331 } else if (c2 == null) {
331 }
332 if (c2 == null) {
332333 return nullGreater ? -1 : 1;
333334 }
334335 return c1.compareTo(c2);
600601 }
601602
602603 // Null-safe equals/hashCode
603 //-----------------------------------------------------------------------
604604 /**
605605 * <p>Compares two objects for equality, where either one or both
606606 * objects may be {@code null}.</p>
624624 */
625625 @Deprecated
626626 public static boolean equals(final Object object1, final Object object2) {
627 if (object1 == object2) {
628 return true;
629 }
630 if (object1 == null || object2 == null) {
631 return false;
632 }
633 return object1.equals(object2);
627 return Objects.equals(object1, object2);
634628 }
635629
636630 /**
665659 }
666660 }
667661 return null;
662 }
663
664 /**
665 * Delegates to {@link Object#getClass()} using generics.
666 *
667 * @param <T> The argument type or null.
668 * @param object The argument.
669 * @return The argument Class or null.
670 * @since 3.13.0
671 */
672 @SuppressWarnings("unchecked")
673 public static <T> Class<T> getClass(final T object) {
674 return object == null ? null : (Class<T>) object.getClass();
668675 }
669676
670677 /**
732739 * @since 3.10
733740 */
734741 public static <T> T getIfNull(final T object, final Supplier<T> defaultSupplier) {
735 return object != null ? object : defaultSupplier == null ? null : defaultSupplier.get();
742 return object != null ? object : Suppliers.get(defaultSupplier);
736743 }
737744
738745 /**
752759 */
753760 @Deprecated
754761 public static int hashCode(final Object obj) {
755 // hashCode(Object) retained for performance, as hash code is often critical
756 return obj == null ? 0 : obj.hashCode();
762 // hashCode(Object) for performance vs. hashCodeMulti(Object[]), as hash code is often critical
763 return Objects.hashCode(obj);
757764 }
758765
759766 /**
783790 int hash = 1;
784791 if (objects != null) {
785792 for (final Object object : objects) {
786 final int tmpHash = hashCode(object);
793 final int tmpHash = Objects.hashCode(object);
787794 hash = hash * 31 + tmpHash;
788795 }
789796 }
803810 *
804811 * @param appendable the appendable to append to
805812 * @param object the object to create a toString for
806 * @throws IOException if an I/O error occurs
813 * @throws IOException if an I/O error occurs.
807814 * @since 3.2
808815 */
809816 public static void identityToString(final Appendable appendable, final Object object) throws IOException {
810 Validate.notNull(object, "Cannot get the toString of a null object");
817 Validate.notNull(object, "object");
811818 appendable.append(object.getClass().getName())
812819 .append(AT_SIGN)
813820 .append(Integer.toHexString(System.identityHashCode(object)));
814821 }
815822
816 // Identity ToString
817 //-----------------------------------------------------------------------
818823 /**
819824 * <p>Gets the toString that would be produced by {@code Object}
820825 * if a class did not override toString itself. {@code null}
865870 */
866871 @Deprecated
867872 public static void identityToString(final StrBuilder builder, final Object object) {
868 Validate.notNull(object, "Cannot get the toString of a null object");
873 Validate.notNull(object, "object");
869874 final String name = object.getClass().getName();
870875 final String hexString = Integer.toHexString(System.identityHashCode(object));
871876 builder.ensureCapacity(builder.length() + name.length() + 1 + hexString.length());
890895 * @since 2.4
891896 */
892897 public static void identityToString(final StringBuffer buffer, final Object object) {
893 Validate.notNull(object, "Cannot get the toString of a null object");
898 Validate.notNull(object, "object");
894899 final String name = object.getClass().getName();
895900 final String hexString = Integer.toHexString(System.identityHashCode(object));
896901 buffer.ensureCapacity(buffer.length() + name.length() + 1 + hexString.length());
915920 * @since 3.2
916921 */
917922 public static void identityToString(final StringBuilder builder, final Object object) {
918 Validate.notNull(object, "Cannot get the toString of a null object");
923 Validate.notNull(object, "object");
919924 final String name = object.getClass().getName();
920925 final String hexString = Integer.toHexString(System.identityHashCode(object));
921926 builder.ensureCapacity(builder.length() + name.length() + 1 + hexString.length());
946951 */
947952
948953
949 // Empty checks
950 //-----------------------------------------------------------------------
951954 /**
952955 * <p>Checks if an Object is empty or null.</p>
953956 *
10621065 public static <T> T median(final Comparator<T> comparator, final T... items) {
10631066 Validate.notEmpty(items, "null/empty items");
10641067 Validate.noNullElements(items);
1065 Validate.notNull(comparator, "null comparator");
1066 final TreeSet<T> sort = new TreeSet<>(comparator);
1067 Collections.addAll(sort, items);
1068 Validate.notNull(comparator, "comparator");
1069 final TreeSet<T> treeSet = new TreeSet<>(comparator);
1070 Collections.addAll(treeSet, items);
10681071 @SuppressWarnings("unchecked") //we know all items added were T instances
1069 final
1070 T result = (T) sort.toArray()[(sort.size() - 1) / 2];
1072 final T result = (T) treeSet.toArray()[(treeSet.size() - 1) / 2];
10711073 return result;
10721074 }
10731075
10921094 return result;
10931095 }
10941096
1095 // Comparable
1096 //-----------------------------------------------------------------------
10971097 /**
10981098 * <p>Null safe comparison of Comparables.</p>
10991099 *
11211121 }
11221122
11231123
1124 // Mode
1125 //-----------------------------------------------------------------------
11261124 /**
11271125 * Find the most frequently occurring item.
11281126 *
11791177 * @return {@code false} if the values of both objects are the same
11801178 */
11811179 public static boolean notEqual(final Object object1, final Object object2) {
1182 return !equals(object1, object2);
1183 }
1184
1185 // ToString
1186 //-----------------------------------------------------------------------
1180 return !Objects.equals(object1, object2);
1181 }
1182
1183 /**
1184 * Checks that the specified object reference is not {@code null} or empty per {@link #isEmpty(Object)}. Use this
1185 * method for validation, for example:
1186 *
1187 * <blockquote>
1188 *
1189 * <pre>
1190 * public Foo(Bar bar) {
1191 * this.bar = Objects.requireNonEmpty(bar);
1192 * }
1193 * </pre>
1194 *
1195 * </blockquote>
1196 *
1197 * @param <T> the type of the reference.
1198 * @param obj the object reference to check for nullity.
1199 * @return {@code obj} if not {@code null}.
1200 * @throws NullPointerException if {@code obj} is {@code null}.
1201 * @throws IllegalArgumentException if {@code obj} is empty per {@link #isEmpty(Object)}.
1202 * @see #isEmpty(Object)
1203 * @since 3.12.0
1204 */
1205 public static <T> T requireNonEmpty(final T obj) {
1206 return requireNonEmpty(obj, "object");
1207 }
1208
1209 /**
1210 * Checks that the specified object reference is not {@code null} or empty per {@link #isEmpty(Object)}. Use this
1211 * method for validation, for example:
1212 *
1213 * <blockquote>
1214 *
1215 * <pre>
1216 * public Foo(Bar bar) {
1217 * this.bar = Objects.requireNonEmpty(bar, "bar");
1218 * }
1219 * </pre>
1220 *
1221 * </blockquote>
1222 *
1223 * @param <T> the type of the reference.
1224 * @param obj the object reference to check for nullity.
1225 * @param message the exception message.
1226 * @return {@code obj} if not {@code null}.
1227 * @throws NullPointerException if {@code obj} is {@code null}.
1228 * @throws IllegalArgumentException if {@code obj} is empty per {@link #isEmpty(Object)}.
1229 * @see #isEmpty(Object)
1230 * @since 3.12.0
1231 */
1232 public static <T> T requireNonEmpty(final T obj, final String message) {
1233 // check for null first to give the most precise exception.
1234 Objects.requireNonNull(obj, message);
1235 if (isEmpty(obj)) {
1236 throw new IllegalArgumentException(message);
1237 }
1238 return obj;
1239 }
1240
11871241 /**
11881242 * <p>Gets the {@code toString} of an {@code Object} returning
11891243 * an empty string ("") if {@code null} input.</p>
12561310 * @since 3.11
12571311 */
12581312 public static String toString(final Object obj, final Supplier<String> supplier) {
1259 return obj == null ? supplier == null ? null : supplier.get() : obj.toString();
1313 return obj == null ? Suppliers.get(supplier) : obj.toString();
1314 }
1315
1316 /**
1317 * Calls {@link Object#wait(long, int)} for the given Duration.
1318 *
1319 * @param obj The receiver of the wait call.
1320 * @param duration How long to wait.
1321 * @throws IllegalArgumentException if the timeout duration is negative.
1322 * @throws IllegalMonitorStateException if the current thread is not the owner of the {@code obj}'s monitor.
1323 * @throws InterruptedException if any thread interrupted the current thread before or while the current thread was
1324 * waiting for a notification. The <em>interrupted status</em> of the current thread is cleared when this
1325 * exception is thrown.
1326 * @see Object#wait(long, int)
1327 * @since 3.12.0
1328 */
1329 public static void wait(final Object obj, final Duration duration) throws InterruptedException {
1330 DurationUtils.accept(obj::wait, DurationUtils.zeroIfNull(duration));
12601331 }
12611332
12621333 /**
12681339 * instance to operate.</p>
12691340 */
12701341 public ObjectUtils() {
1271 super();
12721342 }
12731343
12741344 }
1616 package org.apache.commons.lang3;
1717
1818 import java.util.Random;
19 import java.util.concurrent.ThreadLocalRandom;
1920
2021 /**
2122 * <p>Generates random {@code String}s.</p>
4748 */
4849 public class RandomStringUtils {
4950
50 /**
51 * <p>Random object used by random method. This has to be not local
52 * to the random method so as to not return the same value in the
53 * same millisecond.</p>
54 */
55 private static final Random RANDOM = new Random();
56
57 /**
58 * <p>{@code RandomStringUtils} instances should NOT be constructed in
59 * standard programming. Instead, the class should be used as
60 * {@code RandomStringUtils.random(5);}.</p>
61 *
62 * <p>This constructor is public to permit tools that require a JavaBean instance
63 * to operate.</p>
64 */
65 public RandomStringUtils() {
66 super();
51 private static ThreadLocalRandom random() {
52 return ThreadLocalRandom.current();
6753 }
6854
6955 // Random
70 //-----------------------------------------------------------------------
7156 /**
7257 * <p>Creates a random string whose length is the number of characters
7358 * specified.</p>
7964 */
8065 public static String random(final int count) {
8166 return random(count, false, false);
82 }
83
84 /**
85 * <p>Creates a random string whose length is the number of characters
86 * specified.</p>
87 *
88 * <p>Characters will be chosen from the set of characters whose
89 * ASCII value is between {@code 32} and {@code 126} (inclusive).</p>
90 *
91 * @param count the length of random string to create
92 * @return the random string
93 */
94 public static String randomAscii(final int count) {
95 return random(count, 32, 127, false, false);
96 }
97
98 /**
99 * <p>Creates a random string whose length is between the inclusive minimum and
100 * the exclusive maximum.</p>
101 *
102 * <p>Characters will be chosen from the set of characters whose
103 * ASCII value is between {@code 32} and {@code 126} (inclusive).</p>
104 *
105 * @param minLengthInclusive the inclusive minimum length of the string to generate
106 * @param maxLengthExclusive the exclusive maximum length of the string to generate
107 * @return the random string
108 * @since 3.5
109 */
110 public static String randomAscii(final int minLengthInclusive, final int maxLengthExclusive) {
111 return randomAscii(RandomUtils.nextInt(minLengthInclusive, maxLengthExclusive));
112 }
113
114 /**
115 * <p>Creates a random string whose length is the number of characters
116 * specified.</p>
117 *
118 * <p>Characters will be chosen from the set of Latin alphabetic
119 * characters (a-z, A-Z).</p>
120 *
121 * @param count the length of random string to create
122 * @return the random string
123 */
124 public static String randomAlphabetic(final int count) {
125 return random(count, true, false);
126 }
127
128 /**
129 * <p>Creates a random string whose length is between the inclusive minimum and
130 * the exclusive maximum.</p>
131 *
132 * <p>Characters will be chosen from the set of Latin alphabetic characters (a-z, A-Z).</p>
133 *
134 * @param minLengthInclusive the inclusive minimum length of the string to generate
135 * @param maxLengthExclusive the exclusive maximum length of the string to generate
136 * @return the random string
137 * @since 3.5
138 */
139 public static String randomAlphabetic(final int minLengthInclusive, final int maxLengthExclusive) {
140 return randomAlphabetic(RandomUtils.nextInt(minLengthInclusive, maxLengthExclusive));
141 }
142
143 /**
144 * <p>Creates a random string whose length is the number of characters
145 * specified.</p>
146 *
147 * <p>Characters will be chosen from the set of Latin alphabetic
148 * characters (a-z, A-Z) and the digits 0-9.</p>
149 *
150 * @param count the length of random string to create
151 * @return the random string
152 */
153 public static String randomAlphanumeric(final int count) {
154 return random(count, true, true);
155 }
156
157 /**
158 * <p>Creates a random string whose length is between the inclusive minimum and
159 * the exclusive maximum.</p>
160 *
161 * <p>Characters will be chosen from the set of Latin alphabetic
162 * characters (a-z, A-Z) and the digits 0-9.</p>
163 *
164 * @param minLengthInclusive the inclusive minimum length of the string to generate
165 * @param maxLengthExclusive the exclusive maximum length of the string to generate
166 * @return the random string
167 * @since 3.5
168 */
169 public static String randomAlphanumeric(final int minLengthInclusive, final int maxLengthExclusive) {
170 return randomAlphanumeric(RandomUtils.nextInt(minLengthInclusive, maxLengthExclusive));
171 }
172
173 /**
174 * <p>Creates a random string whose length is the number of characters specified.</p>
175 *
176 * <p>Characters will be chosen from the set of characters which match the POSIX [:graph:]
177 * regular expression character class. This class contains all visible ASCII characters
178 * (i.e. anything except spaces and control characters).</p>
179 *
180 * @param count the length of random string to create
181 * @return the random string
182 * @since 3.5
183 */
184 public static String randomGraph(final int count) {
185 return random(count, 33, 126, false, false);
186 }
187
188 /**
189 * <p>Creates a random string whose length is between the inclusive minimum and
190 * the exclusive maximum.</p>
191 *
192 * <p>Characters will be chosen from the set of \p{Graph} characters.</p>
193 *
194 * @param minLengthInclusive the inclusive minimum length of the string to generate
195 * @param maxLengthExclusive the exclusive maximum length of the string to generate
196 * @return the random string
197 * @since 3.5
198 */
199 public static String randomGraph(final int minLengthInclusive, final int maxLengthExclusive) {
200 return randomGraph(RandomUtils.nextInt(minLengthInclusive, maxLengthExclusive));
201 }
202
203 /**
204 * <p>Creates a random string whose length is the number of characters
205 * specified.</p>
206 *
207 * <p>Characters will be chosen from the set of numeric
208 * characters.</p>
209 *
210 * @param count the length of random string to create
211 * @return the random string
212 */
213 public static String randomNumeric(final int count) {
214 return random(count, false, true);
215 }
216
217 /**
218 * <p>Creates a random string whose length is between the inclusive minimum and
219 * the exclusive maximum.</p>
220 *
221 * <p>Characters will be chosen from the set of \p{Digit} characters.</p>
222 *
223 * @param minLengthInclusive the inclusive minimum length of the string to generate
224 * @param maxLengthExclusive the exclusive maximum length of the string to generate
225 * @return the random string
226 * @since 3.5
227 */
228 public static String randomNumeric(final int minLengthInclusive, final int maxLengthExclusive) {
229 return randomNumeric(RandomUtils.nextInt(minLengthInclusive, maxLengthExclusive));
230 }
231
232 /**
233 * <p>Creates a random string whose length is the number of characters specified.</p>
234 *
235 * <p>Characters will be chosen from the set of characters which match the POSIX [:print:]
236 * regular expression character class. This class includes all visible ASCII characters and spaces
237 * (i.e. anything except control characters).</p>
238 *
239 * @param count the length of random string to create
240 * @return the random string
241 * @since 3.5
242 */
243 public static String randomPrint(final int count) {
244 return random(count, 32, 126, false, false);
245 }
246
247 /**
248 * <p>Creates a random string whose length is between the inclusive minimum and
249 * the exclusive maximum.</p>
250 *
251 * <p>Characters will be chosen from the set of \p{Print} characters.</p>
252 *
253 * @param minLengthInclusive the inclusive minimum length of the string to generate
254 * @param maxLengthExclusive the exclusive maximum length of the string to generate
255 * @return the random string
256 * @since 3.5
257 */
258 public static String randomPrint(final int minLengthInclusive, final int maxLengthExclusive) {
259 return randomPrint(RandomUtils.nextInt(minLengthInclusive, maxLengthExclusive));
26067 }
26168
26269 /**
27582 */
27683 public static String random(final int count, final boolean letters, final boolean numbers) {
27784 return random(count, 0, 0, letters, numbers);
85 }
86
87 /**
88 * <p>Creates a random string whose length is the number of characters
89 * specified.</p>
90 *
91 * <p>Characters will be chosen from the set of characters specified.</p>
92 *
93 * @param count the length of random string to create
94 * @param chars the character array containing the set of characters to use,
95 * may be null
96 * @return the random string
97 * @throws IllegalArgumentException if {@code count} &lt; 0.
98 */
99 public static String random(final int count, final char... chars) {
100 if (chars == null) {
101 return random(count, 0, 0, false, false, null, random());
102 }
103 return random(count, 0, chars.length, false, false, chars, random());
278104 }
279105
280106 /**
294120 * @return the random string
295121 */
296122 public static String random(final int count, final int start, final int end, final boolean letters, final boolean numbers) {
297 return random(count, start, end, letters, numbers, null, RANDOM);
123 return random(count, start, end, letters, numbers, null, random());
298124 }
299125
300126 /**
309135 * @param count the length of random string to create
310136 * @param start the position in set of chars to start at
311137 * @param end the position in set of chars to end before
312 * @param letters only allow letters?
313 * @param numbers only allow numbers?
138 * @param letters if {@code true}, generated string may include
139 * alphabetic characters
140 * @param numbers if {@code true}, generated string may include
141 * numeric characters
314142 * @param chars the set of chars to choose randoms from.
315143 * If {@code null}, then it will use the set of all chars.
316144 * @return the random string
318146 * {@code (end - start) + 1} characters in the set array.
319147 */
320148 public static String random(final int count, final int start, final int end, final boolean letters, final boolean numbers, final char... chars) {
321 return random(count, start, end, letters, numbers, chars, RANDOM);
149 return random(count, start, end, letters, numbers, chars, random());
322150 }
323151
324152 /**
343171 * @param count the length of random string to create
344172 * @param start the position in set of chars to start at (inclusive)
345173 * @param end the position in set of chars to end before (exclusive)
346 * @param letters only allow letters?
347 * @param numbers only allow numbers?
174 * @param letters if {@code true}, generated string may include
175 * alphabetic characters
176 * @param numbers if {@code true}, generated string may include
177 * numeric characters
348178 * @param chars the set of chars to choose randoms from, must not be empty.
349179 * If {@code null}, then it will use the set of all chars.
350180 * @param random a source of randomness.
358188 final char[] chars, final Random random) {
359189 if (count == 0) {
360190 return StringUtils.EMPTY;
361 } else if (count < 0) {
191 }
192 if (count < 0) {
362193 throw new IllegalArgumentException("Requested random string length " + count + " is less than 0.");
363194 }
364195 if (chars != null && chars.length == 0) {
368199 if (start == 0 && end == 0) {
369200 if (chars != null) {
370201 end = chars.length;
202 } else if (!letters && !numbers) {
203 end = Character.MAX_CODE_POINT;
371204 } else {
372 if (!letters && !numbers) {
373 end = Character.MAX_CODE_POINT;
374 } else {
375 end = 'z' + 1;
376 start = ' ';
377 }
205 end = 'z' + 1;
206 start = ' ';
378207 }
379 } else {
380 if (end <= start) {
381 throw new IllegalArgumentException("Parameter end (" + end + ") must be greater than start (" + start + ")");
382 }
208 } else if (end <= start) {
209 throw new IllegalArgumentException("Parameter end (" + end + ") must be greater than start (" + start + ")");
383210 }
384211
385212 final int zero_digit_ascii = 48;
395222 final int gap = end - start;
396223
397224 while (count-- != 0) {
398 int codePoint;
225 final int codePoint;
399226 if (chars == null) {
400227 codePoint = random.nextInt(gap) + start;
401228
433260 return builder.toString();
434261 }
435262
436
437263 /**
438264 * <p>Creates a random string whose length is the number of characters
439265 * specified.</p>
450276 */
451277 public static String random(final int count, final String chars) {
452278 if (chars == null) {
453 return random(count, 0, 0, false, false, null, RANDOM);
279 return random(count, 0, 0, false, false, null, random());
454280 }
455281 return random(count, chars.toCharArray());
456282 }
459285 * <p>Creates a random string whose length is the number of characters
460286 * specified.</p>
461287 *
462 * <p>Characters will be chosen from the set of characters specified.</p>
463 *
464 * @param count the length of random string to create
465 * @param chars the character array containing the set of characters to use,
466 * may be null
467 * @return the random string
468 * @throws IllegalArgumentException if {@code count} &lt; 0.
469 */
470 public static String random(final int count, final char... chars) {
471 if (chars == null) {
472 return random(count, 0, 0, false, false, null, RANDOM);
473 }
474 return random(count, 0, chars.length, false, false, chars, RANDOM);
288 * <p>Characters will be chosen from the set of Latin alphabetic
289 * characters (a-z, A-Z).</p>
290 *
291 * @param count the length of random string to create
292 * @return the random string
293 */
294 public static String randomAlphabetic(final int count) {
295 return random(count, true, false);
296 }
297
298 /**
299 * <p>Creates a random string whose length is between the inclusive minimum and
300 * the exclusive maximum.</p>
301 *
302 * <p>Characters will be chosen from the set of Latin alphabetic characters (a-z, A-Z).</p>
303 *
304 * @param minLengthInclusive the inclusive minimum length of the string to generate
305 * @param maxLengthExclusive the exclusive maximum length of the string to generate
306 * @return the random string
307 * @since 3.5
308 */
309 public static String randomAlphabetic(final int minLengthInclusive, final int maxLengthExclusive) {
310 return randomAlphabetic(RandomUtils.nextInt(minLengthInclusive, maxLengthExclusive));
311 }
312
313 /**
314 * <p>Creates a random string whose length is the number of characters
315 * specified.</p>
316 *
317 * <p>Characters will be chosen from the set of Latin alphabetic
318 * characters (a-z, A-Z) and the digits 0-9.</p>
319 *
320 * @param count the length of random string to create
321 * @return the random string
322 */
323 public static String randomAlphanumeric(final int count) {
324 return random(count, true, true);
325 }
326
327 /**
328 * <p>Creates a random string whose length is between the inclusive minimum and
329 * the exclusive maximum.</p>
330 *
331 * <p>Characters will be chosen from the set of Latin alphabetic
332 * characters (a-z, A-Z) and the digits 0-9.</p>
333 *
334 * @param minLengthInclusive the inclusive minimum length of the string to generate
335 * @param maxLengthExclusive the exclusive maximum length of the string to generate
336 * @return the random string
337 * @since 3.5
338 */
339 public static String randomAlphanumeric(final int minLengthInclusive, final int maxLengthExclusive) {
340 return randomAlphanumeric(RandomUtils.nextInt(minLengthInclusive, maxLengthExclusive));
341 }
342
343 /**
344 * <p>Creates a random string whose length is the number of characters
345 * specified.</p>
346 *
347 * <p>Characters will be chosen from the set of characters whose
348 * ASCII value is between {@code 32} and {@code 126} (inclusive).</p>
349 *
350 * @param count the length of random string to create
351 * @return the random string
352 */
353 public static String randomAscii(final int count) {
354 return random(count, 32, 127, false, false);
355 }
356
357 /**
358 * <p>Creates a random string whose length is between the inclusive minimum and
359 * the exclusive maximum.</p>
360 *
361 * <p>Characters will be chosen from the set of characters whose
362 * ASCII value is between {@code 32} and {@code 126} (inclusive).</p>
363 *
364 * @param minLengthInclusive the inclusive minimum length of the string to generate
365 * @param maxLengthExclusive the exclusive maximum length of the string to generate
366 * @return the random string
367 * @since 3.5
368 */
369 public static String randomAscii(final int minLengthInclusive, final int maxLengthExclusive) {
370 return randomAscii(RandomUtils.nextInt(minLengthInclusive, maxLengthExclusive));
371 }
372
373 /**
374 * <p>Creates a random string whose length is the number of characters specified.</p>
375 *
376 * <p>Characters will be chosen from the set of characters which match the POSIX [:graph:]
377 * regular expression character class. This class contains all visible ASCII characters
378 * (i.e. anything except spaces and control characters).</p>
379 *
380 * @param count the length of random string to create
381 * @return the random string
382 * @since 3.5
383 */
384 public static String randomGraph(final int count) {
385 return random(count, 33, 126, false, false);
386 }
387
388 /**
389 * <p>Creates a random string whose length is between the inclusive minimum and
390 * the exclusive maximum.</p>
391 *
392 * <p>Characters will be chosen from the set of \p{Graph} characters.</p>
393 *
394 * @param minLengthInclusive the inclusive minimum length of the string to generate
395 * @param maxLengthExclusive the exclusive maximum length of the string to generate
396 * @return the random string
397 * @since 3.5
398 */
399 public static String randomGraph(final int minLengthInclusive, final int maxLengthExclusive) {
400 return randomGraph(RandomUtils.nextInt(minLengthInclusive, maxLengthExclusive));
401 }
402
403 /**
404 * <p>Creates a random string whose length is the number of characters
405 * specified.</p>
406 *
407 * <p>Characters will be chosen from the set of numeric
408 * characters.</p>
409 *
410 * @param count the length of random string to create
411 * @return the random string
412 */
413 public static String randomNumeric(final int count) {
414 return random(count, false, true);
415 }
416
417 /**
418 * <p>Creates a random string whose length is between the inclusive minimum and
419 * the exclusive maximum.</p>
420 *
421 * <p>Characters will be chosen from the set of \p{Digit} characters.</p>
422 *
423 * @param minLengthInclusive the inclusive minimum length of the string to generate
424 * @param maxLengthExclusive the exclusive maximum length of the string to generate
425 * @return the random string
426 * @since 3.5
427 */
428 public static String randomNumeric(final int minLengthInclusive, final int maxLengthExclusive) {
429 return randomNumeric(RandomUtils.nextInt(minLengthInclusive, maxLengthExclusive));
430 }
431
432 /**
433 * <p>Creates a random string whose length is the number of characters specified.</p>
434 *
435 * <p>Characters will be chosen from the set of characters which match the POSIX [:print:]
436 * regular expression character class. This class includes all visible ASCII characters and spaces
437 * (i.e. anything except control characters).</p>
438 *
439 * @param count the length of random string to create
440 * @return the random string
441 * @since 3.5
442 */
443 public static String randomPrint(final int count) {
444 return random(count, 32, 126, false, false);
445 }
446
447
448 /**
449 * <p>Creates a random string whose length is between the inclusive minimum and
450 * the exclusive maximum.</p>
451 *
452 * <p>Characters will be chosen from the set of \p{Print} characters.</p>
453 *
454 * @param minLengthInclusive the inclusive minimum length of the string to generate
455 * @param maxLengthExclusive the exclusive maximum length of the string to generate
456 * @return the random string
457 * @since 3.5
458 */
459 public static String randomPrint(final int minLengthInclusive, final int maxLengthExclusive) {
460 return randomPrint(RandomUtils.nextInt(minLengthInclusive, maxLengthExclusive));
461 }
462
463 /**
464 * <p>{@code RandomStringUtils} instances should NOT be constructed in
465 * standard programming. Instead, the class should be used as
466 * {@code RandomStringUtils.random(5);}.</p>
467 *
468 * <p>This constructor is public to permit tools that require a JavaBean instance
469 * to operate.</p>
470 */
471 public RandomStringUtils() {
475472 }
476473
477474 }
1616 package org.apache.commons.lang3;
1717
1818 import java.util.Random;
19 import java.util.concurrent.ThreadLocalRandom;
1920
2021 /**
2122 * <p>Utility library that supplements the standard {@link Random} class.</p>
3334 public class RandomUtils {
3435
3536 /**
36 * Random object used by random method. This has to be not local to the
37 * random method so as to not return the same value in the same millisecond.
38 */
39 private static final Random RANDOM = new Random();
40
41 /**
42 * <p>
43 * {@code RandomUtils} instances should NOT be constructed in standard
44 * programming. Instead, the class should be used as
45 * {@code RandomUtils.nextBytes(5);}.
46 * </p>
47 *
48 * <p>
49 * This constructor is public to permit tools that require a JavaBean
50 * instance to operate.
51 * </p>
52 */
53 public RandomUtils() {
54 super();
55 }
56
57 /**
5837 * <p>
5938 * Returns a random boolean value
6039 * </p>
6342 * @since 3.5
6443 */
6544 public static boolean nextBoolean() {
66 return RANDOM.nextBoolean();
45 return random().nextBoolean();
6746 }
6847
6948 /**
8059 Validate.isTrue(count >= 0, "Count cannot be negative.");
8160
8261 final byte[] result = new byte[count];
83 RANDOM.nextBytes(result);
62 random().nextBytes(result);
8463 return result;
8564 }
8665
8766 /**
88 * <p>
89 * Returns a random integer within the specified range.
90 * </p>
91 *
92 * @param startInclusive
93 * the smallest value that can be returned, must be non-negative
94 * @param endExclusive
95 * the upper bound (not included)
96 * @throws IllegalArgumentException
97 * if {@code startInclusive > endExclusive} or if
98 * {@code startInclusive} is negative
99 * @return the random integer
100 */
101 public static int nextInt(final int startInclusive, final int endExclusive) {
102 Validate.isTrue(endExclusive >= startInclusive,
103 "Start value must be smaller or equal to end value.");
104 Validate.isTrue(startInclusive >= 0, "Both range values must be non-negative.");
105
106 if (startInclusive == endExclusive) {
107 return startInclusive;
108 }
109
110 return startInclusive + RANDOM.nextInt(endExclusive - startInclusive);
67 * <p> Returns a random double within 0 - Double.MAX_VALUE </p>
68 *
69 * @return the random double
70 * @see #nextDouble(double, double)
71 * @since 3.5
72 */
73 public static double nextDouble() {
74 return nextDouble(0, Double.MAX_VALUE);
75 }
76
77 /**
78 * <p>
79 * Returns a random double within the specified range.
80 * </p>
81 *
82 * @param startInclusive
83 * the smallest value that can be returned, must be non-negative
84 * @param endExclusive
85 * the upper bound (not included)
86 * @throws IllegalArgumentException
87 * if {@code startInclusive > endExclusive} or if
88 * {@code startInclusive} is negative
89 * @return the random double
90 */
91 public static double nextDouble(final double startInclusive, final double endExclusive) {
92 Validate.isTrue(endExclusive >= startInclusive,
93 "Start value must be smaller or equal to end value.");
94 Validate.isTrue(startInclusive >= 0, "Both range values must be non-negative.");
95
96 if (startInclusive == endExclusive) {
97 return startInclusive;
98 }
99
100 return startInclusive + ((endExclusive - startInclusive) * random().nextDouble());
101 }
102
103 /**
104 * <p> Returns a random float within 0 - Float.MAX_VALUE </p>
105 *
106 * @return the random float
107 * @see #nextFloat(float, float)
108 * @since 3.5
109 */
110 public static float nextFloat() {
111 return nextFloat(0, Float.MAX_VALUE);
112 }
113
114 /**
115 * <p>
116 * Returns a random float within the specified range.
117 * </p>
118 *
119 * @param startInclusive
120 * the smallest value that can be returned, must be non-negative
121 * @param endExclusive
122 * the upper bound (not included)
123 * @throws IllegalArgumentException
124 * if {@code startInclusive > endExclusive} or if
125 * {@code startInclusive} is negative
126 * @return the random float
127 */
128 public static float nextFloat(final float startInclusive, final float endExclusive) {
129 Validate.isTrue(endExclusive >= startInclusive,
130 "Start value must be smaller or equal to end value.");
131 Validate.isTrue(startInclusive >= 0, "Both range values must be non-negative.");
132
133 if (startInclusive == endExclusive) {
134 return startInclusive;
135 }
136
137 return startInclusive + ((endExclusive - startInclusive) * random().nextFloat());
111138 }
112139
113140 /**
123150
124151 /**
125152 * <p>
126 * Returns a random long within the specified range.
127 * </p>
128 *
129 * @param startInclusive
130 * the smallest value that can be returned, must be non-negative
131 * @param endExclusive
132 * the upper bound (not included)
133 * @throws IllegalArgumentException
134 * if {@code startInclusive > endExclusive} or if
135 * {@code startInclusive} is negative
136 * @return the random long
137 */
138 public static long nextLong(final long startInclusive, final long endExclusive) {
139 Validate.isTrue(endExclusive >= startInclusive,
140 "Start value must be smaller or equal to end value.");
141 Validate.isTrue(startInclusive >= 0, "Both range values must be non-negative.");
142
143 if (startInclusive == endExclusive) {
144 return startInclusive;
145 }
146
147 return (long) nextDouble(startInclusive, endExclusive);
153 * Returns a random integer within the specified range.
154 * </p>
155 *
156 * @param startInclusive
157 * the smallest value that can be returned, must be non-negative
158 * @param endExclusive
159 * the upper bound (not included)
160 * @throws IllegalArgumentException
161 * if {@code startInclusive > endExclusive} or if
162 * {@code startInclusive} is negative
163 * @return the random integer
164 */
165 public static int nextInt(final int startInclusive, final int endExclusive) {
166 Validate.isTrue(endExclusive >= startInclusive,
167 "Start value must be smaller or equal to end value.");
168 Validate.isTrue(startInclusive >= 0, "Both range values must be non-negative.");
169
170 if (startInclusive == endExclusive) {
171 return startInclusive;
172 }
173
174 return startInclusive + random().nextInt(endExclusive - startInclusive);
148175 }
149176
150177 /**
155182 * @since 3.5
156183 */
157184 public static long nextLong() {
158 return nextLong(0, Long.MAX_VALUE);
159 }
160
161 /**
162 * <p>
163 * Returns a random double within the specified range.
164 * </p>
165 *
166 * @param startInclusive
167 * the smallest value that can be returned, must be non-negative
168 * @param endExclusive
169 * the upper bound (not included)
170 * @throws IllegalArgumentException
171 * if {@code startInclusive > endExclusive} or if
172 * {@code startInclusive} is negative
173 * @return the random double
174 */
175 public static double nextDouble(final double startInclusive, final double endExclusive) {
176 Validate.isTrue(endExclusive >= startInclusive,
177 "Start value must be smaller or equal to end value.");
178 Validate.isTrue(startInclusive >= 0, "Both range values must be non-negative.");
179
180 if (startInclusive == endExclusive) {
181 return startInclusive;
182 }
183
184 return startInclusive + ((endExclusive - startInclusive) * RANDOM.nextDouble());
185 }
186
187 /**
188 * <p> Returns a random double within 0 - Double.MAX_VALUE </p>
189 *
190 * @return the random double
191 * @see #nextDouble(double, double)
192 * @since 3.5
193 */
194 public static double nextDouble() {
195 return nextDouble(0, Double.MAX_VALUE);
196 }
197
198 /**
199 * <p>
200 * Returns a random float within the specified range.
201 * </p>
202 *
203 * @param startInclusive
204 * the smallest value that can be returned, must be non-negative
205 * @param endExclusive
206 * the upper bound (not included)
207 * @throws IllegalArgumentException
208 * if {@code startInclusive > endExclusive} or if
209 * {@code startInclusive} is negative
210 * @return the random float
211 */
212 public static float nextFloat(final float startInclusive, final float endExclusive) {
213 Validate.isTrue(endExclusive >= startInclusive,
214 "Start value must be smaller or equal to end value.");
215 Validate.isTrue(startInclusive >= 0, "Both range values must be non-negative.");
216
217 if (startInclusive == endExclusive) {
218 return startInclusive;
219 }
220
221 return startInclusive + ((endExclusive - startInclusive) * RANDOM.nextFloat());
222 }
223
224 /**
225 * <p> Returns a random float within 0 - Float.MAX_VALUE </p>
226 *
227 * @return the random float
228 * @see #nextFloat(float, float)
229 * @since 3.5
230 */
231 public static float nextFloat() {
232 return nextFloat(0, Float.MAX_VALUE);
185 return nextLong(Long.MAX_VALUE);
186 }
187
188 /**
189 * Generates a {@code long} value between 0 (inclusive) and the specified
190 * value (exclusive).
191 *
192 * @param n Bound on the random number to be returned. Must be positive.
193 * @return a random {@code long} value between 0 (inclusive) and {@code n}
194 * (exclusive).
195 */
196 private static long nextLong(final long n) {
197 // Extracted from o.a.c.rng.core.BaseProvider.nextLong(long)
198 long bits;
199 long val;
200 do {
201 bits = random().nextLong() >>> 1;
202 val = bits % n;
203 } while (bits - val + (n - 1) < 0);
204
205 return val;
206 }
207
208 /**
209 * <p>
210 * Returns a random long within the specified range.
211 * </p>
212 *
213 * @param startInclusive
214 * the smallest value that can be returned, must be non-negative
215 * @param endExclusive
216 * the upper bound (not included)
217 * @throws IllegalArgumentException
218 * if {@code startInclusive > endExclusive} or if
219 * {@code startInclusive} is negative
220 * @return the random long
221 */
222 public static long nextLong(final long startInclusive, final long endExclusive) {
223 Validate.isTrue(endExclusive >= startInclusive,
224 "Start value must be smaller or equal to end value.");
225 Validate.isTrue(startInclusive >= 0, "Both range values must be non-negative.");
226
227 if (startInclusive == endExclusive) {
228 return startInclusive;
229 }
230
231 return startInclusive + nextLong(endExclusive - startInclusive);
232 }
233
234 private static ThreadLocalRandom random() {
235 return ThreadLocalRandom.current();
236 }
237
238 /**
239 * <p>
240 * {@code RandomUtils} instances should NOT be constructed in standard
241 * programming. Instead, the class should be used as
242 * {@code RandomUtils.nextBytes(5);}.
243 * </p>
244 *
245 * <p>
246 * This constructor is public to permit tools that require a JavaBean
247 * instance to operate.
248 * </p>
249 */
250 public RandomUtils() {
233251 }
234252 }
3131 */
3232 public final class Range<T> implements Serializable {
3333
34 //-----------------------------------------------------------------------
3534 @SuppressWarnings({"rawtypes", "unchecked"})
3635 private enum ComparableComparator implements Comparator {
3736 INSTANCE;
154153 */
155154 private transient String toString;
156155
157 // Accessors
158 //--------------------------------------------------------------------
159
160156 /**
161157 * Creates an instance.
162158 *
226222 */
227223 public int elementCompareTo(final T element) {
228224 // Comparable API says throw NPE on null
229 Validate.notNull(element, "Element is null");
225 Validate.notNull(element, "element");
230226 if (isAfter(element)) {
231227 return -1;
232 } else if (isBefore(element)) {
228 }
229 if (isBefore(element)) {
233230 return 1;
234 } else {
235 return 0;
236 }
231 }
232 return 0;
237233 }
238234
239235 // Element tests
252248 public boolean equals(final Object obj) {
253249 if (obj == this) {
254250 return true;
255 } else if (obj == null || obj.getClass() != getClass()) {
256 return false;
257 } else {
258 @SuppressWarnings("unchecked") // OK because we checked the class above
259 final
260 Range<T> range = (Range<T>) obj;
261 return minimum.equals(range.minimum) &&
262 maximum.equals(range.maximum);
263 }
251 }
252 if (obj == null || obj.getClass() != getClass()) {
253 return false;
254 }
255 @SuppressWarnings("unchecked") // OK because we checked the class above
256 final
257 Range<T> range = (Range<T>) obj;
258 return minimum.equals(range.minimum) &&
259 maximum.equals(range.maximum);
264260 }
265261
266262 /**
331327 return between(min, max, getComparator());
332328 }
333329
334 // Range tests
335 //--------------------------------------------------------------------
336
337330 /**
338331 * <p>Checks whether this range is after the specified element.</p>
339332 *
404397 }
405398 return comparator.compare(element, maximum) == 0;
406399 }
407
408 // Basics
409 //--------------------------------------------------------------------
410400
411401 /**
412402 * <p>Whether or not the Range is using the natural ordering of the elements.</p>
480470 Validate.notNull(element, "element");
481471 if (isAfter(element)) {
482472 return minimum;
483 } else if (isBefore(element)) {
473 }
474 if (isBefore(element)) {
484475 return maximum;
485 } else {
486 return element;
487 }
476 }
477 return element;
488478 }
489479
490480 /**
255255 * @see java.util.regex.Pattern
256256 */
257257 public static String replaceAll(final String text, final Pattern regex, final String replacement) {
258 if (text == null || regex == null || replacement == null) {
258 if (ObjectUtils.anyNull(text, regex, replacement)) {
259259 return text;
260260 }
261261 return regex.matcher(text).replaceAll(replacement);
309309 * @see java.util.regex.Pattern#DOTALL
310310 */
311311 public static String replaceAll(final String text, final String regex, final String replacement) {
312 if (text == null || regex == null || replacement == null) {
312 if (ObjectUtils.anyNull(text, regex, replacement)) {
313313 return text;
314314 }
315315 return text.replaceAll(regex, replacement);
448448 * @see Pattern#DOTALL
449449 */
450450 public static String replacePattern(final String text, final String regex, final String replacement) {
451 if (text == null || regex == null || replacement == null) {
451 if (ObjectUtils.anyNull(text, regex, replacement)) {
452452 return text;
453453 }
454454 return Pattern.compile(regex, Pattern.DOTALL).matcher(text).replaceAll(replacement);
3737 * detail message.</p>
3838 */
3939 public SerializationException() {
40 super();
4140 }
4241
4342 /**
4444 * @since 1.0
4545 */
4646 public class SerializationUtils {
47
48 /**
49 * <p>SerializationUtils instances should NOT be constructed in standard programming.
50 * Instead, the class should be used as {@code SerializationUtils.clone(object)}.</p>
51 *
52 * <p>This constructor is public to permit tools that require a JavaBean instance
53 * to operate.</p>
54 * @since 2.0
55 */
56 public SerializationUtils() {
57 super();
58 }
59
60 // Clone
61 //-----------------------------------------------------------------------
62 /**
63 * <p>Deep clone an {@code Object} using serialization.</p>
64 *
65 * <p>This is many times slower than writing clone methods by hand
66 * on all objects in your object graph. However, for complex object
67 * graphs, or for those that don't support deep cloning this can
68 * be a simple alternative implementation. Of course all the objects
69 * must be {@code Serializable}.</p>
70 *
71 * @param <T> the type of the object involved
72 * @param object the {@code Serializable} object to clone
73 * @return the cloned object
74 * @throws SerializationException (runtime) if the serialization fails
75 */
76 public static <T extends Serializable> T clone(final T object) {
77 if (object == null) {
78 return null;
79 }
80 final byte[] objectData = serialize(object);
81 final ByteArrayInputStream bais = new ByteArrayInputStream(objectData);
82
83 try (ClassLoaderAwareObjectInputStream in = new ClassLoaderAwareObjectInputStream(bais,
84 object.getClass().getClassLoader())) {
85 /*
86 * when we serialize and deserialize an object,
87 * it is reasonable to assume the deserialized object
88 * is of the same type as the original serialized object
89 */
90 @SuppressWarnings("unchecked") // see above
91 final T readObject = (T) in.readObject();
92 return readObject;
93
94 } catch (final ClassNotFoundException ex) {
95 throw new SerializationException("ClassNotFoundException while reading cloned object data", ex);
96 } catch (final IOException ex) {
97 throw new SerializationException("IOException while reading or closing cloned object data", ex);
98 }
99 }
100
101 /**
102 * Performs a serialization roundtrip. Serializes and deserializes the given object, great for testing objects that
103 * implement {@link Serializable}.
104 *
105 * @param <T>
106 * the type of the object involved
107 * @param msg
108 * the object to roundtrip
109 * @return the serialized and deserialized object
110 * @since 3.3
111 */
112 @SuppressWarnings("unchecked") // OK, because we serialized a type `T`
113 public static <T extends Serializable> T roundtrip(final T msg) {
114 return (T) deserialize(serialize(msg));
115 }
116
117 // Serialize
118 //-----------------------------------------------------------------------
119 /**
120 * <p>Serializes an {@code Object} to the specified stream.</p>
121 *
122 * <p>The stream will be closed once the object is written.
123 * This avoids the need for a finally clause, and maybe also exception
124 * handling, in the application code.</p>
125 *
126 * <p>The stream passed in is not buffered internally within this method.
127 * This is the responsibility of your application if desired.</p>
128 *
129 * @param obj the object to serialize to bytes, may be null
130 * @param outputStream the stream to write to, must not be null
131 * @throws NullPointerException if {@code outputStream} is {@code null}
132 * @throws SerializationException (runtime) if the serialization fails
133 */
134 public static void serialize(final Serializable obj, final OutputStream outputStream) {
135 Validate.notNull(outputStream, "The OutputStream must not be null");
136 try (ObjectOutputStream out = new ObjectOutputStream(outputStream)) {
137 out.writeObject(obj);
138 } catch (final IOException ex) {
139 throw new SerializationException(ex);
140 }
141 }
142
143 /**
144 * <p>Serializes an {@code Object} to a byte array for
145 * storage/serialization.</p>
146 *
147 * @param obj the object to serialize to bytes
148 * @return a byte[] with the converted Serializable
149 * @throws SerializationException (runtime) if the serialization fails
150 */
151 public static byte[] serialize(final Serializable obj) {
152 final ByteArrayOutputStream baos = new ByteArrayOutputStream(512);
153 serialize(obj, baos);
154 return baos.toByteArray();
155 }
156
157 // Deserialize
158 //-----------------------------------------------------------------------
159 /**
160 * <p>
161 * Deserializes an {@code Object} from the specified stream.
162 * </p>
163 *
164 * <p>
165 * The stream will be closed once the object is written. This avoids the need for a finally clause, and maybe also
166 * exception handling, in the application code.
167 * </p>
168 *
169 * <p>
170 * The stream passed in is not buffered internally within this method. This is the responsibility of your
171 * application if desired.
172 * </p>
173 *
174 * <p>
175 * If the call site incorrectly types the return value, a {@link ClassCastException} is thrown from the call site.
176 * Without Generics in this declaration, the call site must type cast and can cause the same ClassCastException.
177 * Note that in both cases, the ClassCastException is in the call site, not in this method.
178 * </p>
179 *
180 * @param <T> the object type to be deserialized
181 * @param inputStream
182 * the serialized object input stream, must not be null
183 * @return the deserialized object
184 * @throws NullPointerException if {@code inputStream} is {@code null}
185 * @throws SerializationException (runtime) if the serialization fails
186 */
187 public static <T> T deserialize(final InputStream inputStream) {
188 Validate.notNull(inputStream, "The InputStream must not be null");
189 try (ObjectInputStream in = new ObjectInputStream(inputStream)) {
190 @SuppressWarnings("unchecked")
191 final T obj = (T) in.readObject();
192 return obj;
193 } catch (final ClassNotFoundException | IOException ex) {
194 throw new SerializationException(ex);
195 }
196 }
197
198 /**
199 * <p>
200 * Deserializes a single {@code Object} from an array of bytes.
201 * </p>
202 *
203 * <p>
204 * If the call site incorrectly types the return value, a {@link ClassCastException} is thrown from the call site.
205 * Without Generics in this declaration, the call site must type cast and can cause the same ClassCastException.
206 * Note that in both cases, the ClassCastException is in the call site, not in this method.
207 * </p>
208 *
209 * @param <T> the object type to be deserialized
210 * @param objectData
211 * the serialized object, must not be null
212 * @return the deserialized object
213 * @throws NullPointerException if {@code objectData} is {@code null}
214 * @throws SerializationException (runtime) if the serialization fails
215 */
216 public static <T> T deserialize(final byte[] objectData) {
217 Validate.notNull(objectData, "The byte[] must not be null");
218 return deserialize(new ByteArrayInputStream(objectData));
219 }
22047
22148 /**
22249 * <p>Custom specialization of the standard JDK {@link java.io.ObjectInputStream}
289116
290117 }
291118
119 /**
120 * <p>Deep clone an {@code Object} using serialization.</p>
121 *
122 * <p>This is many times slower than writing clone methods by hand
123 * on all objects in your object graph. However, for complex object
124 * graphs, or for those that don't support deep cloning this can
125 * be a simple alternative implementation. Of course all the objects
126 * must be {@code Serializable}.</p>
127 *
128 * @param <T> the type of the object involved
129 * @param object the {@code Serializable} object to clone
130 * @return the cloned object
131 * @throws SerializationException (runtime) if the serialization fails
132 */
133 public static <T extends Serializable> T clone(final T object) {
134 if (object == null) {
135 return null;
136 }
137 final byte[] objectData = serialize(object);
138 final ByteArrayInputStream bais = new ByteArrayInputStream(objectData);
139
140 final Class<T> cls = ObjectUtils.getClass(object);
141 try (ClassLoaderAwareObjectInputStream in = new ClassLoaderAwareObjectInputStream(bais, cls.getClassLoader())) {
142 /*
143 * when we serialize and deserialize an object, it is reasonable to assume the deserialized object is of the
144 * same type as the original serialized object
145 */
146 return cls.cast(in.readObject());
147
148 } catch (final ClassNotFoundException | IOException ex) {
149 throw new SerializationException(
150 String.format("%s while reading cloned object data", ex.getClass().getSimpleName()), ex);
151 }
152 }
153
154 /**
155 * <p>
156 * Deserializes a single {@code Object} from an array of bytes.
157 * </p>
158 *
159 * <p>
160 * If the call site incorrectly types the return value, a {@link ClassCastException} is thrown from the call site.
161 * Without Generics in this declaration, the call site must type cast and can cause the same ClassCastException.
162 * Note that in both cases, the ClassCastException is in the call site, not in this method.
163 * </p>
164 *
165 * @param <T> the object type to be deserialized
166 * @param objectData
167 * the serialized object, must not be null
168 * @return the deserialized object
169 * @throws NullPointerException if {@code objectData} is {@code null}
170 * @throws SerializationException (runtime) if the serialization fails
171 */
172 public static <T> T deserialize(final byte[] objectData) {
173 Validate.notNull(objectData, "objectData");
174 return deserialize(new ByteArrayInputStream(objectData));
175 }
176
177 /**
178 * <p>
179 * Deserializes an {@code Object} from the specified stream.
180 * </p>
181 *
182 * <p>
183 * The stream will be closed once the object is written. This avoids the need for a finally clause, and maybe also
184 * exception handling, in the application code.
185 * </p>
186 *
187 * <p>
188 * The stream passed in is not buffered internally within this method. This is the responsibility of your
189 * application if desired.
190 * </p>
191 *
192 * <p>
193 * If the call site incorrectly types the return value, a {@link ClassCastException} is thrown from the call site.
194 * Without Generics in this declaration, the call site must type cast and can cause the same ClassCastException.
195 * Note that in both cases, the ClassCastException is in the call site, not in this method.
196 * </p>
197 *
198 * @param <T> the object type to be deserialized
199 * @param inputStream
200 * the serialized object input stream, must not be null
201 * @return the deserialized object
202 * @throws NullPointerException if {@code inputStream} is {@code null}
203 * @throws SerializationException (runtime) if the serialization fails
204 */
205 @SuppressWarnings("resource") // inputStream is managed by the caller
206 public static <T> T deserialize(final InputStream inputStream) {
207 Validate.notNull(inputStream, "inputStream");
208 try (ObjectInputStream in = new ObjectInputStream(inputStream)) {
209 @SuppressWarnings("unchecked")
210 final T obj = (T) in.readObject();
211 return obj;
212 } catch (final ClassNotFoundException | IOException ex) {
213 throw new SerializationException(ex);
214 }
215 }
216
217 /**
218 * Performs a serialization roundtrip. Serializes and deserializes the given object, great for testing objects that
219 * implement {@link Serializable}.
220 *
221 * @param <T>
222 * the type of the object involved
223 * @param obj
224 * the object to roundtrip
225 * @return the serialized and deserialized object
226 * @since 3.3
227 */
228 @SuppressWarnings("unchecked") // OK, because we serialized a type `T`
229 public static <T extends Serializable> T roundtrip(final T obj) {
230 return (T) deserialize(serialize(obj));
231 }
232
233 /**
234 * <p>Serializes an {@code Object} to a byte array for
235 * storage/serialization.</p>
236 *
237 * @param obj the object to serialize to bytes
238 * @return a byte[] with the converted Serializable
239 * @throws SerializationException (runtime) if the serialization fails
240 */
241 public static byte[] serialize(final Serializable obj) {
242 final ByteArrayOutputStream baos = new ByteArrayOutputStream(512);
243 serialize(obj, baos);
244 return baos.toByteArray();
245 }
246
247 /**
248 * <p>Serializes an {@code Object} to the specified stream.</p>
249 *
250 * <p>The stream will be closed once the object is written.
251 * This avoids the need for a finally clause, and maybe also exception
252 * handling, in the application code.</p>
253 *
254 * <p>The stream passed in is not buffered internally within this method.
255 * This is the responsibility of your application if desired.</p>
256 *
257 * @param obj the object to serialize to bytes, may be null
258 * @param outputStream the stream to write to, must not be null
259 * @throws NullPointerException if {@code outputStream} is {@code null}
260 * @throws SerializationException (runtime) if the serialization fails
261 */
262 @SuppressWarnings("resource") // outputStream is managed by the caller
263 public static void serialize(final Serializable obj, final OutputStream outputStream) {
264 Validate.notNull(outputStream, "outputStream");
265 try (ObjectOutputStream out = new ObjectOutputStream(outputStream)) {
266 out.writeObject(obj);
267 } catch (final IOException ex) {
268 throw new SerializationException(ex);
269 }
270 }
271
272 /**
273 * <p>SerializationUtils instances should NOT be constructed in standard programming.
274 * Instead, the class should be used as {@code SerializationUtils.clone(object)}.</p>
275 *
276 * <p>This constructor is public to permit tools that require a JavaBean instance
277 * to operate.</p>
278 * @since 2.0
279 */
280 public SerializationUtils() {
281 }
282
292283 }
1515 */
1616 package org.apache.commons.lang3;
1717
18 import java.lang.reflect.Array;
1918 import java.util.ArrayList;
2019 import java.util.Collection;
2120 import java.util.Collections;
4241 * not to throw Exceptions, at least not checked Exceptions, AKA instances
4342 * of {@link Exception}. This enforces the use of constructs like
4443 * <pre>
45 * Consumer&lt;java.lang.reflect.Method&gt; consumer = (m) -&gt; {
44 * Consumer&lt;java.lang.reflect.Method&gt; consumer = m -&gt; {
4645 * try {
4746 * m.invoke(o, args);
4847 * } catch (Throwable t) {
6665 @Deprecated
6766 public class Streams {
6867
69 /**
70 * A reduced, and simplified version of a {@link Stream} with
71 * failable method signatures.
72 * @param <O> The streams element type.
73 * @deprecated Use {@link org.apache.commons.lang3.stream.Streams.FailableStream}.
74 */
68 /**
69 * A reduced, and simplified version of a {@link Stream} with
70 * failable method signatures.
71 * @param <O> The streams element type.
72 * @deprecated Use {@link org.apache.commons.lang3.stream.Streams.FailableStream}.
73 */
7574 @Deprecated
7675 public static class FailableStream<O extends Object> {
7776
101100 * Returns a FailableStream consisting of the elements of this stream that match
102101 * the given FailablePredicate.
103102 *
104 * <p>This is an intermediate operation.
103 * <p>
104 * This is an intermediate operation.
105 * </p>
105106 *
106107 * @param predicate a non-interfering, stateless predicate to apply to each
107108 * element to determine if it should be included.
116117 /**
117118 * Performs an action for each element of this stream.
118119 *
119 * <p>This is a terminal operation.
120 *
121 * <p>The behavior of this operation is explicitly nondeterministic.
120 * <p>
121 * This is an intermediate operation.
122 * </p>
123 *
124 * <p>
125 * The behavior of this operation is explicitly nondeterministic.
122126 * For parallel stream pipelines, this operation does <em>not</em>
123127 * guarantee to respect the encounter order of the stream, as doing so
124128 * would sacrifice the benefit of parallelism. For any given element, the
125129 * action may be performed at whatever time and in whatever thread the
126130 * library chooses. If the action accesses shared state, it is
127131 * responsible for providing the required synchronization.
132 * </p>
128133 *
129134 * @param action a non-interfering action to perform on the elements
130135 */
141146 * collection strategies and composition of collect operations such as
142147 * multiple-level grouping or partitioning.
143148 *
144 * <p>If the underlying stream is parallel, and the {@code Collector}
149 * <p>
150 * If the underlying stream is parallel, and the {@code Collector}
145151 * is concurrent, and either the stream is unordered or the collector is
146152 * unordered, then a concurrent reduction will be performed
147153 * (see {@link Collector} for details on concurrent reduction.)
148 *
149 * <p>This is a terminal operation.
150 *
151 * <p>When executed in parallel, multiple intermediate results may be
154 * </p>
155 *
156 * <p>
157 * This is an intermediate operation.
158 * </p>
159 *
160 * <p>
161 * When executed in parallel, multiple intermediate results may be
152162 * instantiated, populated, and merged so as to maintain isolation of
153163 * mutable data structures. Therefore, even when executed in parallel
154164 * with non-thread-safe data structures (such as {@code ArrayList}), no
155165 * additional synchronization is needed for a parallel reduction.
156 *
166 * </p>
167 * <p>
157168 * Note
158169 * The following will accumulate strings into an ArrayList:
170 * </p>
159171 * <pre>{@code
160172 * List<String> asList = stringStream.collect(Collectors.toList());
161173 * }</pre>
162174 *
163 * <p>The following will classify {@code Person} objects by city:
175 * <p>
176 * The following will classify {@code Person} objects by city:
177 * </p>
164178 * <pre>{@code
165179 * Map<String, List<Person>> peopleByCity
166180 * = personStream.collect(Collectors.groupingBy(Person::getCity));
167181 * }</pre>
168182 *
169 * <p>The following will classify {@code Person} objects by state and city,
183 * <p>
184 * The following will classify {@code Person} objects by state and city,
170185 * cascading two {@code Collector}s together:
186 * </p>
171187 * <pre>{@code
172188 * Map<String, Map<String, List<Person>>> peopleByStateAndCity
173189 * = personStream.collect(Collectors.groupingBy(Person::getState,
198214 * return result;
199215 * }</pre>
200216 *
201 * <p>Like {@link #reduce(Object, BinaryOperator)}, {@code collect} operations
217 * <p>
218 * Like {@link #reduce(Object, BinaryOperator)}, {@code collect} operations
202219 * can be parallelized without requiring additional synchronization.
203 *
204 * <p>This is a terminal operation.
205 *
220 * </p>
221 *
222 * <p>
223 * This is an intermediate operation.
224 * </p>
225 *
226 * <p>
206227 * Note There are many existing classes in the JDK whose signatures are
207228 * well-suited for use with method references as arguments to {@code collect()}.
208229 * For example, the following will accumulate strings into an {@code ArrayList}:
230 * </p>
209231 * <pre>{@code
210232 * List<String> asList = stringStream.collect(ArrayList::new, ArrayList::add,
211233 * ArrayList::addAll);
212234 * }</pre>
213235 *
214 * <p>The following will take a stream of strings and concatenates them into a
236 * <p>
237 * The following will take a stream of strings and concatenates them into a
215238 * single string:
239 * </p>
216240 * <pre>{@code
217241 * String concat = stringStream.collect(StringBuilder::new, StringBuilder::append,
218242 * StringBuilder::append)
249273 *
250274 * but is not constrained to execute sequentially.
251275 *
252 * <p>The {@code identity} value must be an identity for the accumulator
276 * <p>
277 * The {@code identity} value must be an identity for the accumulator
253278 * function. This means that for all {@code t},
254279 * {@code accumulator.apply(identity, t)} is equal to {@code t}.
255280 * The {@code accumulator} function must be an associative function.
256 *
257 * <p>This is a terminal operation.
281 * </p>
282 *
283 * <p>
284 * This is an intermediate operation.
285 * </p>
258286 *
259287 * Note Sum, min, max, average, and string concatenation are all special
260288 * cases of reduction. Summing a stream of numbers can be expressed as:
269297 * Integer sum = integers.reduce(0, Integer::sum);
270298 * }</pre>
271299 *
272 * <p>While this may seem a more roundabout way to perform an aggregation
300 * <p>
301 * While this may seem a more roundabout way to perform an aggregation
273302 * compared to simply mutating a running total in a loop, reduction
274303 * operations parallelize more gracefully, without needing additional
275304 * synchronization and with greatly reduced risk of data races.
305 * </p>
276306 *
277307 * @param identity the identity value for the accumulating function
278308 * @param accumulator an associative, non-interfering, stateless
288318 * Returns a stream consisting of the results of applying the given
289319 * function to the elements of this stream.
290320 *
291 * <p>This is an intermediate operation.
321 * <p>
322 * This is an intermediate operation.
323 * </p>
292324 *
293325 * @param <R> The element type of the new stream
294326 * @param mapper A non-interfering, stateless function to apply to each element
313345 * determining the result. If the stream is empty then {@code true} is
314346 * returned and the predicate is not evaluated.
315347 *
316 * <p>This is a short-circuiting terminal operation.
317 *
348 * <p>
349 * This is a short-circuiting terminal operation.
350 * </p>
351 *
352 * <p>
318353 * Note
319354 * This method evaluates the <em>universal quantification</em> of the
320355 * predicate over the elements of the stream (for all x P(x)). If the
321356 * stream is empty, the quantification is said to be <em>vacuously
322357 * satisfied</em> and is always {@code true} (regardless of P(x)).
358 * </p>
323359 *
324360 * @param predicate A non-interfering, stateless predicate to apply to
325361 * elements of this stream
337373 * necessary for determining the result. If the stream is empty then
338374 * {@code false} is returned and the predicate is not evaluated.
339375 *
340 * <p>This is a short-circuiting terminal operation.
376 * <p>
377 * This is a short-circuiting terminal operation.
378 * </p>
341379 *
342380 * Note
343381 * This method evaluates the <em>existential quantification</em> of the
439477 }
440478
441479 /**
480 * A Collector type for arrays.
481 *
482 * @param <O> The array type.
442483 * @deprecated Use {@link org.apache.commons.lang3.stream.Streams.ArrayCollector}.
443484 */
444485 @Deprecated
446487 private static final Set<Characteristics> characteristics = Collections.emptySet();
447488 private final Class<O> elementType;
448489
490 /**
491 * Constructs a new instance for the given element type.
492 *
493 * @param elementType The element type.
494 */
449495 public ArrayCollector(final Class<O> elementType) {
450496 this.elementType = elementType;
451497 }
470516
471517 @Override
472518 public Function<List<O>, O[]> finisher() {
473 return list -> {
474 @SuppressWarnings("unchecked")
475 final O[] array = (O[]) Array.newInstance(elementType, list.size());
476 return list.toArray(array);
477 };
519 return list -> list.toArray(ArrayUtils.newInstance(elementType, list.size()));
478520 }
479521
480522 @Override
427427 * instance to operate.</p>
428428 */
429429 public StringEscapeUtils() {
430 super();
431430 }
432431
433432 // Java and JavaScript
605604 return ESCAPE_HTML3.translate(input);
606605 }
607606
608 //-----------------------------------------------------------------------
609607 /**
610608 * <p>Unescapes a string containing entity escapes to a string
611609 * containing the actual Unicode characters corresponding to the
641639 return UNESCAPE_HTML3.translate(input);
642640 }
643641
644 //-----------------------------------------------------------------------
645642 /**
646643 * <p>Escapes the characters in a {@code String} using XML entities.</p>
647644 *
729726 return ESCAPE_XML11.translate(input);
730727 }
731728
732 //-----------------------------------------------------------------------
733729 /**
734730 * <p>Unescapes a string containing XML entity escapes to a string
735731 * containing the actual Unicode characters corresponding to the
751747 return UNESCAPE_XML.translate(input);
752748 }
753749
754 //-----------------------------------------------------------------------
755750
756751 /**
757752 * <p>Returns a {@code String} value for a CSV column enclosed in double quotes,
2626 import java.util.Locale;
2727 import java.util.Objects;
2828 import java.util.Set;
29 import java.util.StringJoiner;
2930 import java.util.function.Supplier;
3031 import java.util.regex.Pattern;
32
33 import org.apache.commons.lang3.function.Suppliers;
34 import org.apache.commons.lang3.function.ToBooleanBiFunction;
3135
3236 /**
3337 * <p>Operations on {@link java.lang.String} that are
183187 */
184188 private static final Pattern STRIP_ACCENTS_PATTERN = Pattern.compile("\\p{InCombiningDiacriticalMarks}+"); //$NON-NLS-1$
185189
186 // Abbreviating
187 //-----------------------------------------------------------------------
188190 /**
189191 * <p>Abbreviates a String using ellipses. This will turn
190192 * "Now is the time for all good men" into "Now is the time for..."</p>
338340 public static String abbreviate(final String str, final String abbrevMarker, int offset, final int maxWidth) {
339341 if (isNotEmpty(str) && EMPTY.equals(abbrevMarker) && maxWidth > 0) {
340342 return substring(str, 0, maxWidth);
341 } else if (isAnyEmpty(str, abbrevMarker)) {
343 }
344 if (isAnyEmpty(str, abbrevMarker)) {
342345 return str;
343346 }
344347 final int abbrevMarkerLength = abbrevMarker.length();
348351 if (maxWidth < minAbbrevWidth) {
349352 throw new IllegalArgumentException(String.format("Minimum abbreviation width is %d", minAbbrevWidth));
350353 }
351 if (str.length() <= maxWidth) {
354 final int strLen = str.length();
355 if (strLen <= maxWidth) {
352356 return str;
353357 }
354 if (offset > str.length()) {
355 offset = str.length();
356 }
357 if (str.length() - offset < maxWidth - abbrevMarkerLength) {
358 offset = str.length() - (maxWidth - abbrevMarkerLength);
358 if (offset > strLen) {
359 offset = strLen;
360 }
361 if (strLen - offset < maxWidth - abbrevMarkerLength) {
362 offset = strLen - (maxWidth - abbrevMarkerLength);
359363 }
360364 if (offset <= abbrevMarkerLength+1) {
361365 return str.substring(0, maxWidth - abbrevMarkerLength) + abbrevMarker;
363367 if (maxWidth < minAbbrevWidthOffset) {
364368 throw new IllegalArgumentException(String.format("Minimum abbreviation width with offset is %d", minAbbrevWidthOffset));
365369 }
366 if (offset + maxWidth - abbrevMarkerLength < str.length()) {
370 if (offset + maxWidth - abbrevMarkerLength < strLen) {
367371 return abbrevMarker + abbreviate(str.substring(offset), abbrevMarker, maxWidth - abbrevMarkerLength);
368372 }
369 return abbrevMarker + str.substring(str.length() - (maxWidth - abbrevMarkerLength));
373 return abbrevMarker + str.substring(strLen - (maxWidth - abbrevMarkerLength));
370374 }
371375
372376 /**
558562 return new String(newCodePoints, 0, outOffset);
559563 }
560564
561 // Centering
562 //-----------------------------------------------------------------------
563565 /**
564566 * <p>Centers a String in a larger String of size {@code size}
565567 * using the space character (' ').</p>
668670 return str;
669671 }
670672
671 // Chomping
672 //-----------------------------------------------------------------------
673673 /**
674674 * <p>Removes one newline from end of a String if it's there,
675675 * otherwise leave it alone. A newline is &quot;{@code \n}&quot;,
753753 return removeEnd(str, separator);
754754 }
755755
756 // Chopping
757 //-----------------------------------------------------------------------
758756 /**
759757 * <p>Remove the last character from a String.</p>
760758 *
795793 return ret;
796794 }
797795
798 // Compare
799 //-----------------------------------------------------------------------
800796 /**
801797 * <p>Compare two Strings lexicographically, as per {@link String#compareTo(String)}, returning :</p>
802798 * <ul>
868864 * @since 3.5
869865 */
870866 public static int compare(final String str1, final String str2, final boolean nullIsLess) {
871 if (str1 == str2) {
867 if (str1 == str2) { // NOSONARLINT this intentionally uses == to allow for both null
872868 return 0;
873869 }
874870 if (str1 == null) {
961957 * @since 3.5
962958 */
963959 public static int compareIgnoreCase(final String str1, final String str2, final boolean nullIsLess) {
964 if (str1 == str2) {
960 if (str1 == str2) { // NOSONARLINT this intentionally uses == to allow for both null
965961 return 0;
966962 }
967963 if (str1 == null) {
1002998 return CharSequenceUtils.indexOf(seq, searchSeq, 0) >= 0;
1003999 }
10041000
1005 // Contains
1006 //-----------------------------------------------------------------------
10071001 /**
10081002 * <p>Checks if CharSequence contains a search character, handling {@code null}.
10091003 * This method uses {@link String#indexOf(int)} if possible.</p>
10311025 return CharSequenceUtils.indexOf(seq, searchChar, 0) >= 0;
10321026 }
10331027
1034 // ContainsAny
1035 //-----------------------------------------------------------------------
10361028 /**
10371029 * <p>Checks if the CharSequence contains any character in the given
10381030 * set of characters.</p>
10701062 final char ch = cs.charAt(i);
10711063 for (int j = 0; j < searchLength; j++) {
10721064 if (searchChars[j] == ch) {
1073 if (Character.isHighSurrogate(ch)) {
1074 if (j == searchLast) {
1075 // missing low surrogate, fine, like String.indexOf(String)
1076 return true;
1077 }
1078 if (i < csLast && searchChars[j + 1] == cs.charAt(i + 1)) {
1079 return true;
1080 }
1081 } else {
1065 if (!Character.isHighSurrogate(ch)) {
10821066 // ch is in the Basic Multilingual Plane
1067 return true;
1068 }
1069 if (j == searchLast) {
1070 // missing low surrogate, fine, like String.indexOf(String)
1071 return true;
1072 }
1073 if (i < csLast && searchChars[j + 1] == cs.charAt(i + 1)) {
10831074 return true;
10841075 }
10851076 }
11271118 }
11281119
11291120 /**
1130 * <p>Checks if the CharSequence contains any of the CharSequences in the given array.</p>
1131 *
11321121 * <p>
1133 * A {@code null} {@code cs} CharSequence will return {@code false}. A {@code null} or zero
1134 * length search array will return {@code false}.
1122 * Checks if the CharSequence contains any of the CharSequences in the given array.
1123 * </p>
1124 *
1125 * <p>
1126 * A {@code null} {@code cs} CharSequence will return {@code false}. A {@code null} or zero length search array will
1127 * return {@code false}.
11351128 * </p>
11361129 *
11371130 * <pre>
11461139 *
11471140 *
11481141 * @param cs The CharSequence to check, may be null
1149 * @param searchCharSequences The array of CharSequences to search for, may be null.
1150 * Individual CharSequences may be null as well.
1142 * @param searchCharSequences The array of CharSequences to search for, may be null. Individual CharSequences may be
1143 * null as well.
11511144 * @return {@code true} if any of the search CharSequences are found, {@code false} otherwise
11521145 * @since 3.4
11531146 */
11541147 public static boolean containsAny(final CharSequence cs, final CharSequence... searchCharSequences) {
1148 return containsAny(StringUtils::contains, cs, searchCharSequences);
1149 }
1150
1151 /**
1152 * <p>
1153 * Checks if the CharSequence contains any of the CharSequences in the given array.
1154 * </p>
1155 *
1156 * <p>
1157 * A {@code null} {@code cs} CharSequence will return {@code false}. A {@code null} or zero length search array will
1158 * return {@code false}.
1159 * </p>
1160 *
1161 * @param cs The CharSequence to check, may be null
1162 * @param searchCharSequences The array of CharSequences to search for, may be null. Individual CharSequences may be
1163 * null as well.
1164 * @return {@code true} if any of the search CharSequences are found, {@code false} otherwise
1165 * @since 3.12.0
1166 */
1167 private static boolean containsAny(final ToBooleanBiFunction<CharSequence, CharSequence> test,
1168 final CharSequence cs, final CharSequence... searchCharSequences) {
11551169 if (isEmpty(cs) || ArrayUtils.isEmpty(searchCharSequences)) {
11561170 return false;
11571171 }
11581172 for (final CharSequence searchCharSequence : searchCharSequences) {
1159 if (contains(cs, searchCharSequence)) {
1173 if (test.applyAsBoolean(cs, searchCharSequence)) {
11601174 return true;
11611175 }
11621176 }
11631177 return false;
1178 }
1179
1180 /**
1181 * <p>
1182 * Checks if the CharSequence contains any of the CharSequences in the given array, ignoring case.
1183 * </p>
1184 *
1185 * <p>
1186 * A {@code null} {@code cs} CharSequence will return {@code false}. A {@code null} or zero length search array will
1187 * return {@code false}.
1188 * </p>
1189 *
1190 * <pre>
1191 * StringUtils.containsAny(null, *) = false
1192 * StringUtils.containsAny("", *) = false
1193 * StringUtils.containsAny(*, null) = false
1194 * StringUtils.containsAny(*, []) = false
1195 * StringUtils.containsAny("abcd", "ab", null) = true
1196 * StringUtils.containsAny("abcd", "ab", "cd") = true
1197 * StringUtils.containsAny("abc", "d", "abc") = true
1198 * StringUtils.containsAny("abc", "D", "ABC") = true
1199 * StringUtils.containsAny("ABC", "d", "abc") = true
1200 * </pre>
1201 *
1202 *
1203 * @param cs The CharSequence to check, may be null
1204 * @param searchCharSequences The array of CharSequences to search for, may be null. Individual CharSequences may be
1205 * null as well.
1206 * @return {@code true} if any of the search CharSequences are found, {@code false} otherwise
1207 * @since 3.12.0
1208 */
1209 public static boolean containsAnyIgnoreCase(final CharSequence cs, final CharSequence... searchCharSequences) {
1210 return containsAny(StringUtils::containsIgnoreCase, cs, searchCharSequences);
11641211 }
11651212
11661213 /**
12011248 return false;
12021249 }
12031250
1204 // ContainsNone
1205 //-----------------------------------------------------------------------
12061251 /**
12071252 * <p>Checks that the CharSequence does not contain certain characters.</p>
12081253 *
12381283 final char ch = cs.charAt(i);
12391284 for (int j = 0; j < searchLen; j++) {
12401285 if (searchChars[j] == ch) {
1241 if (Character.isHighSurrogate(ch)) {
1242 if (j == searchLast) {
1243 // missing low surrogate, fine, like String.indexOf(String)
1244 return false;
1245 }
1246 if (i < csLast && searchChars[j + 1] == cs.charAt(i + 1)) {
1247 return false;
1248 }
1249 } else {
1286 if (!Character.isHighSurrogate(ch)) {
12501287 // ch is in the Basic Multilingual Plane
1288 return false;
1289 }
1290 if (j == searchLast) {
1291 // missing low surrogate, fine, like String.indexOf(String)
1292 return false;
1293 }
1294 if (i < csLast && searchChars[j + 1] == cs.charAt(i + 1)) {
12511295 return false;
12521296 }
12531297 }
12801324 * @since 3.0 Changed signature from containsNone(String, String) to containsNone(CharSequence, String)
12811325 */
12821326 public static boolean containsNone(final CharSequence cs, final String invalidChars) {
1283 if (cs == null || invalidChars == null) {
1327 if (invalidChars == null) {
12841328 return true;
12851329 }
12861330 return containsNone(cs, invalidChars.toCharArray());
12871331 }
12881332
1289 // ContainsOnly
1290 //-----------------------------------------------------------------------
12911333 /**
12921334 * <p>Checks if the CharSequence contains only certain characters.</p>
12931335 *
13811423 private static void convertRemainingAccentCharacters(final StringBuilder decomposed) {
13821424 for (int i = 0; i < decomposed.length(); i++) {
13831425 if (decomposed.charAt(i) == '\u0141') {
1384 decomposed.deleteCharAt(i);
1385 decomposed.insert(i, 'L');
1426 decomposed.setCharAt(i, 'L');
13861427 } else if (decomposed.charAt(i) == '\u0142') {
1387 decomposed.deleteCharAt(i);
1388 decomposed.insert(i, 'l');
1428 decomposed.setCharAt(i, 'l');
13891429 }
13901430 }
13911431 }
14231463 return count;
14241464 }
14251465
1426 // Count matches
1427 //-----------------------------------------------------------------------
1428 /**
1429 * <p>Counts how many times the substring appears in the larger string.</p>
1466 /**
1467 * <p>Counts how many times the substring appears in the larger string.
1468 * Note that the code only counts non-overlapping matches.</p>
14301469 *
14311470 * <p>A {@code null} or empty ("") String input returns {@code 0}.</p>
14321471 *
14381477 * StringUtils.countMatches("abba", "a") = 2
14391478 * StringUtils.countMatches("abba", "ab") = 1
14401479 * StringUtils.countMatches("abba", "xxx") = 0
1480 * StringUtils.countMatches("ababa", "aba") = 1
14411481 * </pre>
14421482 *
14431483 * @param str the CharSequence to check, may be null
15451585 return str == null ? defaultStr : str;
15461586 }
15471587
1548 // Delete
1549 //-----------------------------------------------------------------------
15501588 /**
15511589 * <p>Deletes all whitespaces from a String as defined by
15521590 * {@link Character#isWhitespace(char)}.</p>
15761614 if (count == sz) {
15771615 return str;
15781616 }
1617 if (count == 0) {
1618 return EMPTY;
1619 }
15791620 return new String(chs, 0, count);
15801621 }
15811622
1582 // Difference
1583 //-----------------------------------------------------------------------
15841623 /**
15851624 * <p>Compares two Strings, and returns the portion where they differ.
15861625 * More precisely, return the remainder of the second String,
17331772 return endsWith(str, suffix, true);
17341773 }
17351774
1736 // Equals
1737 //-----------------------------------------------------------------------
17381775 /**
17391776 * <p>Compares two CharSequences, returning {@code true} if they represent
17401777 * equal sequences of characters.</p>
20172054 return EMPTY;
20182055 }
20192056 return strs[0];
2020 } else if (smallestIndexOfDiff == 0) {
2057 }
2058 if (smallestIndexOfDiff == 0) {
20212059 // there were no common initial characters
20222060 return EMPTY;
2023 } else {
2024 // we found a common initial character sequence
2025 return strs[0].substring(0, smallestIndexOfDiff);
2026 }
2061 }
2062 // we found a common initial character sequence
2063 return strs[0].substring(0, smallestIndexOfDiff);
20272064 }
20282065
20292066 /**
20962133 public static int getFuzzyDistance(final CharSequence term, final CharSequence query, final Locale locale) {
20972134 if (term == null || query == null) {
20982135 throw new IllegalArgumentException("Strings must not be null");
2099 } else if (locale == null) {
2136 }
2137 if (locale == null) {
21002138 throw new IllegalArgumentException("Locale must not be null");
21012139 }
21022140
21722210 * @since 3.10
21732211 */
21742212 public static <T extends CharSequence> T getIfBlank(final T str, final Supplier<T> defaultSupplier) {
2175 return isBlank(str) ? defaultSupplier == null ? null : defaultSupplier.get() : str;
2213 return isBlank(str) ? Suppliers.get(defaultSupplier) : str;
21762214 }
21772215
21782216 /**
22002238 * @since 3.10
22012239 */
22022240 public static <T extends CharSequence> T getIfEmpty(final T str, final Supplier<T> defaultSupplier) {
2203 return isEmpty(str) ? defaultSupplier == null ? null : defaultSupplier.get() : str;
2241 return isEmpty(str) ? Suppliers.get(defaultSupplier) : str;
22042242 }
22052243
22062244 /**
22512289 if (m == 0) {
22522290 return 0D;
22532291 }
2254 final double j = ((m / first.length() + m / second.length() + (m - mtp[1]) / m)) / 3;
2292 final double j = (m / first.length() + m / second.length() + (m - mtp[1]) / m) / 3;
22552293 final double jw = j < 0.7D ? j : j + Math.min(DEFAULT_SCALING_FACTOR, 1D / mtp[3]) * mtp[2] * (1D - j);
22562294 return Math.round(jw * 100.0D) / 100.0D;
22572295 }
22582296
2259 // Misc
2260 //-----------------------------------------------------------------------
22612297 /**
22622298 * <p>Find the Levenshtein distance between two Strings.</p>
22632299 *
23042340
23052341 if (n == 0) {
23062342 return m;
2307 } else if (m == 0) {
2343 }
2344 if (m == 0) {
23082345 return n;
23092346 }
23102347
24422479 // if one string is empty, the edit distance is necessarily the length of the other
24432480 if (n == 0) {
24442481 return m <= threshold ? m : -1;
2445 } else if (m == 0) {
2482 }
2483 if (m == 0) {
24462484 return n <= threshold ? n : -1;
2447 } else if (Math.abs(n - m) > threshold) {
2485 }
2486 if (Math.abs(n - m) > threshold) {
24482487 // no need to calculate the distance if the length difference is greater than the threshold
24492488 return -1;
24502489 }
25872626 return CharSequenceUtils.indexOf(seq, searchSeq, startPos);
25882627 }
25892628
2590 // IndexOf
2591 //-----------------------------------------------------------------------
25922629 /**
25932630 * Returns the index within {@code seq} of the first occurrence of
25942631 * the specified character. If a character with value
26932730 return CharSequenceUtils.indexOf(seq, searchChar, startPos);
26942731 }
26952732
2696 // IndexOfAny chars
2697 //-----------------------------------------------------------------------
26982733 /**
26992734 * <p>Search a CharSequence to find the first index of any
27002735 * character in the given set of characters.</p>
27302765 final char ch = cs.charAt(i);
27312766 for (int j = 0; j < searchLen; j++) {
27322767 if (searchChars[j] == ch) {
2733 if (i < csLast && j < searchLast && Character.isHighSurrogate(ch)) {
2734 // ch is a supplementary character
2735 if (searchChars[j + 1] == cs.charAt(i + 1)) {
2736 return i;
2737 }
2738 } else {
2768 if ((i >= csLast) || (j >= searchLast) || !Character.isHighSurrogate(ch)) {
2769 return i;
2770 }
2771 // ch is a supplementary character
2772 if (searchChars[j + 1] == cs.charAt(i + 1)) {
27392773 return i;
27402774 }
27412775 }
27442778 return INDEX_NOT_FOUND;
27452779 }
27462780
2747 // IndexOfAny strings
2748 //-----------------------------------------------------------------------
27492781 /**
27502782 * <p>Find the first index of any of a set of potential substrings.</p>
27512783 *
28292861 return indexOfAny(cs, searchChars.toCharArray());
28302862 }
28312863
2832 // IndexOfAnyBut chars
2833 //-----------------------------------------------------------------------
28342864 /**
28352865 * <p>Searches a CharSequence to find the first index of any
28362866 * character not in the given set of characters.</p>
28682898 final char ch = cs.charAt(i);
28692899 for (int j = 0; j < searchLen; j++) {
28702900 if (searchChars[j] == ch) {
2871 if (i < csLast && j < searchLast && Character.isHighSurrogate(ch)) {
2872 if (searchChars[j + 1] == cs.charAt(i + 1)) {
2873 continue outer;
2874 }
2875 } else {
2901 if ((i >= csLast) || (j >= searchLast) || !Character.isHighSurrogate(ch)) {
2902 continue outer;
2903 }
2904 if (searchChars[j + 1] == cs.charAt(i + 1)) {
28762905 continue outer;
28772906 }
28782907 }
29182947 if (chFound && CharSequenceUtils.indexOf(searchChars, ch2, 0) < 0) {
29192948 return i;
29202949 }
2921 } else {
2922 if (!chFound) {
2923 return i;
2924 }
2950 } else if (!chFound) {
2951 return i;
29252952 }
29262953 }
29272954 return INDEX_NOT_FOUND;
32783305 return true;
32793306 }
32803307
3281 // Character Tests
3282 //-----------------------------------------------------------------------
32833308 /**
32843309 * <p>Checks if the CharSequence contains only Unicode letters.</p>
32853310 *
33763401 }
33773402 final int sz = cs.length();
33783403 for (int i = 0; i < sz; i++) {
3379 if (!Character.isLetterOrDigit(cs.charAt(i)) && cs.charAt(i) != ' ') {
3404 final char nowChar = cs.charAt(i);
3405 if (nowChar != ' ' && !Character.isLetterOrDigit(nowChar) ) {
33803406 return false;
33813407 }
33823408 }
34113437 }
34123438 final int sz = cs.length();
34133439 for (int i = 0; i < sz; i++) {
3414 if (!Character.isLetter(cs.charAt(i)) && cs.charAt(i) != ' ') {
3440 final char nowChar = cs.charAt(i);
3441 if (nowChar != ' ' && !Character.isLetter(nowChar)) {
34153442 return false;
34163443 }
34173444 }
34423469 * @since 3.2
34433470 */
34443471 public static boolean isAnyBlank(final CharSequence... css) {
3445 if (ArrayUtils.isEmpty(css)) {
3472 if (ArrayUtils.isEmpty(css)) {
3473 return false;
3474 }
3475 for (final CharSequence cs : css) {
3476 if (isBlank(cs)) {
3477 return true;
3478 }
3479 }
34463480 return false;
3447 }
3448 for (final CharSequence cs : css) {
3449 if (isBlank(cs)) {
3450 return true;
3451 }
3452 }
3453 return false;
34543481 }
34553482
34563483 /**
34743501 * @since 3.2
34753502 */
34763503 public static boolean isAnyEmpty(final CharSequence... css) {
3477 if (ArrayUtils.isEmpty(css)) {
3504 if (ArrayUtils.isEmpty(css)) {
3505 return false;
3506 }
3507 for (final CharSequence cs : css) {
3508 if (isEmpty(cs)) {
3509 return true;
3510 }
3511 }
34783512 return false;
3479 }
3480 for (final CharSequence cs : css) {
3481 if (isEmpty(cs)) {
3482 return true;
3483 }
3484 }
3485 return false;
34863513 }
34873514
34883515 /**
35243551 return true;
35253552 }
35263553
3527 // Nested extraction
3528 //-----------------------------------------------------------------------
3529
35303554 /**
35313555 * <p>Checks if a CharSequence is empty (""), null or whitespace only.</p>
35323556 *
35583582 return true;
35593583 }
35603584
3561 // Empty checks
3562 //-----------------------------------------------------------------------
35633585 /**
35643586 * <p>Checks if a CharSequence is empty ("") or null.</p>
35653587 *
36153637 for (int i = 0; i < sz; i++) {
36163638 if (containsUppercase && containsLowercase) {
36173639 return true;
3618 } else if (Character.isUpperCase(cs.charAt(i))) {
3640 }
3641 if (Character.isUpperCase(cs.charAt(i))) {
36193642 containsUppercase = true;
36203643 } else if (Character.isLowerCase(cs.charAt(i))) {
36213644 containsLowercase = true;
37753798 * StringUtils.isNumericSpace(" ") = true
37763799 * StringUtils.isNumericSpace("123") = true
37773800 * StringUtils.isNumericSpace("12 3") = true
3778 * StringUtils.isNumeric("\u0967\u0968\u0969") = true
3779 * StringUtils.isNumeric("\u0967\u0968 \u0969") = true
3801 * StringUtils.isNumericSpace("\u0967\u0968\u0969") = true
3802 * StringUtils.isNumericSpace("\u0967\u0968 \u0969") = true
37803803 * StringUtils.isNumericSpace("ab2c") = false
37813804 * StringUtils.isNumericSpace("12-3") = false
37823805 * StringUtils.isNumericSpace("12.3") = false
37933816 }
37943817 final int sz = cs.length();
37953818 for (int i = 0; i < sz; i++) {
3796 if (!Character.isDigit(cs.charAt(i)) && cs.charAt(i) != ' ') {
3819 final char nowChar = cs.charAt(i);
3820 if (nowChar != ' ' && !Character.isDigit(nowChar)) {
37973821 return false;
37983822 }
37993823 }
38463870 * </p>
38473871 *
38483872 * <pre>
3873 * StringUtils.join(null, *) = null
3874 * StringUtils.join([], *) = ""
3875 * StringUtils.join([null], *) = ""
3876 * StringUtils.join([false, false], ';') = "false;false"
3877 * </pre>
3878 *
3879 * @param array
3880 * the array of values to join together, may be null
3881 * @param delimiter
3882 * the separator character to use
3883 * @return the joined String, {@code null} if null array input
3884 * @since 3.12.0
3885 */
3886 public static String join(final boolean[] array, final char delimiter) {
3887 if (array == null) {
3888 return null;
3889 }
3890 return join(array, delimiter, 0, array.length);
3891 }
3892
3893 /**
3894 * <p>
3895 * Joins the elements of the provided array into a single String containing the provided list of elements.
3896 * </p>
3897 *
3898 * <p>
3899 * No delimiter is added before or after the list. Null objects or empty strings within the array are represented
3900 * by empty strings.
3901 * </p>
3902 *
3903 * <pre>
3904 * StringUtils.join(null, *) = null
3905 * StringUtils.join([], *) = ""
3906 * StringUtils.join([null], *) = ""
3907 * StringUtils.join([true, false, true], ';') = "true;false;true"
3908 * </pre>
3909 *
3910 * @param array
3911 * the array of values to join together, may be null
3912 * @param delimiter
3913 * the separator character to use
3914 * @param startIndex
3915 * the first index to start joining from. It is an error to pass in a start index past the end of the
3916 * array
3917 * @param endIndex
3918 * the index to stop joining from (exclusive). It is an error to pass in an end index past the end of
3919 * the array
3920 * @return the joined String, {@code null} if null array input
3921 * @since 3.12.0
3922 */
3923 public static String join(final boolean[] array, final char delimiter, final int startIndex, final int endIndex) {
3924 if (array == null) {
3925 return null;
3926 }
3927 if (endIndex - startIndex <= 0) {
3928 return EMPTY;
3929 }
3930 final StringJoiner joiner = newStringJoiner(delimiter);
3931 for (int i = startIndex; i < endIndex; i++) {
3932 joiner.add(String.valueOf(array[i]));
3933 }
3934 return joiner.toString();
3935 }
3936
3937 /**
3938 * <p>
3939 * Joins the elements of the provided array into a single String containing the provided list of elements.
3940 * </p>
3941 *
3942 * <p>
3943 * No delimiter is added before or after the list. Null objects or empty strings within the array are represented
3944 * by empty strings.
3945 * </p>
3946 *
3947 * <pre>
38493948 * StringUtils.join(null, *) = null
38503949 * StringUtils.join([], *) = ""
38513950 * StringUtils.join([null], *) = ""
38553954 *
38563955 * @param array
38573956 * the array of values to join together, may be null
3858 * @param separator
3957 * @param delimiter
38593958 * the separator character to use
38603959 * @return the joined String, {@code null} if null array input
38613960 * @since 3.2
38623961 */
3863 public static String join(final byte[] array, final char separator) {
3962 public static String join(final byte[] array, final char delimiter) {
38643963 if (array == null) {
38653964 return null;
38663965 }
3867 return join(array, separator, 0, array.length);
3966 return join(array, delimiter, 0, array.length);
38683967 }
38693968
38703969 /**
38873986 *
38883987 * @param array
38893988 * the array of values to join together, may be null
3890 * @param separator
3989 * @param delimiter
38913990 * the separator character to use
38923991 * @param startIndex
38933992 * the first index to start joining from. It is an error to pass in a start index past the end of the
38983997 * @return the joined String, {@code null} if null array input
38993998 * @since 3.2
39003999 */
3901 public static String join(final byte[] array, final char separator, final int startIndex, final int endIndex) {
4000 public static String join(final byte[] array, final char delimiter, final int startIndex, final int endIndex) {
39024001 if (array == null) {
39034002 return null;
39044003 }
3905 final int noOfItems = endIndex - startIndex;
3906 if (noOfItems <= 0) {
4004 if (endIndex - startIndex <= 0) {
39074005 return EMPTY;
39084006 }
3909 final StringBuilder buf = newStringBuilder(noOfItems);
3910 buf.append(array[startIndex]);
3911 for (int i = startIndex + 1; i < endIndex; i++) {
3912 buf.append(separator);
3913 buf.append(array[i]);
3914 }
3915 return buf.toString();
4007 final StringJoiner joiner = newStringJoiner(delimiter);
4008 for (int i = startIndex; i < endIndex; i++) {
4009 joiner.add(String.valueOf(array[i]));
4010 }
4011 return joiner.toString();
39164012 }
39174013
39184014 /**
39354031 *
39364032 * @param array
39374033 * the array of values to join together, may be null
3938 * @param separator
4034 * @param delimiter
39394035 * the separator character to use
39404036 * @return the joined String, {@code null} if null array input
39414037 * @since 3.2
39424038 */
3943 public static String join(final char[] array, final char separator) {
4039 public static String join(final char[] array, final char delimiter) {
39444040 if (array == null) {
39454041 return null;
39464042 }
3947 return join(array, separator, 0, array.length);
4043 return join(array, delimiter, 0, array.length);
39484044 }
39494045
39504046 /**
39674063 *
39684064 * @param array
39694065 * the array of values to join together, may be null
3970 * @param separator
4066 * @param delimiter
39714067 * the separator character to use
39724068 * @param startIndex
39734069 * the first index to start joining from. It is an error to pass in a start index past the end of the
39784074 * @return the joined String, {@code null} if null array input
39794075 * @since 3.2
39804076 */
3981 public static String join(final char[] array, final char separator, final int startIndex, final int endIndex) {
4077 public static String join(final char[] array, final char delimiter, final int startIndex, final int endIndex) {
39824078 if (array == null) {
39834079 return null;
39844080 }
3985 final int noOfItems = endIndex - startIndex;
3986 if (noOfItems <= 0) {
4081 if (endIndex - startIndex <= 0) {
39874082 return EMPTY;
39884083 }
3989 final StringBuilder buf = newStringBuilder(noOfItems);
3990 buf.append(array[startIndex]);
3991 for (int i = startIndex + 1; i < endIndex; i++) {
3992 buf.append(separator);
3993 buf.append(array[i]);
3994 }
3995 return buf.toString();
4084 final StringJoiner joiner = newStringJoiner(delimiter);
4085 for (int i = startIndex; i < endIndex; i++) {
4086 joiner.add(String.valueOf(array[i]));
4087 }
4088 return joiner.toString();
39964089 }
39974090
39984091 /**
40154108 *
40164109 * @param array
40174110 * the array of values to join together, may be null
4018 * @param separator
4111 * @param delimiter
40194112 * the separator character to use
40204113 * @return the joined String, {@code null} if null array input
40214114 * @since 3.2
40224115 */
4023 public static String join(final double[] array, final char separator) {
4116 public static String join(final double[] array, final char delimiter) {
40244117 if (array == null) {
40254118 return null;
40264119 }
4027 return join(array, separator, 0, array.length);
4120 return join(array, delimiter, 0, array.length);
40284121 }
40294122
40304123 /**
40474140 *
40484141 * @param array
40494142 * the array of values to join together, may be null
4050 * @param separator
4143 * @param delimiter
40514144 * the separator character to use
40524145 * @param startIndex
40534146 * the first index to start joining from. It is an error to pass in a start index past the end of the
40584151 * @return the joined String, {@code null} if null array input
40594152 * @since 3.2
40604153 */
4061 public static String join(final double[] array, final char separator, final int startIndex, final int endIndex) {
4154 public static String join(final double[] array, final char delimiter, final int startIndex, final int endIndex) {
40624155 if (array == null) {
40634156 return null;
40644157 }
4065 final int noOfItems = endIndex - startIndex;
4066 if (noOfItems <= 0) {
4158 if (endIndex - startIndex <= 0) {
40674159 return EMPTY;
40684160 }
4069 final StringBuilder buf = newStringBuilder(noOfItems);
4070 buf.append(array[startIndex]);
4071 for (int i = startIndex + 1; i < endIndex; i++) {
4072 buf.append(separator);
4073 buf.append(array[i]);
4074 }
4075 return buf.toString();
4161 final StringJoiner joiner = newStringJoiner(delimiter);
4162 for (int i = startIndex; i < endIndex; i++) {
4163 joiner.add(String.valueOf(array[i]));
4164 }
4165 return joiner.toString();
40764166 }
40774167
40784168 /**
40954185 *
40964186 * @param array
40974187 * the array of values to join together, may be null
4098 * @param separator
4188 * @param delimiter
40994189 * the separator character to use
41004190 * @return the joined String, {@code null} if null array input
41014191 * @since 3.2
41024192 */
4103 public static String join(final float[] array, final char separator) {
4193 public static String join(final float[] array, final char delimiter) {
41044194 if (array == null) {
41054195 return null;
41064196 }
4107 return join(array, separator, 0, array.length);
4197 return join(array, delimiter, 0, array.length);
41084198 }
41094199
41104200 /**
41274217 *
41284218 * @param array
41294219 * the array of values to join together, may be null
4130 * @param separator
4220 * @param delimiter
41314221 * the separator character to use
41324222 * @param startIndex
41334223 * the first index to start joining from. It is an error to pass in a start index past the end of the
41384228 * @return the joined String, {@code null} if null array input
41394229 * @since 3.2
41404230 */
4141 public static String join(final float[] array, final char separator, final int startIndex, final int endIndex) {
4231 public static String join(final float[] array, final char delimiter, final int startIndex, final int endIndex) {
41424232 if (array == null) {
41434233 return null;
41444234 }
4145 final int noOfItems = endIndex - startIndex;
4146 if (noOfItems <= 0) {
4235 if (endIndex - startIndex <= 0) {
41474236 return EMPTY;
41484237 }
4149 final StringBuilder buf = newStringBuilder(noOfItems);
4150 buf.append(array[startIndex]);
4151 for (int i = startIndex + 1; i < endIndex; i++) {
4152 buf.append(separator);
4153 buf.append(array[i]);
4154 }
4155 return buf.toString();
4238 final StringJoiner joiner = newStringJoiner(delimiter);
4239 for (int i = startIndex; i < endIndex; i++) {
4240 joiner.add(String.valueOf(array[i]));
4241 }
4242 return joiner.toString();
41564243 }
41574244
41584245 /**
42074294 *
42084295 * @param array
42094296 * the array of values to join together, may be null
4210 * @param separator
4297 * @param delimiter
42114298 * the separator character to use
42124299 * @param startIndex
42134300 * the first index to start joining from. It is an error to pass in a start index past the end of the
42184305 * @return the joined String, {@code null} if null array input
42194306 * @since 3.2
42204307 */
4221 public static String join(final int[] array, final char separator, final int startIndex, final int endIndex) {
4308 public static String join(final int[] array, final char delimiter, final int startIndex, final int endIndex) {
42224309 if (array == null) {
42234310 return null;
42244311 }
4225 final int noOfItems = endIndex - startIndex;
4226 if (noOfItems <= 0) {
4312 if (endIndex - startIndex <= 0) {
42274313 return EMPTY;
42284314 }
4229 final StringBuilder buf = newStringBuilder(noOfItems);
4230 buf.append(array[startIndex]);
4231 for (int i = startIndex + 1; i < endIndex; i++) {
4232 buf.append(separator);
4233 buf.append(array[i]);
4234 }
4235 return buf.toString();
4315 final StringJoiner joiner = newStringJoiner(delimiter);
4316 for (int i = startIndex; i < endIndex; i++) {
4317 joiner.add(String.valueOf(array[i]));
4318 }
4319 return joiner.toString();
42364320 }
42374321
42384322 /**
43024386 }
43034387 final Object first = iterator.next();
43044388 if (!iterator.hasNext()) {
4305 return Objects.toString(first, EMPTY);
4389 return toStringOrEmpty(first);
43064390 }
43074391
43084392 // two or more elements
44964580 *
44974581 * @param array
44984582 * the array of values to join together, may be null
4499 * @param separator
4583 * @param delimiter
45004584 * the separator character to use
45014585 * @param startIndex
45024586 * the first index to start joining from. It is an error to pass in a start index past the end of the
45074591 * @return the joined String, {@code null} if null array input
45084592 * @since 3.2
45094593 */
4510 public static String join(final long[] array, final char separator, final int startIndex, final int endIndex) {
4594 public static String join(final long[] array, final char delimiter, final int startIndex, final int endIndex) {
45114595 if (array == null) {
45124596 return null;
45134597 }
4514 final int noOfItems = endIndex - startIndex;
4515 if (noOfItems <= 0) {
4598 if (endIndex - startIndex <= 0) {
45164599 return EMPTY;
45174600 }
4518 final StringBuilder buf = newStringBuilder(noOfItems);
4519 buf.append(array[startIndex]);
4520 for (int i = startIndex + 1; i < endIndex; i++) {
4521 buf.append(separator);
4522 buf.append(array[i]);
4523 }
4524 return buf.toString();
4601 final StringJoiner joiner = newStringJoiner(delimiter);
4602 for (int i = startIndex; i < endIndex; i++) {
4603 joiner.add(String.valueOf(array[i]));
4604 }
4605 return joiner.toString();
45254606 }
45264607
45274608 /**
45424623 * </pre>
45434624 *
45444625 * @param array the array of values to join together, may be null
4545 * @param separator the separator character to use
4626 * @param delimiter the separator character to use
45464627 * @return the joined String, {@code null} if null array input
45474628 * @since 2.0
45484629 */
4549 public static String join(final Object[] array, final char separator) {
4630 public static String join(final Object[] array, final char delimiter) {
45504631 if (array == null) {
45514632 return null;
45524633 }
4553 return join(array, separator, 0, array.length);
4634 return join(array, delimiter, 0, array.length);
45544635 }
45554636
45564637 /**
45714652 * </pre>
45724653 *
45734654 * @param array the array of values to join together, may be null
4574 * @param separator the separator character to use
4655 * @param delimiter the separator character to use
45754656 * @param startIndex the first index to start joining from. It is
45764657 * an error to pass in a start index past the end of the array
45774658 * @param endIndex the index to stop joining from (exclusive). It is
45794660 * @return the joined String, {@code null} if null array input
45804661 * @since 2.0
45814662 */
4582 public static String join(final Object[] array, final char separator, final int startIndex, final int endIndex) {
4663 public static String join(final Object[] array, final char delimiter, final int startIndex, final int endIndex) {
45834664 if (array == null) {
45844665 return null;
45854666 }
4586 final int noOfItems = endIndex - startIndex;
4587 if (noOfItems <= 0) {
4667 if (endIndex - startIndex <= 0) {
45884668 return EMPTY;
45894669 }
4590 final StringBuilder buf = newStringBuilder(noOfItems);
4591 if (array[startIndex] != null) {
4592 buf.append(array[startIndex]);
4593 }
4594 for (int i = startIndex + 1; i < endIndex; i++) {
4595 buf.append(separator);
4596 if (array[i] != null) {
4597 buf.append(array[i]);
4598 }
4599 }
4600 return buf.toString();
4670 final StringJoiner joiner = newStringJoiner(delimiter);
4671 for (int i = startIndex; i < endIndex; i++) {
4672 joiner.add(toStringOrEmpty(array[i]));
4673 }
4674 return joiner.toString();
46014675 }
46024676
46034677 /**
46204694 * </pre>
46214695 *
46224696 * @param array the array of values to join together, may be null
4623 * @param separator the separator character to use, null treated as ""
4697 * @param delimiter the separator character to use, null treated as ""
46244698 * @return the joined String, {@code null} if null array input
46254699 */
4626 public static String join(final Object[] array, final String separator) {
4700 public static String join(final Object[] array, final String delimiter) {
46274701 if (array == null) {
46284702 return null;
46294703 }
4630 return join(array, separator, 0, array.length);
4704 return join(array, delimiter, 0, array.length);
46314705 }
46324706
46334707 /**
46534727 * </pre>
46544728 *
46554729 * @param array the array of values to join together, may be null
4656 * @param separator the separator character to use, null treated as ""
4730 * @param delimiter the separator character to use, null treated as ""
46574731 * @param startIndex the first index to start joining from.
46584732 * @param endIndex the index to stop joining from (exclusive).
46594733 * @return the joined String, {@code null} if null array input; or the empty string
46654739 * {@code endIndex < 0} or <br>
46664740 * {@code endIndex > array.length()}
46674741 */
4668 public static String join(final Object[] array, String separator, final int startIndex, final int endIndex) {
4742 public static String join(final Object[] array, final String delimiter, final int startIndex, final int endIndex) {
46694743 if (array == null) {
46704744 return null;
46714745 }
4672 if (separator == null) {
4673 separator = EMPTY;
4674 }
4675
4676 // endIndex - startIndex > 0: Len = NofStrings *(len(firstString) + len(separator))
4677 // (Assuming that all Strings are roughly equally long)
4678 final int noOfItems = endIndex - startIndex;
4679 if (noOfItems <= 0) {
4746 if (endIndex - startIndex <= 0) {
46804747 return EMPTY;
46814748 }
4682
4683 final StringBuilder buf = newStringBuilder(noOfItems);
4684
4685 if (array[startIndex] != null) {
4686 buf.append(array[startIndex]);
4687 }
4688
4689 for (int i = startIndex + 1; i < endIndex; i++) {
4690 buf.append(separator);
4691
4692 if (array[i] != null) {
4693 buf.append(array[i]);
4694 }
4695 }
4696 return buf.toString();
4749 final StringJoiner joiner = new StringJoiner(toStringOrEmpty(delimiter));
4750 for (int i = startIndex; i < endIndex; i++) {
4751 joiner.add(toStringOrEmpty(array[i]));
4752 }
4753 return joiner.toString();
46974754 }
46984755
46994756 /**
47164773 *
47174774 * @param array
47184775 * the array of values to join together, may be null
4719 * @param separator
4776 * @param delimiter
47204777 * the separator character to use
47214778 * @return the joined String, {@code null} if null array input
47224779 * @since 3.2
47234780 */
4724 public static String join(final short[] array, final char separator) {
4781 public static String join(final short[] array, final char delimiter) {
47254782 if (array == null) {
47264783 return null;
47274784 }
4728 return join(array, separator, 0, array.length);
4785 return join(array, delimiter, 0, array.length);
47294786 }
47304787
47314788 /**
47484805 *
47494806 * @param array
47504807 * the array of values to join together, may be null
4751 * @param separator
4808 * @param delimiter
47524809 * the separator character to use
47534810 * @param startIndex
47544811 * the first index to start joining from. It is an error to pass in a start index past the end of the
47594816 * @return the joined String, {@code null} if null array input
47604817 * @since 3.2
47614818 */
4762 public static String join(final short[] array, final char separator, final int startIndex, final int endIndex) {
4819 public static String join(final short[] array, final char delimiter, final int startIndex, final int endIndex) {
47634820 if (array == null) {
47644821 return null;
47654822 }
4766 final int noOfItems = endIndex - startIndex;
4767 if (noOfItems <= 0) {
4823 if (endIndex - startIndex <= 0) {
47684824 return EMPTY;
47694825 }
4770 final StringBuilder buf = newStringBuilder(noOfItems);
4771 buf.append(array[startIndex]);
4772 for (int i = startIndex + 1; i < endIndex; i++) {
4773 buf.append(separator);
4774 buf.append(array[i]);
4775 }
4776 return buf.toString();
4777 }
4778
4779
4780 // Joining
4781 //-----------------------------------------------------------------------
4826 final StringJoiner joiner = newStringJoiner(delimiter);
4827 for (int i = startIndex; i < endIndex; i++) {
4828 joiner.add(String.valueOf(array[i]));
4829 }
4830 return joiner.toString();
4831 }
4832
47824833 /**
47834834 * <p>Joins the elements of the provided array into a single String
47844835 * containing the provided list of elements.</p>
48204871 * StringUtils.joinWith(null, {"a", "b"}) = "ab"
48214872 * </pre>
48224873 *
4823 * @param separator the separator character to use, null treated as ""
4824 * @param objects the varargs providing the values to join together. {@code null} elements are treated as ""
4874 * @param delimiter the separator character to use, null treated as ""
4875 * @param array the varargs providing the values to join together. {@code null} elements are treated as ""
48254876 * @return the joined String.
48264877 * @throws java.lang.IllegalArgumentException if a null varargs is provided
48274878 * @since 3.5
48284879 */
4829 public static String joinWith(final String separator, final Object... objects) {
4830 if (objects == null) {
4880 public static String joinWith(final String delimiter, final Object... array) {
4881 if (array == null) {
48314882 throw new IllegalArgumentException("Object varargs must not be null");
48324883 }
4833
4834 final String sanitizedSeparator = defaultString(separator);
4835
4836 final StringBuilder result = new StringBuilder();
4837
4838 final Iterator<Object> iterator = Arrays.asList(objects).iterator();
4839 while (iterator.hasNext()) {
4840 final String value = Objects.toString(iterator.next(), "");
4841 result.append(value);
4842
4843 if (iterator.hasNext()) {
4844 result.append(sanitizedSeparator);
4845 }
4846 }
4847
4848 return result.toString();
4884 return join(array, delimiter);
48494885 }
48504886
48514887 /**
48724908 * @since 3.0 Changed signature from lastIndexOf(String, String) to lastIndexOf(CharSequence, CharSequence)
48734909 */
48744910 public static int lastIndexOf(final CharSequence seq, final CharSequence searchSeq) {
4875 if (seq == null || searchSeq == null) {
4911 if (seq == null) {
48764912 return INDEX_NOT_FOUND;
48774913 }
48784914 return CharSequenceUtils.lastIndexOf(seq, searchSeq, seq.length());
49144950 * @since 3.0 Changed signature from lastIndexOf(String, String, int) to lastIndexOf(CharSequence, CharSequence, int)
49154951 */
49164952 public static int lastIndexOf(final CharSequence seq, final CharSequence searchSeq, final int startPos) {
4917 if (seq == null || searchSeq == null) {
4918 return INDEX_NOT_FOUND;
4919 }
49204953 return CharSequenceUtils.lastIndexOf(seq, searchSeq, startPos);
49214954 }
49224955
4923 // LastIndexOf
4924 //-----------------------------------------------------------------------
49254956 /**
49264957 * Returns the index within {@code seq} of the last occurrence of
49274958 * the specified character. For values of {@code searchChar} in the
51245155 if (str == null || searchStr == null) {
51255156 return INDEX_NOT_FOUND;
51265157 }
5127 if (startPos > str.length() - searchStr.length()) {
5128 startPos = str.length() - searchStr.length();
5158 final int searchStrLength = searchStr.length();
5159 final int strLength = str.length();
5160 if (startPos > strLength - searchStrLength) {
5161 startPos = strLength - searchStrLength;
51295162 }
51305163 if (startPos < 0) {
51315164 return INDEX_NOT_FOUND;
51325165 }
5133 if (searchStr.length() == 0) {
5166 if (searchStrLength == 0) {
51345167 return startPos;
51355168 }
51365169
51375170 for (int i = startPos; i >= 0; i--) {
5138 if (CharSequenceUtils.regionMatches(str, true, i, searchStr, 0, searchStr.length())) {
5171 if (CharSequenceUtils.regionMatches(str, true, i, searchStr, 0, searchStrLength)) {
51395172 return i;
51405173 }
51415174 }
51805213 return ordinalIndexOf(str, searchStr, ordinal, true);
51815214 }
51825215
5183 // Left/Right/Mid
5184 //-----------------------------------------------------------------------
51855216 /**
51865217 * <p>Gets the leftmost {@code len} characters of a String.</p>
51875218 *
53155346
53165347 if (pads == padLen) {
53175348 return padStr.concat(str);
5318 } else if (pads < padLen) {
5349 }
5350 if (pads < padLen) {
53195351 return padStr.substring(0, pads).concat(str);
5320 } else {
5321 final char[] padding = new char[pads];
5322 final char[] padChars = padStr.toCharArray();
5323 for (int i = 0; i < pads; i++) {
5324 padding[i] = padChars[i % padLen];
5325 }
5326 return new String(padding).concat(str);
5327 }
5352 }
5353 final char[] padding = new char[pads];
5354 final char[] padChars = padStr.toCharArray();
5355 for (int i = 0; i < pads; i++) {
5356 padding[i] = padChars[i % padLen];
5357 }
5358 return new String(padding).concat(str);
53285359 }
53295360
53305361 /**
53885419 if (str == null) {
53895420 return null;
53905421 }
5391 return str.toLowerCase(locale);
5422 return str.toLowerCase(LocaleUtils.toLocale(locale));
53925423 }
53935424
53945425 private static int[] matches(final CharSequence first, final CharSequence second) {
5395 CharSequence max, min;
5426 final CharSequence max;
5427 final CharSequence min;
53965428 if (first.length() > second.length()) {
53975429 max = first;
53985430 min = second;
54385470 }
54395471 int prefix = 0;
54405472 for (int mi = 0; mi < min.length(); mi++) {
5441 if (first.charAt(mi) == second.charAt(mi)) {
5442 prefix++;
5443 } else {
5473 if (first.charAt(mi) != second.charAt(mi)) {
54445474 break;
54455475 }
5476 prefix++;
54465477 }
54475478 return new int[] { matches, transpositions / 2, prefix, max.length() };
54485479 }
54885519 return str.substring(pos, pos + len);
54895520 }
54905521
5491 private static StringBuilder newStringBuilder(final int noOfItems) {
5492 return new StringBuilder(noOfItems * 16);
5522 private static StringJoiner newStringJoiner(final char delimiter) {
5523 return new StringJoiner(String.valueOf(delimiter));
54935524 }
54945525
54955526 /**
56585689 return index;
56595690 }
56605691
5661 // Overlay
5662 //-----------------------------------------------------------------------
56635692 /**
56645693 * <p>Overlays part of a String with another String.</p>
56655694 *
60866115 * @since 3.5
60876116 */
60886117 public static String removeIgnoreCase(final String str, final String remove) {
6089 if (isEmpty(str) || isEmpty(remove)) {
6090 return str;
6091 }
60926118 return replaceIgnoreCase(str, remove, EMPTY, -1);
60936119 }
60946120
61296155 return RegExUtils.removePattern(source, regex);
61306156 }
61316157
6132 // Remove
6133 //-----------------------------------------------------------------------
61346158 /**
61356159 * <p>Removes a substring only if it is at the beginning of a source string,
61366160 * otherwise returns the source string.</p>
61916215 * @since 2.4
61926216 */
61936217 public static String removeStartIgnoreCase(final String str, final String remove) {
6194 if (isEmpty(str) || isEmpty(remove)) {
6195 return str;
6196 }
6197 if (startsWithIgnoreCase(str, remove)) {
6198 return str.substring(remove.length());
6218 if (str != null && startsWithIgnoreCase(str, remove)) {
6219 return str.substring(length(remove));
61996220 }
62006221 return str;
62016222 }
62276248 return EMPTY;
62286249 }
62296250 final char[] buf = new char[repeat];
6230 for (int i = repeat - 1; i >= 0; i--) {
6231 buf[i] = ch;
6232 }
6251 Arrays.fill(buf, ch);
62336252 return new String(buf);
62346253 }
62356254
6236 // Padding
6237 //-----------------------------------------------------------------------
62386255 /**
62396256 * <p>Repeat a String {@code repeat} times to form a
62406257 * new String.</p>
62556272 */
62566273 public static String repeat(final String str, final int repeat) {
62576274 // Performance tuned for 2.0 (JDK1.4)
6258
62596275 if (str == null) {
62606276 return null;
62616277 }
62916307 return buf.toString();
62926308 }
62936309 }
6294
6295 // Conversion
6296 //-----------------------------------------------------------------------
62976310
62986311 /**
62996312 * <p>Repeat a String {@code repeat} times to form a
64976510 return RegExUtils.replaceAll(text, regex, replacement);
64986511 }
64996512
6500 // Replace, character based
6501 //-----------------------------------------------------------------------
65026513 /**
65036514 * <p>Replaces all occurrences of a character in a String with another.
65046515 * This is a null-safe version of {@link String#replace(char, char)}.</p>
66956706 final Set<String> searchSet = new HashSet<>(Arrays.asList(searchList));
66966707 final Set<String> replacementSet = new HashSet<>(Arrays.asList(replacementList));
66976708 searchSet.retainAll(replacementSet);
6698 if (searchSet.size() > 0) {
6709 if (!searchSet.isEmpty()) {
66996710 throw new IllegalStateException("Aborting to protect against StackOverflowError - " +
67006711 "output of one loop is the input of another");
67016712 }
67356746 // see if we need to keep searching for this
67366747 if (tempIndex == -1) {
67376748 noMoreMatchesForReplIndex[i] = true;
6738 } else {
6739 if (textIndex == -1 || tempIndex < textIndex) {
6740 textIndex = tempIndex;
6741 replaceIndex = i;
6742 }
6749 } else if (textIndex == -1 || tempIndex < textIndex) {
6750 textIndex = tempIndex;
6751 replaceIndex = i;
67436752 }
67446753 }
67456754 // NOTE: logic mostly below END
67806789
67816790 textIndex = -1;
67826791 replaceIndex = -1;
6783 tempIndex = -1;
67846792 // find the next earliest match
67856793 // NOTE: logic mostly duplicated above START
67866794 for (int i = 0; i < searchLength; i++) {
67936801 // see if we need to keep searching for this
67946802 if (tempIndex == -1) {
67956803 noMoreMatchesForReplIndex[i] = true;
6796 } else {
6797 if (textIndex == -1 || tempIndex < textIndex) {
6798 textIndex = tempIndex;
6799 replaceIndex = i;
6800 }
6804 } else if (textIndex == -1 || tempIndex < textIndex) {
6805 textIndex = tempIndex;
6806 replaceIndex = i;
68016807 }
68026808 }
68036809 // NOTE: logic duplicated above END
69186924 }
69196925
69206926 /**
6921 * <p>Case insensitively replaces all occurrences of a String within another String.</p>
6922 *
6923 * <p>A {@code null} reference passed to this method is a no-op.</p>
6924 *
6925 * <pre>
6926 * StringUtils.replaceIgnoreCase(null, *, *) = null
6927 * StringUtils.replaceIgnoreCase("", *, *) = ""
6928 * StringUtils.replaceIgnoreCase("any", null, *) = "any"
6929 * StringUtils.replaceIgnoreCase("any", *, null) = "any"
6930 * StringUtils.replaceIgnoreCase("any", "", *) = "any"
6931 * StringUtils.replaceIgnoreCase("aba", "a", null) = "aba"
6932 * StringUtils.replaceIgnoreCase("abA", "A", "") = "b"
6933 * StringUtils.replaceIgnoreCase("aba", "A", "z") = "zbz"
6934 * </pre>
6935 *
6936 * @see #replaceIgnoreCase(String text, String searchString, String replacement, int max)
6937 * @param text text to search and replace in, may be null
6938 * @param searchString the String to search for (case insensitive), may be null
6939 * @param replacement the String to replace it with, may be null
6940 * @return the text with any replacements processed,
6941 * {@code null} if null String input
6942 * @since 3.5
6943 */
6944 public static String replaceIgnoreCase(final String text, final String searchString, final String replacement) {
6945 return replaceIgnoreCase(text, searchString, replacement, -1);
6946 }
6927 * <p>Case insensitively replaces all occurrences of a String within another String.</p>
6928 *
6929 * <p>A {@code null} reference passed to this method is a no-op.</p>
6930 *
6931 * <pre>
6932 * StringUtils.replaceIgnoreCase(null, *, *) = null
6933 * StringUtils.replaceIgnoreCase("", *, *) = ""
6934 * StringUtils.replaceIgnoreCase("any", null, *) = "any"
6935 * StringUtils.replaceIgnoreCase("any", *, null) = "any"
6936 * StringUtils.replaceIgnoreCase("any", "", *) = "any"
6937 * StringUtils.replaceIgnoreCase("aba", "a", null) = "aba"
6938 * StringUtils.replaceIgnoreCase("abA", "A", "") = "b"
6939 * StringUtils.replaceIgnoreCase("aba", "A", "z") = "zbz"
6940 * </pre>
6941 *
6942 * @see #replaceIgnoreCase(String text, String searchString, String replacement, int max)
6943 * @param text text to search and replace in, may be null
6944 * @param searchString the String to search for (case insensitive), may be null
6945 * @param replacement the String to replace it with, may be null
6946 * @return the text with any replacements processed,
6947 * {@code null} if null String input
6948 * @since 3.5
6949 */
6950 public static String replaceIgnoreCase(final String text, final String searchString, final String replacement) {
6951 return replaceIgnoreCase(text, searchString, replacement, -1);
6952 }
69476953
69486954 /**
69496955 * <p>Case insensitively replaces a String with another String inside a larger String,
69786984 return replace(text, searchString, replacement, max, true);
69796985 }
69806986
6981 // Replacing
6982 //-----------------------------------------------------------------------
69836987 /**
69846988 * <p>Replaces a String with another String inside a larger String, once.</p>
69856989 *
70827086 return RegExUtils.replacePattern(source, regex, replacement);
70837087 }
70847088
7085 // Reversing
7086 //-----------------------------------------------------------------------
70877089 /**
70887090 * <p>Reverses a String as per {@link StringBuilder#reverse()}.</p>
70897091 *
72687270
72697271 if (pads == padLen) {
72707272 return str.concat(padStr);
7271 } else if (pads < padLen) {
7273 }
7274 if (pads < padLen) {
72727275 return str.concat(padStr.substring(0, pads));
7273 } else {
7274 final char[] padding = new char[pads];
7275 final char[] padChars = padStr.toCharArray();
7276 for (int i = 0; i < pads; i++) {
7277 padding[i] = padChars[i % padLen];
7278 }
7279 return str.concat(new String(padding));
7280 }
7281 }
7282
7283 // Rotating (circular shift)
7284 //-----------------------------------------------------------------------
7276 }
7277 final char[] padding = new char[pads];
7278 final char[] padChars = padStr.toCharArray();
7279 for (int i = 0; i < pads; i++) {
7280 padding[i] = padChars[i % padLen];
7281 }
7282 return str.concat(new String(padding));
7283 }
7284
72857285 /**
72867286 * <p>Rotate (circular shift) a String of {@code shift} characters.</p>
72877287 * <ul>
73257325 return builder.toString();
73267326 }
73277327
7328 // Splitting
7329 //-----------------------------------------------------------------------
73307328 /**
73317329 * <p>Splits the provided text into an array, using whitespace as the
73327330 * separator.
77417739 return substrings.toArray(ArrayUtils.EMPTY_STRING_ARRAY);
77427740 }
77437741
7744 // -----------------------------------------------------------------------
77457742 /**
77467743 * <p>Splits the provided text into an array, using whitespace as the
77477744 * separator, preserving all tokens, including empty tokens created by
79067903 return ArrayUtils.EMPTY_STRING_ARRAY;
79077904 }
79087905 final List<String> list = new ArrayList<>();
7909 int i = 0, start = 0;
7906 int i = 0;
7907 int start = 0;
79107908 boolean match = false;
79117909 boolean lastMatch = false;
79127910 while (i < len) {
79577955 }
79587956 final List<String> list = new ArrayList<>();
79597957 int sizePlus1 = 1;
7960 int i = 0, start = 0;
7958 int i = 0;
7959 int start = 0;
79617960 boolean match = false;
79627961 boolean lastMatch = false;
79637962 if (separatorChars == null) {
80698068 if (str == null || prefix == null) {
80708069 return str == prefix;
80718070 }
8072 if (prefix.length() > str.length()) {
8071 // Get length once instead of twice in the unlikely case that it changes.
8072 final int preLen = prefix.length();
8073 if (preLen > str.length()) {
80738074 return false;
80748075 }
8075 return CharSequenceUtils.regionMatches(str, ignoreCase, 0, prefix, 0, prefix.length());
8076 return CharSequenceUtils.regionMatches(str, ignoreCase, 0, prefix, 0, preLen);
80768077 }
80778078
80788079 /**
81358136 return startsWith(str, prefix, true);
81368137 }
81378138
8138 // Stripping
8139 //-----------------------------------------------------------------------
81408139 /**
81418140 * <p>Strips whitespace from the start and end of a String.</p>
81428141 *
81908189 * @return the stripped String, {@code null} if null String input
81918190 */
81928191 public static String strip(String str, final String stripChars) {
8193 if (isEmpty(str)) {
8194 return str;
8195 }
81968192 str = stripStart(str, stripChars);
81978193 return stripEnd(str, stripChars);
81988194 }
82258221 return STRIP_ACCENTS_PATTERN.matcher(decomposed).replaceAll(EMPTY);
82268222 }
82278223
8228 // StripAll
8229 //-----------------------------------------------------------------------
82308224 /**
82318225 * <p>Strips whitespace from the start and end of every String in an array.
82328226 * Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
84308424 return null;
84318425 }
84328426 str = strip(str, null);
8433 return str.isEmpty() ? null : str;
8434 }
8435
8436 // Substring
8437 //-----------------------------------------------------------------------
8427 return str.isEmpty() ? null : str; // NOSONARLINT str cannot be null here
8428 }
8429
84388430 /**
84398431 * <p>Gets a substring from the specified String avoiding exceptions.</p>
84408432 *
86258617 return str.substring(pos + separator.length());
86268618 }
86278619
8628 // startsWith
8629 //-----------------------------------------------------------------------
8630
86318620 /**
86328621 * <p>Gets the substring after the last occurrence of a separator.
86338622 * The separator is not returned.</p>
87088697 return str.substring(pos + separator.length());
87098698 }
87108699
8711 // SubStringAfter/SubStringBefore
8712 //-----------------------------------------------------------------------
8700 /**
8701 * <p>
8702 * Gets the substring before the first occurrence of a separator. The separator is not returned.
8703 * </p>
8704 *
8705 * <p>
8706 * A {@code null} string input will return {@code null}. An empty ("") string input will return the empty string.
8707 * </p>
8708 *
8709 * <p>
8710 * If nothing is found, the string input is returned.
8711 * </p>
8712 *
8713 * <pre>
8714 * StringUtils.substringBefore(null, *) = null
8715 * StringUtils.substringBefore("", *) = ""
8716 * StringUtils.substringBefore("abc", 'a') = ""
8717 * StringUtils.substringBefore("abcba", 'b') = "a"
8718 * StringUtils.substringBefore("abc", 'c') = "ab"
8719 * StringUtils.substringBefore("abc", 'd') = "abc"
8720 * </pre>
8721 *
8722 * @param str the String to get a substring from, may be null
8723 * @param separator the String to search for, may be null
8724 * @return the substring before the first occurrence of the separator, {@code null} if null String input
8725 * @since 3.12.0
8726 */
8727 public static String substringBefore(final String str, final int separator) {
8728 if (isEmpty(str)) {
8729 return str;
8730 }
8731 final int pos = str.indexOf(separator);
8732 if (pos == INDEX_NOT_FOUND) {
8733 return str;
8734 }
8735 return str.substring(0, pos);
8736 }
8737
87138738 /**
87148739 * <p>Gets the substring before the first occurrence of a separator.
87158740 * The separator is not returned.</p>
87898814 return str.substring(0, pos);
87908815 }
87918816
8792 // Substring between
8793 //-----------------------------------------------------------------------
87948817 /**
87958818 * <p>Gets the String that is nested in between two instances of the
87968819 * same String.</p>
88158838 public static String substringBetween(final String str, final String tag) {
88168839 return substringBetween(str, tag, tag);
88178840 }
8818
8819 // endsWith
8820 //-----------------------------------------------------------------------
88218841
88228842 /**
88238843 * <p>Gets the String that is nested in between two Strings.
89768996 * StringUtils.toCodePoints("") = [] // empty array
89778997 * </pre>
89788998 *
8979 * @param str the character sequence to convert
8999 * @param cs the character sequence to convert
89809000 * @return an array of code points
89819001 * @since 3.6
89829002 */
8983 public static int[] toCodePoints(final CharSequence str) {
8984 if (str == null) {
9003 public static int[] toCodePoints(final CharSequence cs) {
9004 if (cs == null) {
89859005 return null;
89869006 }
8987 if (str.length() == 0) {
9007 if (cs.length() == 0) {
89889008 return ArrayUtils.EMPTY_INT_ARRAY;
89899009 }
89909010
8991 final String s = str.toString();
9011 final String s = cs.toString();
89929012 final int[] result = new int[s.codePointCount(0, s.length())];
89939013 int index = 0;
89949014 for (int i = 0; i < result.length; i++) {
90549074 */
90559075 @Deprecated
90569076 public static String toString(final byte[] bytes, final String charsetName) throws UnsupportedEncodingException {
9057 return charsetName != null ? new String(bytes, charsetName) : new String(bytes, Charset.defaultCharset());
9058 }
9059
9060 // Trim
9061 //-----------------------------------------------------------------------
9077 return new String(bytes, Charsets.toCharset(charsetName));
9078 }
9079
9080 private static String toStringOrEmpty(final Object obj) {
9081 return Objects.toString(obj, EMPTY);
9082 }
9083
90629084 /**
90639085 * <p>Removes control characters (char &lt;= 32) from both
90649086 * ends of this String, handling {@code null} by returning
93689390 * @since 3.6
93699391 */
93709392 public static String unwrap(final String str, final String wrapToken) {
9371 if (isEmpty(str) || isEmpty(wrapToken) || str.length() == 1) {
9393 if (isEmpty(str) || isEmpty(wrapToken) || str.length() < 2 * wrapToken.length()) {
93729394 return str;
93739395 }
93749396
93859407 return str;
93869408 }
93879409
9388 // Case conversion
9389 //-----------------------------------------------------------------------
93909410 /**
93919411 * <p>Converts a String to upper case as per {@link String#toUpperCase()}.</p>
93929412 *
94339453 if (str == null) {
94349454 return null;
94359455 }
9436 return str.toUpperCase(locale);
9456 return str.toUpperCase(LocaleUtils.toLocale(locale));
94379457 }
94389458
94399459 /**
96269646 * instance to operate.</p>
96279647 */
96289648 public StringUtils() {
9629 super();
96309649 }
96319650
96329651 }
12871287
12881288 /**
12891289 * <p>
1290 * Is {@code true} if this is Mac OS X Sierra.
1291 * </p>
1292 * <p>
1293 * The field will return {@code false} if {@code OS_NAME} is {@code null}.
1294 * </p>
1295 *
1296 * @since 3.12.0
1297 */
1298 public static final boolean IS_OS_MAC_OSX_SIERRA = getOsMatches("Mac OS X", "10.12");
1299
1300 /**
1301 * <p>
1302 * Is {@code true} if this is Mac OS X High Sierra.
1303 * </p>
1304 * <p>
1305 * The field will return {@code false} if {@code OS_NAME} is {@code null}.
1306 * </p>
1307 *
1308 * @since 3.12.0
1309 */
1310 public static final boolean IS_OS_MAC_OSX_HIGH_SIERRA = getOsMatches("Mac OS X", "10.13");
1311
1312 /**
1313 * <p>
1314 * Is {@code true} if this is Mac OS X Mojave.
1315 * </p>
1316 * <p>
1317 * The field will return {@code false} if {@code OS_NAME} is {@code null}.
1318 * </p>
1319 *
1320 * @since 3.12.0
1321 */
1322 public static final boolean IS_OS_MAC_OSX_MOJAVE = getOsMatches("Mac OS X", "10.14");
1323
1324 /**
1325 * <p>
1326 * Is {@code true} if this is Mac OS X Catalina.
1327 * </p>
1328 * <p>
1329 * The field will return {@code false} if {@code OS_NAME} is {@code null}.
1330 * </p>
1331 *
1332 * @since 3.12.0
1333 */
1334 public static final boolean IS_OS_MAC_OSX_CATALINA = getOsMatches("Mac OS X", "10.15");
1335
1336 /**
1337 * <p>
1338 * Is {@code true} if this is Mac OS X Big Sur.
1339 * </p>
1340 * <p>
1341 * The field will return {@code false} if {@code OS_NAME} is {@code null}.
1342 * </p>
1343 *
1344 * @since 3.12.0
1345 */
1346 public static final boolean IS_OS_MAC_OSX_BIG_SUR = getOsMatches("Mac OS X", "10.16");
1347
1348 /**
1349 * <p>
12901350 * Is {@code true} if this is FreeBSD.
12911351 * </p>
12921352 * <p>
15581618
15591619 /**
15601620 * <p>
1621 * Gets an environment variable, defaulting to {@code defaultValue} if the variable cannot be read.
1622 * </p>
1623 * <p>
1624 * If a {@code SecurityException} is caught, the return value is {@code defaultValue} and a message is written to
1625 * {@code System.err}.
1626 * </p>
1627 *
1628 * @param name
1629 * the environment variable name
1630 * @param defaultValue
1631 * the default value
1632 * @return the environment variable value or {@code defaultValue} if a security problem occurs
1633 * @since 3.8
1634 */
1635 public static String getEnvironmentVariable(final String name, final String defaultValue) {
1636 try {
1637 final String value = System.getenv(name);
1638 return value == null ? defaultValue : value;
1639 } catch (final SecurityException ex) {
1640 // we are not allowed to look at this property
1641 // System.err.println("Caught a SecurityException reading the environment variable '" + name + "'.");
1642 return defaultValue;
1643 }
1644 }
1645
1646 /**
1647 * Gets the host name from an environment variable
1648 * (COMPUTERNAME on Windows, HOSTNAME elsewhere).
1649 *
1650 * <p>
1651 * If you want to know what the network stack says is the host name, you should use {@code InetAddress.getLocalHost().getHostName()}.
1652 * </p>
1653 *
1654 * @return the host name. Will be {@code null} if the environment variable is not defined.
1655 * @since 3.6
1656 */
1657 public static String getHostName() {
1658 return IS_OS_WINDOWS ? System.getenv("COMPUTERNAME") : System.getenv("HOSTNAME");
1659 }
1660
1661 /**
1662 * <p>
15611663 * Gets the Java home directory as a {@code File}.
15621664 * </p>
15631665 *
15691671 */
15701672 public static File getJavaHome() {
15711673 return new File(System.getProperty(JAVA_HOME_KEY));
1572 }
1573
1574 /**
1575 * Gets the host name from an environment variable
1576 * (COMPUTERNAME on Windows, HOSTNAME elsewhere).
1577 *
1578 * <p>
1579 * If you want to know what the network stack says is the host name, you should use {@code InetAddress.getLocalHost().getHostName()}.
1580 * </p>
1581 *
1582 * @return the host name. Will be {@code null} if the environment variable is not defined.
1583 * @since 3.6
1584 */
1585 public static String getHostName() {
1586 return IS_OS_WINDOWS ? System.getenv("COMPUTERNAME") : System.getenv("HOSTNAME");
15871674 }
15881675
15891676 /**
16601747
16611748 /**
16621749 * <p>
1663 * Gets an environment variable, defaulting to {@code defaultValue} if the variable cannot be read.
1664 * </p>
1665 * <p>
1666 * If a {@code SecurityException} is caught, the return value is {@code defaultValue} and a message is written to
1667 * {@code System.err}.
1668 * </p>
1669 *
1670 * @param name
1671 * the environment variable name
1672 * @param defaultValue
1673 * the default value
1674 * @return the environment variable value or {@code defaultValue} if a security problem occurs
1675 * @since 3.8
1676 */
1677 public static String getEnvironmentVariable(final String name, final String defaultValue) {
1678 try {
1679 final String value = System.getenv(name);
1680 return value == null ? defaultValue : value;
1681 } catch (final SecurityException ex) {
1682 // we are not allowed to look at this property
1683 // System.err.println("Caught a SecurityException reading the environment variable '" + name + "'.");
1684 return defaultValue;
1685 }
1686 }
1687
1688 /**
1689 * <p>
16901750 * Gets the user directory as a {@code File}.
16911751 * </p>
16921752 *
17801840 * </p>
17811841 *
17821842 * @param requiredVersion the required version, for example 1.31f
1783 * @return {@code true} if the actual version is equal or greater than the required version
1843 * @return {@code true} if the actual version is equal or less than the required version
17841844 * @since 3.9
17851845 */
17861846 public static boolean isJavaVersionAtMost(final JavaVersion requiredVersion) {
18791939 * </p>
18801940 */
18811941 public SystemUtils() {
1882 super();
18831942 }
18841943
18851944 }
1515 */
1616 package org.apache.commons.lang3;
1717
18 import java.time.Duration;
1819 import java.util.ArrayList;
1920 import java.util.Collection;
2021 import java.util.Collections;
2122 import java.util.List;
23
24 import org.apache.commons.lang3.time.DurationUtils;
2225
2326 /**
2427 * <p>
3538 public class ThreadUtils {
3639
3740 /**
41 * A predicate implementation which always returns true.
42 */
43 private static final class AlwaysTruePredicate implements ThreadPredicate, ThreadGroupPredicate {
44
45 private AlwaysTruePredicate() {
46 }
47
48 @Override
49 public boolean test(final Thread thread) {
50 return true;
51 }
52
53 @Override
54 public boolean test(final ThreadGroup threadGroup) {
55 return true;
56 }
57 }
58
59 /**
60 * A predicate implementation which matches a thread or threadgroup name.
61 */
62 public static class NamePredicate implements ThreadPredicate, ThreadGroupPredicate {
63
64 private final String name;
65
66 /**
67 * Predicate constructor
68 *
69 * @param name thread or threadgroup name
70 * @throws IllegalArgumentException if the name is {@code null}
71 */
72 public NamePredicate(final String name) {
73 Validate.notNull(name, "name");
74 this.name = name;
75 }
76
77 @Override
78 public boolean test(final Thread thread) {
79 return thread != null && thread.getName().equals(name);
80 }
81
82 @Override
83 public boolean test(final ThreadGroup threadGroup) {
84 return threadGroup != null && threadGroup.getName().equals(name);
85 }
86 }
87
88 /**
89 * A predicate for selecting threadgroups.
90 */
91 // When breaking BC, replace this with Predicate<ThreadGroup>
92 @FunctionalInterface
93 public interface ThreadGroupPredicate {
94
95 /**
96 * Evaluates this predicate on the given threadgroup.
97 * @param threadGroup the threadgroup
98 * @return {@code true} if the threadGroup matches the predicate, otherwise {@code false}
99 */
100 boolean test(ThreadGroup threadGroup);
101 }
102
103 /**
104 * A predicate implementation which matches a thread id.
105 */
106 public static class ThreadIdPredicate implements ThreadPredicate {
107
108 private final long threadId;
109
110 /**
111 * Predicate constructor
112 *
113 * @param threadId the threadId to match
114 * @throws IllegalArgumentException if the threadId is zero or negative
115 */
116 public ThreadIdPredicate(final long threadId) {
117 if (threadId <= 0) {
118 throw new IllegalArgumentException("The thread id must be greater than zero");
119 }
120 this.threadId = threadId;
121 }
122
123 @Override
124 public boolean test(final Thread thread) {
125 return thread != null && thread.getId() == threadId;
126 }
127 }
128
129 /**
130 * A predicate for selecting threads.
131 */
132 // When breaking BC, replace this with Predicate<Thread>
133 @FunctionalInterface
134 public interface ThreadPredicate {
135
136 /**
137 * Evaluates this predicate on the given thread.
138 * @param thread the thread
139 * @return {@code true} if the thread matches the predicate, otherwise {@code false}
140 */
141 boolean test(Thread thread);
142 }
143
144 /**
145 * Predicate which always returns true.
146 */
147 public static final AlwaysTruePredicate ALWAYS_TRUE_PREDICATE = new AlwaysTruePredicate();
148
149 /**
150 * Finds the active thread with the specified id.
151 *
152 * @param threadId The thread id
153 * @return The thread with the specified id or {@code null} if no such thread exists
154 * @throws IllegalArgumentException if the specified id is zero or negative
155 * @throws SecurityException
156 * if the current thread cannot access the system thread group
157 *
158 * @throws SecurityException if the current thread cannot modify
159 * thread groups from this thread's thread group up to the system thread group
160 */
161 public static Thread findThreadById(final long threadId) {
162 final Collection<Thread> result = findThreads(new ThreadIdPredicate(threadId));
163 return result.isEmpty() ? null : result.iterator().next();
164 }
165
166 /**
167 * Finds the active thread with the specified id if it belongs to a thread group with the specified group name.
168 *
169 * @param threadId The thread id
170 * @param threadGroupName The thread group name
171 * @return The threads which belongs to a thread group with the specified group name and the thread's id match the specified id.
172 * {@code null} is returned if no such thread exists
173 * @throws IllegalArgumentException if the specified id is zero or negative or the group name is null
174 * @throws SecurityException
175 * if the current thread cannot access the system thread group
176 *
177 * @throws SecurityException if the current thread cannot modify
178 * thread groups from this thread's thread group up to the system thread group
179 */
180 public static Thread findThreadById(final long threadId, final String threadGroupName) {
181 Validate.notNull(threadGroupName, "threadGroupName");
182 final Thread thread = findThreadById(threadId);
183 if (thread != null && thread.getThreadGroup() != null && thread.getThreadGroup().getName().equals(threadGroupName)) {
184 return thread;
185 }
186 return null;
187 }
188
189 /**
38190 * Finds the active thread with the specified id if it belongs to the specified thread group.
39191 *
40192 * @param threadId The thread id
49201 * thread groups from this thread's thread group up to the system thread group
50202 */
51203 public static Thread findThreadById(final long threadId, final ThreadGroup threadGroup) {
52 Validate.notNull(threadGroup, "The thread group must not be null");
204 Validate.notNull(threadGroup, "threadGroup");
53205 final Thread thread = findThreadById(threadId);
54206 if (thread != null && threadGroup.equals(thread.getThreadGroup())) {
55207 return thread;
58210 }
59211
60212 /**
61 * Finds the active thread with the specified id if it belongs to a thread group with the specified group name.
62 *
63 * @param threadId The thread id
213 * Select all active threadgroups which match the given predicate and which is a subgroup of the given thread group (or one of its subgroups).
214 *
215 * @param group the thread group
216 * @param recurse if {@code true} then evaluate the predicate recursively on all threadgroups in all subgroups of the given group
217 * @param predicate the predicate
218 * @return An unmodifiable {@code Collection} of active threadgroups which match the given predicate and which is a subgroup of the given thread group
219 * @throws IllegalArgumentException if the given group or predicate is null
220 * @throws SecurityException if the current thread cannot modify
221 * thread groups from this thread's thread group up to the system thread group
222 */
223 public static Collection<ThreadGroup> findThreadGroups(final ThreadGroup group, final boolean recurse, final ThreadGroupPredicate predicate) {
224 Validate.notNull(group, "group");
225 Validate.notNull(predicate, "predicate");
226
227 int count = group.activeGroupCount();
228 ThreadGroup[] threadGroups;
229 do {
230 threadGroups = new ThreadGroup[count + (count / 2) + 1]; //slightly grow the array size
231 count = group.enumerate(threadGroups, recurse);
232 //return value of enumerate() must be strictly less than the array size according to javadoc
233 } while (count >= threadGroups.length);
234
235 final List<ThreadGroup> result = new ArrayList<>(count);
236 for (int i = 0; i < count; ++i) {
237 if (predicate.test(threadGroups[i])) {
238 result.add(threadGroups[i]);
239 }
240 }
241 return Collections.unmodifiableCollection(result);
242 }
243
244 /**
245 * Select all active threadgroups which match the given predicate.
246 *
247 * @param predicate the predicate
248 * @return An unmodifiable {@code Collection} of active threadgroups matching the given predicate
249 * @throws IllegalArgumentException if the predicate is null
250 * @throws SecurityException
251 * if the current thread cannot access the system thread group
252 * @throws SecurityException if the current thread cannot modify
253 * thread groups from this thread's thread group up to the system thread group
254 */
255 public static Collection<ThreadGroup> findThreadGroups(final ThreadGroupPredicate predicate) {
256 return findThreadGroups(getSystemThreadGroup(), true, predicate);
257 }
258
259 /**
260 * Finds active thread groups with the specified group name.
261 *
64262 * @param threadGroupName The thread group name
65 * @return The threads which belongs to a thread group with the specified group name and the thread's id match the specified id.
66 * {@code null} is returned if no such thread exists
67 * @throws IllegalArgumentException if the specified id is zero or negative or the group name is null
68 * @throws SecurityException
69 * if the current thread cannot access the system thread group
70 *
71 * @throws SecurityException if the current thread cannot modify
72 * thread groups from this thread's thread group up to the system thread group
73 */
74 public static Thread findThreadById(final long threadId, final String threadGroupName) {
75 Validate.notNull(threadGroupName, "The thread group name must not be null");
76 final Thread thread = findThreadById(threadId);
77 if (thread != null && thread.getThreadGroup() != null && thread.getThreadGroup().getName().equals(threadGroupName)) {
78 return thread;
79 }
80 return null;
263 * @return the thread groups with the specified group name or an empty collection if no such thread group exists. The collection returned is always unmodifiable.
264 * @throws IllegalArgumentException if group name is null
265 * @throws SecurityException
266 * if the current thread cannot access the system thread group
267 *
268 * @throws SecurityException if the current thread cannot modify
269 * thread groups from this thread's thread group up to the system thread group
270 */
271 public static Collection<ThreadGroup> findThreadGroupsByName(final String threadGroupName) {
272 return findThreadGroups(new NamePredicate(threadGroupName));
273 }
274
275 /**
276 * Select all active threads which match the given predicate and which belongs to the given thread group (or one of its subgroups).
277 *
278 * @param group the thread group
279 * @param recurse if {@code true} then evaluate the predicate recursively on all threads in all subgroups of the given group
280 * @param predicate the predicate
281 * @return An unmodifiable {@code Collection} of active threads which match the given predicate and which belongs to the given thread group
282 * @throws IllegalArgumentException if the given group or predicate is null
283 * @throws SecurityException if the current thread cannot modify
284 * thread groups from this thread's thread group up to the system thread group
285 */
286 public static Collection<Thread> findThreads(final ThreadGroup group, final boolean recurse, final ThreadPredicate predicate) {
287 Validate.notNull(group, "The group must not be null");
288 Validate.notNull(predicate, "The predicate must not be null");
289
290 int count = group.activeCount();
291 Thread[] threads;
292 do {
293 threads = new Thread[count + (count / 2) + 1]; //slightly grow the array size
294 count = group.enumerate(threads, recurse);
295 //return value of enumerate() must be strictly less than the array size according to javadoc
296 } while (count >= threads.length);
297
298 final List<Thread> result = new ArrayList<>(count);
299 for (int i = 0; i < count; ++i) {
300 if (predicate.test(threads[i])) {
301 result.add(threads[i]);
302 }
303 }
304 return Collections.unmodifiableCollection(result);
305 }
306
307 /**
308 * Select all active threads which match the given predicate.
309 *
310 * @param predicate the predicate
311 * @return An unmodifiable {@code Collection} of active threads matching the given predicate
312 *
313 * @throws IllegalArgumentException if the predicate is null
314 * @throws SecurityException
315 * if the current thread cannot access the system thread group
316 * @throws SecurityException if the current thread cannot modify
317 * thread groups from this thread's thread group up to the system thread group
318 */
319 public static Collection<Thread> findThreads(final ThreadPredicate predicate) {
320 return findThreads(getSystemThreadGroup(), true, predicate);
321 }
322
323 /**
324 * Finds active threads with the specified name.
325 *
326 * @param threadName The thread name
327 * @return The threads with the specified name or an empty collection if no such thread exists. The collection returned is always unmodifiable.
328 * @throws IllegalArgumentException if the specified name is null
329 * @throws SecurityException
330 * if the current thread cannot access the system thread group
331 *
332 * @throws SecurityException if the current thread cannot modify
333 * thread groups from this thread's thread group up to the system thread group
334 */
335 public static Collection<Thread> findThreadsByName(final String threadName) {
336 return findThreads(new NamePredicate(threadName));
337 }
338
339 /**
340 * Finds active threads with the specified name if they belong to a thread group with the specified group name.
341 *
342 * @param threadName The thread name
343 * @param threadGroupName The thread group name
344 * @return The threads which belongs to a thread group with the specified group name and the thread's name match the specified name,
345 * An empty collection is returned if no such thread exists. The collection returned is always unmodifiable.
346 * @throws IllegalArgumentException if the specified thread name or group name is null
347 * @throws SecurityException
348 * if the current thread cannot access the system thread group
349 *
350 * @throws SecurityException if the current thread cannot modify
351 * thread groups from this thread's thread group up to the system thread group
352 */
353 public static Collection<Thread> findThreadsByName(final String threadName, final String threadGroupName) {
354 Validate.notNull(threadName, "threadName");
355 Validate.notNull(threadGroupName, "threadGroupName");
356
357 final Collection<ThreadGroup> threadGroups = findThreadGroups(new NamePredicate(threadGroupName));
358
359 if (threadGroups.isEmpty()) {
360 return Collections.emptyList();
361 }
362
363 final Collection<Thread> result = new ArrayList<>();
364 final NamePredicate threadNamePredicate = new NamePredicate(threadName);
365 for (final ThreadGroup group : threadGroups) {
366 result.addAll(findThreads(group, false, threadNamePredicate));
367 }
368 return Collections.unmodifiableCollection(result);
81369 }
82370
83371 /**
99387 }
100388
101389 /**
102 * Finds active threads with the specified name if they belong to a thread group with the specified group name.
103 *
104 * @param threadName The thread name
105 * @param threadGroupName The thread group name
106 * @return The threads which belongs to a thread group with the specified group name and the thread's name match the specified name,
107 * An empty collection is returned if no such thread exists. The collection returned is always unmodifiable.
108 * @throws IllegalArgumentException if the specified thread name or group name is null
109 * @throws SecurityException
110 * if the current thread cannot access the system thread group
111 *
112 * @throws SecurityException if the current thread cannot modify
113 * thread groups from this thread's thread group up to the system thread group
114 */
115 public static Collection<Thread> findThreadsByName(final String threadName, final String threadGroupName) {
116 Validate.notNull(threadName, "The thread name must not be null");
117 Validate.notNull(threadGroupName, "The thread group name must not be null");
118
119 final Collection<ThreadGroup> threadGroups = findThreadGroups(new NamePredicate(threadGroupName));
120
121 if (threadGroups.isEmpty()) {
122 return Collections.emptyList();
123 }
124
125 final Collection<Thread> result = new ArrayList<>();
126 final NamePredicate threadNamePredicate = new NamePredicate(threadName);
127 for (final ThreadGroup group : threadGroups) {
128 result.addAll(findThreads(group, false, threadNamePredicate));
129 }
130 return Collections.unmodifiableCollection(result);
131 }
132
133 /**
134 * Finds active thread groups with the specified group name.
135 *
136 * @param threadGroupName The thread group name
137 * @return the thread groups with the specified group name or an empty collection if no such thread group exists. The collection returned is always unmodifiable.
138 * @throws IllegalArgumentException if group name is null
139 * @throws SecurityException
140 * if the current thread cannot access the system thread group
141 *
142 * @throws SecurityException if the current thread cannot modify
143 * thread groups from this thread's thread group up to the system thread group
144 */
145 public static Collection<ThreadGroup> findThreadGroupsByName(final String threadGroupName) {
146 return findThreadGroups(new NamePredicate(threadGroupName));
147 }
148
149 /**
150390 * Gets all active thread groups excluding the system thread group (A thread group is active if it has been not destroyed).
151391 *
152392 * @return all thread groups excluding the system thread group. The collection returned is always unmodifiable.
158398 */
159399 public static Collection<ThreadGroup> getAllThreadGroups() {
160400 return findThreadGroups(ALWAYS_TRUE_PREDICATE);
401 }
402
403 /**
404 * Gets all active threads (A thread is active if it has been started and has not yet died).
405 *
406 * @return all active threads. The collection returned is always unmodifiable.
407 * @throws SecurityException
408 * if the current thread cannot access the system thread group
409 *
410 * @throws SecurityException if the current thread cannot modify
411 * thread groups from this thread's thread group up to the system thread group
412 */
413 public static Collection<Thread> getAllThreads() {
414 return findThreads(ALWAYS_TRUE_PREDICATE);
161415 }
162416
163417 /**
176430 }
177431
178432 /**
179 * Gets all active threads (A thread is active if it has been started and has not yet died).
180 *
181 * @return all active threads. The collection returned is always unmodifiable.
182 * @throws SecurityException
183 * if the current thread cannot access the system thread group
184 *
185 * @throws SecurityException if the current thread cannot modify
186 * thread groups from this thread's thread group up to the system thread group
187 */
188 public static Collection<Thread> getAllThreads() {
189 return findThreads(ALWAYS_TRUE_PREDICATE);
190 }
191
192 /**
193 * Finds active threads with the specified name.
194 *
195 * @param threadName The thread name
196 * @return The threads with the specified name or an empty collection if no such thread exists. The collection returned is always unmodifiable.
197 * @throws IllegalArgumentException if the specified name is null
198 * @throws SecurityException
199 * if the current thread cannot access the system thread group
200 *
201 * @throws SecurityException if the current thread cannot modify
202 * thread groups from this thread's thread group up to the system thread group
203 */
204 public static Collection<Thread> findThreadsByName(final String threadName) {
205 return findThreads(new NamePredicate(threadName));
206 }
207
208 /**
209 * Finds the active thread with the specified id.
210 *
211 * @param threadId The thread id
212 * @return The thread with the specified id or {@code null} if no such thread exists
213 * @throws IllegalArgumentException if the specified id is zero or negative
214 * @throws SecurityException
215 * if the current thread cannot access the system thread group
216 *
217 * @throws SecurityException if the current thread cannot modify
218 * thread groups from this thread's thread group up to the system thread group
219 */
220 public static Thread findThreadById(final long threadId) {
221 final Collection<Thread> result = findThreads(new ThreadIdPredicate(threadId));
222 return result.isEmpty() ? null : result.iterator().next();
433 * Waits for the given thread to die for the given duration. Implemented using {@link Thread#join(long, int)}.
434 *
435 * @param thread The thread to join.
436 * @param duration How long to wait.
437 * @throws InterruptedException if any thread has interrupted the current thread.
438 * @see Thread#join(long, int)
439 * @since 3.12.0
440 */
441 public static void join(final Thread thread, final Duration duration) throws InterruptedException {
442 DurationUtils.accept(thread::join, duration);
443 }
444
445 /**
446 * Sleeps the current thread for the given duration. Implemented using {@link Thread#sleep(long, int)}.
447 *
448 * @param duration How long to sleep.
449 * @throws InterruptedException if any thread has interrupted the current thread.
450 * @see Thread#sleep(long, int)
451 * @since 3.12.0
452 */
453 public static void sleep(final Duration duration) throws InterruptedException {
454 DurationUtils.accept(Thread::sleep, duration);
455 }
456
457 /**
458 * Sleeps for the given amount of milliseconds while ignoring {@link InterruptedException}.
459 * <p>
460 * The sleep duration may be shorter than {@code millis} if we catch a {@link InterruptedException}.
461 * </p>
462 *
463 * @param millis the length of time to sleep in milliseconds
464 * @since 3.13.0
465 */
466 public static void sleepQuietly(final long millis) {
467 try {
468 sleep(Duration.ofMillis(millis));
469 } catch (InterruptedException e) {
470 // be quiet.
471 }
223472 }
224473
225474 /**
232481 * </p>
233482 */
234483 public ThreadUtils() {
235 super();
236 }
237
238 /**
239 * A predicate for selecting threads.
240 */
241 // When breaking BC, replace this with Predicate<Thread>
242 @FunctionalInterface
243 public interface ThreadPredicate {
244
245 /**
246 * Evaluates this predicate on the given thread.
247 * @param thread the thread
248 * @return {@code true} if the thread matches the predicate, otherwise {@code false}
249 */
250 boolean test(Thread thread);
251 }
252
253 /**
254 * A predicate for selecting threadgroups.
255 */
256 // When breaking BC, replace this with Predicate<ThreadGroup>
257 @FunctionalInterface
258 public interface ThreadGroupPredicate {
259
260 /**
261 * Evaluates this predicate on the given threadgroup.
262 * @param threadGroup the threadgroup
263 * @return {@code true} if the threadGroup matches the predicate, otherwise {@code false}
264 */
265 boolean test(ThreadGroup threadGroup);
266 }
267
268 /**
269 * Predicate which always returns true.
270 */
271 public static final AlwaysTruePredicate ALWAYS_TRUE_PREDICATE = new AlwaysTruePredicate();
272
273 /**
274 * A predicate implementation which always returns true.
275 */
276 private static final class AlwaysTruePredicate implements ThreadPredicate, ThreadGroupPredicate {
277
278 private AlwaysTruePredicate() {
279 }
280
281 @Override
282 public boolean test(final ThreadGroup threadGroup) {
283 return true;
284 }
285
286 @Override
287 public boolean test(final Thread thread) {
288 return true;
289 }
290 }
291
292 /**
293 * A predicate implementation which matches a thread or threadgroup name.
294 */
295 public static class NamePredicate implements ThreadPredicate, ThreadGroupPredicate {
296
297 private final String name;
298
299 /**
300 * Predicate constructor
301 *
302 * @param name thread or threadgroup name
303 * @throws IllegalArgumentException if the name is {@code null}
304 */
305 public NamePredicate(final String name) {
306 super();
307 Validate.notNull(name, "The name must not be null");
308 this.name = name;
309 }
310
311 @Override
312 public boolean test(final ThreadGroup threadGroup) {
313 return threadGroup != null && threadGroup.getName().equals(name);
314 }
315
316 @Override
317 public boolean test(final Thread thread) {
318 return thread != null && thread.getName().equals(name);
319 }
320 }
321
322 /**
323 * A predicate implementation which matches a thread id.
324 */
325 public static class ThreadIdPredicate implements ThreadPredicate {
326
327 private final long threadId;
328
329 /**
330 * Predicate constructor
331 *
332 * @param threadId the threadId to match
333 * @throws IllegalArgumentException if the threadId is zero or negative
334 */
335 public ThreadIdPredicate(final long threadId) {
336 super();
337 if (threadId <= 0) {
338 throw new IllegalArgumentException("The thread id must be greater than zero");
339 }
340 this.threadId = threadId;
341 }
342
343 @Override
344 public boolean test(final Thread thread) {
345 return thread != null && thread.getId() == threadId;
346 }
347 }
348
349 /**
350 * Select all active threads which match the given predicate.
351 *
352 * @param predicate the predicate
353 * @return An unmodifiable {@code Collection} of active threads matching the given predicate
354 *
355 * @throws IllegalArgumentException if the predicate is null
356 * @throws SecurityException
357 * if the current thread cannot access the system thread group
358 * @throws SecurityException if the current thread cannot modify
359 * thread groups from this thread's thread group up to the system thread group
360 */
361 public static Collection<Thread> findThreads(final ThreadPredicate predicate) {
362 return findThreads(getSystemThreadGroup(), true, predicate);
363 }
364
365 /**
366 * Select all active threadgroups which match the given predicate.
367 *
368 * @param predicate the predicate
369 * @return An unmodifiable {@code Collection} of active threadgroups matching the given predicate
370 * @throws IllegalArgumentException if the predicate is null
371 * @throws SecurityException
372 * if the current thread cannot access the system thread group
373 * @throws SecurityException if the current thread cannot modify
374 * thread groups from this thread's thread group up to the system thread group
375 */
376 public static Collection<ThreadGroup> findThreadGroups(final ThreadGroupPredicate predicate) {
377 return findThreadGroups(getSystemThreadGroup(), true, predicate);
378 }
379
380 /**
381 * Select all active threads which match the given predicate and which belongs to the given thread group (or one of its subgroups).
382 *
383 * @param group the thread group
384 * @param recurse if {@code true} then evaluate the predicate recursively on all threads in all subgroups of the given group
385 * @param predicate the predicate
386 * @return An unmodifiable {@code Collection} of active threads which match the given predicate and which belongs to the given thread group
387 * @throws IllegalArgumentException if the given group or predicate is null
388 * @throws SecurityException if the current thread cannot modify
389 * thread groups from this thread's thread group up to the system thread group
390 */
391 public static Collection<Thread> findThreads(final ThreadGroup group, final boolean recurse, final ThreadPredicate predicate) {
392 Validate.notNull(group, "The group must not be null");
393 Validate.notNull(predicate, "The predicate must not be null");
394
395 int count = group.activeCount();
396 Thread[] threads;
397 do {
398 threads = new Thread[count + (count / 2) + 1]; //slightly grow the array size
399 count = group.enumerate(threads, recurse);
400 //return value of enumerate() must be strictly less than the array size according to javadoc
401 } while (count >= threads.length);
402
403 final List<Thread> result = new ArrayList<>(count);
404 for (int i = 0; i < count; ++i) {
405 if (predicate.test(threads[i])) {
406 result.add(threads[i]);
407 }
408 }
409 return Collections.unmodifiableCollection(result);
410 }
411
412 /**
413 * Select all active threadgroups which match the given predicate and which is a subgroup of the given thread group (or one of its subgroups).
414 *
415 * @param group the thread group
416 * @param recurse if {@code true} then evaluate the predicate recursively on all threadgroups in all subgroups of the given group
417 * @param predicate the predicate
418 * @return An unmodifiable {@code Collection} of active threadgroups which match the given predicate and which is a subgroup of the given thread group
419 * @throws IllegalArgumentException if the given group or predicate is null
420 * @throws SecurityException if the current thread cannot modify
421 * thread groups from this thread's thread group up to the system thread group
422 */
423 public static Collection<ThreadGroup> findThreadGroups(final ThreadGroup group, final boolean recurse, final ThreadGroupPredicate predicate) {
424 Validate.notNull(group, "The group must not be null");
425 Validate.notNull(predicate, "The predicate must not be null");
426
427 int count = group.activeGroupCount();
428 ThreadGroup[] threadGroups;
429 do {
430 threadGroups = new ThreadGroup[count + (count / 2) + 1]; //slightly grow the array size
431 count = group.enumerate(threadGroups, recurse);
432 //return value of enumerate() must be strictly less than the array size according to javadoc
433 } while (count >= threadGroups.length);
434
435 final List<ThreadGroup> result = new ArrayList<>(count);
436 for (int i = 0; i < count; ++i) {
437 if (predicate.test(threadGroups[i])) {
438 result.add(threadGroups[i]);
439 }
440 }
441 return Collections.unmodifiableCollection(result);
442484 }
443485 }
7979 * Constructor. This class should not normally be instantiated.
8080 */
8181 public Validate() {
82 super();
8382 }
8483
8584 // isTrue
1000999 }
10011000
10021001 /**
1003 * Validate that the specified primitive value falls between the two
1004 * inclusive values specified; otherwise, throws an exception.
1005 *
1006 * <pre>Validate.inclusiveBetween(0, 2, 1);</pre>
1007 *
1008 * @param start the inclusive start value
1009 * @param end the inclusive end value
1010 * @param value the value to validate
1011 * @throws IllegalArgumentException if the value falls outside the boundaries (inclusive)
1012 *
1013 * @since 3.3
1014 */
1002 * Validate that the specified primitive value falls between the two
1003 * inclusive values specified; otherwise, throws an exception.
1004 *
1005 * <pre>Validate.inclusiveBetween(0, 2, 1);</pre>
1006 *
1007 * @param start the inclusive start value
1008 * @param end the inclusive end value
1009 * @param value the value to validate
1010 * @throws IllegalArgumentException if the value falls outside the boundaries (inclusive)
1011 *
1012 * @since 3.3
1013 */
10151014 @SuppressWarnings("boxing")
10161015 public static void inclusiveBetween(final long start, final long end, final long value) {
10171016 // TODO when breaking BC, consider returning value
10211020 }
10221021
10231022 /**
1024 * Validate that the specified primitive value falls between the two
1025 * inclusive values specified; otherwise, throws an exception with the
1026 * specified message.
1027 *
1028 * <pre>Validate.inclusiveBetween(0, 2, 1, "Not in range");</pre>
1029 *
1030 * @param start the inclusive start value
1031 * @param end the inclusive end value
1032 * @param value the value to validate
1033 * @param message the exception message if invalid, not null
1034 *
1035 * @throws IllegalArgumentException if the value falls outside the boundaries
1036 *
1037 * @since 3.3
1038 */
1023 * Validate that the specified primitive value falls between the two
1024 * inclusive values specified; otherwise, throws an exception with the
1025 * specified message.
1026 *
1027 * <pre>Validate.inclusiveBetween(0, 2, 1, "Not in range");</pre>
1028 *
1029 * @param start the inclusive start value
1030 * @param end the inclusive end value
1031 * @param value the value to validate
1032 * @param message the exception message if invalid, not null
1033 *
1034 * @throws IllegalArgumentException if the value falls outside the boundaries
1035 *
1036 * @since 3.3
1037 */
10391038 public static void inclusiveBetween(final long start, final long end, final long value, final String message) {
10401039 // TODO when breaking BC, consider returning value
10411040 if (value < start || value > end) {
10441043 }
10451044
10461045 /**
1047 * Validate that the specified primitive value falls between the two
1048 * inclusive values specified; otherwise, throws an exception.
1049 *
1050 * <pre>Validate.inclusiveBetween(0.1, 2.1, 1.1);</pre>
1051 *
1052 * @param start the inclusive start value
1053 * @param end the inclusive end value
1054 * @param value the value to validate
1055 * @throws IllegalArgumentException if the value falls outside the boundaries (inclusive)
1056 *
1057 * @since 3.3
1058 */
1046 * Validate that the specified primitive value falls between the two
1047 * inclusive values specified; otherwise, throws an exception.
1048 *
1049 * <pre>Validate.inclusiveBetween(0.1, 2.1, 1.1);</pre>
1050 *
1051 * @param start the inclusive start value
1052 * @param end the inclusive end value
1053 * @param value the value to validate
1054 * @throws IllegalArgumentException if the value falls outside the boundaries (inclusive)
1055 *
1056 * @since 3.3
1057 */
10591058 @SuppressWarnings("boxing")
10601059 public static void inclusiveBetween(final double start, final double end, final double value) {
10611060 // TODO when breaking BC, consider returning value
10651064 }
10661065
10671066 /**
1068 * Validate that the specified primitive value falls between the two
1069 * inclusive values specified; otherwise, throws an exception with the
1070 * specified message.
1071 *
1072 * <pre>Validate.inclusiveBetween(0.1, 2.1, 1.1, "Not in range");</pre>
1073 *
1074 * @param start the inclusive start value
1075 * @param end the inclusive end value
1076 * @param value the value to validate
1077 * @param message the exception message if invalid, not null
1078 *
1079 * @throws IllegalArgumentException if the value falls outside the boundaries
1080 *
1081 * @since 3.3
1082 */
1067 * Validate that the specified primitive value falls between the two
1068 * inclusive values specified; otherwise, throws an exception with the
1069 * specified message.
1070 *
1071 * <pre>Validate.inclusiveBetween(0.1, 2.1, 1.1, "Not in range");</pre>
1072 *
1073 * @param start the inclusive start value
1074 * @param end the inclusive end value
1075 * @param value the value to validate
1076 * @param message the exception message if invalid, not null
1077 *
1078 * @throws IllegalArgumentException if the value falls outside the boundaries
1079 *
1080 * @since 3.3
1081 */
10831082 public static void inclusiveBetween(final double start, final double end, final double value, final String message) {
10841083 // TODO when breaking BC, consider returning value
10851084 if (value < start || value > end) {
11381137 }
11391138
11401139 /**
1141 * Validate that the specified primitive value falls between the two
1142 * exclusive values specified; otherwise, throws an exception.
1143 *
1144 * <pre>Validate.exclusiveBetween(0, 2, 1);</pre>
1145 *
1146 * @param start the exclusive start value
1147 * @param end the exclusive end value
1148 * @param value the value to validate
1149 * @throws IllegalArgumentException if the value falls out of the boundaries
1150 *
1151 * @since 3.3
1152 */
1140 * Validate that the specified primitive value falls between the two
1141 * exclusive values specified; otherwise, throws an exception.
1142 *
1143 * <pre>Validate.exclusiveBetween(0, 2, 1);</pre>
1144 *
1145 * @param start the exclusive start value
1146 * @param end the exclusive end value
1147 * @param value the value to validate
1148 * @throws IllegalArgumentException if the value falls out of the boundaries
1149 *
1150 * @since 3.3
1151 */
11531152 @SuppressWarnings("boxing")
11541153 public static void exclusiveBetween(final long start, final long end, final long value) {
11551154 // TODO when breaking BC, consider returning value
11591158 }
11601159
11611160 /**
1162 * Validate that the specified primitive value falls between the two
1163 * exclusive values specified; otherwise, throws an exception with the
1164 * specified message.
1165 *
1166 * <pre>Validate.exclusiveBetween(0, 2, 1, "Not in range");</pre>
1167 *
1168 * @param start the exclusive start value
1169 * @param end the exclusive end value
1170 * @param value the value to validate
1171 * @param message the exception message if invalid, not null
1172 *
1173 * @throws IllegalArgumentException if the value falls outside the boundaries
1174 *
1175 * @since 3.3
1176 */
1161 * Validate that the specified primitive value falls between the two
1162 * exclusive values specified; otherwise, throws an exception with the
1163 * specified message.
1164 *
1165 * <pre>Validate.exclusiveBetween(0, 2, 1, "Not in range");</pre>
1166 *
1167 * @param start the exclusive start value
1168 * @param end the exclusive end value
1169 * @param value the value to validate
1170 * @param message the exception message if invalid, not null
1171 *
1172 * @throws IllegalArgumentException if the value falls outside the boundaries
1173 *
1174 * @since 3.3
1175 */
11771176 public static void exclusiveBetween(final long start, final long end, final long value, final String message) {
11781177 // TODO when breaking BC, consider returning value
11791178 if (value <= start || value >= end) {
11821181 }
11831182
11841183 /**
1185 * Validate that the specified primitive value falls between the two
1186 * exclusive values specified; otherwise, throws an exception.
1187 *
1188 * <pre>Validate.exclusiveBetween(0.1, 2.1, 1.1);</pre>
1189 *
1190 * @param start the exclusive start value
1191 * @param end the exclusive end value
1192 * @param value the value to validate
1193 * @throws IllegalArgumentException if the value falls out of the boundaries
1194 *
1195 * @since 3.3
1196 */
1184 * Validate that the specified primitive value falls between the two
1185 * exclusive values specified; otherwise, throws an exception.
1186 *
1187 * <pre>Validate.exclusiveBetween(0.1, 2.1, 1.1);</pre>
1188 *
1189 * @param start the exclusive start value
1190 * @param end the exclusive end value
1191 * @param value the value to validate
1192 * @throws IllegalArgumentException if the value falls out of the boundaries
1193 *
1194 * @since 3.3
1195 */
11971196 @SuppressWarnings("boxing")
11981197 public static void exclusiveBetween(final double start, final double end, final double value) {
11991198 // TODO when breaking BC, consider returning value
12031202 }
12041203
12051204 /**
1206 * Validate that the specified primitive value falls between the two
1207 * exclusive values specified; otherwise, throws an exception with the
1208 * specified message.
1209 *
1210 * <pre>Validate.exclusiveBetween(0.1, 2.1, 1.1, "Not in range");</pre>
1211 *
1212 * @param start the exclusive start value
1213 * @param end the exclusive end value
1214 * @param value the value to validate
1215 * @param message the exception message if invalid, not null
1216 *
1217 * @throws IllegalArgumentException if the value falls outside the boundaries
1218 *
1219 * @since 3.3
1220 */
1205 * Validate that the specified primitive value falls between the two
1206 * exclusive values specified; otherwise, throws an exception with the
1207 * specified message.
1208 *
1209 * <pre>Validate.exclusiveBetween(0.1, 2.1, 1.1, "Not in range");</pre>
1210 *
1211 * @param start the exclusive start value
1212 * @param end the exclusive end value
1213 * @param value the value to validate
1214 * @param message the exception message if invalid, not null
1215 *
1216 * @throws IllegalArgumentException if the value falls outside the boundaries
1217 *
1218 * @since 3.3
1219 */
12211220 public static void exclusiveBetween(final double start, final double end, final double value, final String message) {
12221221 // TODO when breaking BC, consider returning value
12231222 if (value <= start || value >= end) {
148148 * @return {@code true}, if {@link Processor} is {@link Arch#BIT_32}, else {@code false}.
149149 */
150150 public boolean is32Bit() {
151 return Arch.BIT_32.equals(arch);
151 return Arch.BIT_32 == arch;
152152 }
153153
154154 /**
157157 * @return {@code true}, if {@link Processor} is {@link Arch#BIT_64}, else {@code false}.
158158 */
159159 public boolean is64Bit() {
160 return Arch.BIT_64.equals(arch);
160 return Arch.BIT_64 == arch;
161161 }
162162
163163 /**
166166 * @return {@code true}, if {@link Processor} is {@link Type#X86}, else {@code false}.
167167 */
168168 public boolean isX86() {
169 return Type.X86.equals(type);
169 return Type.X86 == type;
170170 }
171171
172172 /**
175175 * @return {@code true}. if {@link Processor} is {@link Type#IA_64}, else {@code false}.
176176 */
177177 public boolean isIA64() {
178 return Type.IA_64.equals(type);
178 return Type.IA_64 == type;
179179 }
180180
181181 /**
184184 * @return {@code true}. if {@link Processor} is {@link Type#PPC}, else {@code false}.
185185 */
186186 public boolean isPPC() {
187 return Type.PPC.equals(type);
187 return Type.PPC == type;
188188 }
189189
190190 }
107107 * {@link #toComparison} to get the result.</p>
108108 */
109109 public CompareToBuilder() {
110 super();
111110 comparison = 0;
112111 }
113112
114 //-----------------------------------------------------------------------
115113 /**
116114 * <p>Compares two {@code Object}s via reflection.</p>
117115 *
336334 }
337335 }
338336
339 //-----------------------------------------------------------------------
340337 /**
341338 * <p>Appends to the {@code builder} the {@code compareTo(Object)}
342339 * result of the superclass.</p>
353350 return this;
354351 }
355352
356 //-----------------------------------------------------------------------
357353 /**
358354 * <p>Appends to the {@code builder} the comparison of
359355 * two {@code Object}s.</p>
420416 if (lhs.getClass().isArray()) {
421417 // factor out array case in order to keep method small enough to be inlined
422418 appendArray(lhs, rhs, comparator);
419 } else // the simple case, not an array, just test the element
420 if (comparator == null) {
421 @SuppressWarnings("unchecked") // assume this can be done; if not throw CCE as per Javadoc
422 final Comparable<Object> comparable = (Comparable<Object>) lhs;
423 comparison = comparable.compareTo(rhs);
423424 } else {
424 // the simple case, not an array, just test the element
425 if (comparator == null) {
426 @SuppressWarnings("unchecked") // assume this can be done; if not throw CCE as per Javadoc
427 final Comparable<Object> comparable = (Comparable<Object>) lhs;
428 comparison = comparable.compareTo(rhs);
429 } else {
430 @SuppressWarnings("unchecked") // assume this can be done; if not throw CCE as per Javadoc
431 final Comparator<Object> comparator2 = (Comparator<Object>) comparator;
432 comparison = comparator2.compare(lhs, rhs);
433 }
425 @SuppressWarnings("unchecked") // assume this can be done; if not throw CCE as per Javadoc
426 final Comparator<Object> comparator2 = (Comparator<Object>) comparator;
427 comparison = comparator2.compare(lhs, rhs);
434428 }
435429 return this;
436430 }
608602 return this;
609603 }
610604
611 //-----------------------------------------------------------------------
612605 /**
613606 * <p>Appends to the {@code builder} the deep comparison of
614607 * two {@code Object} arrays.</p>
1001994 return this;
1002995 }
1003996
1004 //-----------------------------------------------------------------------
1005997 /**
1006998 * Returns a negative integer, a positive integer, or zero as
1007999 * the {@code builder} has judged the "left-hand" side
103103 public DiffBuilder(final T lhs, final T rhs,
104104 final ToStringStyle style, final boolean testTriviallyEqual) {
105105
106 Validate.notNull(lhs, "lhs cannot be null");
107 Validate.notNull(rhs, "rhs cannot be null");
106 Validate.notNull(lhs, "lhs");
107 Validate.notNull(rhs, "rhs");
108108
109109 this.diffs = new ArrayList<>();
110110 this.left = lhs;
810810 return this;
811811 }
812812
813 Object objectToTest;
813 final Object objectToTest;
814814 if (lhs != null) {
815815 objectToTest = lhs;
816816 } else {
948948 public DiffBuilder<T> append(final String fieldName,
949949 final DiffResult<T> diffResult) {
950950 validateFieldNameNotNull(fieldName);
951 Validate.notNull(diffResult, "Diff result cannot be null");
951 Validate.notNull(diffResult, "diffResult");
952952 if (objectsTriviallyEqual) {
953953 return this;
954954 }
976976 }
977977
978978 private void validateFieldNameNotNull(final String fieldName) {
979 Validate.notNull(fieldName, "Field name cannot be null");
979 Validate.notNull(fieldName, "fieldName");
980980 }
981981
982982 }
4747
4848 private static final String DIFFERS_STRING = "differs from";
4949
50 private final List<Diff<?>> diffs;
50 private final List<Diff<?>> diffList;
5151 private final T lhs;
5252 private final T rhs;
5353 private final ToStringStyle style;
6262 * the left hand object
6363 * @param rhs
6464 * the right hand object
65 * @param diffs
65 * @param diffList
6666 * the list of differences, may be empty
6767 * @param style
6868 * the style to use for the {@link #toString()} method. May be
7070 * {@link ToStringStyle#DEFAULT_STYLE} is used
7171 * @throws NullPointerException if {@code lhs}, {@code rhs} or {@code diffs} is {@code null}
7272 */
73 DiffResult(final T lhs, final T rhs, final List<Diff<?>> diffs,
73 DiffResult(final T lhs, final T rhs, final List<Diff<?>> diffList,
7474 final ToStringStyle style) {
75 Validate.notNull(lhs, "Left hand object cannot be null");
76 Validate.notNull(rhs, "Right hand object cannot be null");
77 Validate.notNull(diffs, "List of differences cannot be null");
78
79 this.diffs = diffs;
75 Validate.notNull(lhs, "lhs");
76 Validate.notNull(rhs, "rhs");
77 Validate.notNull(diffList, "diffList");
78
79 this.diffList = diffList;
8080 this.lhs = lhs;
8181 this.rhs = rhs;
8282
116116 * @return an unmodifiable list of {@code Diff}s
117117 */
118118 public List<Diff<?>> getDiffs() {
119 return Collections.unmodifiableList(diffs);
119 return Collections.unmodifiableList(diffList);
120120 }
121121
122122 /**
127127 * @return the number of differences
128128 */
129129 public int getNumberOfDiffs() {
130 return diffs.size();
130 return diffList.size();
131131 }
132132
133133 /**
189189 * @return a {@code String} description of the differences.
190190 */
191191 public String toString(final ToStringStyle style) {
192 if (diffs.isEmpty()) {
192 if (diffList.isEmpty()) {
193193 return OBJECTS_SAME_STRING;
194194 }
195195
196196 final ToStringBuilder lhsBuilder = new ToStringBuilder(lhs, style);
197197 final ToStringBuilder rhsBuilder = new ToStringBuilder(rhs, style);
198198
199 for (final Diff<?> diff : diffs) {
199 for (final Diff<?> diff : diffList) {
200200 lhsBuilder.append(diff.getFieldName(), diff.getLeft());
201201 rhsBuilder.append(diff.getFieldName(), diff.getRight());
202202 }
214214 */
215215 @Override
216216 public Iterator<Diff<?>> iterator() {
217 return diffs.iterator();
217 return diffList.iterator();
218218 }
219219 }
212212 */
213213 private boolean isEquals = true;
214214
215 private boolean testTransients = false;
216 private boolean testRecursive = false;
215 private boolean testTransients;
216 private boolean testRecursive;
217217 private List<Class<?>> bypassReflectionClasses;
218 private Class<?> reflectUpToClass = null;
219 private String[] excludeFields = null;
218 private Class<?> reflectUpToClass;
219 private String[] excludeFields;
220220
221221 /**
222222 * <p>Constructor for EqualsBuilder.</p>
531531 try {
532532 if (testClass.isArray()) {
533533 append(lhs, rhs);
534 } else //If either class is being excluded, call normal object equals method on lhsClass.
535 if (bypassReflectionClasses != null
536 && (bypassReflectionClasses.contains(lhsClass) || bypassReflectionClasses.contains(rhsClass))) {
537 isEquals = lhs.equals(rhs);
534538 } else {
535 //If either class is being excluded, call normal object equals method on lhsClass.
536 if (bypassReflectionClasses != null
537 && (bypassReflectionClasses.contains(lhsClass) || bypassReflectionClasses.contains(rhsClass))) {
538 isEquals = lhs.equals(rhs);
539 } else {
539 reflectionAppend(lhs, rhs, testClass);
540 while (testClass.getSuperclass() != null && testClass != reflectUpToClass) {
541 testClass = testClass.getSuperclass();
540542 reflectionAppend(lhs, rhs, testClass);
541 while (testClass.getSuperclass() != null && testClass != reflectUpToClass) {
542 testClass = testClass.getSuperclass();
543 reflectionAppend(lhs, rhs, testClass);
544 }
545543 }
546544 }
547545 } catch (final IllegalArgumentException e) {
551549 // If a subclass has ivars that we are trying to test them, we get an
552550 // exception and we know that the objects are not equal.
553551 isEquals = false;
554 return this;
555552 }
556553 return this;
557554 }
644641 // factor out array case in order to keep method small enough
645642 // to be inlined
646643 appendArray(lhs, rhs);
644 } else // The simple case, not an array, just test the element
645 if (testRecursive && !ClassUtils.isPrimitiveOrWrapper(lhsClass)) {
646 reflectionAppend(lhs, rhs);
647647 } else {
648 // The simple case, not an array, just test the element
649 if (testRecursive && !ClassUtils.isPrimitiveOrWrapper(lhsClass)) {
650 reflectionAppend(lhs, rhs);
651 } else {
652 isEquals = lhs.equals(rhs);
653 }
648 isEquals = lhs.equals(rhs);
654649 }
655650 return this;
656651 }
1919 import java.lang.reflect.AccessibleObject;
2020 import java.lang.reflect.Field;
2121 import java.lang.reflect.Modifier;
22 import java.util.Arrays;
2322 import java.util.Collection;
2423 import java.util.Comparator;
2524 import java.util.HashSet;
2625 import java.util.Set;
2726
27 import org.apache.commons.lang3.ArraySorter;
2828 import org.apache.commons.lang3.ArrayUtils;
2929 import org.apache.commons.lang3.Validate;
3030
190190 try {
191191 register(object);
192192 // The elements in the returned array are not sorted and are not in any particular order.
193 final Field[] fields = clazz.getDeclaredFields();
194 Arrays.sort(fields, Comparator.comparing(Field::getName));
193 final Field[] fields = ArraySorter.sort(clazz.getDeclaredFields(), Comparator.comparing(Field::getName));
195194 AccessibleObject.setAccessible(fields, true);
196195 for (final Field field : fields) {
197196 if (!ArrayUtils.contains(excludeFields, field.getName())
357356 */
358357 public static <T> int reflectionHashCode(final int initialNonZeroOddNumber, final int multiplierNonZeroOddNumber, final T object,
359358 final boolean testTransients, final Class<? super T> reflectUpToClass, final String... excludeFields) {
360 Validate.notNull(object, "The object to build a hash code for must not be null");
359 Validate.notNull(object, "object");
361360 final HashCodeBuilder builder = new HashCodeBuilder(initialNonZeroOddNumber, multiplierNonZeroOddNumber);
362361 Class<?> clazz = object.getClass();
363362 reflectionAppend(object, clazz, builder, testTransients, excludeFields);
536535 /**
537536 * Running total of the hashCode.
538537 */
539 private int iTotal = 0;
538 private int iTotal;
540539
541540 /**
542541 * <p>
842841 if (object == null) {
843842 iTotal = iTotal * iConstant;
844843
845 } else {
846 if (object.getClass().isArray()) {
847 // factor out array case in order to keep method small enough
848 // to be inlined
849 appendArray(object);
850 } else {
851 iTotal = iTotal * iConstant + object.hashCode();
852 }
844 } else if (object.getClass().isArray()) {
845 // factor out array case in order to keep method small enough
846 // to be inlined
847 appendArray(object);
848 } else {
849 iTotal = iTotal * iConstant + object.hashCode();
853850 }
854851 return this;
855852 }
7878 * Constructor.
7979 */
8080 public MultilineRecursiveToStringStyle() {
81 super();
8281 resetIndent();
8382 }
8483
6262 * <p>Constructor.</p>
6363 */
6464 public RecursiveToStringStyle() {
65 super();
6665 }
6766
6867 @Override
2525 import java.util.Comparator;
2626 import java.util.List;
2727
28 import org.apache.commons.lang3.ArraySorter;
2829 import org.apache.commons.lang3.ArrayUtils;
2930 import org.apache.commons.lang3.ClassUtils;
3031 import org.apache.commons.lang3.Validate;
433434 }
434435
435436 private static Object checkNotNull(final Object obj) {
436 return Validate.notNull(obj, "The Object passed in should not be null.");
437 return Validate.notNull(obj, "obj");
437438 }
438439
439440 /**
440441 * Whether or not to append static fields.
441442 */
442 private boolean appendStatics = false;
443 private boolean appendStatics;
443444
444445 /**
445446 * Whether or not to append transient fields.
446447 */
447 private boolean appendTransients = false;
448 private boolean appendTransients;
448449
449450 /**
450451 * Whether or not to append fields that are null.
461462 /**
462463 * The last super class to stop appending fields for.
463464 */
464 private Class<?> upToClass = null;
465 private Class<?> upToClass;
465466
466467 /**
467468 * <p>
639640 return;
640641 }
641642 // The elements in the returned array are not sorted and are not in any particular order.
642 final Field[] fields = clazz.getDeclaredFields();
643 Arrays.sort(fields, Comparator.comparing(Field::getName));
643 final Field[] fields = ArraySorter.sort(clazz.getDeclaredFields(), Comparator.comparing(Field::getName));
644644 AccessibleObject.setAccessible(fields, true);
645645 for (final Field field : fields) {
646646 final String fieldName = field.getName();
800800 this.excludeFieldNames = null;
801801 } else {
802802 //clone and remove nulls
803 this.excludeFieldNames = toNoNullStringArray(excludeFieldNamesParam);
804 Arrays.sort(this.excludeFieldNames);
803 this.excludeFieldNames = ArraySorter.sort(toNoNullStringArray(excludeFieldNamesParam));
805804 }
806805 return this;
807806 }
3939 * <p>Constructor.</p>
4040 */
4141 public StandardToStringStyle() {
42 super();
4342 }
4443
4544 //---------------------------------------------------------------------
132132 * @throws IllegalArgumentException if the style is {@code null}
133133 */
134134 public static void setDefaultStyle(final ToStringStyle style) {
135 defaultStyle = Validate.notNull(style, "The style must not be null");
135 defaultStyle = Validate.notNull(style, "style");
136136 }
137137
138138 //----------------------------------------------------------------------------
262262 /**
263263 * Whether to use short class names, the default is {@code false}.
264264 */
265 private boolean useShortClassName = false;
265 private boolean useShortClassName;
266266
267267 /**
268268 * Whether to use the identity hash code, the default is {@code true}.
287287 /**
288288 * Whether the field separator should be added before any other fields.
289289 */
290 private boolean fieldSeparatorAtStart = false;
290 private boolean fieldSeparatorAtStart;
291291
292292 /**
293293 * Whether the field separator should be added after any other fields.
294294 */
295 private boolean fieldSeparatorAtEnd = false;
295 private boolean fieldSeparatorAtEnd;
296296
297297 /**
298298 * The field separator {@code ','}.
356356 * <p>Constructor.</p>
357357 */
358358 protected ToStringStyle() {
359 super();
360359 }
361360
362361 //----------------------------------------------------------------------------
575574 appendSummary(buffer, fieldName, (Object[]) value);
576575 }
577576
577 } else if (detail) {
578 appendDetail(buffer, fieldName, value);
578579 } else {
579 if (detail) {
580 appendDetail(buffer, fieldName, value);
581 } else {
582 appendSummary(buffer, fieldName, value);
583 }
580 appendSummary(buffer, fieldName, value);
584581 }
585582 } finally {
586583 unregister(value);
625622 * {@code toString}, not {@code null}
626623 */
627624 protected void appendDetail(final StringBuffer buffer, final String fieldName, final Collection<?> coll) {
628 if (coll != null && !coll.isEmpty()) {
629 buffer.append(arrayStart);
630 int i = 0;
631 for (final Object item : coll) {
632 appendDetail(buffer, fieldName, i++, item);
633 }
634 buffer.append(arrayEnd);
635 return;
636 }
637
638625 buffer.append(coll);
639626 }
640627
21602147 * <p>Use the static constant rather than instantiating.</p>
21612148 */
21622149 DefaultToStringStyle() {
2163 super();
21642150 }
21652151
21662152 /**
21932179 * <p>Use the static constant rather than instantiating.</p>
21942180 */
21952181 NoFieldNameToStringStyle() {
2196 super();
21972182 this.setUseFieldNames(false);
21982183 }
21992184
22272212 * <p>Use the static constant rather than instantiating.</p>
22282213 */
22292214 ShortPrefixToStringStyle() {
2230 super();
22312215 this.setUseShortClassName(true);
22322216 this.setUseIdentityHashCode(false);
22332217 }
22612245 * <p>Use the static constant rather than instantiating.</p>
22622246 */
22632247 SimpleToStringStyle() {
2264 super();
22652248 this.setUseClassName(false);
22662249 this.setUseIdentityHashCode(false);
22672250 this.setUseFieldNames(false);
22972280 * <p>Use the static constant rather than instantiating.</p>
22982281 */
22992282 MultiLineToStringStyle() {
2300 super();
23012283 this.setContentStart("[");
23022284 this.setFieldSeparator(System.lineSeparator() + " ");
23032285 this.setFieldSeparatorAtStart(true);
23342316 * <p>Use the static constant rather than instantiating.</p>
23352317 */
23362318 NoClassNameToStringStyle() {
2337 super();
23382319 this.setUseClassName(false);
23392320 this.setUseIdentityHashCode(false);
23402321 }
23812362 * </p>
23822363 */
23832364 JsonToStringStyle() {
2384 super();
2385
23862365 this.setUseClassName(false);
23872366 this.setUseIdentityHashCode(false);
23882367
25942573 }
25952574
25962575 appendDetail(buffer, fieldName, valueAsString);
2576 }
2577
2578 @Override
2579 protected void appendDetail(final StringBuffer buffer, final String fieldName, final Collection<?> coll) {
2580 if (coll != null && !coll.isEmpty()) {
2581 buffer.append(getArrayStart());
2582 int i = 0;
2583 for (final Object item : coll) {
2584 appendDetail(buffer, fieldName, i++, item);
2585 }
2586 buffer.append(getArrayEnd());
2587 return;
2588 }
2589
2590 buffer.append(coll);
25972591 }
25982592
25992593 @Override
2626 * @since 3.5
2727 */
2828 public abstract class AbstractCircuitBreaker<T> implements CircuitBreaker<T> {
29
2930 /**
3031 * The name of the <em>open</em> property as it is passed to registered
3132 * change listeners.
138139 * {@code CircuitBreaker}.
139140 */
140141 protected enum State {
142
143 /** The closed state. */
141144 CLOSED {
142145 /**
143146 * {@inheritDoc}
148151 }
149152 },
150153
154 /** The open state. */
151155 OPEN {
152156 /**
153157 * {@inheritDoc}
174174
175175 // Determine the executor to use and whether a temporary one has to
176176 // be created
177 ExecutorService tempExec;
177 final ExecutorService tempExec;
178178 executor = getExternalExecutor();
179179 if (executor == null) {
180180 executor = tempExec = createExecutor();
279279 * is <b>null</b>
280280 */
281281 public Builder wrappedFactory(final ThreadFactory factory) {
282 Validate.notNull(factory, "Wrapped ThreadFactory must not be null!");
282 Validate.notNull(factory, "factory");
283283
284284 wrappedFactory = factory;
285285 return this;
294294 * @throws NullPointerException if the naming pattern is <b>null</b>
295295 */
296296 public Builder namingPattern(final String pattern) {
297 Validate.notNull(pattern, "Naming pattern must not be null!");
297 Validate.notNull(pattern, "pattern");
298298
299299 namingPattern = pattern;
300300 return this;
336336 */
337337 public Builder uncaughtExceptionHandler(
338338 final Thread.UncaughtExceptionHandler handler) {
339 Validate.notNull(handler, "Uncaught exception handler must not be null!");
339 Validate.notNull(handler, "handler");
340340
341341 exceptionHandler = handler;
342342 return this;
115115 * Tests the passed in {@code Callable} and throws an exception if it is
116116 * undefined.
117117 *
118 * @param call the object to check
118 * @param callable the object to check
119119 * @throws IllegalArgumentException if the {@code Callable} is <b>null</b>
120120 */
121 private void checkCallable(final Callable<T> call) {
122 Validate.notNull(call, "Callable must not be null!");
121 private void checkCallable(final Callable<T> callable) {
122 Validate.notNull(callable, "callable");
123123 }
124124 }
3232 * Creates a new, uninitialized instance of {@code CircuitBreakingException}.
3333 */
3434 public CircuitBreakingException() {
35 super();
3635 }
3736
3837 /**
4040 * Creates a new, uninitialized instance of {@code ConcurrentException}.
4141 */
4242 protected ConcurrentException() {
43 super();
4443 }
4544
4645 /**
4242 * ConcurrentRuntimeException}.
4343 */
4444 protected ConcurrentRuntimeException() {
45 super();
4645 }
4746
4847 /**
163163 }
164164 }
165165
166 //-----------------------------------------------------------------------
167166 /**
168167 * Invokes the specified {@code ConcurrentInitializer} and returns the
169168 * object produced by the initializer. This method just invokes the {@code
203202 }
204203 }
205204
206 //-----------------------------------------------------------------------
207205 /**
208206 * <p>
209207 * Puts a value in the specified {@code ConcurrentMap} if the key is not yet
304302 }
305303 }
306304
307 //-----------------------------------------------------------------------
308305 /**
309306 * <p>
310307 * Gets an implementation of {@code Future} that is immediately done
173173 public EventCountCircuitBreaker(final int openingThreshold, final long openingInterval,
174174 final TimeUnit openingUnit, final int closingThreshold, final long closingInterval,
175175 final TimeUnit closingUnit) {
176 super();
177176 checkIntervalData = new AtomicReference<>(new CheckIntervalData(0, 0));
178177 this.openingThreshold = openingThreshold;
179178 this.openingInterval = openingUnit.toNanos(openingInterval);
293292 @Override
294293 public void open() {
295294 super.open();
296 checkIntervalData.set(new CheckIntervalData(0, now()));
295 checkIntervalData.set(new CheckIntervalData(0, nanoTime()));
297296 }
298297
299298 /**
305304 @Override
306305 public void close() {
307306 super.close();
308 checkIntervalData.set(new CheckIntervalData(0, now()));
307 checkIntervalData.set(new CheckIntervalData(0, nanoTime()));
309308 }
310309
311310 /**
321320 State currentState;
322321
323322 do {
324 final long time = now();
323 final long time = nanoTime();
325324 currentState = state.get();
326325 currentData = checkIntervalData.get();
327326 nextData = nextCheckIntervalData(increment, currentData, currentState, time);
360359 */
361360 private void changeStateAndStartNewCheckInterval(final State newState) {
362361 changeState(newState);
363 checkIntervalData.set(new CheckIntervalData(0, now()));
362 checkIntervalData.set(new CheckIntervalData(0, nanoTime()));
364363 }
365364
366365 /**
376375 */
377376 private CheckIntervalData nextCheckIntervalData(final int increment,
378377 final CheckIntervalData currentData, final State currentState, final long time) {
379 CheckIntervalData nextData;
378 final CheckIntervalData nextData;
380379 if (stateStrategy(currentState).isCheckIntervalFinished(this, currentData, time)) {
381380 nextData = new CheckIntervalData(increment, time);
382381 } else {
391390 *
392391 * @return the current time in nanoseconds
393392 */
394 long now() {
393 long nanoTime() {
395394 return System.nanoTime();
396395 }
397396
149149 private RuntimeException launderException(final Throwable throwable) {
150150 if (throwable instanceof RuntimeException) {
151151 return (RuntimeException) throwable;
152 } else if (throwable instanceof Error) {
152 }
153 if (throwable instanceof Error) {
153154 throw (Error) throwable;
154 } else {
155 throw new IllegalStateException("Unchecked exception", throwable);
156155 }
156 throw new IllegalStateException("Unchecked exception", throwable);
157157 }
158158 }
105105 * Creates a new instance of {@code MultiBackgroundInitializer}.
106106 */
107107 public MultiBackgroundInitializer() {
108 super();
109108 }
110109
111110 /**
126125 * been invoked.
127126 *
128127 * @param name the name of the initializer (must not be <b>null</b>)
129 * @param init the {@code BackgroundInitializer} to add (must not be
128 * @param backgroundInitializer the {@code BackgroundInitializer} to add (must not be
130129 * <b>null</b>)
131130 * @throws IllegalArgumentException if a required parameter is missing
132131 * @throws IllegalStateException if {@code start()} has already been called
133132 */
134 public void addInitializer(final String name, final BackgroundInitializer<?> init) {
135 Validate.notNull(name, "Name of child initializer must not be null!");
136 Validate.notNull(init, "Child initializer must not be null!");
133 public void addInitializer(final String name, final BackgroundInitializer<?> backgroundInitializer) {
134 Validate.notNull(name, "name");
135 Validate.notNull(backgroundInitializer, "backgroundInitializer");
137136
138137 synchronized (this) {
139138 if (isStarted()) {
140 throw new IllegalStateException(
141 "addInitializer() must not be called after start()!");
139 throw new IllegalStateException("addInitializer() must not be called after start()!");
142140 }
143 childInitializers.put(name, init);
141 childInitializers.put(name, backgroundInitializer);
144142 }
145143 }
146144
177175 */
178176 @Override
179177 protected MultiBackgroundInitializerResults initialize() throws Exception {
180 Map<String, BackgroundInitializer<?>> inits;
178 final Map<String, BackgroundInitializer<?>> inits;
181179 synchronized (this) {
182180 // create a snapshot to operate on
183181 inits = new HashMap<>(
7272 * @param threshold the threshold.
7373 */
7474 public ThresholdCircuitBreaker(final long threshold) {
75 super();
7675 this.used = new AtomicLong(INITIAL_COUNT);
7776 this.threshold = threshold;
7877 }
117117 * @param readLockSupplier Supplies the read lock, usually from the lock object.
118118 * @param writeLockSupplier Supplies the write lock, usually from the lock object.
119119 */
120 protected LockVisitor(final O object, L lock, Supplier<Lock> readLockSupplier, Supplier<Lock> writeLockSupplier) {
121 super();
120 protected LockVisitor(final O object, final L lock, final Supplier<Lock> readLockSupplier, final Supplier<Lock> writeLockSupplier) {
122121 this.object = Objects.requireNonNull(object, "object");
123122 this.lock = Objects.requireNonNull(lock, "lock");
124123 this.readLockSupplier = Objects.requireNonNull(readLockSupplier, "readLockSupplier");
143142 * @see #acceptWriteLocked(FailableConsumer)
144143 * @see #applyReadLocked(FailableFunction)
145144 */
146 public void acceptReadLocked(FailableConsumer<O, ?> consumer) {
145 public void acceptReadLocked(final FailableConsumer<O, ?> consumer) {
147146 lockAcceptUnlock(readLockSupplier, consumer);
148147 }
149148
205204 * @see #acceptReadLocked(FailableConsumer)
206205 * @see #applyWriteLocked(FailableFunction)
207206 */
208 public <T> T applyReadLocked(FailableFunction<O, T, ?> function) {
207 public <T> T applyReadLocked(final FailableFunction<O, T, ?> function) {
209208 return lockApplyUnlock(readLockSupplier, function);
210209 }
211210
271270 lock.lock();
272271 try {
273272 consumer.accept(object);
274 } catch (Throwable t) {
273 } catch (final Throwable t) {
275274 throw Failable.rethrow(t);
276275 } finally {
277276 lock.unlock();
298297 lock.lock();
299298 try {
300299 return function.apply(object);
301 } catch (Throwable t) {
300 } catch (final Throwable t) {
302301 throw Failable.rethrow(t);
303302 } finally {
304303 lock.unlock();
348347 * @param object The locked (hidden) object. The caller is supposed to drop all references to the locked object.
349348 * @param stampedLock the lock to use.
350349 */
351 protected StampedLockVisitor(final O object, StampedLock stampedLock) {
350 protected StampedLockVisitor(final O object, final StampedLock stampedLock) {
352351 super(object, stampedLock, stampedLock::asReadLock, stampedLock::asWriteLock);
353352 }
354353 }
2121 import java.io.ObjectInputStream;
2222 import java.io.ObjectOutputStream;
2323 import java.io.Serializable;
24 import java.lang.reflect.Array;
2524 import java.lang.reflect.InvocationHandler;
2625 import java.lang.reflect.Method;
2726 import java.lang.reflect.Proxy;
2928 import java.util.List;
3029 import java.util.concurrent.CopyOnWriteArrayList;
3130
31 import org.apache.commons.lang3.ArrayUtils;
3232 import org.apache.commons.lang3.Validate;
3333
3434 /**
139139 */
140140 public EventListenerSupport(final Class<L> listenerInterface, final ClassLoader classLoader) {
141141 this();
142 Validate.notNull(listenerInterface, "Listener interface cannot be null.");
143 Validate.notNull(classLoader, "ClassLoader cannot be null.");
142 Validate.notNull(listenerInterface, "listenerInterface");
143 Validate.notNull(classLoader, "classLoader");
144144 Validate.isTrue(listenerInterface.isInterface(), "Class %s is not an interface",
145145 listenerInterface.getName());
146146 initializeTransientFields(listenerInterface, classLoader);
193193 * @since 3.5
194194 */
195195 public void addListener(final L listener, final boolean allowDuplicate) {
196 Validate.notNull(listener, "Listener object cannot be null.");
196 Validate.notNull(listener, "listener");
197197 if (allowDuplicate || !listeners.contains(listener)) {
198198 listeners.add(listener);
199199 }
217217 * {@code null}.
218218 */
219219 public void removeListener(final L listener) {
220 Validate.notNull(listener, "Listener object cannot be null.");
220 Validate.notNull(listener, "listener");
221221 listeners.remove(listener);
222222 }
223223
265265 */
266266 private void readObject(final ObjectInputStream objectInputStream) throws IOException, ClassNotFoundException {
267267 @SuppressWarnings("unchecked") // Will throw CCE here if not correct
268 final
269 L[] srcListeners = (L[]) objectInputStream.readObject();
268 final L[] srcListeners = (L[]) objectInputStream.readObject();
270269
271270 this.listeners = new CopyOnWriteArrayList<>(srcListeners);
272271
273 @SuppressWarnings("unchecked") // Will throw CCE here if not correct
274 final
275 Class<L> listenerInterface = (Class<L>) srcListeners.getClass().getComponentType();
272 final Class<L> listenerInterface = ArrayUtils.getComponentType(srcListeners);
276273
277274 initializeTransientFields(listenerInterface, Thread.currentThread().getContextClassLoader());
278275 }
283280 * @param classLoader the class loader to be used
284281 */
285282 private void initializeTransientFields(final Class<L> listenerInterface, final ClassLoader classLoader) {
286 @SuppressWarnings("unchecked") // Will throw CCE here if not correct
287 final
288 L[] array = (L[]) Array.newInstance(listenerInterface, 0);
289 this.prototypeArray = array;
283 // Will throw CCE here if not correct
284 this.prototypeArray = ArrayUtils.newInstance(listenerInterface, 0);
290285 createProxy(listenerInterface, classLoader);
291286 }
292287
4444 * throw new ContextedException("Error posting account transaction", e)
4545 * .addContextValue("Account Number", accountNumber)
4646 * .addContextValue("Amount Posted", amountPosted)
47 * .addContextValue("Previous Balance", previousBalance)
47 * .addContextValue("Previous Balance", previousBalance);
4848 * }
4949 * }
5050 * </pre>
9696 * The context information is stored using a default implementation.
9797 */
9898 public ContextedException() {
99 super();
10099 exceptionContext = new DefaultExceptionContext();
101100 }
102101
152151 exceptionContext = context;
153152 }
154153
155 //-----------------------------------------------------------------------
156154 /**
157155 * Adds information helpful to a developer in diagnosing and correcting the problem.
158156 * For the information to be meaningful, the value passed should have a reasonable
4444 * throw new ContextedRuntimeException("Error posting account transaction", e)
4545 * .addContextValue("Account Number", accountNumber)
4646 * .addContextValue("Amount Posted", amountPosted)
47 * .addContextValue("Previous Balance", previousBalance)
47 * .addContextValue("Previous Balance", previousBalance);
4848 * }
4949 * }
5050 * </pre>
9696 * The context information is stored using a default implementation.
9797 */
9898 public ContextedRuntimeException() {
99 super();
10099 exceptionContext = new DefaultExceptionContext();
101100 }
102101
152151 exceptionContext = context;
153152 }
154153
155 //-----------------------------------------------------------------------
156154 /**
157155 * Adds information helpful to a developer in diagnosing and correcting the problem.
158156 * For the information to be meaningful, the value passed should have a reasonable
3131 import org.apache.commons.lang3.StringUtils;
3232
3333 /**
34 * <p>Provides utilities for manipulating and examining
35 * {@code Throwable} objects.</p>
34 * Provides utilities for manipulating and examining
35 * {@code Throwable} objects.
3636 *
3737 * @since 1.0
3838 */
4141 private static final int NOT_FOUND = -1;
4242
4343 /**
44 * <p>The names of methods commonly used to access a wrapped exception.</p>
44 * The names of methods commonly used to access a wrapped exception.
4545 */
4646 // TODO: Remove in Lang 4.0
4747 private static final String[] CAUSE_METHOD_NAMES = {
6060 };
6161
6262 /**
63 * <p>Used when printing stack frames to denote the start of a
64 * wrapped exception.</p>
63 * Used when printing stack frames to denote the start of a
64 * wrapped exception.
6565 *
6666 * <p>Package private for accessibility by test suite.</p>
6767 */
6868 static final String WRAPPED_MARKER = " [wrapped] ";
6969
70 //-----------------------------------------------------------------------
71 /**
72 * <p>Introspects the {@code Throwable} to obtain the cause.</p>
70 /**
71 * Claims a Throwable is another Throwable type using type erasure. This
72 * hides a checked exception from the Java compiler, allowing a checked
73 * exception to be thrown without having the exception in the method's throw
74 * clause.
75 */
76 @SuppressWarnings("unchecked")
77 private static <R, T extends Throwable> R eraseType(final Throwable throwable) throws T {
78 throw (T) throwable;
79 }
80
81 /**
82 * Introspects the {@code Throwable} to obtain the cause.
7383 *
7484 * <p>The method searches for methods with specific names that return a
7585 * {@code Throwable} object. This will pick up most wrapping exceptions,
101111 }
102112
103113 /**
104 * <p>Introspects the {@code Throwable} to obtain the cause.</p>
114 * Introspects the {@code Throwable} to obtain the cause.
105115 *
106116 * <p>A {@code null} set of method names means use the default set.
107117 * A {@code null} in the set of method names will be ignored.</p>
141151 }
142152
143153 /**
144 * <p>Finds a {@code Throwable} by method name.</p>
154 * Gets a {@code Throwable} by method name.
145155 *
146156 * @param throwable the exception to examine
147157 * @param methodName the name of the method to find and invoke
166176 return null;
167177 }
168178
169 //-----------------------------------------------------------------------
170 /**
171 * <p>Returns the default names used when searching for the cause of an exception.</p>
179 /**
180 * Gets the default names used when searching for the cause of an exception.
172181 *
173182 * <p>This may be modified and used in the overloaded getCause(Throwable, String[]) method.</p>
174183 *
181190 return ArrayUtils.clone(CAUSE_METHOD_NAMES);
182191 }
183192
184 //-----------------------------------------------------------------------
185193 /**
186194 * Gets a short message summarising the exception.
187195 * <p>
188196 * The message returned is of the form
189197 * {ClassNameWithoutPackage}: {ThrowableMessage}
198 * </p>
190199 *
191200 * @param th the throwable to get a message for, null returns empty string
192201 * @return the message, non-null
202211 }
203212
204213 /**
205 * <p>Introspects the {@code Throwable} to obtain the root cause.</p>
214 * Introspects the {@code Throwable} to obtain the root cause.
206215 *
207216 * <p>This method walks through the exception chain to the last element,
208217 * "root" of the tree, using {@link Throwable#getCause()}, and
223232 return list.isEmpty() ? null : list.get(list.size() - 1);
224233 }
225234
226 //-----------------------------------------------------------------------
227235 /**
228236 * Gets a short message summarising the root cause exception.
229237 * <p>
230238 * The message returned is of the form
231239 * {ClassNameWithoutPackage}: {ThrowableMessage}
240 * </p>
232241 *
233242 * @param th the throwable to get a message for, null returns empty string
234243 * @return the message, non-null
240249 return getMessage(root);
241250 }
242251
243 //-----------------------------------------------------------------------
244 /**
245 * <p>Creates a compact stack trace for the root cause of the supplied
246 * {@code Throwable}.</p>
252 /**
253 * Gets a compact stack trace for the root cause of the supplied
254 * {@code Throwable}.
247255 *
248256 * <p>The output of this method is consistent across JDK versions.
249257 * It consists of the root exception followed by each of its wrapping
279287 }
280288
281289 /**
282 * <p>Produces a {@code List} of stack frames - the message
290 * Gets a {@code List} of stack frames - the message
283291 * is not included. Only the trace of the specified exception is
284 * returned, any caused by trace is stripped.</p>
292 * returned, any caused by trace is stripped.
285293 *
286294 * <p>This works in most cases - it will only fail if the exception
287295 * message contains a line that starts with:
310318 return list;
311319 }
312320
313 //-----------------------------------------------------------------------
314 /**
315 * <p>Returns an array where each element is a line from the argument.</p>
321 /**
322 * Gets an array where each element is a line from the argument.
316323 *
317324 * <p>The end of line is determined by the value of {@link System#lineSeparator()}.</p>
318325 *
330337 }
331338
332339 /**
333 * <p>Captures the stack trace associated with the specified
340 * Gets the stack trace associated with the specified
334341 * {@code Throwable} object, decomposing it into a list of
335 * stack frames.</p>
342 * stack frames.
336343 *
337344 * <p>The result of this method vary by JDK version as this method
338345 * uses {@link Throwable#printStackTrace(java.io.PrintWriter)}.
349356 return getStackFrames(getStackTrace(throwable));
350357 }
351358
352 //-----------------------------------------------------------------------
353 /**
354 * <p>Gets the stack trace from a Throwable as a String.</p>
359 /**
360 * Gets the stack trace from a Throwable as a String.
355361 *
356362 * <p>The result of this method vary by JDK version as this method
357363 * uses {@link Throwable#printStackTrace(java.io.PrintWriter)}.
369375 return sw.getBuffer().toString();
370376 }
371377
372 //-----------------------------------------------------------------------
373 /**
374 * <p>Counts the number of {@code Throwable} objects in the
375 * exception chain.</p>
378 /**
379 * Gets a count of the number of {@code Throwable} objects in the
380 * exception chain.
376381 *
377382 * <p>A throwable without cause will return {@code 1}.
378383 * A throwable with one cause will return {@code 2} and so on.
391396 }
392397
393398 /**
394 * <p>Returns the list of {@code Throwable} objects in the
395 * exception chain.</p>
399 * Gets the list of {@code Throwable} objects in the
400 * exception chain.
396401 *
397402 * <p>A throwable without cause will return a list containing
398403 * one element - the input throwable.
419424 }
420425
421426 /**
422 * <p>Returns the list of {@code Throwable} objects in the
423 * exception chain.</p>
427 * Gets the list of {@code Throwable} objects in the
428 * exception chain.
424429 *
425430 * <p>A throwable without cause will return an array containing
426431 * one element - the input throwable.
443448 }
444449
445450 /**
446 * Does the throwable's causal chain have an immediate or wrapped exception
451 * Tests if the throwable's causal chain have an immediate or wrapped exception
447452 * of the given type?
448453 *
449454 * @param chain
464469 }
465470
466471 /**
467 * <p>Worker method for the {@code indexOfType} methods.</p>
472 * Worker method for the {@code indexOfType} methods.
468473 *
469474 * @param throwable the throwable to inspect, may be null
470475 * @param type the type to search for, subclasses match, null returns -1
502507 }
503508
504509 /**
505 * <p>Returns the (zero-based) index of the first {@code Throwable}
510 * Returns the (zero-based) index of the first {@code Throwable}
506511 * that matches the specified class (exactly) in the exception chain.
507512 * Subclasses of the specified class do not match - see
508 * {@link #indexOfType(Throwable, Class)} for the opposite.</p>
513 * {@link #indexOfType(Throwable, Class)} for the opposite.
509514 *
510515 * <p>A {@code null} throwable returns {@code -1}.
511516 * A {@code null} type returns {@code -1}.
520525 }
521526
522527 /**
523 * <p>Returns the (zero-based) index of the first {@code Throwable}
528 * Returns the (zero-based) index of the first {@code Throwable}
524529 * that matches the specified type in the exception chain from
525530 * a specified index.
526531 * Subclasses of the specified class do not match - see
527 * {@link #indexOfType(Throwable, Class, int)} for the opposite.</p>
532 * {@link #indexOfType(Throwable, Class, int)} for the opposite.
528533 *
529534 * <p>A {@code null} throwable returns {@code -1}.
530535 * A {@code null} type returns {@code -1}.
543548 }
544549
545550 /**
546 * <p>Returns the (zero-based) index of the first {@code Throwable}
551 * Returns the (zero-based) index of the first {@code Throwable}
547552 * that matches the specified class or subclass in the exception chain.
548553 * Subclasses of the specified class do match - see
549 * {@link #indexOfThrowable(Throwable, Class)} for the opposite.</p>
554 * {@link #indexOfThrowable(Throwable, Class)} for the opposite.
550555 *
551556 * <p>A {@code null} throwable returns {@code -1}.
552557 * A {@code null} type returns {@code -1}.
562567 }
563568
564569 /**
565 * <p>Returns the (zero-based) index of the first {@code Throwable}
570 * Returns the (zero-based) index of the first {@code Throwable}
566571 * that matches the specified type in the exception chain from
567572 * a specified index.
568573 * Subclasses of the specified class do match - see
569 * {@link #indexOfThrowable(Throwable, Class)} for the opposite.</p>
574 * {@link #indexOfThrowable(Throwable, Class)} for the opposite.
570575 *
571576 * <p>A {@code null} throwable returns {@code -1}.
572577 * A {@code null} type returns {@code -1}.
585590 return indexOf(throwable, type, fromIndex, true);
586591 }
587592
588 //-----------------------------------------------------------------------
589 /**
590 * <p>Prints a compact stack trace for the root cause of a throwable
591 * to {@code System.err}.</p>
593 /**
594 * Prints a compact stack trace for the root cause of a throwable
595 * to {@code System.err}.
592596 *
593597 * <p>The compact stack trace starts with the root cause and prints
594598 * stack frames up to the place where it was caught and wrapped.
609613 }
610614
611615 /**
612 * <p>Prints a compact stack trace for the root cause of a throwable.</p>
616 * Prints a compact stack trace for the root cause of a throwable.
613617 *
614618 * <p>The compact stack trace starts with the root cause and prints
615619 * stack frames up to the place where it was caught and wrapped.
641645 }
642646
643647 /**
644 * <p>Prints a compact stack trace for the root cause of a throwable.</p>
648 * Prints a compact stack trace for the root cause of a throwable.
645649 *
646650 * <p>The compact stack trace starts with the root cause and prints
647651 * stack frames up to the place where it was caught and wrapped.
673677 }
674678
675679 /**
676 * <p>Removes common frames from the cause trace given the two stack traces.</p>
680 * Removes common frames from the cause trace given the two stack traces.
677681 *
678682 * @param causeFrames stack trace of a cause throwable
679683 * @param wrapperFrames stack trace of a wrapper throwable
700704 }
701705
702706 /**
703 * Throw a checked exception without adding the exception to the throws
707 * Throws a checked exception without adding the exception to the throws
704708 * clause of the calling method. This method prevents throws clause
705709 * pollution and reduces the clutter of "Caused by" exceptions in the
706710 * stacktrace.
707711 * <p>
708712 * The use of this technique may be controversial, but exceedingly useful to
709713 * library developers.
710 * <code>
714 * </p>
715 * <pre>
711716 * public int propagateExample { // note that there is no throws clause
712717 * try {
713718 * return invocation(); // throws IOException
715720 * return ExceptionUtils.rethrow(e); // propagates a checked exception
716721 * }
717722 * }
718 * </code>
723 * </pre>
719724 * <p>
720725 * This is an alternative to the more conservative approach of wrapping the
721726 * checked exception in a RuntimeException:
722 * <code>
727 * </p>
728 * <pre>
723729 * public int wrapExample { // note that there is no throws clause
724730 * try {
725731 * return invocation(); // throws IOException
731737 * throw new UndeclaredThrowableException(e); // wraps a checked exception
732738 * }
733739 * }
734 * </code>
740 * </pre>
735741 * <p>
736742 * One downside to using this approach is that the java compiler will not
737743 * allow invoking code to specify a checked exception in a catch clause
743749 * techniques are required when interacting with non-java jvm code such as
744750 * Jython, Scala, or Groovy, since these languages do not consider any
745751 * exceptions as checked.
752 * </p>
746753 *
747754 * @param throwable
748755 * The throwable to rethrow.
756763 */
757764 public static <R> R rethrow(final Throwable throwable) {
758765 // claim that the typeErasure invocation throws a RuntimeException
759 return ExceptionUtils.<R, RuntimeException>typeErasure(throwable);
760 }
761
762 /**
763 * <p>Worker method for the {@code throwableOfType} methods.</p>
766 return ExceptionUtils.<R, RuntimeException>eraseType(throwable);
767 }
768
769 /**
770 * Worker method for the {@code throwableOfType} methods.
764771 *
765772 * @param <T> the type of Throwable you are searching.
766773 * @param throwable the throwable to inspect, may be null
799806 }
800807
801808 /**
802 * <p>Returns the first {@code Throwable}
809 * Returns the first {@code Throwable}
803810 * that matches the specified class (exactly) in the exception chain.
804811 * Subclasses of the specified class do not match - see
805 * {@link #throwableOfType(Throwable, Class)} for the opposite.</p>
812 * {@link #throwableOfType(Throwable, Class)} for the opposite.
806813 *
807814 * <p>A {@code null} throwable returns {@code null}.
808815 * A {@code null} type returns {@code null}.
819826 }
820827
821828 /**
822 * <p>Returns the first {@code Throwable}
829 * Returns the first {@code Throwable}
823830 * that matches the specified type in the exception chain from
824831 * a specified index.
825832 * Subclasses of the specified class do not match - see
826 * {@link #throwableOfType(Throwable, Class, int)} for the opposite.</p>
833 * {@link #throwableOfType(Throwable, Class, int)} for the opposite.
827834 *
828835 * <p>A {@code null} throwable returns {@code null}.
829836 * A {@code null} type returns {@code null}.
844851 }
845852
846853 /**
847 * <p>Returns the throwable of the first {@code Throwable}
854 * Returns the throwable of the first {@code Throwable}
848855 * that matches the specified class or subclass in the exception chain.
849856 * Subclasses of the specified class do match - see
850 * {@link #throwableOfThrowable(Throwable, Class)} for the opposite..</p>
857 * {@link #throwableOfThrowable(Throwable, Class)} for the opposite.
851858 *
852859 * <p>A {@code null} throwable returns {@code null}.
853860 * A {@code null} type returns {@code null}.
864871 }
865872
866873 /**
867 * <p>Returns the first {@code Throwable}
874 * Returns the first {@code Throwable}
868875 * that matches the specified type in the exception chain from
869876 * a specified index.
870877 * Subclasses of the specified class do match - see
871 * {@link #throwableOfThrowable(Throwable, Class)} for the opposite.</p>
878 * {@link #throwableOfThrowable(Throwable, Class)} for the opposite.
872879 *
873880 * <p>A {@code null} throwable returns {@code null}.
874881 * A {@code null} type returns {@code null}.
889896 }
890897
891898 /**
892 * Claim a Throwable is another Exception type using type erasure. This
893 * hides a checked exception from the java compiler, allowing a checked
894 * exception to be thrown without having the exception in the method's throw
895 * clause.
896 */
897 @SuppressWarnings("unchecked")
898 private static <R, T extends Throwable> R typeErasure(final Throwable throwable) throws T {
899 throw (T) throwable;
900 }
901
902 /**
903 * Throw a checked exception without adding the exception to the throws
899 * Throws a checked exception without adding the exception to the throws
904900 * clause of the calling method. For checked exceptions, this method throws
905901 * an UndeclaredThrowableException wrapping the checked exception. For
906902 * Errors and RuntimeExceptions, the original exception is rethrown.
908904 * The downside to using this approach is that invoking code which needs to
909905 * handle specific checked exceptions must sniff up the exception chain to
910906 * determine if the caught exception was caused by the checked exception.
907 * </p>
911908 *
912909 * @param throwable
913910 * The throwable to rethrow.
931928 }
932929
933930 /**
934 * <p>
935931 * Public constructor allows an instance of {@code ExceptionUtils} to be created, although that is not
936932 * normally necessary.
937 * </p>
938933 */
939934 public ExceptionUtils() {
940 super();
941935 }
942936 }
0 /*
1 * Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package org.apache.commons.lang3.function;
18
19 import java.util.Objects;
20 import java.util.function.IntConsumer;
21
22 /**
23 * A functional interface like {@link IntConsumer} but for {@code boolean}.
24 *
25 * @see IntConsumer
26 * @since 3.13.0
27 */
28 @FunctionalInterface
29 public interface BooleanConsumer {
30
31 /** NOP singleton */
32 BooleanConsumer NOP = t -> {/* NOP */};
33
34 /**
35 * Returns The NOP singleton.
36 *
37 * @return The NOP singleton.
38 */
39 static BooleanConsumer nop() {
40 return NOP;
41 }
42
43 /**
44 * Performs this operation on the given argument.
45 *
46 * @param value the input argument
47 */
48 void accept(boolean value);
49
50 /**
51 * Returns a composed {@code BooleanConsumer} that performs, in sequence, this operation followed by the {@code after}
52 * operation. If performing either operation throws an exception, it is relayed to the caller of the composed operation.
53 * If performing this operation throws an exception, the {@code after} operation will not be performed.
54 *
55 * @param after the operation to perform after this operation
56 * @return a composed {@code BooleanConsumer} that performs in sequence this operation followed by the {@code after}
57 * operation
58 * @throws NullPointerException if {@code after} is null
59 */
60 default BooleanConsumer andThen(final BooleanConsumer after) {
61 Objects.requireNonNull(after);
62 return (final boolean t) -> {
63 accept(t);
64 after.accept(t);
65 };
66 }
67 }
4040 * constructs like:
4141 *
4242 * <pre>
43 * Consumer&lt;java.lang.reflect.Method-&gt; consumer = (m) -&gt; {
43 * Consumer&lt;java.lang.reflect.Method-&gt; consumer = m -&gt; {
4444 * try {
4545 * m.invoke(o, args);
4646 * } catch (Throwable t) {
323323 *
324324 * @param supplier The double supplier to invoke.
325325 * @param <E> The type of checked exception, which the supplier can throw.
326 * @return The boolean, which has been created by the supplier
326 * @return The double, which has been created by the supplier
327327 */
328328 public static <E extends Throwable> double getAsDouble(final FailableDoubleSupplier<E> supplier) {
329329 try {
338338 *
339339 * @param supplier The int supplier to invoke.
340340 * @param <E> The type of checked exception, which the supplier can throw.
341 * @return The boolean, which has been created by the supplier
341 * @return The int, which has been created by the supplier
342342 */
343343 public static <E extends Throwable> int getAsInt(final FailableIntSupplier<E> supplier) {
344344 try {
353353 *
354354 * @param supplier The long supplier to invoke.
355355 * @param <E> The type of checked exception, which the supplier can throw.
356 * @return The boolean, which has been created by the supplier
356 * @return The long, which has been created by the supplier
357357 */
358358 public static <E extends Throwable> long getAsLong(final FailableLongSupplier<E> supplier) {
359359 try {
360360 return supplier.getAsLong();
361 } catch (final Throwable t) {
362 throw rethrow(t);
363 }
364 }
365
366 /**
367 * Invokes a short supplier, and returns the result.
368 *
369 * @param supplier The short supplier to invoke.
370 * @param <E> The type of checked exception, which the supplier can throw.
371 * @return The short, which has been created by the supplier
372 */
373 public static <E extends Throwable> short getAsShort(final FailableShortSupplier<E> supplier) {
374 try {
375 return supplier.getAsShort();
361376 } catch (final Throwable t) {
362377 throw rethrow(t);
363378 }
394409 Objects.requireNonNull(throwable, "throwable");
395410 if (throwable instanceof RuntimeException) {
396411 throw (RuntimeException) throwable;
397 } else if (throwable instanceof Error) {
412 }
413 if (throwable instanceof Error) {
398414 throw (Error) throwable;
399 } else if (throwable instanceof IOException) {
415 }
416 if (throwable instanceof IOException) {
400417 throw new UncheckedIOException((IOException) throwable);
401 } else {
402 throw new UndeclaredThrowableException(throwable);
403 }
418 }
419 throw new UndeclaredThrowableException(throwable);
404420 }
405421
406422 /**
0 /*
1 * Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package org.apache.commons.lang3.function;
18
19 import java.util.function.IntSupplier;
20
21 /**
22 * A functional interface like {@link IntSupplier} but for {@code short} that declares a {@code Throwable}.
23 *
24 * @param <E> Thrown exception.
25 * @since 3.12.0
26 */
27 @FunctionalInterface
28 public interface FailableShortSupplier<E extends Throwable> {
29
30 /**
31 * Supplies an int.
32 *
33 * @return a result
34 * @throws E if the supplier fails
35 */
36 short getAsShort() throws E;
37 }
0 /*
1 * Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package org.apache.commons.lang3.function;
18
19 import java.util.function.Supplier;
20
21 /**
22 * Helps use {@link Supplier}.
23 *
24 * @since 3.13.0
25 */
26 public class Suppliers {
27
28 /**
29 * Null-safe call to {@link Supplier#get()}.
30 *
31 * @param <T> the type of results supplied by this supplier.
32 * @param supplier the supplier or null.
33 * @return Result of {@link Supplier#get()} or null.
34 */
35 public static <T> T get(final Supplier<T> supplier) {
36 return supplier == null ? null : supplier.get();
37 }
38
39 }
0 /*
1 * Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package org.apache.commons.lang3.function;
18
19 import java.util.function.BiFunction;
20
21 /**
22 * A function that accepts two arguments and produces a boolean result. This is the {@code boolean}-producing primitive
23 * specialization for {@link BiFunction}.
24 *
25 * @param <T> the type of the first argument to the function.
26 * @param <U> the type of the second argument to the function.
27 *
28 * @see BiFunction
29 * @since 3.12.0
30 */
31 @FunctionalInterface
32 public interface ToBooleanBiFunction<T, U> {
33
34 /**
35 * Applies this function to the given arguments.
36 *
37 * @param t the first function argument.
38 * @param u the second function argument.
39 * @return the function result.
40 */
41 boolean applyAsBoolean(T t, U u);
42 }
0 /*
1 * Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package org.apache.commons.lang3.function;
18
19 import java.util.Objects;
20 import java.util.function.Consumer;
21
22 /**
23 * Represents an operation that accepts three input arguments and returns no result. This is the three-arity
24 * specialization of {@link Consumer}. Unlike most other functional interfaces, {@code TriConsumer} is expected to
25 * operate via side-effects.
26 *
27 * <p>
28 * This is a {@link FunctionalInterface} whose functional method is {@link #accept(Object, Object, Object)}.
29 * </p>
30 * <p>
31 * Provenance: Apache Log4j 2.7
32 * </p>
33 *
34 * @param <T> type of the first argument
35 * @param <U> type of the second argument
36 * @param <V> type of the third argument
37 * @since 3.13.0
38 */
39 @FunctionalInterface
40 public interface TriConsumer<T, U, V> {
41
42 /**
43 * Performs the operation given the specified arguments.
44 *
45 * @param k the first input argument
46 * @param v the second input argument
47 * @param s the third input argument
48 */
49 void accept(T k, U v, V s);
50
51 /**
52 * Returns a composed {@code TriConsumer} that performs, in sequence, this operation followed by the {@code after}
53 * operation. If performing either operation throws an exception, it is relayed to the caller of the composed
54 * operation. If performing this operation throws an exception, the {@code after} operation will not be performed.
55 *
56 * @param after the operation to perform after this operation.
57 * @return a composed {@code TriConsumer} that performs in sequence this operation followed by the {@code after}
58 * operation.
59 * @throws NullPointerException if {@code after} is null.
60 */
61 default TriConsumer<T, U, V> andThen(final TriConsumer<? super T, ? super U, ? super V> after) {
62 Objects.requireNonNull(after);
63
64 return (t, u, v) -> {
65 accept(t, u, v);
66 after.accept(t, u, v);
67 };
68 }
69
70 }
0 /*
1 * Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package org.apache.commons.lang3.function;
17
18 import java.util.Objects;
19 import java.util.function.Function;
20
21 /**
22 * Represents a function that accepts three arguments and produces a result. This is the three-arity specialization of
23 * {@link Function}.
24 *
25 * <p>
26 * This is a <a href="package-summary.html">functional interface</a> whose functional method is
27 * {@link #apply(Object, Object, Object)}.
28 * </p>
29 *
30 * @param <T> the type of the first argument to the function
31 * @param <U> the type of the second argument to the function
32 * @param <V> the type of the third argument to the function
33 * @param <R> the type of the result of the function
34 *
35 * @see Function
36 * @since 3.12.0
37 */
38 @FunctionalInterface
39 public interface TriFunction<T, U, V, R> {
40
41 /**
42 * Applies this function to the given arguments.
43 *
44 * @param t the first function argument
45 * @param u the second function argument
46 * @param v the third function argument
47 * @return the function result
48 */
49 R apply(T t, U u, V v);
50
51 /**
52 * Returns a composed function that first applies this function to its input, and then applies the {@code after}
53 * function to the result. If evaluation of either function throws an exception, it is relayed to the caller of the
54 * composed function.
55 *
56 * @param <W> the type of output of the {@code after} function, and of the composed function
57 * @param after the function to apply after this function is applied
58 * @return a composed function that first applies this function and then applies the {@code after} function
59 * @throws NullPointerException if after is null
60 */
61 default <W> TriFunction<T, U, V, W> andThen(final Function<? super R, ? extends W> after) {
62 Objects.requireNonNull(after);
63 return (final T t, final U u, final V v) -> after.apply(apply(t, u, v));
64 }
65 }
103103 /**
104104 * Cached output hashCode (class is immutable).
105105 */
106 private transient int hashCode = 0;
106 private transient int hashCode;
107107 /**
108108 * Cached output toString (class is immutable).
109109 */
110 private transient String toString = null;
110 private transient String toString;
111111 /**
112112 * Cached output toProperString (class is immutable).
113113 */
114 private transient String toProperString = null;
114 private transient String toProperString;
115115
116116 /**
117117 * <p>Constructs a {@code Fraction} instance with the 2 parts
121121 * @param denominator the denominator, for example the seven in 'three sevenths'
122122 */
123123 private Fraction(final int numerator, final int denominator) {
124 super();
125124 this.numerator = numerator;
126125 this.denominator = denominator;
127126 }
178177 if (numerator < 0) {
179178 throw new ArithmeticException("The numerator must not be negative");
180179 }
181 long numeratorValue;
180 final long numeratorValue;
182181 if (whole < 0) {
183182 numeratorValue = whole * (long) denominator - numerator;
184183 } else {
311310 * @throws NumberFormatException if the number format is invalid
312311 */
313312 public static Fraction getFraction(String str) {
314 Validate.notNull(str, "The string must not be null");
313 Validate.notNull(str, "str");
315314 // parse double format
316315 int pos = str.indexOf('.');
317316 if (pos >= 0) {
535534 public Fraction pow(final int power) {
536535 if (power == 1) {
537536 return this;
538 } else if (power == 0) {
537 }
538 if (power == 0) {
539539 return ONE;
540 } else if (power < 0) {
540 }
541 if (power < 0) {
541542 if (power == Integer.MIN_VALUE) { // MIN_VALUE can't be negated.
542543 return this.invert().pow(2).pow(-(power / 2));
543544 }
544545 return this.invert().pow(-power);
545 } else {
546 final Fraction f = this.multiplyBy(this);
547 if (power % 2 == 0) { // if even...
548 return f.pow(power / 2);
549 }
550 return f.pow(power / 2).multiplyBy(this);
551 }
546 }
547 final Fraction f = this.multiplyBy(this);
548 if (power % 2 == 0) { // if even...
549 return f.pow(power / 2);
550 }
551 return f.pow(power / 2).multiplyBy(this);
552552 }
553553
554554 /**
729729 * cannot be represented in an {@code int}.
730730 */
731731 private Fraction addSub(final Fraction fraction, final boolean isAdd) {
732 Validate.notNull(fraction, "The fraction must not be null");
732 Validate.notNull(fraction, "fraction");
733733 // zero is identity for addition.
734734 if (numerator == 0) {
735735 return isAdd ? fraction : fraction.negate();
777777 * {@code Integer.MAX_VALUE}
778778 */
779779 public Fraction multiplyBy(final Fraction fraction) {
780 Validate.notNull(fraction, "The fraction must not be null");
780 Validate.notNull(fraction, "fraction");
781781 if (numerator == 0 || fraction.numerator == 0) {
782782 return ZERO;
783783 }
800800 * {@code Integer.MAX_VALUE}
801801 */
802802 public Fraction divideBy(final Fraction fraction) {
803 Validate.notNull(fraction, "The fraction must not be null");
803 Validate.notNull(fraction, "fraction");
804804 if (fraction.numerator == 0) {
805805 throw new ArithmeticException("The fraction to divide by must not be zero");
806806 }
3636 * @since 3.4 Changed signature from min(double[]) to min(double...)
3737 */
3838 public static double min(final double... array) {
39 Validate.notNull(array, "The Array must not be null");
39 Validate.notNull(array, "array");
4040 Validate.isTrue(array.length != 0, "Array cannot be empty.");
4141
4242 // Finds and returns min
5858 * @since 3.4 Changed signature from min(float[]) to min(float...)
5959 */
6060 public static float min(final float... array) {
61 Validate.notNull(array, "The Array must not be null");
61 Validate.notNull(array, "array");
6262 Validate.isTrue(array.length != 0, "Array cannot be empty.");
6363
6464 // Finds and returns min
9696 public static double min(final double a, final double b) {
9797 if (Double.isNaN(a)) {
9898 return b;
99 } else
99 }
100100 if (Double.isNaN(b)) {
101101 return a;
102 } else {
103 return Math.min(a, b);
104 }
102 }
103 return Math.min(a, b);
105104 }
106105
107106 /**
130129 public static float min(final float a, final float b) {
131130 if (Float.isNaN(a)) {
132131 return b;
133 } else
132 }
134133 if (Float.isNaN(b)) {
135134 return a;
136 } else {
137 return Math.min(a, b);
138 }
135 }
136 return Math.min(a, b);
139137 }
140138
141139 /**
148146 * @since 3.4 Changed signature from max(double[]) to max(double...)
149147 */
150148 public static double max(final double... array) {
151 Validate.notNull(array, "The Array must not be null");
149 Validate.notNull(array, "array");
152150 Validate.isTrue(array.length != 0, "Array cannot be empty.");
153151
154152 // Finds and returns max
170168 * @since 3.4 Changed signature from max(float[]) to max(float...)
171169 */
172170 public static float max(final float... array) {
173 Validate.notNull(array, "The Array must not be null");
171 Validate.notNull(array, "array");
174172 Validate.isTrue(array.length != 0, "Array cannot be empty.");
175173
176174 // Finds and returns max
208206 public static double max(final double a, final double b) {
209207 if (Double.isNaN(a)) {
210208 return b;
211 } else
209 }
212210 if (Double.isNaN(b)) {
213211 return a;
214 } else {
215 return Math.max(a, b);
216 }
212 }
213 return Math.max(a, b);
217214 }
218215
219216 /**
242239 public static float max(final float a, final float b) {
243240 if (Float.isNaN(a)) {
244241 return b;
245 } else
242 }
246243 if (Float.isNaN(b)) {
247244 return a;
248 } else {
249 return Math.max(a, b);
250 }
245 }
246 return Math.max(a, b);
251247 }
252248
253249 }
6969 /** Reusable Float constant for minus one. */
7070 public static final Float FLOAT_MINUS_ONE = Float.valueOf(-1.0f);
7171
72 /**
73 * {@link Integer#MAX_VALUE} as a {@link Long}.
74 *
75 * @since 3.12.0
76 */
77 public static final Long LONG_INT_MAX_VALUE = Long.valueOf(Integer.MAX_VALUE);
78
79 /**
80 * {@link Integer#MIN_VALUE} as a {@link Long}.
81 *
82 * @since 3.12.0
83 */
84 public static final Long LONG_INT_MIN_VALUE = Long.valueOf(Integer.MIN_VALUE);
85
7286
7387 /**
7488 * <p>{@code NumberUtils} instances should NOT be constructed in standard programming.
7892 * to operate.</p>
7993 */
8094 public NumberUtils() {
81 super();
82 }
83
84 //-----------------------------------------------------------------------
95 }
96
8597 /**
8698 * <p>Convert a {@code String} to an {@code int}, returning
8799 * {@code zero} if the conversion fails.</p>
325337 return value == null ? defaultValue : value.doubleValue();
326338 }
327339
328 //-----------------------------------------------------------------------
329340 /**
330341 * <p>Convert a {@code String} to a {@code byte}, returning
331342 * {@code zero} if the conversion fails.</p>
579590 );
580591 }
581592
582 //-----------------------------------------------------------------------
583593 // must handle Long, Float, Integer, Float, Short,
584594 // BigDecimal, BigInteger and Byte
585595 // useful methods:
630640 * <p>If a type specifier is not found, it will check for a decimal point
631641 * and then try successively larger types from {@code Integer} to
632642 * {@code BigInteger} and from {@code Float} to
633 * {@code BigDecimal}.</p>
634 *
643 * {@code BigDecimal}.</p>
644 *
635645 * <p>
636646 * Integral values with a leading {@code 0} will be interpreted as octal; the returned number will
637647 * be Integer, Long or BigDecimal as appropriate.
654664 throw new NumberFormatException("A blank string is not a valid number");
655665 }
656666 // Need to deal with all possible hex prefixes here
657 final String[] hex_prefixes = {"0x", "0X", "-0x", "-0X", "#", "-#"};
667 final String[] hex_prefixes = {"0x", "0X", "#"};
668 final int length = str.length();
669 final int offset = str.charAt(0) == '+' || str.charAt(0) == '-' ? 1 : 0;
658670 int pfxLen = 0;
659671 for (final String pfx : hex_prefixes) {
660 if (str.startsWith(pfx)) {
661 pfxLen += pfx.length();
672 if (str.startsWith(pfx, offset)) {
673 pfxLen += pfx.length() + offset;
662674 break;
663675 }
664676 }
665677 if (pfxLen > 0) { // we have a hex number
666678 char firstSigDigit = 0; // strip leading zeroes
667 for (int i = pfxLen; i < str.length(); i++) {
679 for (int i = pfxLen; i < length; i++) {
668680 firstSigDigit = str.charAt(i);
669 if (firstSigDigit == '0') { // count leading zeroes
670 pfxLen++;
671 } else {
681 if (firstSigDigit != '0') {
672682 break;
673683 }
674 }
675 final int hexDigits = str.length() - pfxLen;
684 pfxLen++;
685 }
686 final int hexDigits = length - pfxLen;
676687 if (hexDigits > 16 || hexDigits == 16 && firstSigDigit > '7') { // too many for Long
677688 return createBigInteger(str);
678689 }
681692 }
682693 return createInteger(str);
683694 }
684 final char lastChar = str.charAt(str.length() - 1);
685 String mant;
686 String dec;
687 String exp;
695 final char lastChar = str.charAt(length - 1);
696 final String mant;
697 final String dec;
698 final String exp;
688699 final int decPos = str.indexOf('.');
689700 final int expPos = str.indexOf('e') + str.indexOf('E') + 1; // assumes both not present
690701 // if both e and E are present, this is caught by the checks on expPos (which prevent IOOBE)
691702 // and the parsing which will detect if e or E appear in a number due to using the wrong offset
692703
704 // Detect if the return type has been requested
705 final boolean requestType = !Character.isDigit(lastChar) && lastChar != '.';
693706 if (decPos > -1) { // there is a decimal point
694707 if (expPos > -1) { // there is an exponent
695 if (expPos < decPos || expPos > str.length()) { // prevents double exponent causing IOOBE
708 if (expPos < decPos || expPos > length) { // prevents double exponent causing IOOBE
696709 throw new NumberFormatException(str + " is not a valid number.");
697710 }
698711 dec = str.substring(decPos + 1, expPos);
699712 } else {
700 dec = str.substring(decPos + 1);
713 // No exponent, but there may be a type character to remove
714 dec = str.substring(decPos + 1, requestType ? length - 1 : length);
701715 }
702716 mant = getMantissa(str, decPos);
703717 } else {
704718 if (expPos > -1) {
705 if (expPos > str.length()) { // prevents double exponent causing IOOBE
719 if (expPos > length) { // prevents double exponent causing IOOBE
706720 throw new NumberFormatException(str + " is not a valid number.");
707721 }
708722 mant = getMantissa(str, expPos);
709723 } else {
710 mant = getMantissa(str);
724 // No decimal, no exponent, but there may be a type character to remove
725 mant = getMantissa(str, requestType ? length - 1 : length);
711726 }
712727 dec = null;
713728 }
714 if (!Character.isDigit(lastChar) && lastChar != '.') {
715 if (expPos > -1 && expPos < str.length() - 1) {
716 exp = str.substring(expPos + 1, str.length() - 1);
729 if (requestType) {
730 if (expPos > -1 && expPos < length - 1) {
731 exp = str.substring(expPos + 1, length - 1);
717732 } else {
718733 exp = null;
719734 }
720735 //Requesting a specific type..
721 final String numeric = str.substring(0, str.length() - 1);
722 final boolean allZeros = isAllZeros(mant) && isAllZeros(exp);
736 final String numeric = str.substring(0, length - 1);
723737 switch (lastChar) {
724738 case 'l' :
725739 case 'L' :
739753 case 'F' :
740754 try {
741755 final Float f = createFloat(str);
742 if (!(f.isInfinite() || f.floatValue() == 0.0F && !allZeros)) {
756 if (!(f.isInfinite() || f.floatValue() == 0.0F && !isZero(mant, dec))) {
743757 //If it's too big for a float or the float value = 0 and the string
744758 //has non-zeros in it, then float does not have the precision we want
745759 return f;
753767 case 'D' :
754768 try {
755769 final Double d = createDouble(str);
756 if (!(d.isInfinite() || d.floatValue() == 0.0D && !allZeros)) {
770 if (!(d.isInfinite() || d.doubleValue() == 0.0D && !isZero(mant, dec))) {
757771 return d;
758772 }
759773 } catch (final NumberFormatException nfe) { // NOPMD
772786 }
773787 //User doesn't have a preference on the return type, so let's start
774788 //small and go from there...
775 if (expPos > -1 && expPos < str.length() - 1) {
776 exp = str.substring(expPos + 1, str.length());
789 if (expPos > -1 && expPos < length - 1) {
790 exp = str.substring(expPos + 1);
777791 } else {
778792 exp = null;
779793 }
793807 }
794808
795809 //Must be a Float, Double, BigDecimal
796 final boolean allZeros = isAllZeros(mant) && isAllZeros(exp);
797810 try {
798811 final Float f = createFloat(str);
799812 final Double d = createDouble(str);
800813 if (!f.isInfinite()
801 && !(f.floatValue() == 0.0F && !allZeros)
814 && !(f.floatValue() == 0.0F && !isZero(mant, dec))
802815 && f.toString().equals(d.toString())) {
803816 return f;
804817 }
805 if (!d.isInfinite() && !(d.doubleValue() == 0.0D && !allZeros)) {
818 if (!d.isInfinite() && !(d.doubleValue() == 0.0D && !isZero(mant, dec))) {
806819 final BigDecimal b = createBigDecimal(str);
807820 if (b.compareTo(BigDecimal.valueOf(d.doubleValue())) == 0) {
808821 return d;
821834 * <p>Returns mantissa of the given number.</p>
822835 *
823836 * @param str the string representation of the number
824 * @return mantissa of the given number
825 */
826 private static String getMantissa(final String str) {
827 return getMantissa(str, str.length());
828 }
829
830 /**
831 * <p>Utility method for {@link #createNumber(java.lang.String)}.</p>
832 *
833 * <p>Returns mantissa of the given number.</p>
834 *
835 * @param str the string representation of the number
836837 * @param stopPos the position of the exponent or decimal point
837838 * @return mantissa of the given number
838839 */
844845 }
845846
846847 /**
847 * <p>Utility method for {@link #createNumber(java.lang.String)}.</p>
848 *
849 * <p>Returns {@code true} if s is {@code null}.</p>
850 *
851 * @param str the String to check
848 * Utility method for {@link #createNumber(java.lang.String)}.
849 *
850 * <p>This will check if the magnitude of the number is zero by checking if there
851 * are only zeros before and after the decimal place.</p>
852 *
853 * <p>Note: It is <strong>assumed</strong> that the input string has been converted
854 * to either a Float or Double with a value of zero when this method is called.
855 * This eliminates invalid input for example {@code ".", ".D", ".e0"}.</p>
856 *
857 * <p>Thus the method only requires checking if both arguments are null, empty or
858 * contain only zeros.</p>
859 *
860 * <p>Given {@code s = mant + "." + dec}:</p>
861 * <ul>
862 * <li>{@code true} if s is {@code "0.0"}
863 * <li>{@code true} if s is {@code "0."}
864 * <li>{@code true} if s is {@code ".0"}
865 * <li>{@code false} otherwise (this assumes {@code "."} is not possible)
866 * </ul>
867 *
868 * @param mant the mantissa decimal digits before the decimal point (sign must be removed; never null)
869 * @param dec the decimal digits after the decimal point (exponent and type specifier removed;
870 * can be null)
871 * @return true if the magnitude is zero
872 */
873 private static boolean isZero(final String mant, final String dec) {
874 return isAllZeros(mant) && isAllZeros(dec);
875 }
876
877 /**
878 * Utility method for {@link #createNumber(java.lang.String)}.
879 *
880 * <p>Returns {@code true} if s is {@code null} or empty.</p>
881 *
882 * @param str the String to check
852883 * @return if it is all zeros or {@code null}
853884 */
854885 private static boolean isAllZeros(final String str) {
860891 return false;
861892 }
862893 }
863 return !str.isEmpty();
864 }
865
866 //-----------------------------------------------------------------------
894 return true;
895 }
896
867897 /**
868898 * <p>Convert a {@code String} to a {@code Float}.</p>
869899 *
947977 if (str == null) {
948978 return null;
949979 }
980 if (str.isEmpty()) {
981 throw new NumberFormatException("An empty string is not a valid number");
982 }
950983 int pos = 0; // offset within string
951984 int radix = 10;
952985 boolean negate = false; // need to negate later?
953 if (str.startsWith("-")) {
986 final char char0 = str.charAt(0);
987 if (char0 == '-') {
954988 negate = true;
989 pos = 1;
990 } else if (char0 == '+') {
955991 pos = 1;
956992 }
957993 if (str.startsWith("0x", pos) || str.startsWith("0X", pos)) { // hex
9961032 *
9971033 * @param array an array, must not be null or empty
9981034 * @return the minimum value in the array
999 * @throws IllegalArgumentException if {@code array} is {@code null}
1035 * @throws NullPointerException if {@code array} is {@code null}
10001036 * @throws IllegalArgumentException if {@code array} is empty
10011037 * @since 3.4 Changed signature from min(long[]) to min(long...)
10021038 */
10201056 *
10211057 * @param array an array, must not be null or empty
10221058 * @return the minimum value in the array
1023 * @throws IllegalArgumentException if {@code array} is {@code null}
1059 * @throws NullPointerException if {@code array} is {@code null}
10241060 * @throws IllegalArgumentException if {@code array} is empty
10251061 * @since 3.4 Changed signature from min(int[]) to min(int...)
10261062 */
10441080 *
10451081 * @param array an array, must not be null or empty
10461082 * @return the minimum value in the array
1047 * @throws IllegalArgumentException if {@code array} is {@code null}
1083 * @throws NullPointerException if {@code array} is {@code null}
10481084 * @throws IllegalArgumentException if {@code array} is empty
10491085 * @since 3.4 Changed signature from min(short[]) to min(short...)
10501086 */
10681104 *
10691105 * @param array an array, must not be null or empty
10701106 * @return the minimum value in the array
1071 * @throws IllegalArgumentException if {@code array} is {@code null}
1107 * @throws NullPointerException if {@code array} is {@code null}
10721108 * @throws IllegalArgumentException if {@code array} is empty
10731109 * @since 3.4 Changed signature from min(byte[]) to min(byte...)
10741110 */
10921128 *
10931129 * @param array an array, must not be null or empty
10941130 * @return the minimum value in the array
1095 * @throws IllegalArgumentException if {@code array} is {@code null}
1131 * @throws NullPointerException if {@code array} is {@code null}
10961132 * @throws IllegalArgumentException if {@code array} is empty
10971133 * @see IEEE754rUtils#min(double[]) IEEE754rUtils for a version of this method that handles NaN differently
10981134 * @since 3.4 Changed signature from min(double[]) to min(double...)
11201156 *
11211157 * @param array an array, must not be null or empty
11221158 * @return the minimum value in the array
1123 * @throws IllegalArgumentException if {@code array} is {@code null}
1159 * @throws NullPointerException if {@code array} is {@code null}
11241160 * @throws IllegalArgumentException if {@code array} is empty
11251161 * @see IEEE754rUtils#min(float[]) IEEE754rUtils for a version of this method that handles NaN differently
11261162 * @since 3.4 Changed signature from min(float[]) to min(float...)
11501186 *
11511187 * @param array an array, must not be null or empty
11521188 * @return the maximum value in the array
1153 * @throws IllegalArgumentException if {@code array} is {@code null}
1189 * @throws NullPointerException if {@code array} is {@code null}
11541190 * @throws IllegalArgumentException if {@code array} is empty
11551191 * @since 3.4 Changed signature from max(long[]) to max(long...)
11561192 */
11741210 *
11751211 * @param array an array, must not be null or empty
11761212 * @return the maximum value in the array
1177 * @throws IllegalArgumentException if {@code array} is {@code null}
1213 * @throws NullPointerException if {@code array} is {@code null}
11781214 * @throws IllegalArgumentException if {@code array} is empty
11791215 * @since 3.4 Changed signature from max(int[]) to max(int...)
11801216 */
11981234 *
11991235 * @param array an array, must not be null or empty
12001236 * @return the maximum value in the array
1201 * @throws IllegalArgumentException if {@code array} is {@code null}
1237 * @throws NullPointerException if {@code array} is {@code null}
12021238 * @throws IllegalArgumentException if {@code array} is empty
12031239 * @since 3.4 Changed signature from max(short[]) to max(short...)
12041240 */
12221258 *
12231259 * @param array an array, must not be null or empty
12241260 * @return the maximum value in the array
1225 * @throws IllegalArgumentException if {@code array} is {@code null}
1261 * @throws NullPointerException if {@code array} is {@code null}
12261262 * @throws IllegalArgumentException if {@code array} is empty
12271263 * @since 3.4 Changed signature from max(byte[]) to max(byte...)
12281264 */
12461282 *
12471283 * @param array an array, must not be null or empty
12481284 * @return the maximum value in the array
1249 * @throws IllegalArgumentException if {@code array} is {@code null}
1285 * @throws NullPointerException if {@code array} is {@code null}
12501286 * @throws IllegalArgumentException if {@code array} is empty
12511287 * @see IEEE754rUtils#max(double[]) IEEE754rUtils for a version of this method that handles NaN differently
12521288 * @since 3.4 Changed signature from max(double[]) to max(double...)
12741310 *
12751311 * @param array an array, must not be null or empty
12761312 * @return the maximum value in the array
1277 * @throws IllegalArgumentException if {@code array} is {@code null}
1313 * @throws NullPointerException if {@code array} is {@code null}
12781314 * @throws IllegalArgumentException if {@code array} is empty
12791315 * @see IEEE754rUtils#max(float[]) IEEE754rUtils for a version of this method that handles NaN differently
12801316 * @since 3.4 Changed signature from max(float[]) to max(float...)
13011337 * Checks if the specified array is neither null nor empty.
13021338 *
13031339 * @param array the array to check
1304 * @throws IllegalArgumentException if {@code array} is either {@code null} or empty
1340 * @throws IllegalArgumentException if {@code array} is empty
1341 * @throws NullPointerException if {@code array} is {@code null}
13051342 */
13061343 private static void validateArray(final Object array) {
1307 Validate.notNull(array, "The Array must not be null");
1344 Validate.notNull(array, "array");
13081345 Validate.isTrue(Array.getLength(array) != 0, "Array cannot be empty.");
13091346 }
13101347
13111348 // 3 param min
1312 //-----------------------------------------------------------------------
13131349 /**
13141350 * <p>Gets the minimum of three {@code long} values.</p>
13151351 *
14151451 }
14161452
14171453 // 3 param max
1418 //-----------------------------------------------------------------------
14191454 /**
14201455 * <p>Gets the maximum of three {@code long} values.</p>
14211456 *
15201555 return Math.max(Math.max(a, b), c);
15211556 }
15221557
1523 //-----------------------------------------------------------------------
15241558 /**
15251559 * <p>Checks whether the {@code String} contains only
15261560 * digit characters.</p>
16141648 }
16151649 }
16161650 return true;
1617 } else if (Character.isDigit(chars[start + 1])) {
1618 // leading 0, but not hex, must be octal
1619 int i = start + 1;
1620 for (; i < chars.length; i++) {
1621 if (chars[i] < '0' || chars[i] > '7') {
1622 return false;
1651 }
1652 if (Character.isDigit(chars[start + 1])) {
1653 // leading 0, but not hex, must be octal
1654 int i = start + 1;
1655 for (; i < chars.length; i++) {
1656 if (chars[i] < '0' || chars[i] > '7') {
1657 return false;
1658 }
16231659 }
1660 return true;
16241661 }
1625 return true;
1626 }
16271662 }
16281663 sz--; // don't want to loop to the last char, check it afterwords
16291664 // for type qualifiers
4444 * Constructs a new MutableBoolean with the default value of false.
4545 */
4646 public MutableBoolean() {
47 super();
4847 }
4948
5049 /**
5352 * @param value the initial value to store
5453 */
5554 public MutableBoolean(final boolean value) {
56 super();
5755 this.value = value;
5856 }
5957
6462 * @throws NullPointerException if the object is null
6563 */
6664 public MutableBoolean(final Boolean value) {
67 super();
6865 this.value = value.booleanValue();
6966 }
7067
71 //-----------------------------------------------------------------------
7268 /**
7369 * Gets the value as a Boolean instance.
7470 *
117113 this.value = value.booleanValue();
118114 }
119115
120 //-----------------------------------------------------------------------
121116 /**
122117 * Checks if the current value is {@code true}.
123118 *
138133 return !value;
139134 }
140135
141 //-----------------------------------------------------------------------
142136 /**
143137 * Returns the value of this MutableBoolean as a boolean.
144138 *
148142 return value;
149143 }
150144
151 //-----------------------------------------------------------------------
152145 /**
153146 * Gets this mutable as an instance of Boolean.
154147 *
159152 return Boolean.valueOf(booleanValue());
160153 }
161154
162 //-----------------------------------------------------------------------
163155 /**
164156 * Compares this object to the specified object. The result is {@code true} if and only if the argument is
165157 * not {@code null} and is an {@code MutableBoolean} object that contains the same
186178 return value ? Boolean.TRUE.hashCode() : Boolean.FALSE.hashCode();
187179 }
188180
189 //-----------------------------------------------------------------------
190181 /**
191182 * Compares this mutable to another in ascending order.
192183 *
199190 return BooleanUtils.compare(this.value, other.value);
200191 }
201192
202 //-----------------------------------------------------------------------
203193 /**
204194 * Returns the String value of this mutable.
205195 *
4141 * Constructs a new MutableByte with the default value of zero.
4242 */
4343 public MutableByte() {
44 super();
4544 }
4645
4746 /**
5049 * @param value the initial value to store
5150 */
5251 public MutableByte(final byte value) {
53 super();
5452 this.value = value;
5553 }
5654
6159 * @throws NullPointerException if the object is null
6260 */
6361 public MutableByte(final Number value) {
64 super();
6562 this.value = value.byteValue();
6663 }
6764
7370 * @since 2.5
7471 */
7572 public MutableByte(final String value) {
76 super();
7773 this.value = Byte.parseByte(value);
7874 }
7975
80 //-----------------------------------------------------------------------
8176 /**
8277 * Gets the value as a Byte instance.
8378 *
108103 this.value = value.byteValue();
109104 }
110105
111 //-----------------------------------------------------------------------
112106 /**
113107 * Increments the value.
114108 *
177171 return value;
178172 }
179173
180 //-----------------------------------------------------------------------
181174 /**
182175 * Adds a value to the value of this instance.
183176 *
276269 return last;
277270 }
278271
279 //-----------------------------------------------------------------------
280272 // shortValue relies on Number implementation
281273 /**
282274 * Returns the value of this MutableByte as a byte.
328320 return value;
329321 }
330322
331 //-----------------------------------------------------------------------
332323 /**
333324 * Gets this mutable as an instance of Byte.
334325 *
338329 return Byte.valueOf(byteValue());
339330 }
340331
341 //-----------------------------------------------------------------------
342332 /**
343333 * Compares this object to the specified object. The result is {@code true} if and only if the argument is
344334 * not {@code null} and is a {@code MutableByte} object that contains the same {@code byte} value
365355 return value;
366356 }
367357
368 //-----------------------------------------------------------------------
369358 /**
370359 * Compares this mutable to another in ascending order.
371360 *
377366 return NumberUtils.compare(this.value, other.value);
378367 }
379368
380 //-----------------------------------------------------------------------
381369 /**
382370 * Returns the String value of this mutable.
383371 *
3939 * Constructs a new MutableDouble with the default value of zero.
4040 */
4141 public MutableDouble() {
42 super();
4342 }
4443
4544 /**
4847 * @param value the initial value to store
4948 */
5049 public MutableDouble(final double value) {
51 super();
5250 this.value = value;
5351 }
5452
5957 * @throws NullPointerException if the object is null
6058 */
6159 public MutableDouble(final Number value) {
62 super();
6360 this.value = value.doubleValue();
6461 }
6562
7168 * @since 2.5
7269 */
7370 public MutableDouble(final String value) {
74 super();
7571 this.value = Double.parseDouble(value);
7672 }
7773
78 //-----------------------------------------------------------------------
7974 /**
8075 * Gets the value as a Double instance.
8176 *
106101 this.value = value.doubleValue();
107102 }
108103
109 //-----------------------------------------------------------------------
110104 /**
111105 * Checks whether the double value is the special NaN value.
112106 *
125119 return Double.isInfinite(value);
126120 }
127121
128 //-----------------------------------------------------------------------
129122 /**
130123 * Increments the value.
131124 *
194187 return value;
195188 }
196189
197 //-----------------------------------------------------------------------
198190 /**
199191 * Adds a value to the value of this instance.
200192 *
293285 return last;
294286 }
295287
296 //-----------------------------------------------------------------------
297288 // shortValue and byteValue rely on Number implementation
298289 /**
299290 * Returns the value of this MutableDouble as an int.
335326 return value;
336327 }
337328
338 //-----------------------------------------------------------------------
339329 /**
340330 * Gets this mutable as an instance of Double.
341331 *
345335 return Double.valueOf(doubleValue());
346336 }
347337
348 //-----------------------------------------------------------------------
349338 /**
350339 * Compares this object against the specified object. The result is {@code true} if and only if the argument
351340 * is not {@code null} and is a {@code Double} object that represents a double that has the identical
392381 return (int) (bits ^ bits >>> 32);
393382 }
394383
395 //-----------------------------------------------------------------------
396384 /**
397385 * Compares this mutable to another in ascending order.
398386 *
404392 return Double.compare(this.value, other.value);
405393 }
406394
407 //-----------------------------------------------------------------------
408395 /**
409396 * Returns the String value of this mutable.
410397 *
3939 * Constructs a new MutableFloat with the default value of zero.
4040 */
4141 public MutableFloat() {
42 super();
4342 }
4443
4544 /**
4847 * @param value the initial value to store
4948 */
5049 public MutableFloat(final float value) {
51 super();
5250 this.value = value;
5351 }
5452
5957 * @throws NullPointerException if the object is null
6058 */
6159 public MutableFloat(final Number value) {
62 super();
6360 this.value = value.floatValue();
6461 }
6562
7168 * @since 2.5
7269 */
7370 public MutableFloat(final String value) {
74 super();
7571 this.value = Float.parseFloat(value);
7672 }
7773
78 //-----------------------------------------------------------------------
7974 /**
8075 * Gets the value as a Float instance.
8176 *
106101 this.value = value.floatValue();
107102 }
108103
109 //-----------------------------------------------------------------------
110104 /**
111105 * Checks whether the float value is the special NaN value.
112106 *
125119 return Float.isInfinite(value);
126120 }
127121
128 //-----------------------------------------------------------------------
129122 /**
130123 * Increments the value.
131124 *
194187 return value;
195188 }
196189
197 //-----------------------------------------------------------------------
198190 /**
199191 * Adds a value to the value of this instance.
200192 *
293285 return last;
294286 }
295287
296 //-----------------------------------------------------------------------
297288 // shortValue and byteValue rely on Number implementation
298289 /**
299290 * Returns the value of this MutableFloat as an int.
335326 return value;
336327 }
337328
338 //-----------------------------------------------------------------------
339329 /**
340330 * Gets this mutable as an instance of Float.
341331 *
345335 return Float.valueOf(floatValue());
346336 }
347337
348 //-----------------------------------------------------------------------
349338 /**
350339 * Compares this object against some other object. The result is {@code true} if and only if the argument is
351340 * not {@code null} and is a {@code Float} object that represents a {@code float} that has the
393382 return Float.floatToIntBits(value);
394383 }
395384
396 //-----------------------------------------------------------------------
397385 /**
398386 * Compares this mutable to another in ascending order.
399387 *
405393 return Float.compare(this.value, other.value);
406394 }
407395
408 //-----------------------------------------------------------------------
409396 /**
410397 * Returns the String value of this mutable.
411398 *
4141 * Constructs a new MutableInt with the default value of zero.
4242 */
4343 public MutableInt() {
44 super();
4544 }
4645
4746 /**
5049 * @param value the initial value to store
5150 */
5251 public MutableInt(final int value) {
53 super();
5452 this.value = value;
5553 }
5654
6159 * @throws NullPointerException if the object is null
6260 */
6361 public MutableInt(final Number value) {
64 super();
6562 this.value = value.intValue();
6663 }
6764
7370 * @since 2.5
7471 */
7572 public MutableInt(final String value) {
76 super();
7773 this.value = Integer.parseInt(value);
7874 }
7975
80 //-----------------------------------------------------------------------
8176 /**
8277 * Gets the value as a Integer instance.
8378 *
108103 this.value = value.intValue();
109104 }
110105
111 //-----------------------------------------------------------------------
112106 /**
113107 * Increments the value.
114108 *
177171 return value;
178172 }
179173
180 //-----------------------------------------------------------------------
181174 /**
182175 * Adds a value to the value of this instance.
183176 *
276269 return last;
277270 }
278271
279 //-----------------------------------------------------------------------
280272 // shortValue and byteValue rely on Number implementation
281273 /**
282274 * Returns the value of this MutableInt as an int.
318310 return value;
319311 }
320312
321 //-----------------------------------------------------------------------
322313 /**
323314 * Gets this mutable as an instance of Integer.
324315 *
328319 return Integer.valueOf(intValue());
329320 }
330321
331 //-----------------------------------------------------------------------
332322 /**
333323 * Compares this object to the specified object. The result is {@code true} if and only if the argument is
334324 * not {@code null} and is a {@code MutableInt} object that contains the same {@code int} value
355345 return value;
356346 }
357347
358 //-----------------------------------------------------------------------
359348 /**
360349 * Compares this mutable to another in ascending order.
361350 *
367356 return NumberUtils.compare(this.value, other.value);
368357 }
369358
370 //-----------------------------------------------------------------------
371359 /**
372360 * Returns the String value of this mutable.
373361 *
4141 * Constructs a new MutableLong with the default value of zero.
4242 */
4343 public MutableLong() {
44 super();
4544 }
4645
4746 /**
5049 * @param value the initial value to store
5150 */
5251 public MutableLong(final long value) {
53 super();
5452 this.value = value;
5553 }
5654
6159 * @throws NullPointerException if the object is null
6260 */
6361 public MutableLong(final Number value) {
64 super();
6562 this.value = value.longValue();
6663 }
6764
7370 * @since 2.5
7471 */
7572 public MutableLong(final String value) {
76 super();
7773 this.value = Long.parseLong(value);
7874 }
7975
80 //-----------------------------------------------------------------------
8176 /**
8277 * Gets the value as a Long instance.
8378 *
108103 this.value = value.longValue();
109104 }
110105
111 //-----------------------------------------------------------------------
112106 /**
113107 * Increments the value.
114108 *
177171 return value;
178172 }
179173
180 //-----------------------------------------------------------------------
181174 /**
182175 * Adds a value to the value of this instance.
183176 *
276269 return last;
277270 }
278271
279 //-----------------------------------------------------------------------
280272 // shortValue and byteValue rely on Number implementation
281273 /**
282274 * Returns the value of this MutableLong as an int.
318310 return value;
319311 }
320312
321 //-----------------------------------------------------------------------
322313 /**
323314 * Gets this mutable as an instance of Long.
324315 *
328319 return Long.valueOf(longValue());
329320 }
330321
331 //-----------------------------------------------------------------------
332322 /**
333323 * Compares this object to the specified object. The result is {@code true} if and only if the argument
334324 * is not {@code null} and is a {@code MutableLong} object that contains the same {@code long}
355345 return (int) (value ^ (value >>> 32));
356346 }
357347
358 //-----------------------------------------------------------------------
359348 /**
360349 * Compares this mutable to another in ascending order.
361350 *
367356 return NumberUtils.compare(this.value, other.value);
368357 }
369358
370 //-----------------------------------------------------------------------
371359 /**
372360 * Returns the String value of this mutable.
373361 *
4040 * Constructs a new MutableObject with the default value of {@code null}.
4141 */
4242 public MutableObject() {
43 super();
4443 }
4544
4645 /**
4948 * @param value the initial value to store
5049 */
5150 public MutableObject(final T value) {
52 super();
5351 this.value = value;
5452 }
5553
56 //-----------------------------------------------------------------------
5754 /**
5855 * Gets the value.
5956 *
7471 this.value = value;
7572 }
7673
77 //-----------------------------------------------------------------------
7874 /**
7975 * <p>
8076 * Compares this object against the specified object. The result is {@code true} if and only if the argument
112108 return value == null ? 0 : value.hashCode();
113109 }
114110
115 //-----------------------------------------------------------------------
116111 /**
117112 * Returns the String value of this mutable.
118113 *
4141 * Constructs a new MutableShort with the default value of zero.
4242 */
4343 public MutableShort() {
44 super();
4544 }
4645
4746 /**
5049 * @param value the initial value to store
5150 */
5251 public MutableShort(final short value) {
53 super();
5452 this.value = value;
5553 }
5654
6159 * @throws NullPointerException if the object is null
6260 */
6361 public MutableShort(final Number value) {
64 super();
6562 this.value = value.shortValue();
6663 }
6764
7370 * @since 2.5
7471 */
7572 public MutableShort(final String value) {
76 super();
7773 this.value = Short.parseShort(value);
7874 }
7975
80 //-----------------------------------------------------------------------
8176 /**
8277 * Gets the value as a Short instance.
8378 *
108103 this.value = value.shortValue();
109104 }
110105
111 //-----------------------------------------------------------------------
112106 /**
113107 * Increments the value.
114108 *
177171 return value;
178172 }
179173
180 //-----------------------------------------------------------------------
181174 /**
182175 * Adds a value to the value of this instance.
183176 *
276269 return last;
277270 }
278271
279 //-----------------------------------------------------------------------
280272 // byteValue relies on Number implementation
281273 /**
282274 * Returns the value of this MutableShort as a short.
328320 return value;
329321 }
330322
331 //-----------------------------------------------------------------------
332323 /**
333324 * Gets this mutable as an instance of Short.
334325 *
338329 return Short.valueOf(shortValue());
339330 }
340331
341 //-----------------------------------------------------------------------
342332 /**
343333 * Compares this object to the specified object. The result is {@code true} if and only if the argument
344334 * is not {@code null} and is a {@code MutableShort} object that contains the same {@code short}
365355 return value;
366356 }
367357
368 //-----------------------------------------------------------------------
369358 /**
370359 * Compares this mutable to another in ascending order.
371360 *
377366 return NumberUtils.compare(this.value, other.value);
378367 }
379368
380 //-----------------------------------------------------------------------
381369 /**
382370 * Returns the String value of this mutable.
383371 *
5454 * instance to operate.</p>
5555 */
5656 public ConstructorUtils() {
57 super();
5857 }
5958
6059 /**
181180 return ctor.newInstance(args);
182181 }
183182
184 //-----------------------------------------------------------------------
185183 /**
186184 * <p>Finds a constructor given a class and signature, checking accessibility.</p>
187185 *
198196 */
199197 public static <T> Constructor<T> getAccessibleConstructor(final Class<T> cls,
200198 final Class<?>... parameterTypes) {
201 Validate.notNull(cls, "class cannot be null");
199 Validate.notNull(cls, "cls");
202200 try {
203201 return getAccessibleConstructor(cls.getConstructor(parameterTypes));
204202 } catch (final NoSuchMethodException e) {
218216 * @throws NullPointerException if {@code ctor} is {@code null}
219217 */
220218 public static <T> Constructor<T> getAccessibleConstructor(final Constructor<T> ctor) {
221 Validate.notNull(ctor, "constructor cannot be null");
219 Validate.notNull(ctor, "ctor");
222220 return MemberUtils.isAccessible(ctor)
223221 && isAccessible(ctor.getDeclaringClass()) ? ctor : null;
224222 }
243241 */
244242 public static <T> Constructor<T> getMatchingAccessibleConstructor(final Class<T> cls,
245243 final Class<?>... parameterTypes) {
246 Validate.notNull(cls, "class cannot be null");
244 Validate.notNull(cls, "cls");
247245 // see if we can find the constructor directly
248246 // most of the time this works and it's much faster
249247 try {
270268 if (result == null || MemberUtils.compareConstructorFit(ctor, result, parameterTypes) < 0) {
271269 // temporary variable for annotation, see comment above (1)
272270 @SuppressWarnings("unchecked")
273 final
274 Constructor<T> constructor = (Constructor<T>) ctor;
271 final Constructor<T> constructor = (Constructor<T>) ctor;
275272 result = constructor;
276273 }
277274 }
4747 * </p>
4848 */
4949 public FieldUtils() {
50 super();
5150 }
5251
5352 /**
8584 * in the inheritance hierarchy
8685 */
8786 public static Field getField(final Class<?> cls, final String fieldName, final boolean forceAccess) {
88 Validate.notNull(cls, "The class must not be null");
87 Validate.notNull(cls, "cls");
8988 Validate.isTrue(StringUtils.isNotBlank(fieldName), "The field name must not be blank/empty");
9089 // FIXME is this workaround still needed? lang requires Java 6
9190 // Sun Java 1.3 has a bugged implementation of getField hence we write the
108107 // getDeclaredField checks for non-public scopes as well
109108 // and it returns accurate results
110109 if (!Modifier.isPublic(field.getModifiers())) {
111 if (forceAccess) {
112 field.setAccessible(true);
113 } else {
110 if (!forceAccess) {
114111 continue;
115112 }
113 field.setAccessible(true);
116114 }
117115 return field;
118116 } catch (final NoSuchFieldException ex) { // NOPMD
168166 * if the class is {@code null}, or the field name is blank or empty
169167 */
170168 public static Field getDeclaredField(final Class<?> cls, final String fieldName, final boolean forceAccess) {
171 Validate.notNull(cls, "The class must not be null");
169 Validate.notNull(cls, "cls");
172170 Validate.isTrue(StringUtils.isNotBlank(fieldName), "The field name must not be blank/empty");
173171 try {
174172 // only consider the specified class by using getDeclaredField()
175173 final Field field = cls.getDeclaredField(fieldName);
176174 if (!MemberUtils.isAccessible(field)) {
177 if (forceAccess) {
178 field.setAccessible(true);
179 } else {
175 if (!forceAccess) {
180176 return null;
181177 }
178 field.setAccessible(true);
182179 }
183180 return field;
184181 } catch (final NoSuchFieldException e) { // NOPMD
213210 * @since 3.2
214211 */
215212 public static List<Field> getAllFieldsList(final Class<?> cls) {
216 Validate.notNull(cls, "The class must not be null");
213 Validate.notNull(cls, "cls");
217214 final List<Field> allFields = new ArrayList<>();
218215 Class<?> currentClass = cls;
219216 while (currentClass != null) {
252249 * @since 3.4
253250 */
254251 public static List<Field> getFieldsListWithAnnotation(final Class<?> cls, final Class<? extends Annotation> annotationCls) {
255 Validate.notNull(annotationCls, "The annotation class must not be null");
252 Validate.notNull(annotationCls, "annotationCls");
256253 final List<Field> allFields = getAllFieldsList(cls);
257254 final List<Field> annotatedFields = new ArrayList<>();
258255 for (final Field field : allFields) {
293290 * if the field is not made accessible
294291 */
295292 public static Object readStaticField(final Field field, final boolean forceAccess) throws IllegalAccessException {
296 Validate.notNull(field, "The field must not be null");
293 Validate.notNull(field, "field");
297294 Validate.isTrue(Modifier.isStatic(field.getModifiers()), "The field '%s' is not static", field.getName());
298295 return readField(field, (Object) null, forceAccess);
299296 }
419416 * if the field is not made accessible
420417 */
421418 public static Object readField(final Field field, final Object target, final boolean forceAccess) throws IllegalAccessException {
422 Validate.notNull(field, "The field must not be null");
419 Validate.notNull(field, "field");
423420 if (forceAccess && !field.isAccessible()) {
424421 field.setAccessible(true);
425422 } else {
463460 * if the named field is not made accessible
464461 */
465462 public static Object readField(final Object target, final String fieldName, final boolean forceAccess) throws IllegalAccessException {
466 Validate.notNull(target, "target object must not be null");
463 Validate.notNull(target, "target");
467464 final Class<?> cls = target.getClass();
468465 final Field field = getField(cls, fieldName, forceAccess);
469466 Validate.isTrue(field != null, "Cannot locate field %s on %s", fieldName, cls);
506503 * if the field is not made accessible
507504 */
508505 public static Object readDeclaredField(final Object target, final String fieldName, final boolean forceAccess) throws IllegalAccessException {
509 Validate.notNull(target, "target object must not be null");
506 Validate.notNull(target, "target");
510507 final Class<?> cls = target.getClass();
511508 final Field field = getDeclaredField(cls, fieldName, forceAccess);
512509 Validate.isTrue(field != null, "Cannot locate declared field %s.%s", cls, fieldName);
547544 * if the field is not made accessible or is {@code final}
548545 */
549546 public static void writeStaticField(final Field field, final Object value, final boolean forceAccess) throws IllegalAccessException {
550 Validate.notNull(field, "The field must not be null");
547 Validate.notNull(field, "field");
551548 Validate.isTrue(Modifier.isStatic(field.getModifiers()), "The field %s.%s is not static", field.getDeclaringClass().getName(),
552549 field.getName());
553550 writeField(field, (Object) null, value, forceAccess);
681678 */
682679 public static void writeField(final Field field, final Object target, final Object value, final boolean forceAccess)
683680 throws IllegalAccessException {
684 Validate.notNull(field, "The field must not be null");
681 Validate.notNull(field, "field");
685682 if (forceAccess && !field.isAccessible()) {
686683 field.setAccessible(true);
687684 } else {
721718 */
722719 @Deprecated
723720 public static void removeFinalModifier(final Field field, final boolean forceAccess) {
724 Validate.notNull(field, "The field must not be null");
721 Validate.notNull(field, "field");
725722
726723 try {
727724 if (Modifier.isFinal(field.getModifiers())) {
790787 */
791788 public static void writeField(final Object target, final String fieldName, final Object value, final boolean forceAccess)
792789 throws IllegalAccessException {
793 Validate.notNull(target, "target object must not be null");
790 Validate.notNull(target, "target");
794791 final Class<?> cls = target.getClass();
795792 final Field field = getField(cls, fieldName, forceAccess);
796793 Validate.isTrue(field != null, "Cannot locate declared field %s.%s", cls.getName(), fieldName);
838835 */
839836 public static void writeDeclaredField(final Object target, final String fieldName, final Object value, final boolean forceAccess)
840837 throws IllegalAccessException {
841 Validate.notNull(target, "target object must not be null");
838 Validate.notNull(target, "target");
842839 final Class<?> cls = target.getClass();
843840 final Field field = getDeclaredField(cls, fieldName, forceAccess);
844841 Validate.isTrue(field != null, "Cannot locate declared field %s.%s", cls.getName(), fieldName);
3333 * instance to operate.</p>
3434 */
3535 public InheritanceUtils() {
36 super();
3736 }
3837
3938 /**
1515 */
1616 package org.apache.commons.lang3.reflect;
1717
18 import static java.util.stream.Collectors.toList;
19
1820 import java.lang.annotation.Annotation;
1921 import java.lang.reflect.Array;
2022 import java.lang.reflect.InvocationTargetException;
2931 import java.util.LinkedHashSet;
3032 import java.util.List;
3133 import java.util.Map;
32 import java.util.Objects;
3334 import java.util.Set;
35 import java.util.TreeMap;
36 import java.util.stream.Collectors;
37 import java.util.stream.Stream;
3438
3539 import org.apache.commons.lang3.ArrayUtils;
3640 import org.apache.commons.lang3.ClassUtils;
7074 * instance to operate.</p>
7175 */
7276 public MethodUtils() {
73 super();
7477 }
7578
7679 /**
739742 */
740743 public static Method getMatchingMethod(final Class<?> cls, final String methodName,
741744 final Class<?>... parameterTypes) {
742 Validate.notNull(cls, "Null class not allowed.");
743 Validate.notEmpty(methodName, "Null or blank methodName not allowed.");
744
745 // Address methods in superclasses
746 Method[] methodArray = cls.getDeclaredMethods();
747 final List<Class<?>> superclassList = ClassUtils.getAllSuperclasses(cls);
748 for (final Class<?> klass : superclassList) {
749 methodArray = ArrayUtils.addAll(methodArray, klass.getDeclaredMethods());
750 }
751
752 Method inexactMatch = null;
753 for (final Method method : methodArray) {
754 if (methodName.equals(method.getName()) &&
755 Objects.deepEquals(parameterTypes, method.getParameterTypes())) {
745 Validate.notNull(cls, "cls");
746 Validate.notEmpty(methodName, "methodName");
747
748 final List<Method> methods = Stream.of(cls.getDeclaredMethods())
749 .filter(method -> method.getName().equals(methodName))
750 .collect(toList());
751
752 ClassUtils.getAllSuperclasses(cls).stream()
753 .map(Class::getDeclaredMethods)
754 .flatMap(Stream::of)
755 .filter(method -> method.getName().equals(methodName))
756 .forEach(methods::add);
757
758 for (final Method method : methods) {
759 if (Arrays.deepEquals(method.getParameterTypes(), parameterTypes)) {
756760 return method;
757 } else if (methodName.equals(method.getName()) &&
758 ClassUtils.isAssignable(parameterTypes, method.getParameterTypes(), true)) {
759 if ((inexactMatch == null) || (distance(parameterTypes, method.getParameterTypes())
760 < distance(parameterTypes, inexactMatch.getParameterTypes()))) {
761 inexactMatch = method;
762 }
763 }
764
765 }
766 return inexactMatch;
761 }
762 }
763
764 final TreeMap<Integer, List<Method>> candidates = new TreeMap<>();
765
766 methods.stream()
767 .filter(method -> ClassUtils.isAssignable(parameterTypes, method.getParameterTypes(), true))
768 .forEach(method -> {
769 final int distance = distance(parameterTypes, method.getParameterTypes());
770 final List<Method> candidatesAtDistance = candidates.computeIfAbsent(distance, k -> new ArrayList<>());
771 candidatesAtDistance.add(method);
772 });
773
774 if (candidates.isEmpty()) {
775 return null;
776 }
777
778 final List<Method> bestCandidates = candidates.values().iterator().next();
779 if (bestCandidates.size() == 1) {
780 return bestCandidates.get(0);
781 }
782
783 throw new IllegalStateException(
784 String.format("Found multiple candidates for method %s on class %s : %s",
785 methodName + Stream.of(parameterTypes).map(String::valueOf).collect(Collectors.joining(",", "(", ")")),
786 cls.getName(),
787 bestCandidates.stream().map(Method::toString).collect(Collectors.joining(",", "[", "]")))
788 );
767789 }
768790
769791 /**
770792 * <p>Returns the aggregate number of inheritance hops between assignable argument class types. Returns -1
771793 * if the arguments aren't assignable. Fills a specific purpose for getMatchingMethod and is not generalized.</p>
772 * @param classArray
773 * @param toClassArray
794 * @param fromClassArray the Class array to calculate the distance from.
795 * @param toClassArray the Class array to calculate the distance to.
774796 * @return the aggregate number of inheritance hops between assignable argument class types.
775797 */
776 private static int distance(final Class<?>[] classArray, final Class<?>[] toClassArray) {
798 private static int distance(final Class<?>[] fromClassArray, final Class<?>[] toClassArray) {
777799 int answer = 0;
778800
779 if (!ClassUtils.isAssignable(classArray, toClassArray, true)) {
801 if (!ClassUtils.isAssignable(fromClassArray, toClassArray, true)) {
780802 return -1;
781803 }
782 for (int offset = 0; offset < classArray.length; offset++) {
804 for (int offset = 0; offset < fromClassArray.length; offset++) {
783805 // Note InheritanceUtils.distance() uses different scoring system.
784 if (classArray[offset].equals(toClassArray[offset])) {
806 final Class<?> aClass = fromClassArray[offset];
807 final Class<?> toClass = toClassArray[offset];
808 if (aClass == null || aClass.equals(toClass)) {
785809 continue;
786 } else if (ClassUtils.isAssignable(classArray[offset], toClassArray[offset], true)
787 && !ClassUtils.isAssignable(classArray[offset], toClassArray[offset], false)) {
810 }
811 if (ClassUtils.isAssignable(aClass, toClass, true)
812 && !ClassUtils.isAssignable(aClass, toClass, false)) {
788813 answer++;
789814 } else {
790815 answer = answer + 2;
907932 final Class<? extends Annotation> annotationCls,
908933 final boolean searchSupers, final boolean ignoreAccess) {
909934
910 Validate.notNull(cls, "The class must not be null");
911 Validate.notNull(annotationCls, "The annotation class must not be null");
935 Validate.notNull(cls, "cls");
936 Validate.notNull(annotationCls, "annotationCls");
912937 final List<Class<?>> classes = (searchSupers ? getAllSuperclassesAndInterfaces(cls)
913938 : new ArrayList<>());
914939 classes.add(0, cls);
949974 public static <A extends Annotation> A getAnnotation(final Method method, final Class<A> annotationCls,
950975 final boolean searchSupers, final boolean ignoreAccess) {
951976
952 Validate.notNull(method, "The method must not be null");
953 Validate.notNull(annotationCls, "The annotation class must not be null");
977 Validate.notNull(method, "method");
978 Validate.notNull(annotationCls, "annotationCls");
954979 if (!ignoreAccess && !MemberUtils.isAccessible(method)) {
955980 return null;
956981 }
9971022 int interfaceIndex = 0;
9981023 while (interfaceIndex < allInterfaces.size() ||
9991024 superClassIndex < allSuperclasses.size()) {
1000 Class<?> acls;
1025 final Class<?> acls;
10011026 if (interfaceIndex >= allInterfaces.size()) {
10021027 acls = allSuperclasses.get(superClassIndex++);
10031028 } else if ((superClassIndex >= allSuperclasses.size()) || (interfaceIndex < superClassIndex) || !(superClassIndex < interfaceIndex)) {
3838 import org.apache.commons.lang3.builder.Builder;
3939
4040 /**
41 * <p> Utility methods focusing on type inspection, particularly with regard to
42 * generics. </p>
41 * Utility methods focusing on type inspection, particularly with regard to
42 * generics.
4343 *
4444 * @since 3.0
4545 */
4646 public class TypeUtils {
4747
4848 /**
49 * {@link WildcardType} builder.
50 * @since 3.2
51 */
52 public static class WildcardTypeBuilder implements Builder<WildcardType> {
53 /**
54 * Constructor
55 */
56 private WildcardTypeBuilder() {
57 }
58
59 private Type[] upperBounds;
60 private Type[] lowerBounds;
61
62 /**
63 * Specify upper bounds of the wildcard type to build.
64 * @param bounds to set
65 * @return {@code this}
66 */
67 public WildcardTypeBuilder withUpperBounds(final Type... bounds) {
68 this.upperBounds = bounds;
69 return this;
70 }
71
72 /**
73 * Specify lower bounds of the wildcard type to build.
74 * @param bounds to set
75 * @return {@code this}
76 */
77 public WildcardTypeBuilder withLowerBounds(final Type... bounds) {
78 this.lowerBounds = bounds;
79 return this;
80 }
81
82 /**
83 * {@inheritDoc}
84 */
85 @Override
86 public WildcardType build() {
87 return new WildcardTypeImpl(upperBounds, lowerBounds);
88 }
89 }
90
91 /**
9249 * GenericArrayType implementation class.
9350 * @since 3.2
9451 */
10158 */
10259 private GenericArrayTypeImpl(final Type componentType) {
10360 this.componentType = componentType;
61 }
62
63 /**
64 * {@inheritDoc}
65 */
66 @Override
67 public boolean equals(final Object obj) {
68 return obj == this || obj instanceof GenericArrayType && TypeUtils.equals(this, (GenericArrayType) obj);
10469 }
10570
10671 /**
10974 @Override
11075 public Type getGenericComponentType() {
11176 return componentType;
112 }
113
114 /**
115 * {@inheritDoc}
116 */
117 @Override
118 public String toString() {
119 return TypeUtils.toString(this);
120 }
121
122 /**
123 * {@inheritDoc}
124 */
125 @Override
126 public boolean equals(final Object obj) {
127 return obj == this || obj instanceof GenericArrayType && TypeUtils.equals(this, (GenericArrayType) obj);
12877 }
12978
13079 /**
13685 result |= componentType.hashCode();
13786 return result;
13887 }
88
89 /**
90 * {@inheritDoc}
91 */
92 @Override
93 public String toString() {
94 return TypeUtils.toString(this);
95 }
13996 }
14097
14198 /**
163120 * {@inheritDoc}
164121 */
165122 @Override
166 public Type getRawType() {
167 return raw;
123 public boolean equals(final Object obj) {
124 return obj == this || obj instanceof ParameterizedType && TypeUtils.equals(this, ((ParameterizedType) obj));
125 }
126
127 /**
128 * {@inheritDoc}
129 */
130 @Override
131 public Type[] getActualTypeArguments() {
132 return typeArguments.clone();
168133 }
169134
170135 /**
179144 * {@inheritDoc}
180145 */
181146 @Override
182 public Type[] getActualTypeArguments() {
183 return typeArguments.clone();
184 }
185
186 /**
187 * {@inheritDoc}
188 */
189 @Override
190 public String toString() {
191 return TypeUtils.toString(this);
192 }
193
194 /**
195 * {@inheritDoc}
196 */
197 @Override
198 public boolean equals(final Object obj) {
199 return obj == this || obj instanceof ParameterizedType && TypeUtils.equals(this, ((ParameterizedType) obj));
147 public Type getRawType() {
148 return raw;
200149 }
201150
202151 /**
212161 result |= Arrays.hashCode(typeArguments);
213162 return result;
214163 }
164
165 /**
166 * {@inheritDoc}
167 */
168 @Override
169 public String toString() {
170 return TypeUtils.toString(this);
171 }
172 }
173
174 /**
175 * {@link WildcardType} builder.
176 * @since 3.2
177 */
178 public static class WildcardTypeBuilder implements Builder<WildcardType> {
179 private Type[] upperBounds;
180
181 private Type[] lowerBounds;
182 /**
183 * Constructor
184 */
185 private WildcardTypeBuilder() {
186 }
187
188 /**
189 * {@inheritDoc}
190 */
191 @Override
192 public WildcardType build() {
193 return new WildcardTypeImpl(upperBounds, lowerBounds);
194 }
195
196 /**
197 * Specify lower bounds of the wildcard type to build.
198 * @param bounds to set
199 * @return {@code this}
200 */
201 public WildcardTypeBuilder withLowerBounds(final Type... bounds) {
202 this.lowerBounds = bounds;
203 return this;
204 }
205
206 /**
207 * Specify upper bounds of the wildcard type to build.
208 * @param bounds to set
209 * @return {@code this}
210 */
211 public WildcardTypeBuilder withUpperBounds(final Type... bounds) {
212 this.upperBounds = bounds;
213 return this;
214 }
215215 }
216216
217217 /**
236236 * {@inheritDoc}
237237 */
238238 @Override
239 public Type[] getUpperBounds() {
240 return upperBounds.clone();
239 public boolean equals(final Object obj) {
240 return obj == this || obj instanceof WildcardType && TypeUtils.equals(this, (WildcardType) obj);
241241 }
242242
243243 /**
252252 * {@inheritDoc}
253253 */
254254 @Override
255 public String toString() {
256 return TypeUtils.toString(this);
257 }
258
259 /**
260 * {@inheritDoc}
261 */
262 @Override
263 public boolean equals(final Object obj) {
264 return obj == this || obj instanceof WildcardType && TypeUtils.equals(this, (WildcardType) obj);
255 public Type[] getUpperBounds() {
256 return upperBounds.clone();
265257 }
266258
267259 /**
275267 result |= Arrays.hashCode(lowerBounds);
276268 return result;
277269 }
270
271 /**
272 * {@inheritDoc}
273 */
274 @Override
275 public String toString() {
276 return TypeUtils.toString(this);
277 }
278278 }
279279
280280 /**
284284 public static final WildcardType WILDCARD_ALL = wildcardType().withUpperBounds(Object.class).build();
285285
286286 /**
287 * <p>{@code TypeUtils} instances should NOT be constructed in standard
288 * programming. Instead, the class should be used as
289 * {@code TypeUtils.isAssignable(cls, toClass)}.</p> <p>This
290 * constructor is public to permit tools that require a JavaBean instance to
291 * operate.</p>
292 */
293 public TypeUtils() {
294 super();
295 }
296
297 /**
298 * <p>Checks if the subject type may be implicitly cast to the target type
299 * following the Java generics rules. If both types are {@link Class}
300 * objects, the method returns the result of
301 * {@link ClassUtils#isAssignable(Class, Class)}.</p>
302 *
303 * @param type the subject type to be assigned to the target type
304 * @param toType the target type
305 * @return {@code true} if {@code type} is assignable to {@code toType}.
306 */
307 public static boolean isAssignable(final Type type, final Type toType) {
308 return isAssignable(type, toType, null);
309 }
310
311 /**
312 * <p>Checks if the subject type may be implicitly cast to the target type
313 * following the Java generics rules.</p>
314 *
315 * @param type the subject type to be assigned to the target type
316 * @param toType the target type
317 * @param typeVarAssigns optional map of type variable assignments
318 * @return {@code true} if {@code type} is assignable to {@code toType}.
319 */
320 private static boolean isAssignable(final Type type, final Type toType,
321 final Map<TypeVariable<?>, Type> typeVarAssigns) {
322 if (toType == null || toType instanceof Class<?>) {
323 return isAssignable(type, (Class<?>) toType);
324 }
325
326 if (toType instanceof ParameterizedType) {
327 return isAssignable(type, (ParameterizedType) toType, typeVarAssigns);
328 }
329
330 if (toType instanceof GenericArrayType) {
331 return isAssignable(type, (GenericArrayType) toType, typeVarAssigns);
332 }
333
334 if (toType instanceof WildcardType) {
335 return isAssignable(type, (WildcardType) toType, typeVarAssigns);
336 }
337
338 if (toType instanceof TypeVariable<?>) {
339 return isAssignable(type, (TypeVariable<?>) toType, typeVarAssigns);
340 }
341
342 throw new IllegalStateException("found an unhandled type: " + toType);
343 }
344
345 /**
346 * <p>Checks if the subject type may be implicitly cast to the target class
347 * following the Java generics rules.</p>
348 *
349 * @param type the subject type to be assigned to the target type
350 * @param toClass the target class
351 * @return {@code true} if {@code type} is assignable to {@code toClass}.
352 */
353 private static boolean isAssignable(final Type type, final Class<?> toClass) {
354 if (type == null) {
355 // consistency with ClassUtils.isAssignable() behavior
356 return toClass == null || !toClass.isPrimitive();
357 }
358
359 // only a null type can be assigned to null type which
360 // would have cause the previous to return true
361 if (toClass == null) {
362 return false;
363 }
364
365 // all types are assignable to themselves
366 if (toClass.equals(type)) {
287 * Appends {@code types} to {@code builder} with separator {@code sep}.
288 *
289 * @param builder destination
290 * @param sep separator
291 * @param types to append
292 * @return {@code builder}
293 * @since 3.2
294 */
295 private static <T> StringBuilder appendAllTo(final StringBuilder builder, final String sep,
296 @SuppressWarnings("unchecked") final T... types) {
297 Validate.notEmpty(Validate.noNullElements(types));
298 if (types.length > 0) {
299 builder.append(toString(types[0]));
300 for (int i = 1; i < types.length; i++) {
301 builder.append(sep).append(toString(types[i]));
302 }
303 }
304 return builder;
305 }
306
307 private static void appendRecursiveTypes(final StringBuilder builder, final int[] recursiveTypeIndexes,
308 final Type[] argumentTypes) {
309 for (int i = 0; i < recursiveTypeIndexes.length; i++) {
310 appendAllTo(builder.append('<'), ", ", argumentTypes[i].toString()).append('>');
311 }
312
313 final Type[] argumentsFiltered = ArrayUtils.removeAll(argumentTypes, recursiveTypeIndexes);
314
315 if (argumentsFiltered.length > 0) {
316 appendAllTo(builder.append('<'), ", ", argumentsFiltered).append('>');
317 }
318 }
319
320 /**
321 * Formats a {@link Class} as a {@link String}.
322 *
323 * @param cls {@code Class} to format
324 * @return String
325 * @since 3.2
326 */
327 private static String classToString(final Class<?> cls) {
328 if (cls.isArray()) {
329 return toString(cls.getComponentType()) + "[]";
330 }
331
332 final StringBuilder buf = new StringBuilder();
333
334 if (cls.getEnclosingClass() != null) {
335 buf.append(classToString(cls.getEnclosingClass())).append('.').append(cls.getSimpleName());
336 } else {
337 buf.append(cls.getName());
338 }
339 if (cls.getTypeParameters().length > 0) {
340 buf.append('<');
341 appendAllTo(buf, ", ", cls.getTypeParameters());
342 buf.append('>');
343 }
344 return buf.toString();
345 }
346
347 /**
348 * Tests, recursively, whether any of the type parameters associated with {@code type} are bound to variables.
349 *
350 * @param type the type to check for type variables
351 * @return boolean
352 * @since 3.2
353 */
354 public static boolean containsTypeVariables(final Type type) {
355 if (type instanceof TypeVariable<?>) {
367356 return true;
368357 }
369
370358 if (type instanceof Class<?>) {
371 // just comparing two classes
372 return ClassUtils.isAssignable((Class<?>) type, toClass);
373 }
374
359 return ((Class<?>) type).getTypeParameters().length > 0;
360 }
375361 if (type instanceof ParameterizedType) {
376 // only have to compare the raw type to the class
377 return isAssignable(getRawType((ParameterizedType) type), toClass);
378 }
379
380 // *
381 if (type instanceof TypeVariable<?>) {
382 // if any of the bounds are assignable to the class, then the
383 // type is assignable to the class.
384 for (final Type bound : ((TypeVariable<?>) type).getBounds()) {
385 if (isAssignable(bound, toClass)) {
362 for (final Type arg : ((ParameterizedType) type).getActualTypeArguments()) {
363 if (containsTypeVariables(arg)) {
386364 return true;
387365 }
388366 }
389
390367 return false;
391368 }
392
393 // the only classes to which a generic array type can be assigned
394 // are class Object and array classes
369 if (type instanceof WildcardType) {
370 final WildcardType wild = (WildcardType) type;
371 return containsTypeVariables(getImplicitLowerBounds(wild)[0])
372 || containsTypeVariables(getImplicitUpperBounds(wild)[0]);
373 }
395374 if (type instanceof GenericArrayType) {
396 return toClass.equals(Object.class)
397 || toClass.isArray()
398 && isAssignable(((GenericArrayType) type).getGenericComponentType(), toClass
399 .getComponentType());
400 }
401
402 // wildcard types are not assignable to a class (though one would think
403 // "? super Object" would be assignable to Object)
375 return containsTypeVariables(((GenericArrayType) type).getGenericComponentType());
376 }
377 return false;
378 }
379
380 private static boolean containsVariableTypeSameParametrizedTypeBound(final TypeVariable<?> typeVariable,
381 final ParameterizedType parameterizedType) {
382 return ArrayUtils.contains(typeVariable.getBounds(), parameterizedType);
383 }
384
385 /**
386 * Tries to determine the type arguments of a class/interface based on a
387 * super parameterized type's type arguments. This method is the inverse of
388 * {@link #getTypeArguments(Type, Class)} which gets a class/interface's
389 * type arguments based on a subtype. It is far more limited in determining
390 * the type arguments for the subject class's type variables in that it can
391 * only determine those parameters that map from the subject {@link Class}
392 * object to the supertype.
393 *
394 * <p>
395 * Example: {@link java.util.TreeSet
396 * TreeSet} sets its parameter as the parameter for
397 * {@link java.util.NavigableSet NavigableSet}, which in turn sets the
398 * parameter of {@link java.util.SortedSet}, which in turn sets the
399 * parameter of {@link Set}, which in turn sets the parameter of
400 * {@link java.util.Collection}, which in turn sets the parameter of
401 * {@link java.lang.Iterable}. Since {@code TreeSet}'s parameter maps
402 * (indirectly) to {@code Iterable}'s parameter, it will be able to
403 * determine that based on the super type {@code Iterable<? extends
404 * Map<Integer, ? extends Collection<?>>>}, the parameter of
405 * {@code TreeSet} is {@code ? extends Map<Integer, ? extends
406 * Collection<?>>}.
407 * </p>
408 *
409 * @param cls the class whose type parameters are to be determined, not {@code null}
410 * @param superParameterizedType the super type from which {@code cls}'s type
411 * arguments are to be determined, not {@code null}
412 * @return a {@code Map} of the type assignments that could be determined
413 * for the type variables in each type in the inheritance hierarchy from
414 * {@code type} to {@code toClass} inclusive.
415 */
416 public static Map<TypeVariable<?>, Type> determineTypeArguments(final Class<?> cls,
417 final ParameterizedType superParameterizedType) {
418 Validate.notNull(cls, "cls");
419 Validate.notNull(superParameterizedType, "superParameterizedType");
420
421 final Class<?> superClass = getRawType(superParameterizedType);
422
423 // compatibility check
424 if (!isAssignable(cls, superClass)) {
425 return null;
426 }
427
428 if (cls.equals(superClass)) {
429 return getTypeArguments(superParameterizedType, superClass, null);
430 }
431
432 // get the next class in the inheritance hierarchy
433 final Type midType = getClosestParentType(cls, superClass);
434
435 // can only be a class or a parameterized type
436 if (midType instanceof Class<?>) {
437 return determineTypeArguments((Class<?>) midType, superParameterizedType);
438 }
439
440 final ParameterizedType midParameterizedType = (ParameterizedType) midType;
441 final Class<?> midClass = getRawType(midParameterizedType);
442 // get the type variables of the mid class that map to the type
443 // arguments of the super class
444 final Map<TypeVariable<?>, Type> typeVarAssigns = determineTypeArguments(midClass, superParameterizedType);
445 // map the arguments of the mid type to the class type variables
446 mapTypeVariablesToArguments(cls, midParameterizedType, typeVarAssigns);
447
448 return typeVarAssigns;
449 }
450
451 /**
452 * Tests whether {@code t} equals {@code a}.
453 *
454 * @param genericArrayType LHS
455 * @param type RHS
456 * @return boolean
457 * @since 3.2
458 */
459 private static boolean equals(final GenericArrayType genericArrayType, final Type type) {
460 return type instanceof GenericArrayType
461 && equals(genericArrayType.getGenericComponentType(), ((GenericArrayType) type).getGenericComponentType());
462 }
463
464 /**
465 * Tests whether {@code t} equals {@code p}.
466 *
467 * @param parameterizedType LHS
468 * @param type RHS
469 * @return boolean
470 * @since 3.2
471 */
472 private static boolean equals(final ParameterizedType parameterizedType, final Type type) {
473 if (type instanceof ParameterizedType) {
474 final ParameterizedType other = (ParameterizedType) type;
475 if (equals(parameterizedType.getRawType(), other.getRawType())
476 && equals(parameterizedType.getOwnerType(), other.getOwnerType())) {
477 return equals(parameterizedType.getActualTypeArguments(), other.getActualTypeArguments());
478 }
479 }
480 return false;
481 }
482
483 /**
484 * Tests equality of types.
485 *
486 * @param type1 the first type
487 * @param type2 the second type
488 * @return boolean
489 * @since 3.2
490 */
491 public static boolean equals(final Type type1, final Type type2) {
492 if (Objects.equals(type1, type2)) {
493 return true;
494 }
495 if (type1 instanceof ParameterizedType) {
496 return equals((ParameterizedType) type1, type2);
497 }
498 if (type1 instanceof GenericArrayType) {
499 return equals((GenericArrayType) type1, type2);
500 }
501 if (type1 instanceof WildcardType) {
502 return equals((WildcardType) type1, type2);
503 }
504 return false;
505 }
506
507 /**
508 * Tests whether {@code t1} equals {@code t2}.
509 *
510 * @param type1 LHS
511 * @param type2 RHS
512 * @return boolean
513 * @since 3.2
514 */
515 private static boolean equals(final Type[] type1, final Type[] type2) {
516 if (type1.length == type2.length) {
517 for (int i = 0; i < type1.length; i++) {
518 if (!equals(type1[i], type2[i])) {
519 return false;
520 }
521 }
522 return true;
523 }
524 return false;
525 }
526
527 /**
528 * Tests whether {@code t} equals {@code w}.
529 *
530 * @param wildcardType LHS
531 * @param type RHS
532 * @return boolean
533 * @since 3.2
534 */
535 private static boolean equals(final WildcardType wildcardType, final Type type) {
404536 if (type instanceof WildcardType) {
405 return false;
406 }
407
408 throw new IllegalStateException("found an unhandled type: " + type);
409 }
410
411 /**
412 * <p>Checks if the subject type may be implicitly cast to the target
413 * parameterized type following the Java generics rules.</p>
414 *
415 * @param type the subject type to be assigned to the target type
416 * @param toParameterizedType the target parameterized type
417 * @param typeVarAssigns a map with type variables
418 * @return {@code true} if {@code type} is assignable to {@code toType}.
419 */
420 private static boolean isAssignable(final Type type, final ParameterizedType toParameterizedType,
421 final Map<TypeVariable<?>, Type> typeVarAssigns) {
422 if (type == null) {
423 return true;
424 }
425
426 // only a null type can be assigned to null type which
427 // would have cause the previous to return true
428 if (toParameterizedType == null) {
429 return false;
430 }
431
432 // all types are assignable to themselves
433 if (toParameterizedType.equals(type)) {
434 return true;
435 }
436
437 // get the target type's raw type
438 final Class<?> toClass = getRawType(toParameterizedType);
439 // get the subject type's type arguments including owner type arguments
440 // and supertype arguments up to and including the target class.
441 final Map<TypeVariable<?>, Type> fromTypeVarAssigns = getTypeArguments(type, toClass, null);
442
443 // null means the two types are not compatible
444 if (fromTypeVarAssigns == null) {
445 return false;
446 }
447
448 // compatible types, but there's no type arguments. this is equivalent
449 // to comparing Map< ?, ? > to Map, and raw types are always assignable
450 // to parameterized types.
451 if (fromTypeVarAssigns.isEmpty()) {
452 return true;
453 }
454
455 // get the target type's type arguments including owner type arguments
456 final Map<TypeVariable<?>, Type> toTypeVarAssigns = getTypeArguments(toParameterizedType,
457 toClass, typeVarAssigns);
458
459 // now to check each type argument
460 for (final TypeVariable<?> var : toTypeVarAssigns.keySet()) {
461 final Type toTypeArg = unrollVariableAssignments(var, toTypeVarAssigns);
462 final Type fromTypeArg = unrollVariableAssignments(var, fromTypeVarAssigns);
463
464 if (toTypeArg == null && fromTypeArg instanceof Class) {
465 continue;
466 }
467
468 // parameters must either be absent from the subject type, within
469 // the bounds of the wildcard type, or be an exact match to the
470 // parameters of the target type.
471 if (fromTypeArg != null
472 && !toTypeArg.equals(fromTypeArg)
473 && !(toTypeArg instanceof WildcardType && isAssignable(fromTypeArg, toTypeArg,
474 typeVarAssigns))) {
475 return false;
476 }
477 }
478 return true;
479 }
480
481 /**
482 * Look up {@code var} in {@code typeVarAssigns} <em>transitively</em>,
483 * i.e. keep looking until the value found is <em>not</em> a type variable.
484 * @param typeVariable the type variable to look up
485 * @param typeVarAssigns the map used for the look up
486 * @return Type or {@code null} if some variable was not in the map
487 * @since 3.2
488 */
489 private static Type unrollVariableAssignments(TypeVariable<?> typeVariable,
490 final Map<TypeVariable<?>, Type> typeVarAssigns) {
491 Type result;
492 do {
493 result = typeVarAssigns.get(typeVariable);
494 if (result instanceof TypeVariable<?> && !result.equals(typeVariable)) {
495 typeVariable = (TypeVariable<?>) result;
496 continue;
497 }
498 break;
499 } while (true);
537 final WildcardType other = (WildcardType) type;
538 return equals(getImplicitLowerBounds(wildcardType), getImplicitLowerBounds(other))
539 && equals(getImplicitUpperBounds(wildcardType), getImplicitUpperBounds(other));
540 }
541 return false;
542 }
543
544 /**
545 * Helper method to establish the formal parameters for a parameterized type.
546 *
547 * @param mappings map containing the assignments
548 * @param variables expected map keys
549 * @return array of map values corresponding to specified keys
550 */
551 private static Type[] extractTypeArgumentsFrom(final Map<TypeVariable<?>, Type> mappings, final TypeVariable<?>[] variables) {
552 final Type[] result = new Type[variables.length];
553 int index = 0;
554 for (final TypeVariable<?> var : variables) {
555 Validate.isTrue(mappings.containsKey(var), "missing argument mapping for %s", toString(var));
556 result[index++] = mappings.get(var);
557 }
500558 return result;
501559 }
502560
503 /**
504 * <p>Checks if the subject type may be implicitly cast to the target
505 * generic array type following the Java generics rules.</p>
506 *
507 * @param type the subject type to be assigned to the target type
508 * @param toGenericArrayType the target generic array type
509 * @param typeVarAssigns a map with type variables
510 * @return {@code true} if {@code type} is assignable to
511 * {@code toGenericArrayType}.
512 */
513 private static boolean isAssignable(final Type type, final GenericArrayType toGenericArrayType,
514 final Map<TypeVariable<?>, Type> typeVarAssigns) {
515 if (type == null) {
516 return true;
517 }
518
519 // only a null type can be assigned to null type which
520 // would have cause the previous to return true
521 if (toGenericArrayType == null) {
522 return false;
523 }
524
525 // all types are assignable to themselves
526 if (toGenericArrayType.equals(type)) {
527 return true;
528 }
529
530 final Type toComponentType = toGenericArrayType.getGenericComponentType();
531
561 private static int[] findRecursiveTypes(final ParameterizedType parameterizedType) {
562 final Type[] filteredArgumentTypes = Arrays.copyOf(parameterizedType.getActualTypeArguments(),
563 parameterizedType.getActualTypeArguments().length);
564 int[] indexesToRemove = {};
565 for (int i = 0; i < filteredArgumentTypes.length; i++) {
566 if ((filteredArgumentTypes[i] instanceof TypeVariable<?>) && containsVariableTypeSameParametrizedTypeBound(
567 ((TypeVariable<?>) filteredArgumentTypes[i]), parameterizedType)) {
568 indexesToRemove = ArrayUtils.add(indexesToRemove, i);
569 }
570 }
571 return indexesToRemove;
572 }
573
574 /**
575 * Creates a generic array type instance.
576 *
577 * @param componentType the type of the elements of the array. For example the component type of {@code boolean[]}
578 * is {@code boolean}
579 * @return {@link GenericArrayType}
580 * @since 3.2
581 */
582 public static GenericArrayType genericArrayType(final Type componentType) {
583 return new GenericArrayTypeImpl(Validate.notNull(componentType, "componentType"));
584 }
585
586 /**
587 * Formats a {@link GenericArrayType} as a {@link String}.
588 *
589 * @param genericArrayType {@code GenericArrayType} to format
590 * @return String
591 * @since 3.2
592 */
593 private static String genericArrayTypeToString(final GenericArrayType genericArrayType) {
594 return String.format("%s[]", toString(genericArrayType.getGenericComponentType()));
595 }
596
597 /**
598 * Gets the array component type of {@code type}.
599 *
600 * @param type the type to be checked
601 * @return component type or null if type is not an array type
602 */
603 public static Type getArrayComponentType(final Type type) {
532604 if (type instanceof Class<?>) {
533605 final Class<?> cls = (Class<?>) type;
534
535 // compare the component types
536 return cls.isArray()
537 && isAssignable(cls.getComponentType(), toComponentType, typeVarAssigns);
538 }
539
606 return cls.isArray() ? cls.getComponentType() : null;
607 }
540608 if (type instanceof GenericArrayType) {
541 // compare the component types
542 return isAssignable(((GenericArrayType) type).getGenericComponentType(),
543 toComponentType, typeVarAssigns);
544 }
545
609 return ((GenericArrayType) type).getGenericComponentType();
610 }
611 return null;
612 }
613
614 /**
615 * Gets the closest parent type to the
616 * super class specified by {@code superClass}.
617 *
618 * @param cls the class in question
619 * @param superClass the super class
620 * @return the closes parent type
621 */
622 private static Type getClosestParentType(final Class<?> cls, final Class<?> superClass) {
623 // only look at the interfaces if the super class is also an interface
624 if (superClass.isInterface()) {
625 // get the generic interfaces of the subject class
626 final Type[] interfaceTypes = cls.getGenericInterfaces();
627 // will hold the best generic interface match found
628 Type genericInterface = null;
629
630 // find the interface closest to the super class
631 for (final Type midType : interfaceTypes) {
632 Class<?> midClass = null;
633
634 if (midType instanceof ParameterizedType) {
635 midClass = getRawType((ParameterizedType) midType);
636 } else if (midType instanceof Class<?>) {
637 midClass = (Class<?>) midType;
638 } else {
639 throw new IllegalStateException("Unexpected generic"
640 + " interface type found: " + midType);
641 }
642
643 // check if this interface is further up the inheritance chain
644 // than the previously found match
645 if (isAssignable(midClass, superClass)
646 && isAssignable(genericInterface, (Type) midClass)) {
647 genericInterface = midType;
648 }
649 }
650
651 // found a match?
652 if (genericInterface != null) {
653 return genericInterface;
654 }
655 }
656
657 // none of the interfaces were descendants of the target class, so the
658 // super class has to be one, instead
659 return cls.getGenericSuperclass();
660 }
661
662 /**
663 * Gets an array containing the sole type of {@link Object} if
664 * {@link TypeVariable#getBounds()} returns an empty array. Otherwise, it
665 * returns the result of {@link TypeVariable#getBounds()} passed into
666 * {@link #normalizeUpperBounds}.
667 *
668 * @param typeVariable the subject type variable, not {@code null}
669 * @return a non-empty array containing the bounds of the type variable.
670 */
671 public static Type[] getImplicitBounds(final TypeVariable<?> typeVariable) {
672 Validate.notNull(typeVariable, "typeVariable");
673 final Type[] bounds = typeVariable.getBounds();
674
675 return bounds.length == 0 ? new Type[] { Object.class } : normalizeUpperBounds(bounds);
676 }
677
678 /**
679 * Gets an array containing a single value of {@code null} if
680 * {@link WildcardType#getLowerBounds()} returns an empty array. Otherwise,
681 * it returns the result of {@link WildcardType#getLowerBounds()}.
682 *
683 * @param wildcardType the subject wildcard type, not {@code null}
684 * @return a non-empty array containing the lower bounds of the wildcard
685 * type.
686 */
687 public static Type[] getImplicitLowerBounds(final WildcardType wildcardType) {
688 Validate.notNull(wildcardType, "wildcardType");
689 final Type[] bounds = wildcardType.getLowerBounds();
690
691 return bounds.length == 0 ? new Type[] { null } : bounds;
692 }
693
694 /**
695 * Gets an array containing the sole value of {@link Object} if
696 * {@link WildcardType#getUpperBounds()} returns an empty array. Otherwise,
697 * it returns the result of {@link WildcardType#getUpperBounds()}
698 * passed into {@link #normalizeUpperBounds}.
699 *
700 * @param wildcardType the subject wildcard type, not {@code null}
701 * @return a non-empty array containing the upper bounds of the wildcard
702 * type.
703 */
704 public static Type[] getImplicitUpperBounds(final WildcardType wildcardType) {
705 Validate.notNull(wildcardType, "wildcardType");
706 final Type[] bounds = wildcardType.getUpperBounds();
707
708 return bounds.length == 0 ? new Type[] { Object.class } : normalizeUpperBounds(bounds);
709 }
710
711 /**
712 * Transforms the passed in type to a {@link Class} object. Type-checking method of convenience.
713 *
714 * @param parameterizedType the type to be converted
715 * @return the corresponding {@code Class} object
716 * @throws IllegalStateException if the conversion fails
717 */
718 private static Class<?> getRawType(final ParameterizedType parameterizedType) {
719 final Type rawType = parameterizedType.getRawType();
720
721 // check if raw type is a Class object
722 // not currently necessary, but since the return type is Type instead of
723 // Class, there's enough reason to believe that future versions of Java
724 // may return other Type implementations. And type-safety checking is
725 // rarely a bad idea.
726 if (!(rawType instanceof Class<?>)) {
727 throw new IllegalStateException("Wait... What!? Type of rawType: " + rawType);
728 }
729
730 return (Class<?>) rawType;
731 }
732
733 /**
734 * Gets the raw type of a Java type, given its context. Primarily for use
735 * with {@link TypeVariable}s and {@link GenericArrayType}s, or when you do
736 * not know the runtime type of {@code type}: if you know you have a
737 * {@link Class} instance, it is already raw; if you know you have a
738 * {@link ParameterizedType}, its raw type is only a method call away.
739 *
740 * @param type to resolve
741 * @param assigningType type to be resolved against
742 * @return the resolved {@link Class} object or {@code null} if
743 * the type could not be resolved
744 */
745 public static Class<?> getRawType(final Type type, final Type assigningType) {
746 if (type instanceof Class<?>) {
747 // it is raw, no problem
748 return (Class<?>) type;
749 }
750
751 if (type instanceof ParameterizedType) {
752 // simple enough to get the raw type of a ParameterizedType
753 return getRawType((ParameterizedType) type);
754 }
755
756 if (type instanceof TypeVariable<?>) {
757 if (assigningType == null) {
758 return null;
759 }
760
761 // get the entity declaring this type variable
762 final Object genericDeclaration = ((TypeVariable<?>) type).getGenericDeclaration();
763
764 // can't get the raw type of a method- or constructor-declared type
765 // variable
766 if (!(genericDeclaration instanceof Class<?>)) {
767 return null;
768 }
769
770 // get the type arguments for the declaring class/interface based
771 // on the enclosing type
772 final Map<TypeVariable<?>, Type> typeVarAssigns = getTypeArguments(assigningType,
773 (Class<?>) genericDeclaration);
774
775 // enclosingType has to be a subclass (or subinterface) of the
776 // declaring type
777 if (typeVarAssigns == null) {
778 return null;
779 }
780
781 // get the argument assigned to this type variable
782 final Type typeArgument = typeVarAssigns.get(type);
783
784 if (typeArgument == null) {
785 return null;
786 }
787
788 // get the argument for this type variable
789 return getRawType(typeArgument, assigningType);
790 }
791
792 if (type instanceof GenericArrayType) {
793 // get raw component type
794 final Class<?> rawComponentType = getRawType(((GenericArrayType) type)
795 .getGenericComponentType(), assigningType);
796
797 // create array type from raw component type and return its class
798 return Array.newInstance(rawComponentType, 0).getClass();
799 }
800
801 // (hand-waving) this is not the method you're looking for
546802 if (type instanceof WildcardType) {
547 // so long as one of the upper bounds is assignable, it's good
548 for (final Type bound : getImplicitUpperBounds((WildcardType) type)) {
549 if (isAssignable(bound, toGenericArrayType)) {
550 return true;
551 }
552 }
553
554 return false;
555 }
556
557 if (type instanceof TypeVariable<?>) {
558 // probably should remove the following logic and just return false.
559 // type variables cannot specify arrays as bounds.
560 for (final Type bound : getImplicitBounds((TypeVariable<?>) type)) {
561 if (isAssignable(bound, toGenericArrayType)) {
562 return true;
563 }
564 }
565
566 return false;
567 }
568
569 if (type instanceof ParameterizedType) {
570 // the raw type of a parameterized type is never an array or
571 // generic array, otherwise the declaration would look like this:
572 // Collection[]< ? extends String > collection;
573 return false;
574 }
575
576 throw new IllegalStateException("found an unhandled type: " + type);
577 }
578
579 /**
580 * <p>Checks if the subject type may be implicitly cast to the target
581 * wildcard type following the Java generics rules.</p>
582 *
583 * @param type the subject type to be assigned to the target type
584 * @param toWildcardType the target wildcard type
585 * @param typeVarAssigns a map with type variables
586 * @return {@code true} if {@code type} is assignable to
587 * {@code toWildcardType}.
588 */
589 private static boolean isAssignable(final Type type, final WildcardType toWildcardType,
590 final Map<TypeVariable<?>, Type> typeVarAssigns) {
591 if (type == null) {
592 return true;
593 }
594
595 // only a null type can be assigned to null type which
596 // would have cause the previous to return true
597 if (toWildcardType == null) {
598 return false;
599 }
600
601 // all types are assignable to themselves
602 if (toWildcardType.equals(type)) {
603 return true;
604 }
605
606 final Type[] toUpperBounds = getImplicitUpperBounds(toWildcardType);
607 final Type[] toLowerBounds = getImplicitLowerBounds(toWildcardType);
608
609 if (type instanceof WildcardType) {
610 final WildcardType wildcardType = (WildcardType) type;
611 final Type[] upperBounds = getImplicitUpperBounds(wildcardType);
612 final Type[] lowerBounds = getImplicitLowerBounds(wildcardType);
613
614 for (Type toBound : toUpperBounds) {
615 // if there are assignments for unresolved type variables,
616 // now's the time to substitute them.
617 toBound = substituteTypeVariables(toBound, typeVarAssigns);
618
619 // each upper bound of the subject type has to be assignable to
620 // each
621 // upper bound of the target type
622 for (final Type bound : upperBounds) {
623 if (!isAssignable(bound, toBound, typeVarAssigns)) {
624 return false;
625 }
626 }
627 }
628
629 for (Type toBound : toLowerBounds) {
630 // if there are assignments for unresolved type variables,
631 // now's the time to substitute them.
632 toBound = substituteTypeVariables(toBound, typeVarAssigns);
633
634 // each lower bound of the target type has to be assignable to
635 // each
636 // lower bound of the subject type
637 for (final Type bound : lowerBounds) {
638 if (!isAssignable(toBound, bound, typeVarAssigns)) {
639 return false;
640 }
641 }
642 }
643 return true;
644 }
645
646 for (final Type toBound : toUpperBounds) {
647 // if there are assignments for unresolved type variables,
648 // now's the time to substitute them.
649 if (!isAssignable(type, substituteTypeVariables(toBound, typeVarAssigns),
650 typeVarAssigns)) {
651 return false;
652 }
653 }
654
655 for (final Type toBound : toLowerBounds) {
656 // if there are assignments for unresolved type variables,
657 // now's the time to substitute them.
658 if (!isAssignable(substituteTypeVariables(toBound, typeVarAssigns), type,
659 typeVarAssigns)) {
660 return false;
661 }
662 }
663 return true;
664 }
665
666 /**
667 * <p>Checks if the subject type may be implicitly cast to the target type
668 * variable following the Java generics rules.</p>
669 *
670 * @param type the subject type to be assigned to the target type
671 * @param toTypeVariable the target type variable
672 * @param typeVarAssigns a map with type variables
673 * @return {@code true} if {@code type} is assignable to
674 * {@code toTypeVariable}.
675 */
676 private static boolean isAssignable(final Type type, final TypeVariable<?> toTypeVariable,
677 final Map<TypeVariable<?>, Type> typeVarAssigns) {
678 if (type == null) {
679 return true;
680 }
681
682 // only a null type can be assigned to null type which
683 // would have cause the previous to return true
684 if (toTypeVariable == null) {
685 return false;
686 }
687
688 // all types are assignable to themselves
689 if (toTypeVariable.equals(type)) {
690 return true;
691 }
692
693 if (type instanceof TypeVariable<?>) {
694 // a type variable is assignable to another type variable, if
695 // and only if the former is the latter, extends the latter, or
696 // is otherwise a descendant of the latter.
697 final Type[] bounds = getImplicitBounds((TypeVariable<?>) type);
698
699 for (final Type bound : bounds) {
700 if (isAssignable(bound, toTypeVariable, typeVarAssigns)) {
701 return true;
702 }
703 }
704 }
705
706 if (type instanceof Class<?> || type instanceof ParameterizedType
707 || type instanceof GenericArrayType || type instanceof WildcardType) {
708 return false;
709 }
710
711 throw new IllegalStateException("found an unhandled type: " + type);
712 }
713
714 /**
715 * <p>Find the mapping for {@code type} in {@code typeVarAssigns}.</p>
716 *
717 * @param type the type to be replaced
718 * @param typeVarAssigns the map with type variables
719 * @return the replaced type
720 * @throws IllegalArgumentException if the type cannot be substituted
721 */
722 private static Type substituteTypeVariables(final Type type, final Map<TypeVariable<?>, Type> typeVarAssigns) {
723 if (type instanceof TypeVariable<?> && typeVarAssigns != null) {
724 final Type replacementType = typeVarAssigns.get(type);
725
726 if (replacementType == null) {
727 throw new IllegalArgumentException("missing assignment type for type variable "
728 + type);
729 }
730 return replacementType;
731 }
732 return type;
733 }
734
735 /**
736 * <p>Retrieves all the type arguments for this parameterized type
803 return null;
804 }
805
806 throw new IllegalArgumentException("unknown type: " + type);
807 }
808
809 /**
810 * Gets a map of the type arguments of a class in the context of {@code toClass}.
811 *
812 * @param cls the class in question
813 * @param toClass the context class
814 * @param subtypeVarAssigns a map with type variables
815 * @return the {@code Map} with type arguments
816 */
817 private static Map<TypeVariable<?>, Type> getTypeArguments(Class<?> cls, final Class<?> toClass,
818 final Map<TypeVariable<?>, Type> subtypeVarAssigns) {
819 // make sure they're assignable
820 if (!isAssignable(cls, toClass)) {
821 return null;
822 }
823
824 // can't work with primitives
825 if (cls.isPrimitive()) {
826 // both classes are primitives?
827 if (toClass.isPrimitive()) {
828 // dealing with widening here. No type arguments to be
829 // harvested with these two types.
830 return new HashMap<>();
831 }
832
833 // work with wrapper the wrapper class instead of the primitive
834 cls = ClassUtils.primitiveToWrapper(cls);
835 }
836
837 // create a copy of the incoming map, or an empty one if it's null
838 final HashMap<TypeVariable<?>, Type> typeVarAssigns = subtypeVarAssigns == null ? new HashMap<>()
839 : new HashMap<>(subtypeVarAssigns);
840
841 // has target class been reached?
842 if (toClass.equals(cls)) {
843 return typeVarAssigns;
844 }
845
846 // walk the inheritance hierarchy until the target class is reached
847 return getTypeArguments(getClosestParentType(cls, toClass), toClass, typeVarAssigns);
848 }
849
850 /**
851 * Gets all the type arguments for this parameterized type
737852 * including owner hierarchy arguments such as
738853 * {@code Outer<K, V>.Inner<T>.DeepInner<E>} .
739854 * The arguments are returned in a
740855 * {@link Map} specifying the argument type for each {@link TypeVariable}.
741 * </p>
742856 *
743857 * @param type specifies the subject parameterized type from which to
744858 * harvest the parameters.
750864 }
751865
752866 /**
753 * <p>Gets the type arguments of a class/interface based on a subtype. For
867 * Gets a map of the type arguments of a parameterized type in the context of {@code toClass}.
868 *
869 * @param parameterizedType the parameterized type
870 * @param toClass the class
871 * @param subtypeVarAssigns a map with type variables
872 * @return the {@code Map} with type arguments
873 */
874 private static Map<TypeVariable<?>, Type> getTypeArguments(
875 final ParameterizedType parameterizedType, final Class<?> toClass,
876 final Map<TypeVariable<?>, Type> subtypeVarAssigns) {
877 final Class<?> cls = getRawType(parameterizedType);
878
879 // make sure they're assignable
880 if (!isAssignable(cls, toClass)) {
881 return null;
882 }
883
884 final Type ownerType = parameterizedType.getOwnerType();
885 final Map<TypeVariable<?>, Type> typeVarAssigns;
886
887 if (ownerType instanceof ParameterizedType) {
888 // get the owner type arguments first
889 final ParameterizedType parameterizedOwnerType = (ParameterizedType) ownerType;
890 typeVarAssigns = getTypeArguments(parameterizedOwnerType,
891 getRawType(parameterizedOwnerType), subtypeVarAssigns);
892 } else {
893 // no owner, prep the type variable assignments map
894 typeVarAssigns = subtypeVarAssigns == null ? new HashMap<>()
895 : new HashMap<>(subtypeVarAssigns);
896 }
897
898 // get the subject parameterized type's arguments
899 final Type[] typeArgs = parameterizedType.getActualTypeArguments();
900 // and get the corresponding type variables from the raw class
901 final TypeVariable<?>[] typeParams = cls.getTypeParameters();
902
903 // map the arguments to their respective type variables
904 for (int i = 0; i < typeParams.length; i++) {
905 final Type typeArg = typeArgs[i];
906 typeVarAssigns.put(
907 typeParams[i],
908 typeVarAssigns.getOrDefault(typeArg, typeArg)
909 );
910 }
911
912 if (toClass.equals(cls)) {
913 // target class has been reached. Done.
914 return typeVarAssigns;
915 }
916
917 // walk the inheritance hierarchy until the target class is reached
918 return getTypeArguments(getClosestParentType(cls, toClass), toClass, typeVarAssigns);
919 }
920
921 /**
922 * Gets the type arguments of a class/interface based on a subtype. For
754923 * instance, this method will determine that both of the parameters for the
755924 * interface {@link Map} are {@link Object} for the subtype
756925 * {@link java.util.Properties Properties} even though the subtype does not
757 * directly implement the {@code Map} interface.</p>
758 * <p>This method returns {@code null} if {@code type} is not assignable to
926 * directly implement the {@code Map} interface.
927 *
928 * <p>
929 * This method returns {@code null} if {@code type} is not assignable to
759930 * {@code toClass}. It returns an empty map if none of the classes or
760 * interfaces in its inheritance hierarchy specify any type arguments.</p>
761 * <p>A side effect of this method is that it also retrieves the type
931 * interfaces in its inheritance hierarchy specify any type arguments.
932 * </p>
933 *
934 * <p>
935 * A side effect of this method is that it also retrieves the type
762936 * arguments for the classes and interfaces that are part of the hierarchy
763937 * between {@code type} and {@code toClass}. So with the above
764938 * example, this method will also determine that the type arguments for
771945 * this method will look at the inheritance hierarchy of only one of the
772946 * implementations/subclasses; the first interface encountered that isn't a
773947 * subinterface to one of the others in the {@code type} to
774 * {@code toClass} hierarchy.</p>
948 * {@code toClass} hierarchy.
949 * </p>
775950 *
776951 * @param type the type from which to determine the type parameters of
777952 * {@code toClass}
786961 }
787962
788963 /**
789 * <p>Return a map of the type arguments of {@code type} in the context of {@code toClass}.</p>
964 * Gets a map of the type arguments of {@code type} in the context of {@code toClass}.
790965 *
791966 * @param type the type in question
792967 * @param toClass the class
8351010 }
8361011
8371012 /**
838 * <p>Return a map of the type arguments of a parameterized type in the context of {@code toClass}.</p>
839 *
840 * @param parameterizedType the parameterized type
841 * @param toClass the class
842 * @param subtypeVarAssigns a map with type variables
843 * @return the {@code Map} with type arguments
844 */
845 private static Map<TypeVariable<?>, Type> getTypeArguments(
846 final ParameterizedType parameterizedType, final Class<?> toClass,
847 final Map<TypeVariable<?>, Type> subtypeVarAssigns) {
848 final Class<?> cls = getRawType(parameterizedType);
849
850 // make sure they're assignable
851 if (!isAssignable(cls, toClass)) {
852 return null;
853 }
854
855 final Type ownerType = parameterizedType.getOwnerType();
856 Map<TypeVariable<?>, Type> typeVarAssigns;
857
858 if (ownerType instanceof ParameterizedType) {
859 // get the owner type arguments first
860 final ParameterizedType parameterizedOwnerType = (ParameterizedType) ownerType;
861 typeVarAssigns = getTypeArguments(parameterizedOwnerType,
862 getRawType(parameterizedOwnerType), subtypeVarAssigns);
863 } else {
864 // no owner, prep the type variable assignments map
865 typeVarAssigns = subtypeVarAssigns == null ? new HashMap<>()
866 : new HashMap<>(subtypeVarAssigns);
867 }
868
869 // get the subject parameterized type's arguments
870 final Type[] typeArgs = parameterizedType.getActualTypeArguments();
871 // and get the corresponding type variables from the raw class
872 final TypeVariable<?>[] typeParams = cls.getTypeParameters();
873
874 // map the arguments to their respective type variables
875 for (int i = 0; i < typeParams.length; i++) {
876 final Type typeArg = typeArgs[i];
877 typeVarAssigns.put(
878 typeParams[i],
879 typeVarAssigns.getOrDefault(typeArg, typeArg)
880 );
881 }
882
883 if (toClass.equals(cls)) {
884 // target class has been reached. Done.
885 return typeVarAssigns;
886 }
887
888 // walk the inheritance hierarchy until the target class is reached
889 return getTypeArguments(getClosestParentType(cls, toClass), toClass, typeVarAssigns);
890 }
891
892 /**
893 * <p>Return a map of the type arguments of a class in the context of {@code toClass}.</p>
894 *
895 * @param cls the class in question
896 * @param toClass the context class
897 * @param subtypeVarAssigns a map with type variables
898 * @return the {@code Map} with type arguments
899 */
900 private static Map<TypeVariable<?>, Type> getTypeArguments(Class<?> cls, final Class<?> toClass,
901 final Map<TypeVariable<?>, Type> subtypeVarAssigns) {
902 // make sure they're assignable
903 if (!isAssignable(cls, toClass)) {
904 return null;
905 }
906
907 // can't work with primitives
908 if (cls.isPrimitive()) {
909 // both classes are primitives?
910 if (toClass.isPrimitive()) {
911 // dealing with widening here. No type arguments to be
912 // harvested with these two types.
913 return new HashMap<>();
914 }
915
916 // work with wrapper the wrapper class instead of the primitive
917 cls = ClassUtils.primitiveToWrapper(cls);
918 }
919
920 // create a copy of the incoming map, or an empty one if it's null
921 final HashMap<TypeVariable<?>, Type> typeVarAssigns = subtypeVarAssigns == null ? new HashMap<>()
922 : new HashMap<>(subtypeVarAssigns);
923
924 // has target class been reached?
925 if (toClass.equals(cls)) {
926 return typeVarAssigns;
927 }
928
929 // walk the inheritance hierarchy until the target class is reached
930 return getTypeArguments(getClosestParentType(cls, toClass), toClass, typeVarAssigns);
931 }
932
933 /**
934 * <p>Tries to determine the type arguments of a class/interface based on a
935 * super parameterized type's type arguments. This method is the inverse of
936 * {@link #getTypeArguments(Type, Class)} which gets a class/interface's
937 * type arguments based on a subtype. It is far more limited in determining
938 * the type arguments for the subject class's type variables in that it can
939 * only determine those parameters that map from the subject {@link Class}
940 * object to the supertype.</p> <p>Example: {@link java.util.TreeSet
941 * TreeSet} sets its parameter as the parameter for
942 * {@link java.util.NavigableSet NavigableSet}, which in turn sets the
943 * parameter of {@link java.util.SortedSet}, which in turn sets the
944 * parameter of {@link Set}, which in turn sets the parameter of
945 * {@link java.util.Collection}, which in turn sets the parameter of
946 * {@link java.lang.Iterable}. Since {@code TreeSet}'s parameter maps
947 * (indirectly) to {@code Iterable}'s parameter, it will be able to
948 * determine that based on the super type {@code Iterable<? extends
949 * Map<Integer, ? extends Collection<?>>>}, the parameter of
950 * {@code TreeSet} is {@code ? extends Map<Integer, ? extends
951 * Collection<?>>}.</p>
952 *
953 * @param cls the class whose type parameters are to be determined, not {@code null}
954 * @param superType the super type from which {@code cls}'s type
955 * arguments are to be determined, not {@code null}
956 * @return a {@code Map} of the type assignments that could be determined
957 * for the type variables in each type in the inheritance hierarchy from
958 * {@code type} to {@code toClass} inclusive.
959 */
960 public static Map<TypeVariable<?>, Type> determineTypeArguments(final Class<?> cls,
961 final ParameterizedType superType) {
962 Validate.notNull(cls, "cls is null");
963 Validate.notNull(superType, "superType is null");
964
965 final Class<?> superClass = getRawType(superType);
966
967 // compatibility check
968 if (!isAssignable(cls, superClass)) {
969 return null;
970 }
971
972 if (cls.equals(superClass)) {
973 return getTypeArguments(superType, superClass, null);
974 }
975
976 // get the next class in the inheritance hierarchy
977 final Type midType = getClosestParentType(cls, superClass);
978
979 // can only be a class or a parameterized type
980 if (midType instanceof Class<?>) {
981 return determineTypeArguments((Class<?>) midType, superType);
982 }
983
984 final ParameterizedType midParameterizedType = (ParameterizedType) midType;
985 final Class<?> midClass = getRawType(midParameterizedType);
986 // get the type variables of the mid class that map to the type
987 // arguments of the super class
988 final Map<TypeVariable<?>, Type> typeVarAssigns = determineTypeArguments(midClass, superType);
989 // map the arguments of the mid type to the class type variables
990 mapTypeVariablesToArguments(cls, midParameterizedType, typeVarAssigns);
991
992 return typeVarAssigns;
993 }
994
995 /**
996 * <p>Performs a mapping of type variables.</p>
1013 * Tests whether the specified type denotes an array type.
1014 *
1015 * @param type the type to be checked
1016 * @return {@code true} if {@code type} is an array class or a {@link GenericArrayType}.
1017 */
1018 public static boolean isArrayType(final Type type) {
1019 return type instanceof GenericArrayType || type instanceof Class<?> && ((Class<?>) type).isArray();
1020 }
1021
1022 /**
1023 * Tests if the subject type may be implicitly cast to the target class
1024 * following the Java generics rules.
1025 *
1026 * @param type the subject type to be assigned to the target type
1027 * @param toClass the target class
1028 * @return {@code true} if {@code type} is assignable to {@code toClass}.
1029 */
1030 private static boolean isAssignable(final Type type, final Class<?> toClass) {
1031 if (type == null) {
1032 // consistency with ClassUtils.isAssignable() behavior
1033 return toClass == null || !toClass.isPrimitive();
1034 }
1035
1036 // only a null type can be assigned to null type which
1037 // would have cause the previous to return true
1038 if (toClass == null) {
1039 return false;
1040 }
1041
1042 // all types are assignable to themselves
1043 if (toClass.equals(type)) {
1044 return true;
1045 }
1046
1047 if (type instanceof Class<?>) {
1048 // just comparing two classes
1049 return ClassUtils.isAssignable((Class<?>) type, toClass);
1050 }
1051
1052 if (type instanceof ParameterizedType) {
1053 // only have to compare the raw type to the class
1054 return isAssignable(getRawType((ParameterizedType) type), toClass);
1055 }
1056
1057 // *
1058 if (type instanceof TypeVariable<?>) {
1059 // if any of the bounds are assignable to the class, then the
1060 // type is assignable to the class.
1061 for (final Type bound : ((TypeVariable<?>) type).getBounds()) {
1062 if (isAssignable(bound, toClass)) {
1063 return true;
1064 }
1065 }
1066
1067 return false;
1068 }
1069
1070 // the only classes to which a generic array type can be assigned
1071 // are class Object and array classes
1072 if (type instanceof GenericArrayType) {
1073 return toClass.equals(Object.class)
1074 || toClass.isArray()
1075 && isAssignable(((GenericArrayType) type).getGenericComponentType(), toClass
1076 .getComponentType());
1077 }
1078
1079 // wildcard types are not assignable to a class (though one would think
1080 // "? super Object" would be assignable to Object)
1081 if (type instanceof WildcardType) {
1082 return false;
1083 }
1084
1085 throw new IllegalStateException("found an unhandled type: " + type);
1086 }
1087
1088 /**
1089 * Tests if the subject type may be implicitly cast to the target
1090 * generic array type following the Java generics rules.
1091 *
1092 * @param type the subject type to be assigned to the target type
1093 * @param toGenericArrayType the target generic array type
1094 * @param typeVarAssigns a map with type variables
1095 * @return {@code true} if {@code type} is assignable to
1096 * {@code toGenericArrayType}.
1097 */
1098 private static boolean isAssignable(final Type type, final GenericArrayType toGenericArrayType,
1099 final Map<TypeVariable<?>, Type> typeVarAssigns) {
1100 if (type == null) {
1101 return true;
1102 }
1103
1104 // only a null type can be assigned to null type which
1105 // would have cause the previous to return true
1106 if (toGenericArrayType == null) {
1107 return false;
1108 }
1109
1110 // all types are assignable to themselves
1111 if (toGenericArrayType.equals(type)) {
1112 return true;
1113 }
1114
1115 final Type toComponentType = toGenericArrayType.getGenericComponentType();
1116
1117 if (type instanceof Class<?>) {
1118 final Class<?> cls = (Class<?>) type;
1119
1120 // compare the component types
1121 return cls.isArray()
1122 && isAssignable(cls.getComponentType(), toComponentType, typeVarAssigns);
1123 }
1124
1125 if (type instanceof GenericArrayType) {
1126 // compare the component types
1127 return isAssignable(((GenericArrayType) type).getGenericComponentType(),
1128 toComponentType, typeVarAssigns);
1129 }
1130
1131 if (type instanceof WildcardType) {
1132 // so long as one of the upper bounds is assignable, it's good
1133 for (final Type bound : getImplicitUpperBounds((WildcardType) type)) {
1134 if (isAssignable(bound, toGenericArrayType)) {
1135 return true;
1136 }
1137 }
1138
1139 return false;
1140 }
1141
1142 if (type instanceof TypeVariable<?>) {
1143 // probably should remove the following logic and just return false.
1144 // type variables cannot specify arrays as bounds.
1145 for (final Type bound : getImplicitBounds((TypeVariable<?>) type)) {
1146 if (isAssignable(bound, toGenericArrayType)) {
1147 return true;
1148 }
1149 }
1150
1151 return false;
1152 }
1153
1154 if (type instanceof ParameterizedType) {
1155 // the raw type of a parameterized type is never an array or
1156 // generic array, otherwise the declaration would look like this:
1157 // Collection[]< ? extends String > collection;
1158 return false;
1159 }
1160
1161 throw new IllegalStateException("found an unhandled type: " + type);
1162 }
1163
1164 /**
1165 * Tests if the subject type may be implicitly cast to the target
1166 * parameterized type following the Java generics rules.
1167 *
1168 * @param type the subject type to be assigned to the target type
1169 * @param toParameterizedType the target parameterized type
1170 * @param typeVarAssigns a map with type variables
1171 * @return {@code true} if {@code type} is assignable to {@code toType}.
1172 */
1173 private static boolean isAssignable(final Type type, final ParameterizedType toParameterizedType,
1174 final Map<TypeVariable<?>, Type> typeVarAssigns) {
1175 if (type == null) {
1176 return true;
1177 }
1178
1179 // only a null type can be assigned to null type which
1180 // would have cause the previous to return true
1181 if (toParameterizedType == null) {
1182 return false;
1183 }
1184
1185 // cannot cast an array type to a parameterized type.
1186 if (type instanceof GenericArrayType) {
1187 return false;
1188 }
1189
1190 // all types are assignable to themselves
1191 if (toParameterizedType.equals(type)) {
1192 return true;
1193 }
1194
1195 // get the target type's raw type
1196 final Class<?> toClass = getRawType(toParameterizedType);
1197 // get the subject type's type arguments including owner type arguments
1198 // and supertype arguments up to and including the target class.
1199 final Map<TypeVariable<?>, Type> fromTypeVarAssigns = getTypeArguments(type, toClass, null);
1200
1201 // null means the two types are not compatible
1202 if (fromTypeVarAssigns == null) {
1203 return false;
1204 }
1205
1206 // compatible types, but there's no type arguments. this is equivalent
1207 // to comparing Map< ?, ? > to Map, and raw types are always assignable
1208 // to parameterized types.
1209 if (fromTypeVarAssigns.isEmpty()) {
1210 return true;
1211 }
1212
1213 // get the target type's type arguments including owner type arguments
1214 final Map<TypeVariable<?>, Type> toTypeVarAssigns = getTypeArguments(toParameterizedType,
1215 toClass, typeVarAssigns);
1216
1217 // now to check each type argument
1218 for (final TypeVariable<?> var : toTypeVarAssigns.keySet()) {
1219 final Type toTypeArg = unrollVariableAssignments(var, toTypeVarAssigns);
1220 final Type fromTypeArg = unrollVariableAssignments(var, fromTypeVarAssigns);
1221
1222 if (toTypeArg == null && fromTypeArg instanceof Class) {
1223 continue;
1224 }
1225
1226 // parameters must either be absent from the subject type, within
1227 // the bounds of the wildcard type, or be an exact match to the
1228 // parameters of the target type.
1229 if (fromTypeArg != null && toTypeArg != null
1230 && !toTypeArg.equals(fromTypeArg)
1231 && !(toTypeArg instanceof WildcardType && isAssignable(fromTypeArg, toTypeArg,
1232 typeVarAssigns))) {
1233 return false;
1234 }
1235 }
1236 return true;
1237 }
1238
1239 /**
1240 * Tests if the subject type may be implicitly cast to the target type
1241 * following the Java generics rules. If both types are {@link Class}
1242 * objects, the method returns the result of
1243 * {@link ClassUtils#isAssignable(Class, Class)}.
1244 *
1245 * @param type the subject type to be assigned to the target type
1246 * @param toType the target type
1247 * @return {@code true} if {@code type} is assignable to {@code toType}.
1248 */
1249 public static boolean isAssignable(final Type type, final Type toType) {
1250 return isAssignable(type, toType, null);
1251 }
1252
1253 /**
1254 * Tests if the subject type may be implicitly cast to the target type
1255 * following the Java generics rules.
1256 *
1257 * @param type the subject type to be assigned to the target type
1258 * @param toType the target type
1259 * @param typeVarAssigns optional map of type variable assignments
1260 * @return {@code true} if {@code type} is assignable to {@code toType}.
1261 */
1262 private static boolean isAssignable(final Type type, final Type toType,
1263 final Map<TypeVariable<?>, Type> typeVarAssigns) {
1264 if (toType == null || toType instanceof Class<?>) {
1265 return isAssignable(type, (Class<?>) toType);
1266 }
1267
1268 if (toType instanceof ParameterizedType) {
1269 return isAssignable(type, (ParameterizedType) toType, typeVarAssigns);
1270 }
1271
1272 if (toType instanceof GenericArrayType) {
1273 return isAssignable(type, (GenericArrayType) toType, typeVarAssigns);
1274 }
1275
1276 if (toType instanceof WildcardType) {
1277 return isAssignable(type, (WildcardType) toType, typeVarAssigns);
1278 }
1279
1280 if (toType instanceof TypeVariable<?>) {
1281 return isAssignable(type, (TypeVariable<?>) toType, typeVarAssigns);
1282 }
1283
1284 throw new IllegalStateException("found an unhandled type: " + toType);
1285 }
1286
1287 /**
1288 * Tests if the subject type may be implicitly cast to the target type
1289 * variable following the Java generics rules.
1290 *
1291 * @param type the subject type to be assigned to the target type
1292 * @param toTypeVariable the target type variable
1293 * @param typeVarAssigns a map with type variables
1294 * @return {@code true} if {@code type} is assignable to
1295 * {@code toTypeVariable}.
1296 */
1297 private static boolean isAssignable(final Type type, final TypeVariable<?> toTypeVariable,
1298 final Map<TypeVariable<?>, Type> typeVarAssigns) {
1299 if (type == null) {
1300 return true;
1301 }
1302
1303 // only a null type can be assigned to null type which
1304 // would have cause the previous to return true
1305 if (toTypeVariable == null) {
1306 return false;
1307 }
1308
1309 // all types are assignable to themselves
1310 if (toTypeVariable.equals(type)) {
1311 return true;
1312 }
1313
1314 if (type instanceof TypeVariable<?>) {
1315 // a type variable is assignable to another type variable, if
1316 // and only if the former is the latter, extends the latter, or
1317 // is otherwise a descendant of the latter.
1318 final Type[] bounds = getImplicitBounds((TypeVariable<?>) type);
1319
1320 for (final Type bound : bounds) {
1321 if (isAssignable(bound, toTypeVariable, typeVarAssigns)) {
1322 return true;
1323 }
1324 }
1325 }
1326
1327 if (type instanceof Class<?> || type instanceof ParameterizedType
1328 || type instanceof GenericArrayType || type instanceof WildcardType) {
1329 return false;
1330 }
1331
1332 throw new IllegalStateException("found an unhandled type: " + type);
1333 }
1334
1335 /**
1336 * Tests if the subject type may be implicitly cast to the target
1337 * wildcard type following the Java generics rules.
1338 *
1339 * @param type the subject type to be assigned to the target type
1340 * @param toWildcardType the target wildcard type
1341 * @param typeVarAssigns a map with type variables
1342 * @return {@code true} if {@code type} is assignable to
1343 * {@code toWildcardType}.
1344 */
1345 private static boolean isAssignable(final Type type, final WildcardType toWildcardType,
1346 final Map<TypeVariable<?>, Type> typeVarAssigns) {
1347 if (type == null) {
1348 return true;
1349 }
1350
1351 // only a null type can be assigned to null type which
1352 // would have cause the previous to return true
1353 if (toWildcardType == null) {
1354 return false;
1355 }
1356
1357 // all types are assignable to themselves
1358 if (toWildcardType.equals(type)) {
1359 return true;
1360 }
1361
1362 final Type[] toUpperBounds = getImplicitUpperBounds(toWildcardType);
1363 final Type[] toLowerBounds = getImplicitLowerBounds(toWildcardType);
1364
1365 if (type instanceof WildcardType) {
1366 final WildcardType wildcardType = (WildcardType) type;
1367 final Type[] upperBounds = getImplicitUpperBounds(wildcardType);
1368 final Type[] lowerBounds = getImplicitLowerBounds(wildcardType);
1369
1370 for (Type toBound : toUpperBounds) {
1371 // if there are assignments for unresolved type variables,
1372 // now's the time to substitute them.
1373 toBound = substituteTypeVariables(toBound, typeVarAssigns);
1374
1375 // each upper bound of the subject type has to be assignable to
1376 // each
1377 // upper bound of the target type
1378 for (final Type bound : upperBounds) {
1379 if (!isAssignable(bound, toBound, typeVarAssigns)) {
1380 return false;
1381 }
1382 }
1383 }
1384
1385 for (Type toBound : toLowerBounds) {
1386 // if there are assignments for unresolved type variables,
1387 // now's the time to substitute them.
1388 toBound = substituteTypeVariables(toBound, typeVarAssigns);
1389
1390 // each lower bound of the target type has to be assignable to
1391 // each
1392 // lower bound of the subject type
1393 for (final Type bound : lowerBounds) {
1394 if (!isAssignable(toBound, bound, typeVarAssigns)) {
1395 return false;
1396 }
1397 }
1398 }
1399 return true;
1400 }
1401
1402 for (final Type toBound : toUpperBounds) {
1403 // if there are assignments for unresolved type variables,
1404 // now's the time to substitute them.
1405 if (!isAssignable(type, substituteTypeVariables(toBound, typeVarAssigns),
1406 typeVarAssigns)) {
1407 return false;
1408 }
1409 }
1410
1411 for (final Type toBound : toLowerBounds) {
1412 // if there are assignments for unresolved type variables,
1413 // now's the time to substitute them.
1414 if (!isAssignable(substituteTypeVariables(toBound, typeVarAssigns), type,
1415 typeVarAssigns)) {
1416 return false;
1417 }
1418 }
1419 return true;
1420 }
1421
1422 /**
1423 * Tests if the given value can be assigned to the target type
1424 * following the Java generics rules.
1425 *
1426 * @param value the value to be checked
1427 * @param type the target type
1428 * @return {@code true} if {@code value} is an instance of {@code type}.
1429 */
1430 public static boolean isInstance(final Object value, final Type type) {
1431 if (type == null) {
1432 return false;
1433 }
1434
1435 return value == null ? !(type instanceof Class<?>) || !((Class<?>) type).isPrimitive()
1436 : isAssignable(value.getClass(), type, null);
1437 }
1438
1439 /**
1440 * Maps type variables.
9971441 *
9981442 * @param <T> the generic type of the class in question
9991443 * @param cls the class in question
10401484 }
10411485
10421486 /**
1043 * <p>Get the closest parent type to the
1044 * super class specified by {@code superClass}.</p>
1045 *
1046 * @param cls the class in question
1047 * @param superClass the super class
1048 * @return the closes parent type
1049 */
1050 private static Type getClosestParentType(final Class<?> cls, final Class<?> superClass) {
1051 // only look at the interfaces if the super class is also an interface
1052 if (superClass.isInterface()) {
1053 // get the generic interfaces of the subject class
1054 final Type[] interfaceTypes = cls.getGenericInterfaces();
1055 // will hold the best generic interface match found
1056 Type genericInterface = null;
1057
1058 // find the interface closest to the super class
1059 for (final Type midType : interfaceTypes) {
1060 Class<?> midClass = null;
1061
1062 if (midType instanceof ParameterizedType) {
1063 midClass = getRawType((ParameterizedType) midType);
1064 } else if (midType instanceof Class<?>) {
1065 midClass = (Class<?>) midType;
1066 } else {
1067 throw new IllegalStateException("Unexpected generic"
1068 + " interface type found: " + midType);
1069 }
1070
1071 // check if this interface is further up the inheritance chain
1072 // than the previously found match
1073 if (isAssignable(midClass, superClass)
1074 && isAssignable(genericInterface, (Type) midClass)) {
1075 genericInterface = midType;
1076 }
1077 }
1078
1079 // found a match?
1080 if (genericInterface != null) {
1081 return genericInterface;
1082 }
1083 }
1084
1085 // none of the interfaces were descendants of the target class, so the
1086 // super class has to be one, instead
1087 return cls.getGenericSuperclass();
1088 }
1089
1090 /**
1091 * <p>Checks if the given value can be assigned to the target type
1092 * following the Java generics rules.</p>
1093 *
1094 * @param value the value to be checked
1095 * @param type the target type
1096 * @return {@code true} if {@code value} is an instance of {@code type}.
1097 */
1098 public static boolean isInstance(final Object value, final Type type) {
1099 if (type == null) {
1100 return false;
1101 }
1102
1103 return value == null ? !(type instanceof Class<?>) || !((Class<?>) type).isPrimitive()
1104 : isAssignable(value.getClass(), type, null);
1105 }
1106
1107 /**
1108 * <p>This method strips out the redundant upper bound types in type
1487 * Strips out the redundant upper bound types in type
11091488 * variable types and wildcard types (or it would with wildcard types if
1110 * multiple upper bounds were allowed).</p> <p>Example, with the variable
1111 * type declaration:
1489 * multiple upper bounds were allowed).
1490 *
1491 * <p>
1492 * Example, with the variable type declaration:
1493 * </p>
11121494 *
11131495 * <pre>&lt;K extends java.util.Collection&lt;String&gt; &amp;
11141496 * java.util.List&lt;String&gt;&gt;</pre>
11261508 * redundant types.
11271509 */
11281510 public static Type[] normalizeUpperBounds(final Type[] bounds) {
1129 Validate.notNull(bounds, "null value specified for bounds array");
1511 Validate.notNull(bounds, "bounds");
11301512 // don't bother if there's only one (or none) type
11311513 if (bounds.length < 2) {
11321514 return bounds;
11531535 }
11541536
11551537 /**
1156 * <p>Returns an array containing the sole type of {@link Object} if
1157 * {@link TypeVariable#getBounds()} returns an empty array. Otherwise, it
1158 * returns the result of {@link TypeVariable#getBounds()} passed into
1159 * {@link #normalizeUpperBounds}.</p>
1160 *
1161 * @param typeVariable the subject type variable, not {@code null}
1162 * @return a non-empty array containing the bounds of the type variable.
1163 */
1164 public static Type[] getImplicitBounds(final TypeVariable<?> typeVariable) {
1165 Validate.notNull(typeVariable, "typeVariable is null");
1166 final Type[] bounds = typeVariable.getBounds();
1167
1168 return bounds.length == 0 ? new Type[] { Object.class } : normalizeUpperBounds(bounds);
1169 }
1170
1171 /**
1172 * <p>Returns an array containing the sole value of {@link Object} if
1173 * {@link WildcardType#getUpperBounds()} returns an empty array. Otherwise,
1174 * it returns the result of {@link WildcardType#getUpperBounds()}
1175 * passed into {@link #normalizeUpperBounds}.</p>
1176 *
1177 * @param wildcardType the subject wildcard type, not {@code null}
1178 * @return a non-empty array containing the upper bounds of the wildcard
1179 * type.
1180 */
1181 public static Type[] getImplicitUpperBounds(final WildcardType wildcardType) {
1182 Validate.notNull(wildcardType, "wildcardType is null");
1183 final Type[] bounds = wildcardType.getUpperBounds();
1184
1185 return bounds.length == 0 ? new Type[] { Object.class } : normalizeUpperBounds(bounds);
1186 }
1187
1188 /**
1189 * <p>Returns an array containing a single value of {@code null} if
1190 * {@link WildcardType#getLowerBounds()} returns an empty array. Otherwise,
1191 * it returns the result of {@link WildcardType#getLowerBounds()}.</p>
1192 *
1193 * @param wildcardType the subject wildcard type, not {@code null}
1194 * @return a non-empty array containing the lower bounds of the wildcard
1195 * type.
1196 */
1197 public static Type[] getImplicitLowerBounds(final WildcardType wildcardType) {
1198 Validate.notNull(wildcardType, "wildcardType is null");
1199 final Type[] bounds = wildcardType.getLowerBounds();
1200
1201 return bounds.length == 0 ? new Type[] { null } : bounds;
1202 }
1203
1204 /**
1205 * <p>Determines whether or not specified types satisfy the bounds of their
1538 * Creates a parameterized type instance.
1539 *
1540 * @param rawClass the raw class to create a parameterized type instance for
1541 * @param typeVariableMap the map used for parameterization
1542 * @return {@link ParameterizedType}
1543 * @since 3.2
1544 */
1545 public static final ParameterizedType parameterize(final Class<?> rawClass,
1546 final Map<TypeVariable<?>, Type> typeVariableMap) {
1547 Validate.notNull(rawClass, "rawClass");
1548 Validate.notNull(typeVariableMap, "typeVariableMap");
1549 return parameterizeWithOwner(null, rawClass,
1550 extractTypeArgumentsFrom(typeVariableMap, rawClass.getTypeParameters()));
1551 }
1552
1553 /**
1554 * Creates a parameterized type instance.
1555 *
1556 * @param rawClass the raw class to create a parameterized type instance for
1557 * @param typeArguments the types used for parameterization
1558 * @return {@link ParameterizedType}
1559 * @since 3.2
1560 */
1561 public static final ParameterizedType parameterize(final Class<?> rawClass, final Type... typeArguments) {
1562 return parameterizeWithOwner(null, rawClass, typeArguments);
1563 }
1564
1565 /**
1566 * Formats a {@link ParameterizedType} as a {@link String}.
1567 *
1568 * @param parameterizedType {@code ParameterizedType} to format
1569 * @return String
1570 * @since 3.2
1571 */
1572 private static String parameterizedTypeToString(final ParameterizedType parameterizedType) {
1573 final StringBuilder builder = new StringBuilder();
1574
1575 final Type useOwner = parameterizedType.getOwnerType();
1576 final Class<?> raw = (Class<?>) parameterizedType.getRawType();
1577
1578 if (useOwner == null) {
1579 builder.append(raw.getName());
1580 } else {
1581 if (useOwner instanceof Class<?>) {
1582 builder.append(((Class<?>) useOwner).getName());
1583 } else {
1584 builder.append(useOwner.toString());
1585 }
1586 builder.append('.').append(raw.getSimpleName());
1587 }
1588
1589 final int[] recursiveTypeIndexes = findRecursiveTypes(parameterizedType);
1590
1591 if (recursiveTypeIndexes.length > 0) {
1592 appendRecursiveTypes(builder, recursiveTypeIndexes, parameterizedType.getActualTypeArguments());
1593 } else {
1594 appendAllTo(builder.append('<'), ", ", parameterizedType.getActualTypeArguments()).append('>');
1595 }
1596
1597 return builder.toString();
1598 }
1599
1600 /**
1601 * Creates a parameterized type instance.
1602 *
1603 * @param owner the owning type
1604 * @param rawClass the raw class to create a parameterized type instance for
1605 * @param typeVariableMap the map used for parameterization
1606 * @return {@link ParameterizedType}
1607 * @since 3.2
1608 */
1609 public static final ParameterizedType parameterizeWithOwner(final Type owner, final Class<?> rawClass,
1610 final Map<TypeVariable<?>, Type> typeVariableMap) {
1611 Validate.notNull(rawClass, "rawClass");
1612 Validate.notNull(typeVariableMap, "typeVariableMap");
1613 return parameterizeWithOwner(owner, rawClass,
1614 extractTypeArgumentsFrom(typeVariableMap, rawClass.getTypeParameters()));
1615 }
1616
1617 /**
1618 * Creates a parameterized type instance.
1619 *
1620 * @param owner the owning type
1621 * @param rawClass the raw class to create a parameterized type instance for
1622 * @param typeArguments the types used for parameterization
1623 *
1624 * @return {@link ParameterizedType}
1625 * @since 3.2
1626 */
1627 public static final ParameterizedType parameterizeWithOwner(final Type owner, final Class<?> rawClass,
1628 final Type... typeArguments) {
1629 Validate.notNull(rawClass, "rawClass");
1630 final Type useOwner;
1631 if (rawClass.getEnclosingClass() == null) {
1632 Validate.isTrue(owner == null, "no owner allowed for top-level %s", rawClass);
1633 useOwner = null;
1634 } else if (owner == null) {
1635 useOwner = rawClass.getEnclosingClass();
1636 } else {
1637 Validate.isTrue(isAssignable(owner, rawClass.getEnclosingClass()),
1638 "%s is invalid owner type for parameterized %s", owner, rawClass);
1639 useOwner = owner;
1640 }
1641 Validate.noNullElements(typeArguments, "null type argument at index %s");
1642 Validate.isTrue(rawClass.getTypeParameters().length == typeArguments.length,
1643 "invalid number of type parameters specified: expected %d, got %d", rawClass.getTypeParameters().length,
1644 typeArguments.length);
1645
1646 return new ParameterizedTypeImpl(rawClass, useOwner, typeArguments);
1647 }
1648
1649 /**
1650 * Finds the mapping for {@code type} in {@code typeVarAssigns}.
1651 *
1652 * @param type the type to be replaced
1653 * @param typeVarAssigns the map with type variables
1654 * @return the replaced type
1655 * @throws IllegalArgumentException if the type cannot be substituted
1656 */
1657 private static Type substituteTypeVariables(final Type type, final Map<TypeVariable<?>, Type> typeVarAssigns) {
1658 if (type instanceof TypeVariable<?> && typeVarAssigns != null) {
1659 final Type replacementType = typeVarAssigns.get(type);
1660
1661 if (replacementType == null) {
1662 throw new IllegalArgumentException("missing assignment type for type variable "
1663 + type);
1664 }
1665 return replacementType;
1666 }
1667 return type;
1668 }
1669
1670 /**
1671 * Formats a {@link TypeVariable} including its {@link GenericDeclaration}.
1672 *
1673 * @param typeVariable the type variable to create a String representation for, not {@code null}
1674 * @return String
1675 * @since 3.2
1676 */
1677 public static String toLongString(final TypeVariable<?> typeVariable) {
1678 Validate.notNull(typeVariable, "typeVariable");
1679 final StringBuilder buf = new StringBuilder();
1680 final GenericDeclaration d = typeVariable.getGenericDeclaration();
1681 if (d instanceof Class<?>) {
1682 Class<?> c = (Class<?>) d;
1683 while (true) {
1684 if (c.getEnclosingClass() == null) {
1685 buf.insert(0, c.getName());
1686 break;
1687 }
1688 buf.insert(0, c.getSimpleName()).insert(0, '.');
1689 c = c.getEnclosingClass();
1690 }
1691 } else if (d instanceof Type) {// not possible as of now
1692 buf.append(toString((Type) d));
1693 } else {
1694 buf.append(d);
1695 }
1696 return buf.append(':').append(typeVariableToString(typeVariable)).toString();
1697 }
1698
1699 private static <T> String toString(final T object) {
1700 return object instanceof Type ? toString((Type) object) : object.toString();
1701 }
1702
1703 /**
1704 * Formats a given type as a Java-esque String.
1705 *
1706 * @param type the type to create a String representation for, not {@code null}
1707 * @return String
1708 * @since 3.2
1709 */
1710 public static String toString(final Type type) {
1711 Validate.notNull(type);
1712 if (type instanceof Class<?>) {
1713 return classToString((Class<?>) type);
1714 }
1715 if (type instanceof ParameterizedType) {
1716 return parameterizedTypeToString((ParameterizedType) type);
1717 }
1718 if (type instanceof WildcardType) {
1719 return wildcardTypeToString((WildcardType) type);
1720 }
1721 if (type instanceof TypeVariable<?>) {
1722 return typeVariableToString((TypeVariable<?>) type);
1723 }
1724 if (type instanceof GenericArrayType) {
1725 return genericArrayTypeToString((GenericArrayType) type);
1726 }
1727 throw new IllegalArgumentException(ObjectUtils.identityToString(type));
1728 }
1729
1730 /**
1731 * Determines whether or not specified types satisfy the bounds of their
12061732 * mapped type variables. When a type parameter extends another (such as
12071733 * {@code <T, S extends T>}), uses another as a type parameter (such as
12081734 * {@code <T, S extends Comparable>>}), or otherwise depends on
12091735 * another type variable to be specified, the dependencies must be included
1210 * in {@code typeVarAssigns}.</p>
1211 *
1212 * @param typeVarAssigns specifies the potential types to be assigned to the
1736 * in {@code typeVarAssigns}.
1737 *
1738 * @param typeVariableMap specifies the potential types to be assigned to the
12131739 * type variables, not {@code null}.
12141740 * @return whether or not the types can be assigned to their respective type
12151741 * variables.
12161742 */
1217 public static boolean typesSatisfyVariables(final Map<TypeVariable<?>, Type> typeVarAssigns) {
1218 Validate.notNull(typeVarAssigns, "typeVarAssigns is null");
1743 public static boolean typesSatisfyVariables(final Map<TypeVariable<?>, Type> typeVariableMap) {
1744 Validate.notNull(typeVariableMap, "typeVariableMap");
12191745 // all types must be assignable to all the bounds of their mapped
12201746 // type variable.
1221 for (final Map.Entry<TypeVariable<?>, Type> entry : typeVarAssigns.entrySet()) {
1747 for (final Map.Entry<TypeVariable<?>, Type> entry : typeVariableMap.entrySet()) {
12221748 final TypeVariable<?> typeVar = entry.getKey();
12231749 final Type type = entry.getValue();
12241750
12251751 for (final Type bound : getImplicitBounds(typeVar)) {
1226 if (!isAssignable(type, substituteTypeVariables(bound, typeVarAssigns),
1227 typeVarAssigns)) {
1752 if (!isAssignable(type, substituteTypeVariables(bound, typeVariableMap),
1753 typeVariableMap)) {
12281754 return false;
12291755 }
12301756 }
12331759 }
12341760
12351761 /**
1236 * <p>Transforms the passed in type to a {@link Class} object. Type-checking method of convenience.</p>
1237 *
1238 * @param parameterizedType the type to be converted
1239 * @return the corresponding {@code Class} object
1240 * @throws IllegalStateException if the conversion fails
1241 */
1242 private static Class<?> getRawType(final ParameterizedType parameterizedType) {
1243 final Type rawType = parameterizedType.getRawType();
1244
1245 // check if raw type is a Class object
1246 // not currently necessary, but since the return type is Type instead of
1247 // Class, there's enough reason to believe that future versions of Java
1248 // may return other Type implementations. And type-safety checking is
1249 // rarely a bad idea.
1250 if (!(rawType instanceof Class<?>)) {
1251 throw new IllegalStateException("Wait... What!? Type of rawType: " + rawType);
1252 }
1253
1254 return (Class<?>) rawType;
1255 }
1256
1257 /**
1258 * <p>Get the raw type of a Java type, given its context. Primarily for use
1259 * with {@link TypeVariable}s and {@link GenericArrayType}s, or when you do
1260 * not know the runtime type of {@code type}: if you know you have a
1261 * {@link Class} instance, it is already raw; if you know you have a
1262 * {@link ParameterizedType}, its raw type is only a method call away.</p>
1263 *
1264 * @param type to resolve
1265 * @param assigningType type to be resolved against
1266 * @return the resolved {@link Class} object or {@code null} if
1267 * the type could not be resolved
1268 */
1269 public static Class<?> getRawType(final Type type, final Type assigningType) {
1270 if (type instanceof Class<?>) {
1271 // it is raw, no problem
1272 return (Class<?>) type;
1273 }
1274
1275 if (type instanceof ParameterizedType) {
1276 // simple enough to get the raw type of a ParameterizedType
1277 return getRawType((ParameterizedType) type);
1278 }
1279
1280 if (type instanceof TypeVariable<?>) {
1281 if (assigningType == null) {
1282 return null;
1283 }
1284
1285 // get the entity declaring this type variable
1286 final Object genericDeclaration = ((TypeVariable<?>) type).getGenericDeclaration();
1287
1288 // can't get the raw type of a method- or constructor-declared type
1289 // variable
1290 if (!(genericDeclaration instanceof Class<?>)) {
1291 return null;
1292 }
1293
1294 // get the type arguments for the declaring class/interface based
1295 // on the enclosing type
1296 final Map<TypeVariable<?>, Type> typeVarAssigns = getTypeArguments(assigningType,
1297 (Class<?>) genericDeclaration);
1298
1299 // enclosingType has to be a subclass (or subinterface) of the
1300 // declaring type
1301 if (typeVarAssigns == null) {
1302 return null;
1303 }
1304
1305 // get the argument assigned to this type variable
1306 final Type typeArgument = typeVarAssigns.get(type);
1307
1308 if (typeArgument == null) {
1309 return null;
1310 }
1311
1312 // get the argument for this type variable
1313 return getRawType(typeArgument, assigningType);
1314 }
1315
1316 if (type instanceof GenericArrayType) {
1317 // get raw component type
1318 final Class<?> rawComponentType = getRawType(((GenericArrayType) type)
1319 .getGenericComponentType(), assigningType);
1320
1321 // create array type from raw component type and return its class
1322 return Array.newInstance(rawComponentType, 0).getClass();
1323 }
1324
1325 // (hand-waving) this is not the method you're looking for
1326 if (type instanceof WildcardType) {
1327 return null;
1328 }
1329
1330 throw new IllegalArgumentException("unknown type: " + type);
1331 }
1332
1333 /**
1334 * Learn whether the specified type denotes an array type.
1335 * @param type the type to be checked
1336 * @return {@code true} if {@code type} is an array class or a {@link GenericArrayType}.
1337 */
1338 public static boolean isArrayType(final Type type) {
1339 return type instanceof GenericArrayType || type instanceof Class<?> && ((Class<?>) type).isArray();
1340 }
1341
1342 /**
1343 * Gets the array component type of {@code type}.
1344 * @param type the type to be checked
1345 * @return component type or null if type is not an array type
1346 */
1347 public static Type getArrayComponentType(final Type type) {
1348 if (type instanceof Class<?>) {
1349 final Class<?> cls = (Class<?>) type;
1350 return cls.isArray() ? cls.getComponentType() : null;
1351 }
1352 if (type instanceof GenericArrayType) {
1353 return ((GenericArrayType) type).getGenericComponentType();
1354 }
1355 return null;
1762 * Formats a {@link TypeVariable} as a {@link String}.
1763 *
1764 * @param typeVariable {@code TypeVariable} to format
1765 * @return String
1766 * @since 3.2
1767 */
1768 private static String typeVariableToString(final TypeVariable<?> typeVariable) {
1769 final StringBuilder buf = new StringBuilder(typeVariable.getName());
1770 final Type[] bounds = typeVariable.getBounds();
1771 if (bounds.length > 0 && !(bounds.length == 1 && Object.class.equals(bounds[0]))) {
1772 buf.append(" extends ");
1773 appendAllTo(buf, " & ", typeVariable.getBounds());
1774 }
1775 return buf.toString();
1776 }
1777
1778 /**
1779 * Unrolls variables in a type bounds array.
1780 *
1781 * @param typeArguments assignments {@link Map}
1782 * @param bounds in which to expand variables
1783 * @return {@code bounds} with any variables reassigned
1784 * @since 3.2
1785 */
1786 private static Type[] unrollBounds(final Map<TypeVariable<?>, Type> typeArguments, final Type[] bounds) {
1787 Type[] result = bounds;
1788 int i = 0;
1789 for (; i < result.length; i++) {
1790 final Type unrolled = unrollVariables(typeArguments, result[i]);
1791 if (unrolled == null) {
1792 result = ArrayUtils.remove(result, i--);
1793 } else {
1794 result[i] = unrolled;
1795 }
1796 }
1797 return result;
1798 }
1799
1800 /**
1801 * Look up {@code var} in {@code typeVarAssigns} <em>transitively</em>,
1802 * i.e. keep looking until the value found is <em>not</em> a type variable.
1803 *
1804 * @param typeVariable the type variable to look up
1805 * @param typeVarAssigns the map used for the look up
1806 * @return Type or {@code null} if some variable was not in the map
1807 * @since 3.2
1808 */
1809 private static Type unrollVariableAssignments(TypeVariable<?> typeVariable,
1810 final Map<TypeVariable<?>, Type> typeVarAssigns) {
1811 Type result;
1812 do {
1813 result = typeVarAssigns.get(typeVariable);
1814 if (result instanceof TypeVariable<?> && !result.equals(typeVariable)) {
1815 typeVariable = (TypeVariable<?>) result;
1816 continue;
1817 }
1818 break;
1819 } while (true);
1820 return result;
13561821 }
13571822
13581823 /**
13991864 }
14001865
14011866 /**
1402 * Local helper method to unroll variables in a type bounds array.
1403 *
1404 * @param typeArguments assignments {@link Map}
1405 * @param bounds in which to expand variables
1406 * @return {@code bounds} with any variables reassigned
1407 * @since 3.2
1408 */
1409 private static Type[] unrollBounds(final Map<TypeVariable<?>, Type> typeArguments, final Type[] bounds) {
1410 Type[] result = bounds;
1411 int i = 0;
1412 for (; i < result.length; i++) {
1413 final Type unrolled = unrollVariables(typeArguments, result[i]);
1414 if (unrolled == null) {
1415 result = ArrayUtils.remove(result, i--);
1416 } else {
1417 result[i] = unrolled;
1418 }
1419 }
1420 return result;
1421 }
1422
1423 /**
1424 * Learn, recursively, whether any of the type parameters associated with {@code type} are bound to variables.
1425 *
1426 * @param type the type to check for type variables
1427 * @return boolean
1428 * @since 3.2
1429 */
1430 public static boolean containsTypeVariables(final Type type) {
1431 if (type instanceof TypeVariable<?>) {
1432 return true;
1433 }
1434 if (type instanceof Class<?>) {
1435 return ((Class<?>) type).getTypeParameters().length > 0;
1436 }
1437 if (type instanceof ParameterizedType) {
1438 for (final Type arg : ((ParameterizedType) type).getActualTypeArguments()) {
1439 if (containsTypeVariables(arg)) {
1440 return true;
1441 }
1442 }
1443 return false;
1444 }
1445 if (type instanceof WildcardType) {
1446 final WildcardType wild = (WildcardType) type;
1447 return containsTypeVariables(getImplicitLowerBounds(wild)[0])
1448 || containsTypeVariables(getImplicitUpperBounds(wild)[0]);
1449 }
1450 return false;
1451 }
1452
1453 /**
1454 * Create a parameterized type instance.
1455 *
1456 * @param rawClass the raw class to create a parameterized type instance for
1457 * @param typeArguments the types used for parameterization
1458 * @return {@link ParameterizedType}
1459 * @since 3.2
1460 */
1461 public static final ParameterizedType parameterize(final Class<?> rawClass, final Type... typeArguments) {
1462 return parameterizeWithOwner(null, rawClass, typeArguments);
1463 }
1464
1465 /**
1466 * Create a parameterized type instance.
1467 *
1468 * @param rawClass the raw class to create a parameterized type instance for
1469 * @param typeArgMappings the mapping used for parameterization
1470 * @return {@link ParameterizedType}
1471 * @since 3.2
1472 */
1473 public static final ParameterizedType parameterize(final Class<?> rawClass,
1474 final Map<TypeVariable<?>, Type> typeArgMappings) {
1475 Validate.notNull(rawClass, "raw class is null");
1476 Validate.notNull(typeArgMappings, "typeArgMappings is null");
1477 return parameterizeWithOwner(null, rawClass,
1478 extractTypeArgumentsFrom(typeArgMappings, rawClass.getTypeParameters()));
1479 }
1480
1481 /**
1482 * Create a parameterized type instance.
1483 *
1484 * @param owner the owning type
1485 * @param rawClass the raw class to create a parameterized type instance for
1486 * @param typeArguments the types used for parameterization
1487 *
1488 * @return {@link ParameterizedType}
1489 * @since 3.2
1490 */
1491 public static final ParameterizedType parameterizeWithOwner(final Type owner, final Class<?> rawClass,
1492 final Type... typeArguments) {
1493 Validate.notNull(rawClass, "raw class is null");
1494 final Type useOwner;
1495 if (rawClass.getEnclosingClass() == null) {
1496 Validate.isTrue(owner == null, "no owner allowed for top-level %s", rawClass);
1497 useOwner = null;
1498 } else if (owner == null) {
1499 useOwner = rawClass.getEnclosingClass();
1500 } else {
1501 Validate.isTrue(isAssignable(owner, rawClass.getEnclosingClass()),
1502 "%s is invalid owner type for parameterized %s", owner, rawClass);
1503 useOwner = owner;
1504 }
1505 Validate.noNullElements(typeArguments, "null type argument at index %s");
1506 Validate.isTrue(rawClass.getTypeParameters().length == typeArguments.length,
1507 "invalid number of type parameters specified: expected %d, got %d", rawClass.getTypeParameters().length,
1508 typeArguments.length);
1509
1510 return new ParameterizedTypeImpl(rawClass, useOwner, typeArguments);
1511 }
1512
1513 /**
1514 * Create a parameterized type instance.
1515 *
1516 * @param owner the owning type
1517 * @param rawClass the raw class to create a parameterized type instance for
1518 * @param typeArgMappings the mapping used for parameterization
1519 * @return {@link ParameterizedType}
1520 * @since 3.2
1521 */
1522 public static final ParameterizedType parameterizeWithOwner(final Type owner, final Class<?> rawClass,
1523 final Map<TypeVariable<?>, Type> typeArgMappings) {
1524 Validate.notNull(rawClass, "raw class is null");
1525 Validate.notNull(typeArgMappings, "typeArgMappings is null");
1526 return parameterizeWithOwner(owner, rawClass,
1527 extractTypeArgumentsFrom(typeArgMappings, rawClass.getTypeParameters()));
1528 }
1529
1530 /**
1531 * Helper method to establish the formal parameters for a parameterized type.
1532 * @param mappings map containing the assignments
1533 * @param variables expected map keys
1534 * @return array of map values corresponding to specified keys
1535 */
1536 private static Type[] extractTypeArgumentsFrom(final Map<TypeVariable<?>, Type> mappings, final TypeVariable<?>[] variables) {
1537 final Type[] result = new Type[variables.length];
1538 int index = 0;
1539 for (final TypeVariable<?> var : variables) {
1540 Validate.isTrue(mappings.containsKey(var), "missing argument mapping for %s", toString(var));
1541 result[index++] = mappings.get(var);
1542 }
1543 return result;
1544 }
1545
1546 /**
15471867 * Gets a {@link WildcardTypeBuilder}.
1868 *
15481869 * @return {@link WildcardTypeBuilder}
15491870 * @since 3.2
15501871 */
15531874 }
15541875
15551876 /**
1556 * Create a generic array type instance.
1557 *
1558 * @param componentType the type of the elements of the array. For example the component type of {@code boolean[]}
1559 * is {@code boolean}
1560 * @return {@link GenericArrayType}
1561 * @since 3.2
1562 */
1563 public static GenericArrayType genericArrayType(final Type componentType) {
1564 return new GenericArrayTypeImpl(Validate.notNull(componentType, "componentType is null"));
1565 }
1566
1567 /**
1568 * Check equality of types.
1569 *
1570 * @param type1 the first type
1571 * @param type2 the second type
1572 * @return boolean
1573 * @since 3.2
1574 */
1575 public static boolean equals(final Type type1, final Type type2) {
1576 if (Objects.equals(type1, type2)) {
1577 return true;
1578 }
1579 if (type1 instanceof ParameterizedType) {
1580 return equals((ParameterizedType) type1, type2);
1581 }
1582 if (type1 instanceof GenericArrayType) {
1583 return equals((GenericArrayType) type1, type2);
1584 }
1585 if (type1 instanceof WildcardType) {
1586 return equals((WildcardType) type1, type2);
1587 }
1588 return false;
1589 }
1590
1591 /**
1592 * Learn whether {@code t} equals {@code p}.
1593 * @param parameterizedType LHS
1594 * @param type RHS
1595 * @return boolean
1596 * @since 3.2
1597 */
1598 private static boolean equals(final ParameterizedType parameterizedType, final Type type) {
1599 if (type instanceof ParameterizedType) {
1600 final ParameterizedType other = (ParameterizedType) type;
1601 if (equals(parameterizedType.getRawType(), other.getRawType())
1602 && equals(parameterizedType.getOwnerType(), other.getOwnerType())) {
1603 return equals(parameterizedType.getActualTypeArguments(), other.getActualTypeArguments());
1604 }
1605 }
1606 return false;
1607 }
1608
1609 /**
1610 * Learn whether {@code t} equals {@code a}.
1611 * @param genericArrayType LHS
1612 * @param type RHS
1613 * @return boolean
1614 * @since 3.2
1615 */
1616 private static boolean equals(final GenericArrayType genericArrayType, final Type type) {
1617 return type instanceof GenericArrayType
1618 && equals(genericArrayType.getGenericComponentType(), ((GenericArrayType) type).getGenericComponentType());
1619 }
1620
1621 /**
1622 * Learn whether {@code t} equals {@code w}.
1623 * @param wildcardType LHS
1624 * @param type RHS
1625 * @return boolean
1626 * @since 3.2
1627 */
1628 private static boolean equals(final WildcardType wildcardType, final Type type) {
1629 if (type instanceof WildcardType) {
1630 final WildcardType other = (WildcardType) type;
1631 return equals(getImplicitLowerBounds(wildcardType), getImplicitLowerBounds(other))
1632 && equals(getImplicitUpperBounds(wildcardType), getImplicitUpperBounds(other));
1633 }
1634 return false;
1635 }
1636
1637 /**
1638 * Learn whether {@code t1} equals {@code t2}.
1639 * @param type1 LHS
1640 * @param type2 RHS
1641 * @return boolean
1642 * @since 3.2
1643 */
1644 private static boolean equals(final Type[] type1, final Type[] type2) {
1645 if (type1.length == type2.length) {
1646 for (int i = 0; i < type1.length; i++) {
1647 if (!equals(type1[i], type2[i])) {
1648 return false;
1649 }
1650 }
1651 return true;
1652 }
1653 return false;
1654 }
1655
1656 /**
1657 * Present a given type as a Java-esque String.
1658 *
1659 * @param type the type to create a String representation for, not {@code null}
1660 * @return String
1661 * @since 3.2
1662 */
1663 public static String toString(final Type type) {
1664 Validate.notNull(type);
1665 if (type instanceof Class<?>) {
1666 return classToString((Class<?>) type);
1667 }
1668 if (type instanceof ParameterizedType) {
1669 return parameterizedTypeToString((ParameterizedType) type);
1670 }
1671 if (type instanceof WildcardType) {
1672 return wildcardTypeToString((WildcardType) type);
1673 }
1674 if (type instanceof TypeVariable<?>) {
1675 return typeVariableToString((TypeVariable<?>) type);
1676 }
1677 if (type instanceof GenericArrayType) {
1678 return genericArrayTypeToString((GenericArrayType) type);
1679 }
1680 throw new IllegalArgumentException(ObjectUtils.identityToString(type));
1681 }
1682
1683 /**
1684 * Format a {@link TypeVariable} including its {@link GenericDeclaration}.
1685 *
1686 * @param var the type variable to create a String representation for, not {@code null}
1687 * @return String
1688 * @since 3.2
1689 */
1690 public static String toLongString(final TypeVariable<?> var) {
1691 Validate.notNull(var, "var is null");
1692 final StringBuilder buf = new StringBuilder();
1693 final GenericDeclaration d = var.getGenericDeclaration();
1694 if (d instanceof Class<?>) {
1695 Class<?> c = (Class<?>) d;
1696 while (true) {
1697 if (c.getEnclosingClass() == null) {
1698 buf.insert(0, c.getName());
1699 break;
1700 }
1701 buf.insert(0, c.getSimpleName()).insert(0, '.');
1702 c = c.getEnclosingClass();
1703 }
1704 } else if (d instanceof Type) {// not possible as of now
1705 buf.append(toString((Type) d));
1706 } else {
1707 buf.append(d);
1708 }
1709 return buf.append(':').append(typeVariableToString(var)).toString();
1710 }
1711
1712 /**
1713 * Wrap the specified {@link Type} in a {@link Typed} wrapper.
1714 *
1715 * @param <T> inferred generic type
1716 * @param type to wrap
1717 * @return Typed&lt;T&gt;
1718 * @since 3.2
1719 */
1720 public static <T> Typed<T> wrap(final Type type) {
1721 return () -> type;
1722 }
1723
1724 /**
1725 * Wrap the specified {@link Class} in a {@link Typed} wrapper.
1726 *
1727 * @param <T> generic type
1728 * @param type to wrap
1729 * @return Typed&lt;T&gt;
1730 * @since 3.2
1731 */
1732 public static <T> Typed<T> wrap(final Class<T> type) {
1733 return wrap((Type) type);
1734 }
1735
1736 /**
1737 * Format a {@link Class} as a {@link String}.
1738 * @param cls {@code Class} to format
1739 * @return String
1740 * @since 3.2
1741 */
1742 private static String classToString(final Class<?> cls) {
1743 if (cls.isArray()) {
1744 return toString(cls.getComponentType()) + "[]";
1745 }
1746
1747 final StringBuilder buf = new StringBuilder();
1748
1749 if (cls.getEnclosingClass() != null) {
1750 buf.append(classToString(cls.getEnclosingClass())).append('.').append(cls.getSimpleName());
1751 } else {
1752 buf.append(cls.getName());
1753 }
1754 if (cls.getTypeParameters().length > 0) {
1755 buf.append('<');
1756 appendAllTo(buf, ", ", cls.getTypeParameters());
1757 buf.append('>');
1758 }
1759 return buf.toString();
1760 }
1761
1762 /**
1763 * Format a {@link TypeVariable} as a {@link String}.
1764 * @param typeVariable {@code TypeVariable} to format
1765 * @return String
1766 * @since 3.2
1767 */
1768 private static String typeVariableToString(final TypeVariable<?> typeVariable) {
1769 final StringBuilder buf = new StringBuilder(typeVariable.getName());
1770 final Type[] bounds = typeVariable.getBounds();
1771 if (bounds.length > 0 && !(bounds.length == 1 && Object.class.equals(bounds[0]))) {
1772 buf.append(" extends ");
1773 appendAllTo(buf, " & ", typeVariable.getBounds());
1774 }
1775 return buf.toString();
1776 }
1777
1778 /**
1779 * Format a {@link ParameterizedType} as a {@link String}.
1780 * @param parameterizedType {@code ParameterizedType} to format
1781 * @return String
1782 * @since 3.2
1783 */
1784 private static String parameterizedTypeToString(final ParameterizedType parameterizedType) {
1785 final StringBuilder builder = new StringBuilder();
1786
1787 final Type useOwner = parameterizedType.getOwnerType();
1788 final Class<?> raw = (Class<?>) parameterizedType.getRawType();
1789
1790 if (useOwner == null) {
1791 builder.append(raw.getName());
1792 } else {
1793 if (useOwner instanceof Class<?>) {
1794 builder.append(((Class<?>) useOwner).getName());
1795 } else {
1796 builder.append(useOwner.toString());
1797 }
1798 builder.append('.').append(raw.getSimpleName());
1799 }
1800
1801 final int[] recursiveTypeIndexes = findRecursiveTypes(parameterizedType);
1802
1803 if (recursiveTypeIndexes.length > 0) {
1804 appendRecursiveTypes(builder, recursiveTypeIndexes, parameterizedType.getActualTypeArguments());
1805 } else {
1806 appendAllTo(builder.append('<'), ", ", parameterizedType.getActualTypeArguments()).append('>');
1807 }
1808
1809 return builder.toString();
1810 }
1811
1812 private static void appendRecursiveTypes(final StringBuilder builder, final int[] recursiveTypeIndexes,
1813 final Type[] argumentTypes) {
1814 for (int i = 0; i < recursiveTypeIndexes.length; i++) {
1815 appendAllTo(builder.append('<'), ", ", argumentTypes[i].toString()).append('>');
1816 }
1817
1818 final Type[] argumentsFiltered = ArrayUtils.removeAll(argumentTypes, recursiveTypeIndexes);
1819
1820 if (argumentsFiltered.length > 0) {
1821 appendAllTo(builder.append('<'), ", ", argumentsFiltered).append('>');
1822 }
1823 }
1824
1825 private static int[] findRecursiveTypes(final ParameterizedType parameterizedType) {
1826 final Type[] filteredArgumentTypes = Arrays.copyOf(parameterizedType.getActualTypeArguments(),
1827 parameterizedType.getActualTypeArguments().length);
1828 int[] indexesToRemove = {};
1829 for (int i = 0; i < filteredArgumentTypes.length; i++) {
1830 if (filteredArgumentTypes[i] instanceof TypeVariable<?>) {
1831 if (containsVariableTypeSameParametrizedTypeBound(((TypeVariable<?>) filteredArgumentTypes[i]),
1832 parameterizedType)) {
1833 indexesToRemove = ArrayUtils.add(indexesToRemove, i);
1834 }
1835 }
1836 }
1837 return indexesToRemove;
1838 }
1839
1840 private static boolean containsVariableTypeSameParametrizedTypeBound(final TypeVariable<?> typeVariable,
1841 final ParameterizedType parameterizedType) {
1842 return ArrayUtils.contains(typeVariable.getBounds(), parameterizedType);
1843 }
1844
1845 /**
1846 * Format a {@link WildcardType} as a {@link String}.
1877 * Formats a {@link WildcardType} as a {@link String}.
1878 *
18471879 * @param wildcardType {@code WildcardType} to format
18481880 * @return String
18491881 * @since 3.2
18611893 }
18621894
18631895 /**
1864 * Format a {@link GenericArrayType} as a {@link String}.
1865 * @param genericArrayType {@code GenericArrayType} to format
1866 * @return String
1867 * @since 3.2
1868 */
1869 private static String genericArrayTypeToString(final GenericArrayType genericArrayType) {
1870 return String.format("%s[]", toString(genericArrayType.getGenericComponentType()));
1871 }
1872
1873 /**
1874 * Append {@code types} to {@code builder} with separator {@code sep}.
1875 * @param builder destination
1876 * @param sep separator
1877 * @param types to append
1878 * @return {@code builder}
1879 * @since 3.2
1880 */
1881 private static <T> StringBuilder appendAllTo(final StringBuilder builder, final String sep,
1882 @SuppressWarnings("unchecked") final T... types) {
1883 Validate.notEmpty(Validate.noNullElements(types));
1884 if (types.length > 0) {
1885 builder.append(toString(types[0]));
1886 for (int i = 1; i < types.length; i++) {
1887 builder.append(sep).append(toString(types[i]));
1888 }
1889 }
1890 return builder;
1891 }
1892
1893 private static <T> String toString(final T object) {
1894 return object instanceof Type ? toString((Type) object) : object.toString();
1896 * Wraps the specified {@link Class} in a {@link Typed} wrapper.
1897 *
1898 * @param <T> generic type
1899 * @param type to wrap
1900 * @return Typed&lt;T&gt;
1901 * @since 3.2
1902 */
1903 public static <T> Typed<T> wrap(final Class<T> type) {
1904 return wrap((Type) type);
1905 }
1906
1907 /**
1908 * Wraps the specified {@link Type} in a {@link Typed} wrapper.
1909 *
1910 * @param <T> inferred generic type
1911 * @param type to wrap
1912 * @return Typed&lt;T&gt;
1913 * @since 3.2
1914 */
1915 public static <T> Typed<T> wrap(final Type type) {
1916 return () -> type;
1917 }
1918
1919 /**
1920 * {@code TypeUtils} instances should NOT be constructed in standard
1921 * programming. Instead, the class should be used as
1922 * {@code TypeUtils.isAssignable(cls, toClass)}.
1923 * <p>
1924 * This constructor is public to permit tools that require a JavaBean instance
1925 * to operate.
1926 * </p>
1927 */
1928 public TypeUtils() {
18951929 }
18961930
18971931 }
1515 */
1616 package org.apache.commons.lang3.stream;
1717
18 import java.lang.reflect.Array;
1918 import java.util.ArrayList;
2019 import java.util.Collection;
2120 import java.util.Collections;
2221 import java.util.List;
22 import java.util.Objects;
2323 import java.util.Set;
2424 import java.util.function.BiConsumer;
2525 import java.util.function.BinaryOperator;
3131 import java.util.stream.Collectors;
3232 import java.util.stream.Stream;
3333
34 import org.apache.commons.lang3.ArrayUtils;
3435 import org.apache.commons.lang3.function.Failable;
3536 import org.apache.commons.lang3.function.FailableConsumer;
3637 import org.apache.commons.lang3.function.FailableFunction;
4142 * {@code java.util.stream} package, or more generally, with Java 8 lambdas. More
4243 * specifically, it attempts to address the fact that lambdas are supposed
4344 * not to throw Exceptions, at least not checked Exceptions, AKA instances
44 * of {@link Exception}. This enforces the use of constructs like
45 * of {@link Exception}. This enforces the use of constructs like:
4546 * <pre>
46 * Consumer&lt;java.lang.reflect.Method&gt; consumer = (m) -&gt; {
47 * Consumer&lt;java.lang.reflect.Method&gt; consumer = m -&gt; {
4748 * try {
4849 * m.invoke(o, args);
4950 * } catch (Throwable t) {
5253 * };
5354 * stream.forEach(consumer);
5455 * </pre>
56 * <p>
5557 * Using a {@link FailableStream}, this can be rewritten as follows:
58 * </p>
5659 * <pre>
5760 * Streams.failable(stream).forEach((m) -&gt; m.invoke(o, args));
5861 * </pre>
6568 */
6669 public class Streams {
6770
71 /**
72 * A Collector type for arrays.
73 *
74 * @param <O> The array type.
75 */
6876 public static class ArrayCollector<O> implements Collector<O, List<O>, O[]> {
6977 private static final Set<Characteristics> characteristics = Collections.emptySet();
7078 private final Class<O> elementType;
7179
80 /**
81 * Constructs a new instance for the given element type.
82 *
83 * @param elementType The element type.
84 */
7285 public ArrayCollector(final Class<O> elementType) {
73 this.elementType = elementType;
86 this.elementType = Objects.requireNonNull(elementType, "elementType");
7487 }
7588
7689 @Override
93106
94107 @Override
95108 public Function<List<O>, O[]> finisher() {
96 return list -> {
97 @SuppressWarnings("unchecked")
98 final O[] array = (O[]) Array.newInstance(elementType, list.size());
99 return list.toArray(array);
100 };
109 return list -> list.toArray(ArrayUtils.newInstance(elementType, list.size()));
101110 }
102111
103112 @Override
132141 *
133142 * <p>
134143 * This is a short-circuiting terminal operation.
144 * </p>
135145 *
136146 * Note This method evaluates the <em>universal quantification</em> of the predicate over the elements of
137147 * the stream (for all x P(x)). If the stream is empty, the quantification is said to be <em>vacuously
153163 *
154164 * <p>
155165 * This is a short-circuiting terminal operation.
166 * </p>
156167 *
157168 * Note This method evaluates the <em>existential quantification</em> of the predicate over the elements of
158169 * the stream (for some x P(x)).
165176 return stream().anyMatch(Failable.asPredicate(predicate));
166177 }
167178
179 /**
180 * Throws IllegalStateException if this stream is already terminated.
181 *
182 * @throws IllegalStateException if this stream is already terminated.
183 */
168184 protected void assertNotTerminated() {
169185 if (terminated) {
170186 throw new IllegalStateException("This stream is already terminated.");
181197 * If the underlying stream is parallel, and the {@code Collector} is concurrent, and either the stream is
182198 * unordered or the collector is unordered, then a concurrent reduction will be performed (see {@link Collector}
183199 * for details on concurrent reduction.)
200 * </p>
184201 *
185202 * <p>
186203 * This is a terminal operation.
204 * </p>
187205 *
188206 * <p>
189207 * When executed in parallel, multiple intermediate results may be instantiated, populated, and merged so as to
190208 * maintain isolation of mutable data structures. Therefore, even when executed in parallel with non-thread-safe
191209 * data structures (such as {@code ArrayList}), no additional synchronization is needed for a parallel
192210 * reduction.
211 * </p>
193212 *
194213 * Note The following will accumulate strings into an ArrayList:
195214 *
201220 *
202221 * <p>
203222 * The following will classify {@code Person} objects by city:
223 * </p>
204224 *
205225 * <pre>
206226 * {@code
211231 * <p>
212232 * The following will classify {@code Person} objects by state and city, cascading two {@code Collector}s
213233 * together:
234 * </p>
214235 *
215236 * <pre>
216237 * {@code
249270 * <p>
250271 * Like {@link #reduce(Object, BinaryOperator)}, {@code collect} operations can be parallelized without
251272 * requiring additional synchronization.
273 * </p>
252274 *
253275 * <p>
254276 * This is a terminal operation.
277 * </p>
255278 *
256279 * Note There are many existing classes in the JDK whose signatures are well-suited for use with method
257280 * references as arguments to {@code collect()}. For example, the following will accumulate strings into an
265288 *
266289 * <p>
267290 * The following will take a stream of strings and concatenates them into a single string:
291 * </p>
268292 *
269293 * <pre>
270294 * {@code
294318 *
295319 * <p>
296320 * This is an intermediate operation.
321 * </p>
297322 *
298323 * @param predicate a non-interfering, stateless predicate to apply to each element to determine if it should be
299324 * included.
310335 *
311336 * <p>
312337 * This is a terminal operation.
338 * </p>
313339 *
314340 * <p>
315341 * The behavior of this operation is explicitly nondeterministic. For parallel stream pipelines, this operation
317343 * benefit of parallelism. For any given element, the action may be performed at whatever time and in whatever
318344 * thread the library chooses. If the action accesses shared state, it is responsible for providing the required
319345 * synchronization.
346 * </p>
320347 *
321348 * @param action a non-interfering action to perform on the elements
322349 */
325352 stream().forEach(Failable.asConsumer(action));
326353 }
327354
355 /**
356 * Marks this stream as terminated.
357 *
358 * @throws IllegalStateException if this stream is already terminated.
359 */
328360 protected void makeTerminated() {
329361 assertNotTerminated();
330362 terminated = true;
335367 *
336368 * <p>
337369 * This is an intermediate operation.
370 * </p>
338371 *
339372 * @param <R> The element type of the new stream
340373 * @param mapper A non-interfering, stateless function to apply to each element
364397 * The {@code identity} value must be an identity for the accumulator function. This means that for all
365398 * {@code t}, {@code accumulator.apply(identity, t)} is equal to {@code t}. The {@code accumulator} function
366399 * must be an associative function.
400 * </p>
367401 *
368402 * <p>
369403 * This is a terminal operation.
404 * </p>
370405 *
371406 * Note Sum, min, max, average, and string concatenation are all special cases of reduction. Summing a
372407 * stream of numbers can be expressed as:
389424 * While this may seem a more roundabout way to perform an aggregation compared to simply mutating a running
390425 * total in a loop, reduction operations parallelize more gracefully, without needing additional synchronization
391426 * and with greatly reduced risk of data races.
427 * </p>
392428 *
393429 * @param identity the identity value for the accumulating function
394430 * @param accumulator an associative, non-interfering, stateless function for combining two values
407443 public Stream<O> stream() {
408444 return stream;
409445 }
446 }
447
448 private static <O> Stream<O> nullSafeStream(final Collection<O> collection) {
449 return collection == null ? Stream.empty() : collection.stream();
450 }
451
452 /**
453 * Null-safe version of {@link Stream#of(Object[])}.
454 *
455 * @param <T> the type of stream elements.
456 * @param values the elements of the new stream, may be {@code null}.
457 * @return the new stream on {@code values} or {@link Stream#empty()}.
458 * @since 3.13.0
459 */
460 @SafeVarargs // Creating a stream from an array is safe
461 public static <T> Stream<T> of(final T... values) {
462 return values == null ? Stream.empty() : Stream.of(values);
410463 }
411464
412465 /**
446499 * @return The {@link FailableStream}, which has been created by converting the stream.
447500 */
448501 public static <O> FailableStream<O> stream(final Collection<O> stream) {
449 return stream(stream.stream());
502 return stream(nullSafeStream(stream));
450503 }
451504
452505 /**
2525 import java.util.Map;
2626 import java.util.Objects;
2727
28 import org.apache.commons.lang3.LocaleUtils;
2829 import org.apache.commons.lang3.ObjectUtils;
2930 import org.apache.commons.lang3.Validate;
3031
3738 * and the formats supported by {@code java.text.MessageFormat} can be overridden
3839 * at the format and/or format style level (see MessageFormat). A "format element"
3940 * embedded in the message pattern is specified (<b>()?</b> signifies optionality):<br>
40 * {@code {}<i>argument-number</i><b>(</b>{@code ,}<i>format-name</i><b>
41 * (</b>{@code ,}<i>format-style</i><b>)?)?</b>{@code }}
41 * <code>{</code><i>argument-number</i><b>(</b>{@code ,}<i>format-name</i><b>
42 * (</b>{@code ,}<i>format-style</i><b>)?)?</b><code>}</code>
4243 *
4344 * <p>
4445 * <i>format-name</i> and <i>format-style</i> values are trimmed of surrounding whitespace
117118 /**
118119 * Create a new ExtendedMessageFormat.
119120 *
120 * @param pattern the pattern to use, not null
121 * @param locale the locale to use, not null
122 * @param registry the registry of format factories, may be null
121 * @param pattern the pattern to use, not null.
122 * @param locale the locale to use.
123 * @param registry the registry of format factories, may be null.
123124 * @throws IllegalArgumentException in case of a bad pattern.
124125 */
125126 public ExtendedMessageFormat(final String pattern, final Locale locale, final Map<String, ? extends FormatFactory> registry) {
126127 super(DUMMY_PATTERN);
127 setLocale(locale);
128 setLocale(LocaleUtils.toLocale(locale));
128129 this.registry = registry;
129130 applyPattern(pattern);
130131 }
5353 * instance to operate.</p>
5454 */
5555 public FormattableUtils() {
56 super();
5756 }
5857
59 //-----------------------------------------------------------------------
6058 /**
6159 * Gets the default formatted representation of the specified
6260 * {@code Formattable}.
100100 /** The null text. */
101101 private String nullText;
102102
103 //-----------------------------------------------------------------------
104103 /**
105104 * Constructor that creates an empty builder initial capacity 32 characters.
106105 */
114113 * @param initialCapacity the initial capacity, zero or less will be converted to 32
115114 */
116115 public StrBuilder(int initialCapacity) {
117 super();
118116 if (initialCapacity <= 0) {
119117 initialCapacity = CAPACITY;
120118 }
128126 * @param str the string to copy, null treated as blank string
129127 */
130128 public StrBuilder(final String str) {
131 super();
132129 if (str == null) {
133130 buffer = new char[CAPACITY];
134131 } else {
137134 }
138135 }
139136
140 //-----------------------------------------------------------------------
141137 /**
142138 * Gets the text to be appended when a new line is added.
143139 *
158154 return this;
159155 }
160156
161 //-----------------------------------------------------------------------
162157 /**
163158 * Gets the text to be appended when null is added.
164159 *
182177 return this;
183178 }
184179
185 //-----------------------------------------------------------------------
186180 /**
187181 * Gets the length of the string builder.
188182 *
219213 return this;
220214 }
221215
222 //-----------------------------------------------------------------------
223216 /**
224217 * Gets the current size of the internal character array buffer.
225218 *
258251 return this;
259252 }
260253
261 //-----------------------------------------------------------------------
262254 /**
263255 * Gets the length of the string builder.
264256 * <p>
284276 }
285277
286278 /**
279 * Checks is the string builder is not empty (convenience Collections API style method).
280 * <p>
281 * This method is the same as checking {@link #length()} and is provided to match the
282 * API of Collections.
283 *
284 * @return {@code true} if the size is greater than {@code 0}.
285 * @since 3.12.0
286 */
287 public boolean isNotEmpty() {
288 return size > 0;
289 }
290
291 /**
287292 * Clears the string builder (convenience Collections API style method).
288293 * <p>
289294 * This method does not reduce the size of the internal character buffer.
299304 return this;
300305 }
301306
302 //-----------------------------------------------------------------------
303307 /**
304308 * Gets the character at the specified index.
305309 *
352356 return this;
353357 }
354358
355 //-----------------------------------------------------------------------
356359 /**
357360 * Copies the builder's character array into a new character array.
358361 *
426429 System.arraycopy(buffer, startIndex, destination, destinationIndex, endIndex - startIndex);
427430 }
428431
429 //-----------------------------------------------------------------------
430432 /**
431433 * If possible, reads chars from the provided {@link Readable} directly into underlying
432434 * character buffer without making extra copies.
433435 *
434436 * @param readable object to read from
435437 * @return the number of characters read
436 * @throws IOException if an I/O error occurs
438 * @throws IOException if an I/O error occurs.
437439 *
438440 * @since 3.4
439441 * @see #appendTo(Appendable)
468470 return size - oldSize;
469471 }
470472
471 //-----------------------------------------------------------------------
472473 /**
473474 * Appends the new line string to this string builder.
474475 * <p>
957958 return append(String.valueOf(value));
958959 }
959960
960 //-----------------------------------------------------------------------
961961 /**
962962 * Appends an object followed by a new line to this string builder.
963963 * Appending null will call {@link #appendNull()}.
11791179 return append(value).appendNewLine();
11801180 }
11811181
1182 //-----------------------------------------------------------------------
11831182 /**
11841183 * Appends each item in an array to the builder without any separators.
11851184 * Appending a null array will have no effect.
12411240 return this;
12421241 }
12431242
1244 //-----------------------------------------------------------------------
12451243 /**
12461244 * Appends an array placing separators between each value, but
12471245 * not before the first or after the last.
13111309 return this;
13121310 }
13131311
1314 //-----------------------------------------------------------------------
13151312 /**
13161313 * Appends a separator if the builder is currently non-empty.
13171314 * Appending a null separator will have no effect.
13911388 * @since 2.3
13921389 */
13931390 public StrBuilder appendSeparator(final char separator) {
1394 if (size() > 0) {
1391 if (isNotEmpty()) {
13951392 append(separator);
13961393 }
13971394 return this;
14091406 * @since 2.5
14101407 */
14111408 public StrBuilder appendSeparator(final char standard, final char defaultIfEmpty) {
1412 if (size() > 0) {
1409 if (isNotEmpty()) {
14131410 append(standard);
14141411 } else {
14151412 append(defaultIfEmpty);
14731470 return this;
14741471 }
14751472
1476 //-----------------------------------------------------------------------
14771473 /**
14781474 * Appends the pad character to the builder the specified number of times.
14791475 *
14911487 return this;
14921488 }
14931489
1494 //-----------------------------------------------------------------------
14951490 /**
14961491 * Appends an object to the builder padding on the left to a fixed width.
14971492 * The {@code toString} of the object is used.
15861581 return appendFixedWidthPadRight(String.valueOf(value), width, padChar);
15871582 }
15881583
1589 //-----------------------------------------------------------------------
15901584 /**
15911585 * Inserts the string representation of an object into this builder.
15921586 * Inserting null will use the stored null text value.
17811775 return insert(index, String.valueOf(value));
17821776 }
17831777
1784 //-----------------------------------------------------------------------
17851778 /**
17861779 * Internal method to delete a range without validation.
17871780 *
18131806 return this;
18141807 }
18151808
1816 //-----------------------------------------------------------------------
18171809 /**
18181810 * Deletes the character wherever it occurs in the builder.
18191811 *
18531845 return this;
18541846 }
18551847
1856 //-----------------------------------------------------------------------
18571848 /**
18581849 * Deletes the string wherever it occurs in the builder.
18591850 *
18891880 return this;
18901881 }
18911882
1892 //-----------------------------------------------------------------------
18931883 /**
18941884 * Deletes all parts of the builder that the matcher matches.
18951885 * <p>
19181908 return replace(matcher, null, 0, size, 1);
19191909 }
19201910
1921 //-----------------------------------------------------------------------
19221911 /**
19231912 * Internal method to delete a range without validation.
19241913 *
19591948 return this;
19601949 }
19611950
1962 //-----------------------------------------------------------------------
19631951 /**
19641952 * Replaces the search character with the replace character
19651953 * throughout the builder.
19991987 return this;
20001988 }
20011989
2002 //-----------------------------------------------------------------------
20031990 /**
20041991 * Replaces the search string with the replace string throughout the builder.
20051992 *
20392026 return this;
20402027 }
20412028
2042 //-----------------------------------------------------------------------
20432029 /**
20442030 * Replaces all matches within the builder with the replace string.
20452031 * <p>
21312117 return this;
21322118 }
21332119
2134 //-----------------------------------------------------------------------
21352120 /**
21362121 * Reverses the string builder placing each character in the opposite index.
21372122 *
21522137 return this;
21532138 }
21542139
2155 //-----------------------------------------------------------------------
21562140 /**
21572141 * Trims the builder by removing characters less than or equal to a space
21582142 * from the beginning and end.
21812165 return this;
21822166 }
21832167
2184 //-----------------------------------------------------------------------
21852168 /**
21862169 * Checks whether this builder starts with the specified string.
21872170 * <p>
22372220 return true;
22382221 }
22392222
2240 //-----------------------------------------------------------------------
22412223 /**
22422224 * {@inheritDoc}
22432225 * @since 3.0
23002282 public String leftString(final int length) {
23012283 if (length <= 0) {
23022284 return StringUtils.EMPTY;
2303 } else if (length >= size) {
2285 }
2286 if (length >= size) {
23042287 return new String(buffer, 0, size);
2305 } else {
2306 return new String(buffer, 0, length);
2307 }
2288 }
2289 return new String(buffer, 0, length);
23082290 }
23092291
23102292 /**
23222304 public String rightString(final int length) {
23232305 if (length <= 0) {
23242306 return StringUtils.EMPTY;
2325 } else if (length >= size) {
2307 }
2308 if (length >= size) {
23262309 return new String(buffer, 0, size);
2327 } else {
2328 return new String(buffer, size - length, length);
2329 }
2310 }
2311 return new String(buffer, size - length, length);
23302312 }
23312313
23322314 /**
23582340 return new String(buffer, index, length);
23592341 }
23602342
2361 //-----------------------------------------------------------------------
23622343 /**
23632344 * Checks if the string builder contains the specified char.
23642345 *
24002381 return indexOf(matcher, 0) >= 0;
24012382 }
24022383
2403 //-----------------------------------------------------------------------
24042384 /**
24052385 * Searches the string builder to find the first reference to the specified char.
24062386 *
25242504 return -1;
25252505 }
25262506
2527 //-----------------------------------------------------------------------
25282507 /**
25292508 * Searches the string builder to find the last reference to the specified char.
25302509 *
26452624 return -1;
26462625 }
26472626
2648 //-----------------------------------------------------------------------
26492627 /**
26502628 * Creates a tokenizer that can tokenize the contents of this builder.
26512629 * <p>
26822660 return new StrBuilderTokenizer();
26832661 }
26842662
2685 //-----------------------------------------------------------------------
26862663 /**
26872664 * Gets the contents of this builder as a Reader.
26882665 * <p>
27062683 return new StrBuilderReader();
27072684 }
27082685
2709 //-----------------------------------------------------------------------
27102686 /**
27112687 * Gets this builder as a Writer that can be written to.
27122688 * <p>
28372813 return hash;
28382814 }
28392815
2840 //-----------------------------------------------------------------------
28412816 /**
28422817 * Gets a String version of the string builder, creating a new instance
28432818 * each time the method is called.
28842859 return toString();
28852860 }
28862861
2887 //-----------------------------------------------------------------------
28882862 /**
28892863 * Validates parameters defining a range of the builder.
28902864 *
29192893 }
29202894 }
29212895
2922 //-----------------------------------------------------------------------
29232896 /**
29242897 * Inner class to allow StrBuilder to operate as a tokenizer.
29252898 */
29292902 * Default constructor.
29302903 */
29312904 StrBuilderTokenizer() {
2932 super();
29332905 }
29342906
29352907 /** {@inheritDoc} */
29522924 }
29532925 }
29542926
2955 //-----------------------------------------------------------------------
29562927 /**
29572928 * Inner class to allow StrBuilder to operate as a reader.
29582929 */
29662937 * Default constructor.
29672938 */
29682939 StrBuilderReader() {
2969 super();
29702940 }
29712941
29722942 /** {@inheritDoc} */
29782948 /** {@inheritDoc} */
29792949 @Override
29802950 public int read() {
2981 if (ready() == false) {
2951 if (!ready()) {
29822952 return -1;
29832953 }
29842954 return StrBuilder.this.charAt(pos++);
30433013 }
30443014 }
30453015
3046 //-----------------------------------------------------------------------
30473016 /**
30483017 * Inner class to allow StrBuilder to operate as a writer.
30493018 */
30533022 * Default constructor.
30543023 */
30553024 StrBuilderWriter() {
3056 super();
30573025 }
30583026
30593027 /** {@inheritDoc} */
3333 * @param <V> Unused.
3434 * @since 2.2
3535 * @deprecated as of 3.6, use commons-text
36 * <a href="https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/StringLookupFactory.html">
36 * <a href="https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/lookup/StringLookupFactory.html">
3737 * StringLookupFactory</a> instead
3838 */
3939 @Deprecated
4949 */
5050 private static final StrLookup<String> SYSTEM_PROPERTIES_LOOKUP = new SystemPropertiesStrLookup();
5151
52 //-----------------------------------------------------------------------
5352 /**
5453 * Returns a lookup which always returns null.
5554 *
8887 return new MapStrLookup<>(map);
8988 }
9089
91 //-----------------------------------------------------------------------
9290 /**
9391 * Constructor.
9492 */
9593 protected StrLookup() {
96 super();
9794 }
9895
9996 /**
121118 */
122119 public abstract String lookup(String key);
123120
124 //-----------------------------------------------------------------------
125121 /**
126122 * Lookup implementation that uses a Map.
127123 */
161157 }
162158 }
163159
164 //-----------------------------------------------------------------------
165160 /**
166161 * Lookup implementation based on system properties.
167162 */
1717
1818 import java.util.Arrays;
1919
20 import org.apache.commons.lang3.ArraySorter;
2021 import org.apache.commons.lang3.StringUtils;
2122
2223 /**
2829 *
2930 * @since 2.2
3031 * @deprecated as of 3.6, use commons-text
31 * <a href="https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/StringMatcherFactory.html">
32 * <a href="https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/matcher/StringMatcherFactory.html">
3233 * StringMatcherFactory</a> instead
3334 */
3435 @Deprecated
211212 return new StringMatcher(str);
212213 }
213214
214 //-----------------------------------------------------------------------
215215 /**
216216 * Constructor.
217217 */
218218 protected StrMatcher() {
219 super();
220219 }
221220
222221 /**
270269 return isMatch(buffer, pos, 0, buffer.length);
271270 }
272271
273 //-----------------------------------------------------------------------
274272 /**
275273 * Class used to define a set of characters for matching purposes.
276274 */
284282 * @param chars the characters to match, must not be null
285283 */
286284 CharSetMatcher(final char[] chars) {
287 super();
288 this.chars = chars.clone();
289 Arrays.sort(this.chars);
285 this.chars = ArraySorter.sort(chars.clone());
290286 }
291287
292288 /**
304300 }
305301 }
306302
307 //-----------------------------------------------------------------------
308303 /**
309304 * Class used to define a character for matching purposes.
310305 */
318313 * @param ch the character to match
319314 */
320315 CharMatcher(final char ch) {
321 super();
322316 this.ch = ch;
323317 }
324318
337331 }
338332 }
339333
340 //-----------------------------------------------------------------------
341334 /**
342335 * Class used to define a set of characters for matching purposes.
343336 */
351344 * @param str the string to match, must not be null
352345 */
353346 StringMatcher(final String str) {
354 super();
355347 chars = str.toCharArray();
356348 }
357349
385377
386378 }
387379
388 //-----------------------------------------------------------------------
389380 /**
390381 * Class used to match no characters.
391382 */
395386 * Constructs a new instance of {@code NoMatcher}.
396387 */
397388 NoMatcher() {
398 super();
399389 }
400390
401391 /**
413403 }
414404 }
415405
416 //-----------------------------------------------------------------------
417406 /**
418407 * Class used to match whitespace as per trim().
419408 */
423412 * Constructs a new instance of {@code TrimMatcher}.
424413 */
425414 TrimMatcher() {
426 super();
427415 }
428416
429417 /**
172172 /**
173173 * Whether escapes should be preserved. Default is false;
174174 */
175 private boolean preserveEscapes = false;
176
177 //-----------------------------------------------------------------------
175 private boolean preserveEscapes;
176
178177 /**
179178 * Replaces all the occurrences of variables in the given source object with
180179 * their matching values from the map.
238237 return new StrSubstitutor(StrLookup.systemPropertiesLookup()).replace(source);
239238 }
240239
241 //-----------------------------------------------------------------------
242240 /**
243241 * Creates a new instance with defaults for variable prefix and suffix
244242 * and the escaping character.
386384 this.setValueDelimiterMatcher(valueDelimiterMatcher);
387385 }
388386
389 //-----------------------------------------------------------------------
390387 /**
391388 * Replaces all the occurrences of variables with their matching values
392389 * from the resolver using the given source string as a template.
399396 return null;
400397 }
401398 final StrBuilder buf = new StrBuilder(source);
402 if (substitute(buf, 0, source.length()) == false) {
399 if (!substitute(buf, 0, source.length())) {
403400 return source;
404401 }
405402 return buf.toString();
422419 return null;
423420 }
424421 final StrBuilder buf = new StrBuilder(length).append(source, offset, length);
425 if (substitute(buf, 0, length) == false) {
422 if (!substitute(buf, 0, length)) {
426423 return source.substring(offset, offset + length);
427424 }
428425 return buf.toString();
429426 }
430427
431 //-----------------------------------------------------------------------
432428 /**
433429 * Replaces all the occurrences of variables with their matching values
434430 * from the resolver using the given source array as a template.
468464 return buf.toString();
469465 }
470466
471 //-----------------------------------------------------------------------
472467 /**
473468 * Replaces all the occurrences of variables with their matching values
474469 * from the resolver using the given source buffer as a template.
547542 return buf.toString();
548543 }
549544
550 //-----------------------------------------------------------------------
551545 /**
552546 * Replaces all the occurrences of variables with their matching values
553547 * from the resolver using the given source builder as a template.
587581 return buf.toString();
588582 }
589583
590 //-----------------------------------------------------------------------
591584 /**
592585 * Replaces all the occurrences of variables in the given source object with
593586 * their matching values from the resolver. The input source object is
605598 return buf.toString();
606599 }
607600
608 //-----------------------------------------------------------------------
609601 /**
610602 * Replaces all the occurrences of variables within the given source buffer
611603 * with their matching values from the resolver.
639631 return false;
640632 }
641633 final StrBuilder buf = new StrBuilder(length).append(source, offset, length);
642 if (substitute(buf, 0, length) == false) {
634 if (!substitute(buf, 0, length)) {
643635 return false;
644636 }
645637 source.replace(offset, offset + length, buf.toString());
646638 return true;
647639 }
648640
649 //-----------------------------------------------------------------------
650641 /**
651642 * Replaces all the occurrences of variables within the given source buffer
652643 * with their matching values from the resolver.
682673 return false;
683674 }
684675 final StrBuilder buf = new StrBuilder(length).append(source, offset, length);
685 if (substitute(buf, 0, length) == false) {
676 if (!substitute(buf, 0, length)) {
686677 return false;
687678 }
688679 source.replace(offset, offset + length, buf.toString());
689680 return true;
690681 }
691682
692 //-----------------------------------------------------------------------
693683 /**
694684 * Replaces all the occurrences of variables within the given source
695685 * builder with their matching values from the resolver.
723713 return substitute(source, offset, length);
724714 }
725715
726 //-----------------------------------------------------------------------
727716 /**
728717 * Internal method that substitutes the variables.
729718 * <p>
772761 bufEnd);
773762 if (startMatchLen == 0) {
774763 pos++;
764 } else // found variable start marker
765 if (pos > offset && chars[pos - 1] == escape) {
766 // escaped
767 if (preserveEscapes) {
768 pos++;
769 continue;
770 }
771 buf.deleteCharAt(pos - 1);
772 chars = buf.buffer; // in case buffer was altered
773 lengthChange--;
774 altered = true;
775 bufEnd--;
775776 } else {
776 // found variable start marker
777 if (pos > offset && chars[pos - 1] == escape) {
778 // escaped
779 if (preserveEscapes) {
780 pos++;
777 // find suffix
778 final int startPos = pos;
779 pos += startMatchLen;
780 int endMatchLen = 0;
781 int nestedVarCount = 0;
782 while (pos < bufEnd) {
783 if (substitutionInVariablesEnabled
784 && (endMatchLen = pfxMatcher.isMatch(chars,
785 pos, offset, bufEnd)) != 0) {
786 // found a nested variable start
787 nestedVarCount++;
788 pos += endMatchLen;
781789 continue;
782790 }
783 buf.deleteCharAt(pos - 1);
784 chars = buf.buffer; // in case buffer was altered
785 lengthChange--;
786 altered = true;
787 bufEnd--;
788 } else {
789 // find suffix
790 final int startPos = pos;
791 pos += startMatchLen;
792 int endMatchLen = 0;
793 int nestedVarCount = 0;
794 while (pos < bufEnd) {
795 if (substitutionInVariablesEnabled
796 && (endMatchLen = pfxMatcher.isMatch(chars,
797 pos, offset, bufEnd)) != 0) {
798 // found a nested variable start
799 nestedVarCount++;
791
792 endMatchLen = suffMatcher.isMatch(chars, pos, offset,
793 bufEnd);
794 if (endMatchLen == 0) {
795 pos++;
796 } else {
797 // found variable end marker
798 if (nestedVarCount == 0) {
799 String varNameExpr = new String(chars, startPos
800 + startMatchLen, pos - startPos
801 - startMatchLen);
802 if (substitutionInVariablesEnabled) {
803 final StrBuilder bufName = new StrBuilder(varNameExpr);
804 substitute(bufName, 0, bufName.length());
805 varNameExpr = bufName.toString();
806 }
800807 pos += endMatchLen;
801 continue;
802 }
803
804 endMatchLen = suffMatcher.isMatch(chars, pos, offset,
805 bufEnd);
806 if (endMatchLen == 0) {
807 pos++;
808 } else {
809 // found variable end marker
810 if (nestedVarCount == 0) {
811 String varNameExpr = new String(chars, startPos
812 + startMatchLen, pos - startPos
813 - startMatchLen);
814 if (substitutionInVariablesEnabled) {
815 final StrBuilder bufName = new StrBuilder(varNameExpr);
816 substitute(bufName, 0, bufName.length());
817 varNameExpr = bufName.toString();
818 }
819 pos += endMatchLen;
820 final int endPos = pos;
821
822 String varName = varNameExpr;
823 String varDefaultValue = null;
824
825 if (valueDelimMatcher != null) {
826 final char [] varNameExprChars = varNameExpr.toCharArray();
827 int valueDelimiterMatchLen = 0;
828 for (int i = 0; i < varNameExprChars.length; i++) {
829 // if there's any nested variable when nested variable substitution disabled, then stop resolving name and default value.
830 if (!substitutionInVariablesEnabled
831 && pfxMatcher.isMatch(varNameExprChars, i, i, varNameExprChars.length) != 0) {
832 break;
833 }
834 if ((valueDelimiterMatchLen = valueDelimMatcher.isMatch(varNameExprChars, i)) != 0) {
835 varName = varNameExpr.substring(0, i);
836 varDefaultValue = varNameExpr.substring(i + valueDelimiterMatchLen);
837 break;
838 }
808 final int endPos = pos;
809
810 String varName = varNameExpr;
811 String varDefaultValue = null;
812
813 if (valueDelimMatcher != null) {
814 final char [] varNameExprChars = varNameExpr.toCharArray();
815 int valueDelimiterMatchLen = 0;
816 for (int i = 0; i < varNameExprChars.length; i++) {
817 // if there's any nested variable when nested variable substitution disabled, then stop resolving name and default value.
818 if (!substitutionInVariablesEnabled
819 && pfxMatcher.isMatch(varNameExprChars, i, i, varNameExprChars.length) != 0) {
820 break;
821 }
822 if ((valueDelimiterMatchLen = valueDelimMatcher.isMatch(varNameExprChars, i)) != 0) {
823 varName = varNameExpr.substring(0, i);
824 varDefaultValue = varNameExpr.substring(i + valueDelimiterMatchLen);
825 break;
839826 }
840827 }
841
842 // on the first call initialize priorVariables
843 if (priorVariables == null) {
844 priorVariables = new ArrayList<>();
845 priorVariables.add(new String(chars,
846 offset, length));
847 }
848
849 // handle cyclic substitution
850 checkCyclicSubstitution(varName, priorVariables);
851 priorVariables.add(varName);
852
853 // resolve the variable
854 String varValue = resolveVariable(varName, buf,
855 startPos, endPos);
856 if (varValue == null) {
857 varValue = varDefaultValue;
858 }
859 if (varValue != null) {
860 // recursive replace
861 final int varLen = varValue.length();
862 buf.replace(startPos, endPos, varValue);
863 altered = true;
864 int change = substitute(buf, startPos,
865 varLen, priorVariables);
866 change = change
867 + varLen - (endPos - startPos);
868 pos += change;
869 bufEnd += change;
870 lengthChange += change;
871 chars = buf.buffer; // in case buffer was
872 // altered
873 }
874
875 // remove variable from the cyclic stack
876 priorVariables
877 .remove(priorVariables.size() - 1);
878 break;
879828 }
880 nestedVarCount--;
881 pos += endMatchLen;
829
830 // on the first call initialize priorVariables
831 if (priorVariables == null) {
832 priorVariables = new ArrayList<>();
833 priorVariables.add(new String(chars,
834 offset, length));
835 }
836
837 // handle cyclic substitution
838 checkCyclicSubstitution(varName, priorVariables);
839 priorVariables.add(varName);
840
841 // resolve the variable
842 String varValue = resolveVariable(varName, buf,
843 startPos, endPos);
844 if (varValue == null) {
845 varValue = varDefaultValue;
846 }
847 if (varValue != null) {
848 // recursive replace
849 final int varLen = varValue.length();
850 buf.replace(startPos, endPos, varValue);
851 altered = true;
852 int change = substitute(buf, startPos,
853 varLen, priorVariables);
854 change = change
855 + varLen - (endPos - startPos);
856 pos += change;
857 bufEnd += change;
858 lengthChange += change;
859 chars = buf.buffer; // in case buffer was
860 // altered
861 }
862
863 // remove variable from the cyclic stack
864 priorVariables
865 .remove(priorVariables.size() - 1);
866 break;
882867 }
868 nestedVarCount--;
869 pos += endMatchLen;
883870 }
884871 }
885872 }
897884 * @param priorVariables the list of prior variables
898885 */
899886 private void checkCyclicSubstitution(final String varName, final List<String> priorVariables) {
900 if (priorVariables.contains(varName) == false) {
887 if (!priorVariables.contains(varName)) {
901888 return;
902889 }
903890 final StrBuilder buf = new StrBuilder(256);
934921 }
935922
936923 // Escape
937 //-----------------------------------------------------------------------
938924 /**
939925 * Returns the escape character.
940926 *
956942 }
957943
958944 // Prefix
959 //-----------------------------------------------------------------------
960945 /**
961946 * Gets the variable prefix matcher currently in use.
962947 * <p>
10211006 }
10221007
10231008 // Suffix
1024 //-----------------------------------------------------------------------
10251009 /**
10261010 * Gets the variable suffix matcher currently in use.
10271011 * <p>
10861070 }
10871071
10881072 // Variable Default Value Delimiter
1089 //-----------------------------------------------------------------------
10901073 /**
10911074 * Gets the variable default value delimiter matcher currently in use.
10921075 * <p>
11601143 }
11611144
11621145 // Resolver
1163 //-----------------------------------------------------------------------
11641146 /**
11651147 * Gets the VariableResolver that is used to lookup variables.
11661148 *
11801162 }
11811163
11821164 // Substitution support in variable names
1183 //-----------------------------------------------------------------------
11841165 /**
11851166 * Returns a flag whether substitution is done in variable names.
11861167 *
125125 private StrMatcher trimmerMatcher = StrMatcher.noneMatcher();
126126
127127 /** Whether to return empty tokens as null */
128 private boolean emptyAsNull = false;
128 private boolean emptyAsNull;
129129 /** Whether to ignore empty tokens */
130130 private boolean ignoreEmptyTokens = true;
131131
132 //-----------------------------------------------------------------------
133132
134133 /**
135134 * Returns a clone of {@code CSV_TOKENIZER_PROTOTYPE}.
231230 return tok;
232231 }
233232
234 //-----------------------------------------------------------------------
235233 /**
236234 * Constructs a tokenizer splitting on space, tab, newline and formfeed
237235 * as per StringTokenizer, but with no text to tokenize.
239237 * This constructor is normally used with {@link #reset(String)}.
240238 */
241239 public StrTokenizer() {
242 super();
243240 this.chars = null;
244241 }
245242
250247 * @param input the string which is to be parsed
251248 */
252249 public StrTokenizer(final String input) {
253 super();
254250 if (input != null) {
255251 chars = input.toCharArray();
256252 } else {
324320 * @param input the string which is to be parsed, not cloned
325321 */
326322 public StrTokenizer(final char[] input) {
327 super();
328323 this.chars = ArrayUtils.clone(input);
329324 }
330325
388383 }
389384
390385 // API
391 //-----------------------------------------------------------------------
392386 /**
393387 * Gets the number of tokens found in the String.
394388 *
493487 }
494488
495489 // ListIterator
496 //-----------------------------------------------------------------------
497490 /**
498491 * Checks whether there are any more tokens.
499492 *
594587 }
595588
596589 // Implementation
597 //-----------------------------------------------------------------------
598590 /**
599591 * Checks if tokenization has been done, and if not then do it.
600592 */
837829 }
838830
839831 // Delimiter
840 //-----------------------------------------------------------------------
841832 /**
842833 * Gets the field delimiter matcher.
843834 *
885876 }
886877
887878 // Quote
888 //-----------------------------------------------------------------------
889879 /**
890880 * Gets the quote matcher currently in use.
891881 * <p>
929919 }
930920
931921 // Ignored
932 //-----------------------------------------------------------------------
933922 /**
934923 * Gets the ignored character matcher.
935924 * <p>
973962 }
974963
975964 // Trimmer
976 //-----------------------------------------------------------------------
977965 /**
978966 * Gets the trimmer character matcher.
979967 * <p>
1003991 return this;
1004992 }
1005993
1006 //-----------------------------------------------------------------------
1007994 /**
1008995 * Gets whether the tokenizer currently returns empty tokens as null.
1009996 * The default for this property is false.
10261013 return this;
10271014 }
10281015
1029 //-----------------------------------------------------------------------
10301016 /**
10311017 * Gets whether the tokenizer currently ignores empty tokens.
10321018 * The default for this property is true.
10491035 return this;
10501036 }
10511037
1052 //-----------------------------------------------------------------------
10531038 /**
10541039 * Gets the String content that the tokenizer is parsing.
10551040 *
10621047 return new String(chars);
10631048 }
10641049
1065 //-----------------------------------------------------------------------
10661050 /**
10671051 * Creates a new instance of this Tokenizer. The new instance is reset so
10681052 * that it will be at the start of the token list.
10961080 return cloned;
10971081 }
10981082
1099 //-----------------------------------------------------------------------
11001083 /**
11011084 * Gets the String content that the tokenizer is parsing.
11021085 *
4545 * instance to operate.</p>
4646 */
4747 public WordUtils() {
48 super();
4948 }
5049
5150 // Wrapping
315314 wrappedLine.append(newLineStr);
316315 offset = spaceToWrapAt + 1;
317316
317 } else // really long word or URL
318 if (wrapLongWords) {
319 // wrap really long word one line at a time
320 wrappedLine.append(str, offset, wrapLength + offset);
321 wrappedLine.append(newLineStr);
322 offset += wrapLength;
318323 } else {
319 // really long word or URL
320 if (wrapLongWords) {
321 // wrap really long word one line at a time
322 wrappedLine.append(str, offset, wrapLength + offset);
324 // do not wrap really long word, just extend beyond limit
325 matcher = patternToWrapOn.matcher(str.substring(offset + wrapLength));
326 if (matcher.find()) {
327 spaceToWrapAt = matcher.start() + offset + wrapLength;
328 }
329
330 if (spaceToWrapAt >= 0) {
331 wrappedLine.append(str, offset, spaceToWrapAt);
323332 wrappedLine.append(newLineStr);
324 offset += wrapLength;
333 offset = spaceToWrapAt + 1;
325334 } else {
326 // do not wrap really long word, just extend beyond limit
327 matcher = patternToWrapOn.matcher(str.substring(offset + wrapLength));
328 if (matcher.find()) {
329 spaceToWrapAt = matcher.start() + offset + wrapLength;
330 }
331
332 if (spaceToWrapAt >= 0) {
333 wrappedLine.append(str, offset, spaceToWrapAt);
334 wrappedLine.append(newLineStr);
335 offset = spaceToWrapAt + 1;
336 } else {
337 wrappedLine.append(str, offset, str.length());
338 offset = inputLineLength;
339 }
335 wrappedLine.append(str, offset, str.length());
336 offset = inputLineLength;
340337 }
341338 }
342339 }
348345 }
349346
350347 // Capitalizing
351 //-----------------------------------------------------------------------
352348 /**
353349 * <p>Capitalizes all the whitespace separated words in a String.
354350 * Only the first character of each word is changed. To convert the
423419 return new String(buffer);
424420 }
425421
426 //-----------------------------------------------------------------------
427422 /**
428423 * <p>Converts all the whitespace separated words in a String into capitalized words,
429424 * that is each word is made up of a titlecase character and then a series of
482477 return capitalize(str, delimiters);
483478 }
484479
485 //-----------------------------------------------------------------------
486480 /**
487481 * <p>Uncapitalizes all the whitespace separated words in a String.
488482 * Only the first character of each word is changed.</p>
548542 return new String(buffer);
549543 }
550544
551 //-----------------------------------------------------------------------
552545 /**
553546 * <p>Swaps the case of a String using a word based algorithm.</p>
554547 *
598591 return new String(buffer);
599592 }
600593
601 //-----------------------------------------------------------------------
602594 /**
603595 * <p>Extracts the initial characters from each word in the String.</p>
604596 *
676668 return new String(buf, 0, count);
677669 }
678670
679 //-----------------------------------------------------------------------
680671 /**
681672 * <p>Checks if the String contains all words in the given array.</p>
682673 *
716707 return true;
717708 }
718709
719 //-----------------------------------------------------------------------
720710 /**
721711 * Is the character a delimiter.
722712 *
2626 *
2727 * @since 3.0
2828 * @deprecated as of 3.6, use commons-text
29 * <a href="https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/AggregateTranslator.html">
29 * <a href="https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/translate/AggregateTranslator.html">
3030 * AggregateTranslator</a> instead
3131 */
3232 @Deprecated
107107 if (codepoint < below || codepoint > above) {
108108 return false;
109109 }
110 } else {
111 if (codepoint >= below && codepoint <= above) {
112 return false;
113 }
110 } else if (codepoint >= below && codepoint <= above) {
111 return false;
114112 }
115113
116114 out.write("&#");
2525 * Translate XML numeric entities of the form &amp;#[xX]?\d+;? to
2626 * the specific codepoint.
2727 *
28 * Note that the semi-colon is optional.
28 * Note that the semicolon is optional.
2929 *
3030 * @since 3.0
3131 * @deprecated as of 3.6, use commons-text
3535 @Deprecated
3636 public class NumericEntityUnescaper extends CharSequenceTranslator {
3737
38 /** Enumerates NumericEntityUnescaper options for unescaping. */
3839 public enum OPTION {
39 semiColonRequired, semiColonOptional, errorIfNoSemiColon
40
41 /**
42 * Require a semicolon.
43 */
44 semiColonRequired,
45
46 /**
47 * Do not require a semicolon.
48 */
49 semiColonOptional,
50
51 /**
52 * Throw an exception if a semicolon is missing.
53 */
54 errorIfNoSemiColon
4055 }
4156
4257 // TODO?: Create an OptionsSet class to hide some of the conditional logic below
4661 * Create a UnicodeUnescaper.
4762 *
4863 * The constructor takes a list of options, only one type of which is currently
49 * available (whether to allow, error or ignore the semi-colon on the end of a
64 * available (whether to allow, error or ignore the semicolon on the end of a
5065 * numeric entity to being missing).
5166 *
5267 * For example, to support numeric entities without a ';':
111126 if (!semiNext) {
112127 if (isSet(OPTION.semiColonRequired)) {
113128 return 0;
114 } else
129 }
115130 if (isSet(OPTION.errorIfNoSemiColon)) {
116131 throw new IllegalArgumentException("Semi-colon required at end of numeric entity");
117132 }
118133 }
119134
120 int entityValue;
135 final int entityValue;
121136 try {
122137 if (isHex) {
123138 entityValue = Integer.parseInt(input.subSequence(start, end).toString(), 16);
107107 if (codepoint < below || codepoint > above) {
108108 return false;
109109 }
110 } else {
111 if (codepoint >= below && codepoint <= above) {
112 return false;
113 }
110 } else if (codepoint >= below && codepoint <= above) {
111 return false;
114112 }
115113
116114 // TODO: Handle potential + sign per various Unicode escape implementations
3333 */
3434 @Override
3535 public boolean translate(final int codepoint, final Writer out) throws IOException {
36 if (codepoint >= Character.MIN_SURROGATE && codepoint <= Character.MAX_SURROGATE) {
37 // It's a surrogate. Write nothing and say we've translated.
38 return true;
39 }
36 // true: It's a surrogate. Write nothing and say we've translated.
37 return codepoint >= Character.MIN_SURROGATE && codepoint <= Character.MAX_SURROGATE;
4038 // It's not a surrogate. Don't translate it.
41 return false;
4239 }
4340 }
4441
3939 * @param calendar A Calendar.
4040 */
4141 public CalendarUtils(final Calendar calendar) {
42 super();
4342 this.calendar = Objects.requireNonNull(calendar, "calendar");
4443 }
4544
192192 public static final FastDateFormat SMTP_DATETIME_FORMAT
193193 = FastDateFormat.getInstance("EEE, dd MMM yyyy HH:mm:ss Z", Locale.US);
194194
195 //-----------------------------------------------------------------------
196195 /**
197196 * <p>DateFormatUtils instances should NOT be constructed in standard programming.</p>
198197 *
200199 * to operate.</p>
201200 */
202201 public DateFormatUtils() {
203 super();
204202 }
205203
206204 /**
7575 boolean parse(String source, ParsePosition pos, Calendar calendar);
7676
7777 // Accessors
78 //-----------------------------------------------------------------------
7978 /**
8079 * <p>Gets the pattern used by this parser.</p>
8180 *
139139
140140
141141 // Accessors
142 //-----------------------------------------------------------------------
143142 /**
144143 * <p>Gets the pattern used by this printer.</p>
145144 *
2525 import java.util.TimeZone;
2626 import java.util.concurrent.TimeUnit;
2727
28 import org.apache.commons.lang3.LocaleUtils;
2829 import org.apache.commons.lang3.Validate;
2930
3031 /**
4445 * <p>
4546 * Several methods are provided for adding to {@code Date} objects, of the form
4647 * {@code addXXX(Date date, int amount)}. It is important to note these methods
47 * use a {@code Calendar} internally (with default timezone and locale) and may
48 * use a {@code Calendar} internally (with default time zone and locale) and may
4849 * be affected by changes to daylight saving time (DST).
4950 * </p>
5051 *
145146 * instance to operate.</p>
146147 */
147148 public DateUtils() {
148 super();
149 }
150
151 //-----------------------------------------------------------------------
149 }
150
152151 /**
153152 * <p>Checks if two date objects are on the same day ignoring time.</p>
154153 *
195194 cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR);
196195 }
197196
198 //-----------------------------------------------------------------------
199197 /**
200198 * <p>Checks if two date objects represent the same instant in time.</p>
201199 *
232230 return cal1.getTime().getTime() == cal2.getTime().getTime();
233231 }
234232
235 //-----------------------------------------------------------------------
236233 /**
237234 * <p>Checks if two calendar objects represent the same local time.</p>
238235 *
259256 cal1.getClass() == cal2.getClass();
260257 }
261258
262 //-----------------------------------------------------------------------
263259 /**
264260 * <p>Parses a string representing a date by trying a variety of different parsers.</p>
265261 *
278274 return parseDate(str, null, parsePatterns);
279275 }
280276
281 //-----------------------------------------------------------------------
282277 /**
283278 * <p>Parses a string representing a date by trying a variety of different parsers,
284279 * using the default date format symbols for the given locale.</p>
301296 return parseDateWithLeniency(str, locale, parsePatterns, true);
302297 }
303298
304 //-----------------------------------------------------------------------
305299 /**
306300 * <p>Parses a string representing a date by trying a variety of different parsers.</p>
307301 *
367361 }
368362
369363 final TimeZone tz = TimeZone.getDefault();
370 final Locale lcl = locale == null ? Locale.getDefault() : locale;
364 final Locale lcl = LocaleUtils.toLocale(locale);
371365 final ParsePosition pos = new ParsePosition(0);
372366 final Calendar calendar = Calendar.getInstance(tz, lcl);
373367 calendar.setLenient(lenient);
387381 throw new ParseException("Unable to parse the date: " + str, -1);
388382 }
389383
390 //-----------------------------------------------------------------------
391384 /**
392385 * Adds a number of years to a date returning a new object.
393386 * The original {@code Date} is unchanged.
401394 return add(date, Calendar.YEAR, amount);
402395 }
403396
404 //-----------------------------------------------------------------------
405397 /**
406398 * Adds a number of months to a date returning a new object.
407399 * The original {@code Date} is unchanged.
415407 return add(date, Calendar.MONTH, amount);
416408 }
417409
418 //-----------------------------------------------------------------------
419410 /**
420411 * Adds a number of weeks to a date returning a new object.
421412 * The original {@code Date} is unchanged.
429420 return add(date, Calendar.WEEK_OF_YEAR, amount);
430421 }
431422
432 //-----------------------------------------------------------------------
433423 /**
434424 * Adds a number of days to a date returning a new object.
435425 * The original {@code Date} is unchanged.
443433 return add(date, Calendar.DAY_OF_MONTH, amount);
444434 }
445435
446 //-----------------------------------------------------------------------
447436 /**
448437 * Adds a number of hours to a date returning a new object.
449438 * The original {@code Date} is unchanged.
457446 return add(date, Calendar.HOUR_OF_DAY, amount);
458447 }
459448
460 //-----------------------------------------------------------------------
461449 /**
462450 * Adds a number of minutes to a date returning a new object.
463451 * The original {@code Date} is unchanged.
471459 return add(date, Calendar.MINUTE, amount);
472460 }
473461
474 //-----------------------------------------------------------------------
475462 /**
476463 * Adds a number of seconds to a date returning a new object.
477464 * The original {@code Date} is unchanged.
485472 return add(date, Calendar.SECOND, amount);
486473 }
487474
488 //-----------------------------------------------------------------------
489475 /**
490476 * Adds a number of milliseconds to a date returning a new object.
491477 * The original {@code Date} is unchanged.
499485 return add(date, Calendar.MILLISECOND, amount);
500486 }
501487
502 //-----------------------------------------------------------------------
503488 /**
504489 * Adds to a date returning a new object.
505490 * The original {@code Date} is unchanged.
518503 return c.getTime();
519504 }
520505
521 //-----------------------------------------------------------------------
522506 /**
523507 * Sets the years field to a date returning a new object.
524508 * The original {@code Date} is unchanged.
533517 return set(date, Calendar.YEAR, amount);
534518 }
535519
536 //-----------------------------------------------------------------------
537520 /**
538521 * Sets the months field to a date returning a new object.
539522 * The original {@code Date} is unchanged.
548531 return set(date, Calendar.MONTH, amount);
549532 }
550533
551 //-----------------------------------------------------------------------
552534 /**
553535 * Sets the day of month field to a date returning a new object.
554536 * The original {@code Date} is unchanged.
563545 return set(date, Calendar.DAY_OF_MONTH, amount);
564546 }
565547
566 //-----------------------------------------------------------------------
567548 /**
568549 * Sets the hours field to a date returning a new object. Hours range
569550 * from 0-23.
579560 return set(date, Calendar.HOUR_OF_DAY, amount);
580561 }
581562
582 //-----------------------------------------------------------------------
583563 /**
584564 * Sets the minute field to a date returning a new object.
585565 * The original {@code Date} is unchanged.
594574 return set(date, Calendar.MINUTE, amount);
595575 }
596576
597 //-----------------------------------------------------------------------
598577 /**
599578 * Sets the seconds field to a date returning a new object.
600579 * The original {@code Date} is unchanged.
609588 return set(date, Calendar.SECOND, amount);
610589 }
611590
612 //-----------------------------------------------------------------------
613591 /**
614592 * Sets the milliseconds field to a date returning a new object.
615593 * The original {@code Date} is unchanged.
624602 return set(date, Calendar.MILLISECOND, amount);
625603 }
626604
627 //-----------------------------------------------------------------------
628605 /**
629606 * Sets the specified field to a date returning a new object.
630607 * This does not use a lenient calendar.
647624 return c.getTime();
648625 }
649626
650 //-----------------------------------------------------------------------
651627 /**
652628 * Converts a {@code Date} into a {@code Calendar}.
653629 *
662638 return c;
663639 }
664640
665 //-----------------------------------------------------------------------
666641 /**
667642 * Converts a {@code Date} of a given {@code TimeZone} into a {@code Calendar}
668643 * @param date the date to convert to a Calendar
676651 return c;
677652 }
678653
679 //-----------------------------------------------------------------------
680654 /**
681655 * <p>Rounds a date, leaving the field specified as the most
682656 * significant field.</p>
686660 * 28 Mar 2002 14:00:00.000. If this was passed with MONTH, it
687661 * would return 1 April 2002 0:00:00.000.</p>
688662 *
689 * <p>For a date in a timezone that handles the change to daylight
663 * <p>For a date in a time zone that handles the change to daylight
690664 * saving time, rounding to Calendar.HOUR_OF_DAY will behave as follows.
691665 * Suppose daylight saving time begins at 02:00 on March 30. Rounding a
692666 * date that crosses this time would produce the following values:
720694 * 28 Mar 2002 14:00:00.000. If this was passed with MONTH, it
721695 * would return 1 April 2002 0:00:00.000.</p>
722696 *
723 * <p>For a date in a timezone that handles the change to daylight
697 * <p>For a date in a time zone that handles the change to daylight
724698 * saving time, rounding to Calendar.HOUR_OF_DAY will behave as follows.
725699 * Suppose daylight saving time begins at 02:00 on March 30. Rounding a
726700 * date that crosses this time would produce the following values:
760734 * 28 Mar 2002 14:00:00.000. If this was passed with MONTH, it
761735 * would return 1 April 2002 0:00:00.000.</p>
762736 *
763 * <p>For a date in a timezone that handles the change to daylight
737 * <p>For a date in a time zone that handles the change to daylight
764738 * saving time, rounding to Calendar.HOUR_OF_DAY will behave as follows.
765739 * Suppose daylight saving time begins at 02:00 on March 30. Rounding a
766740 * date that crosses this time would produce the following values:
785759 }
786760 if (date instanceof Date) {
787761 return round((Date) date, field);
788 } else if (date instanceof Calendar) {
762 }
763 if (date instanceof Calendar) {
789764 return round((Calendar) date, field).getTime();
790 } else {
791 throw new ClassCastException("Could not round " + date);
792 }
793 }
794
795 //-----------------------------------------------------------------------
765 }
766 throw new ClassCastException("Could not round " + date);
767 }
768
796769 /**
797770 * <p>Truncates a date, leaving the field specified as the most
798771 * significant field.</p>
862835 }
863836 if (date instanceof Date) {
864837 return truncate((Date) date, field);
865 } else if (date instanceof Calendar) {
838 }
839 if (date instanceof Calendar) {
866840 return truncate((Calendar) date, field).getTime();
867 } else {
868 throw new ClassCastException("Could not truncate " + date);
869 }
870 }
871
872 //-----------------------------------------------------------------------
841 }
842 throw new ClassCastException("Could not truncate " + date);
843 }
844
873845 /**
874846 * <p>Gets a date ceiling, leaving the field specified as the most
875847 * significant field.</p>
942914 }
943915 if (date instanceof Date) {
944916 return ceiling((Date) date, field);
945 } else if (date instanceof Calendar) {
917 }
918 if (date instanceof Calendar) {
946919 return ceiling((Calendar) date, field).getTime();
947 } else {
948 throw new ClassCastException("Could not find ceiling of for type: " + date.getClass());
949 }
950 }
951
952 //-----------------------------------------------------------------------
920 }
921 throw new ClassCastException("Could not find ceiling of for type: " + date.getClass());
922 }
923
953924 /**
954925 * <p>Internal calculation method.</p>
955926 *
10981069
10991070 }
11001071
1101 //-----------------------------------------------------------------------
11021072 /**
11031073 * <p>Constructs an {@code Iterator} over each day in a date
11041074 * range defined by a focus date and range style.</p>
12501220 }
12511221 if (focus instanceof Date) {
12521222 return iterator((Date) focus, rangeStyle);
1253 } else if (focus instanceof Calendar) {
1223 }
1224 if (focus instanceof Calendar) {
12541225 return iterator((Calendar) focus, rangeStyle);
1255 } else {
1256 throw new ClassCastException("Could not iterate based on " + focus);
1257 }
1226 }
1227 throw new ClassCastException("Could not iterate based on " + focus);
12581228 }
12591229
12601230 /**
17851755 }
17861756
17871757 private static void validateDateNotNull(final Date date) {
1788 Validate.notNull(date, "The date must not be null");
1789 }
1790
1791 //-----------------------------------------------------------------------
1758 Validate.notNull(date, "date");
1759 }
1760
17921761 /**
17931762 * <p>Date iterator.</p>
17941763 */
18031772 * @param endFinal end date (inclusive)
18041773 */
18051774 DateIterator(final Calendar startFinal, final Calendar endFinal) {
1806 super();
18071775 this.endFinal = endFinal;
18081776 spot = startFinal;
18091777 spot.add(Calendar.DATE, -1);
5656 * to operate.</p>
5757 */
5858 public DurationFormatUtils() {
59 super();
6059 }
6160
6261 /**
6867 */
6968 public static final String ISO_EXTENDED_FORMAT_PATTERN = "'P'yyyy'Y'M'M'd'DT'H'H'm'M's.SSS'S'";
7069
71 //-----------------------------------------------------------------------
7270 /**
7371 * <p>Formats the time gap as a string.</p>
7472 *
222220 return duration.trim();
223221 }
224222
225 //-----------------------------------------------------------------------
226223 /**
227224 * <p>Formats the time gap as a string.</p>
228225 *
254251 /**
255252 * <p>Formats the time gap as a string, using the specified format.
256253 * Padding the left hand side of numbers with zeroes is optional and
257 * the timezone may be specified. </p>
254 * the time zone may be specified. </p>
258255 *
259256 * <p>When calculating the difference between months/days, it chooses to
260257 * calculate months first. So when working out the number of months and
288285
289286 final Token[] tokens = lexx(format);
290287
291 // timezones get funky around 0, so normalizing everything to GMT
288 // time zones get funky around 0, so normalizing everything to GMT
292289 // stops the hours being off
293290 final Calendar start = Calendar.getInstance(timezone);
294291 start.setTime(new Date(startMillis));
343340 } else {
344341 // there are no M's in the format string
345342
346 if ( !Token.containsTokenWithValue(tokens, y) ) {
343 if (!Token.containsTokenWithValue(tokens, y)) {
347344 int target = end.get(Calendar.YEAR);
348345 if (months < 0) {
349346 // target is end-year -1
368365 years = 0;
369366 }
370367
371 while ( start.get(Calendar.MONTH) != end.get(Calendar.MONTH) ) {
368 while (start.get(Calendar.MONTH) != end.get(Calendar.MONTH)) {
372369 days += start.getActualMaximum(Calendar.DAY_OF_MONTH);
373370 start.add(Calendar.MONTH, 1);
374371 }
407404 return format(tokens, years, months, days, hours, minutes, seconds, milliseconds, padWithZeros);
408405 }
409406
410 //-----------------------------------------------------------------------
411407 /**
412408 * <p>The internal method to do the formatting.</p>
413409 *
431427 final int count = token.getCount();
432428 if (value instanceof StringBuilder) {
433429 buffer.append(value.toString());
434 } else {
435 if (value.equals(y)) {
436 buffer.append(paddedValue(years, padWithZeros, count));
437 lastOutputSeconds = false;
438 } else if (value.equals(M)) {
439 buffer.append(paddedValue(months, padWithZeros, count));
440 lastOutputSeconds = false;
441 } else if (value.equals(d)) {
442 buffer.append(paddedValue(days, padWithZeros, count));
443 lastOutputSeconds = false;
444 } else if (value.equals(H)) {
445 buffer.append(paddedValue(hours, padWithZeros, count));
446 lastOutputSeconds = false;
447 } else if (value.equals(m)) {
448 buffer.append(paddedValue(minutes, padWithZeros, count));
449 lastOutputSeconds = false;
450 } else if (value.equals(s)) {
451 buffer.append(paddedValue(seconds, padWithZeros, count));
452 lastOutputSeconds = true;
453 } else if (value.equals(S)) {
454 if (lastOutputSeconds) {
455 // ensure at least 3 digits are displayed even if padding is not selected
456 final int width = padWithZeros ? Math.max(3, count) : 3;
457 buffer.append(paddedValue(milliseconds, true, width));
458 } else {
459 buffer.append(paddedValue(milliseconds, padWithZeros, count));
460 }
461 lastOutputSeconds = false;
462 }
430 } else if (value.equals(y)) {
431 buffer.append(paddedValue(years, padWithZeros, count));
432 lastOutputSeconds = false;
433 } else if (value.equals(M)) {
434 buffer.append(paddedValue(months, padWithZeros, count));
435 lastOutputSeconds = false;
436 } else if (value.equals(d)) {
437 buffer.append(paddedValue(days, padWithZeros, count));
438 lastOutputSeconds = false;
439 } else if (value.equals(H)) {
440 buffer.append(paddedValue(hours, padWithZeros, count));
441 lastOutputSeconds = false;
442 } else if (value.equals(m)) {
443 buffer.append(paddedValue(minutes, padWithZeros, count));
444 lastOutputSeconds = false;
445 } else if (value.equals(s)) {
446 buffer.append(paddedValue(seconds, padWithZeros, count));
447 lastOutputSeconds = true;
448 } else if (value.equals(S)) {
449 if (lastOutputSeconds) {
450 // ensure at least 3 digits are displayed even if padding is not selected
451 final int width = padWithZeros ? Math.max(3, count) : 3;
452 buffer.append(paddedValue(milliseconds, true, width));
453 } else {
454 buffer.append(paddedValue(milliseconds, padWithZeros, count));
455 }
456 lastOutputSeconds = false;
463457 }
464458 }
465459 return buffer.toString();
479473 return padWithZeros ? StringUtils.leftPad(longString, count, '0') : longString;
480474 }
481475
482 static final Object y = "y";
483 static final Object M = "M";
484 static final Object d = "d";
485 static final Object H = "H";
486 static final Object m = "m";
487 static final Object s = "s";
488 static final Object S = "S";
476 static final String y = "y";
477 static final String M = "M";
478 static final String d = "d";
479 static final String H = "H";
480 static final String m = "m";
481 static final String s = "s";
482 static final String S = "S";
489483
490484 /**
491485 * Parses a classic date format string into Tokens
507501 buffer.append(ch); // buffer can't be null if inLiteral is true
508502 continue;
509503 }
510 Object value = null;
504 String value = null;
511505 switch (ch) {
512506 // TODO: Need to handle escaping of '
513507 case '\'':
563557 if (inLiteral) { // i.e. we have not found the end of the literal
564558 throw new IllegalArgumentException("Unmatched quote in format: " + format);
565559 }
566 return list.toArray(new Token[0]);
567 }
568
569 //-----------------------------------------------------------------------
560 return list.toArray(Token.EMPTY_ARRAY);
561 }
562
570563 /**
571564 * Element that is parsed from the format pattern.
572565 */
573566 static class Token {
567
568 /** Empty array. */
569 private static final Token[] EMPTY_ARRAY = {};
574570
575571 /**
576572 * Helper method to determine if a set of tokens contain a value
656652 }
657653 if (this.value instanceof StringBuilder) {
658654 return this.value.toString().equals(tok2.value.toString());
659 } else if (this.value instanceof Number) {
655 }
656 if (this.value instanceof Number) {
660657 return this.value.equals(tok2.value);
661 } else {
662 return this.value == tok2.value;
663 }
658 }
659 return this.value == tok2.value;
664660 }
665661 return false;
666662 }
0 /*
1 * Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package org.apache.commons.lang3.time;
18
19 import java.time.Duration;
20 import java.time.temporal.ChronoUnit;
21 import java.util.Objects;
22 import java.util.concurrent.TimeUnit;
23
24 import org.apache.commons.lang3.ObjectUtils;
25 import org.apache.commons.lang3.Range;
26 import org.apache.commons.lang3.function.FailableBiConsumer;
27 import org.apache.commons.lang3.math.NumberUtils;
28
29 /**
30 * Utilities for {@link Duration}.
31 *
32 * @since 3.12.0
33 */
34 public class DurationUtils {
35
36 /**
37 * An Integer Range that accepts Longs.
38 */
39 static final Range<Long> LONG_TO_INT_RANGE = Range.between(NumberUtils.LONG_INT_MIN_VALUE,
40 NumberUtils.LONG_INT_MAX_VALUE);
41
42 /**
43 * Accepts the function with the duration as a long milliseconds and int nanoseconds.
44 *
45 * @param <T> The function exception.
46 * @param consumer Accepting function.
47 * @param duration The duration to pick apart.
48 * @throws T See the function signature.
49 */
50 @SuppressWarnings("boxing") // boxing unavoidable
51 public static <T extends Throwable> void accept(final FailableBiConsumer<Long, Integer, T> consumer, final Duration duration)
52 throws T {
53 if (consumer != null && duration != null) {
54 consumer.accept(duration.toMillis(), getNanosOfMiili(duration));
55 }
56 }
57
58 /**
59 * Gets the nanosecond part of a Duration converted to milliseconds.
60 * <p>
61 * Handy when calling an API that takes a long of milliseconds and an int of nanoseconds. For example,
62 * {@link Object#wait(long, int)} and {@link Thread#sleep(long, int)}.
63 * </p>
64 * <p>
65 * Note that is this different from {@link Duration#getNano()} because a duration are seconds and nanoseconds.
66 * </p>
67 *
68 * @param duration The duration to query.
69 * @return nanoseconds between 0 and 999,999.
70 */
71 public static int getNanosOfMiili(final Duration duration) {
72 return duration.getNano() % 1_000_000;
73 }
74
75 /**
76 * Tests whether the given Duration is positive (&gt;0).
77 *
78 * @param duration the value to test
79 * @return whether the given Duration is positive (&gt;0).
80 */
81 public static boolean isPositive(final Duration duration) {
82 return !duration.isNegative() && !duration.isZero();
83 }
84
85 /**
86 * Converts a {@link TimeUnit} to a {@link ChronoUnit}.
87 *
88 * @param timeUnit A non-null TimeUnit.
89 * @return The corresponding ChronoUnit.
90 */
91 static ChronoUnit toChronoUnit(final TimeUnit timeUnit) {
92 // TODO when using Java >= 9: Use TimeUnit.toChronoUnit().
93 switch (Objects.requireNonNull(timeUnit)) {
94 case NANOSECONDS:
95 return ChronoUnit.NANOS;
96 case MICROSECONDS:
97 return ChronoUnit.MICROS;
98 case MILLISECONDS:
99 return ChronoUnit.MILLIS;
100 case SECONDS:
101 return ChronoUnit.SECONDS;
102 case MINUTES:
103 return ChronoUnit.MINUTES;
104 case HOURS:
105 return ChronoUnit.HOURS;
106 case DAYS:
107 return ChronoUnit.DAYS;
108 default:
109 throw new IllegalArgumentException(timeUnit.toString());
110 }
111 }
112
113 /**
114 * Converts an amount and TimeUnit into a Duration.
115 *
116 * @param amount the amount of the duration, measured in terms of the unit, positive or negative
117 * @param timeUnit the unit that the duration is measured in, must have an exact duration, not null
118 * @return a Duration.
119 */
120 public static Duration toDuration(final long amount, final TimeUnit timeUnit) {
121 return Duration.of(amount, toChronoUnit(timeUnit));
122 }
123
124 /**
125 * Converts a Duration to milliseconds bound to an int (instead of a long).
126 * <p>
127 * Handy for low-level APIs that take millisecond timeouts in ints rather than longs.
128 * </p>
129 * <ul>
130 * <li>If the duration milliseconds are greater than {@link Integer#MAX_VALUE}, then return
131 * {@link Integer#MAX_VALUE}.</li>
132 * <li>If the duration milliseconds are lesser than {@link Integer#MIN_VALUE}, then return
133 * {@link Integer#MIN_VALUE}.</li>
134 * </ul>
135 *
136 * @param duration The duration to convert, not null.
137 * @return int milliseconds.
138 */
139 public static int toMillisInt(final Duration duration) {
140 Objects.requireNonNull(duration, "duration");
141 // intValue() does not do a narrowing conversion here
142 return LONG_TO_INT_RANGE.fit(Long.valueOf(duration.toMillis())).intValue();
143 }
144
145 /**
146 * Returns the given non-null value or {@link Duration#ZERO} if null.
147 *
148 * @param duration The duration to test.
149 * @return The given duration or {@link Duration#ZERO}.
150 */
151 public static Duration zeroIfNull(final Duration duration) {
152 return ObjectUtils.defaultIfNull(duration, Duration.ZERO);
153 }
154
155 }
9898 */
9999 public static final int SHORT = DateFormat.SHORT;
100100
101 private static final FormatCache<FastDateFormat> cache= new FormatCache<FastDateFormat>() {
101 private static final FormatCache<FastDateFormat> cache = new FormatCache<FastDateFormat>() {
102102 @Override
103103 protected FastDateFormat createInstance(final String pattern, final TimeZone timeZone, final Locale locale) {
104104 return new FastDateFormat(pattern, timeZone, locale);
108108 private final FastDatePrinter printer;
109109 private final FastDateParser parser;
110110
111 //-----------------------------------------------------------------------
112111 /**
113112 * <p>Gets a formatter instance using the default pattern in the
114113 * default locale.</p>
178177 return cache.getInstance(pattern, timeZone, locale);
179178 }
180179
181 //-----------------------------------------------------------------------
182180 /**
183181 * <p>Gets a date formatter instance using the specified style in the
184182 * default time zone and locale.</p>
240238 return cache.getDateInstance(style, timeZone, locale);
241239 }
242240
243 //-----------------------------------------------------------------------
244241 /**
245242 * <p>Gets a time formatter instance using the specified style in the
246243 * default time zone and locale.</p>
302299 return cache.getTimeInstance(style, timeZone, locale);
303300 }
304301
305 //-----------------------------------------------------------------------
306302 /**
307303 * <p>Gets a date/time formatter instance using the specified style
308304 * in the default time zone and locale.</p>
369365 }
370366
371367 // Constructor
372 //-----------------------------------------------------------------------
373368 /**
374369 * <p>Constructs a new FastDateFormat.</p>
375370 *
383378 }
384379
385380 // Constructor
386 //-----------------------------------------------------------------------
387381 /**
388382 * <p>Constructs a new FastDateFormat.</p>
389383 *
394388 * @throws NullPointerException if pattern, timeZone, or locale is null.
395389 */
396390 protected FastDateFormat(final String pattern, final TimeZone timeZone, final Locale locale, final Date centuryStart) {
397 printer= new FastDatePrinter(pattern, timeZone, locale);
398 parser= new FastDateParser(pattern, timeZone, locale, centuryStart);
391 printer = new FastDatePrinter(pattern, timeZone, locale);
392 parser = new FastDateParser(pattern, timeZone, locale, centuryStart);
399393 }
400394
401395 // Format methods
402 //-----------------------------------------------------------------------
403396 /**
404397 * <p>Formats a {@code Date}, {@code Calendar} or
405398 * {@code Long} (milliseconds) object.</p>
538531 }
539532
540533 // Parsing
541 //-----------------------------------------------------------------------
542534
543535
544536 /* (non-Javadoc)
575567 }
576568
577569 // Accessors
578 //-----------------------------------------------------------------------
579570 /**
580571 * <p>Gets the pattern used by this formatter.</p>
581572 *
622613 }
623614
624615 // Basics
625 //-----------------------------------------------------------------------
626616 /**
627617 * <p>Compares two objects for equality.</p>
628618 *
3737 import java.util.concurrent.ConcurrentMap;
3838 import java.util.regex.Matcher;
3939 import java.util.regex.Pattern;
40
41 import org.apache.commons.lang3.LocaleUtils;
4042
4143 /**
4244 * <p>FastDateParser is a fast and thread-safe version of
121123 *
122124 * @since 3.5
123125 */
124 protected FastDateParser(final String pattern, final TimeZone timeZone, final Locale locale, final Date centuryStart) {
126 protected FastDateParser(final String pattern, final TimeZone timeZone, final Locale locale,
127 final Date centuryStart) {
125128 this.pattern = pattern;
126129 this.timeZone = timeZone;
127 this.locale = locale;
128
129 final Calendar definingCalendar = Calendar.getInstance(timeZone, locale);
130
131 int centuryStartYear;
132 if (centuryStart!=null) {
130 this.locale = LocaleUtils.toLocale(locale);
131
132 final Calendar definingCalendar = Calendar.getInstance(timeZone, this.locale);
133
134 final int centuryStartYear;
135 if (centuryStart != null) {
133136 definingCalendar.setTime(centuryStart);
134 centuryStartYear= definingCalendar.get(Calendar.YEAR);
135 } else if (locale.equals(JAPANESE_IMPERIAL)) {
136 centuryStartYear= 0;
137 centuryStartYear = definingCalendar.get(Calendar.YEAR);
138 } else if (this.locale.equals(JAPANESE_IMPERIAL)) {
139 centuryStartYear = 0;
137140 } else {
138141 // from 80 years ago to 20 years from now
139142 definingCalendar.setTime(new Date());
140 centuryStartYear= definingCalendar.get(Calendar.YEAR)-80;
141 }
142 century= centuryStartYear / 100 * 100;
143 startYear= centuryStartYear - century;
143 centuryStartYear = definingCalendar.get(Calendar.YEAR) - 80;
144 }
145 century = centuryStartYear / 100 * 100;
146 startYear = centuryStartYear - century;
144147
145148 init(definingCalendar);
146149 }
147150
148151 /**
149 * Initialize derived fields from defining fields.
152 * Initializes derived fields from defining fields.
150153 * This is called from constructor and from readObject (de-serialization)
151154 *
152155 * @param definingCalendar the {@link java.util.Calendar} instance used to initialize this FastDateParser
157160 final StrategyParser fm = new StrategyParser(definingCalendar);
158161 for (;;) {
159162 final StrategyAndWidth field = fm.getNextStrategy();
160 if (field==null) {
163 if (field == null) {
161164 break;
162165 }
163166 patterns.add(field);
165168 }
166169
167170 // helper classes to parse the format string
168 //-----------------------------------------------------------------------
169171
170172 /**
171173 * Holds strategy and field width
172174 */
173175 private static class StrategyAndWidth {
176
174177 final Strategy strategy;
175178 final int width;
176179
185188 }
186189 final Strategy nextStrategy = lt.next().strategy;
187190 lt.previous();
188 return nextStrategy.isNumber() ?width :0;
189 }
191 return nextStrategy.isNumber() ? width : 0;
192 }
193
194 @Override
195 public String toString() {
196 return "StrategyAndWidth [strategy=" + strategy + ", width=" + width + "]";
197 }
190198 }
191199
192200 /**
232240 final char c = pattern.charAt(currentIdx);
233241 if (!activeQuote && isFormatLetter(c)) {
234242 break;
235 } else if (c == '\'' && (++currentIdx == pattern.length() || pattern.charAt(currentIdx) != '\'')) {
243 }
244 if (c == '\'' && (++currentIdx == pattern.length() || pattern.charAt(currentIdx) != '\'')) {
236245 activeQuote = !activeQuote;
237246 continue;
238247 }
254263 }
255264
256265 // Accessors
257 //-----------------------------------------------------------------------
258266 /* (non-Javadoc)
259267 * @see org.apache.commons.lang3.time.DateParser#getPattern()
260268 */
281289
282290
283291 // Basics
284 //-----------------------------------------------------------------------
285 /**
286 * <p>Compare another object for equality with this object.</p>
292 /**
293 * <p>Compares another object for equality with this object.</p>
287294 *
288295 * @param obj the object to compare to
289296 * @return {@code true}if equal to this instance
294301 return false;
295302 }
296303 final FastDateParser other = (FastDateParser) obj;
297 return pattern.equals(other.pattern)
298 && timeZone.equals(other.timeZone)
299 && locale.equals(other.locale);
300 }
301
302 /**
303 * <p>Return a hash code compatible with equals.</p>
304 return pattern.equals(other.pattern) && timeZone.equals(other.timeZone) && locale.equals(other.locale);
305 }
306
307 /**
308 * <p>Returns a hash code compatible with equals.</p>
304309 *
305310 * @return a hash code compatible with equals
306311 */
310315 }
311316
312317 /**
313 * <p>Get a string version of this formatter.</p>
318 * <p>Gets a string version of this formatter.</p>
314319 *
315320 * @return a debugging string
316321 */
317322 @Override
318323 public String toString() {
319 return "FastDateParser[" + pattern + "," + locale + "," + timeZone.getID() + "]";
324 return "FastDateParser[" + pattern + ", " + locale + ", " + timeZone.getID() + "]";
325 }
326
327 /**
328 * Converts all state of this instance to a String handy for debugging.
329 *
330 * @return a string.
331 * @since 3.12.0
332 */
333 public String toStringAll() {
334 return "FastDateParser [pattern=" + pattern + ", timeZone=" + timeZone + ", locale=" + locale + ", century="
335 + century + ", startYear=" + startYear + ", patterns=" + patterns + "]";
320336 }
321337
322338 // Serializing
323 //-----------------------------------------------------------------------
324 /**
325 * Create the object after serialization. This implementation reinitializes the
339 /**
340 * Creates the object after serialization. This implementation reinitializes the
326341 * transient properties.
327342 *
328343 * @param in ObjectInputStream from which the object is being deserialized.
350365 @Override
351366 public Date parse(final String source) throws ParseException {
352367 final ParsePosition pp = new ParsePosition(0);
353 final Date date= parse(source, pp);
368 final Date date = parse(source, pp);
354369 if (date == null) {
355370 // Add a note re supported date range
356371 if (locale.equals(JAPANESE_IMPERIAL)) {
357 throw new ParseException(
358 "(The " +locale + " locale does not support dates before 1868 AD)\n" +
359 "Unparseable date: \""+source, pp.getErrorIndex());
360 }
361 throw new ParseException("Unparseable date: "+source, pp.getErrorIndex());
372 throw new ParseException("(The " + locale + " locale does not support dates before 1868 AD)\n"
373 + "Unparseable date: \"" + source, pp.getErrorIndex());
374 }
375 throw new ParseException("Unparseable date: " + source, pp.getErrorIndex());
362376 }
363377 return date;
364378 }
386400 @Override
387401 public Date parse(final String source, final ParsePosition pos) {
388402 // timing tests indicate getting new instance is 19% faster than cloning
389 final Calendar cal= Calendar.getInstance(timeZone, locale);
403 final Calendar cal = Calendar.getInstance(timeZone, locale);
390404 cal.clear();
391405
392406 return parse(source, pos, cal) ? cal.getTime() : null;
393407 }
394408
395409 /**
396 * Parse a formatted date string according to the format. Updates the Calendar with parsed fields.
410 * Parses a formatted date string according to the format. Updates the Calendar with parsed fields.
397411 * Upon success, the ParsePosition index is updated to indicate how much of the source text was consumed.
398412 * Not all source text needs to be consumed. Upon parse failure, ParsePosition error index is updated to
399413 * the offset of the source text which does not match the supplied format.
419433 }
420434
421435 // Support for strategies
422 //-----------------------------------------------------------------------
423436
424437 private static StringBuilder simpleQuote(final StringBuilder sb, final String value) {
425438 for (int i = 0; i < value.length(); ++i) {
451464
452465 /**
453466 * Gets the short and long values displayed for a field
454 * @param cal The calendar to obtain the short and long values
467 * @param calendar The calendar to obtain the short and long values
455468 * @param locale The locale of display names
456469 * @param field The field of interest
457470 * @param regex The regular expression to build
458471 * @return The map of string display names to field values
459472 */
460 private static Map<String, Integer> appendDisplayNames(final Calendar cal, final Locale locale, final int field, final StringBuilder regex) {
473 private static Map<String, Integer> appendDisplayNames(final Calendar calendar, Locale locale, final int field,
474 final StringBuilder regex) {
461475 final Map<String, Integer> values = new HashMap<>();
462
463 final Map<String, Integer> displayNames = cal.getDisplayNames(field, Calendar.ALL_STYLES, locale);
476 locale = LocaleUtils.toLocale(locale);
477 final Map<String, Integer> displayNames = calendar.getDisplayNames(field, Calendar.ALL_STYLES, locale);
464478 final TreeSet<String> sorted = new TreeSet<>(LONGER_FIRST_LOWERCASE);
465479 for (final Map.Entry<String, Integer> displayName : displayNames.entrySet()) {
466480 final String key = displayName.getKey().toLowerCase(locale);
475489 }
476490
477491 /**
478 * Adjust dates to be within appropriate century
492 * Adjusts dates to be within appropriate century
479493 * @param twoDigitYear The year to adjust
480494 * @return A value between centuryStart(inclusive) to centuryStart+100(exclusive)
481495 */
488502 * A strategy to parse a single field from the parsing pattern
489503 */
490504 private abstract static class Strategy {
491 /**
492 * Is this field a number?
493 * The default implementation returns false.
505
506 /**
507 * Is this field a number? The default implementation returns false.
494508 *
495509 * @return true, if field is a number
496510 */
498512 return false;
499513 }
500514
501 abstract boolean parse(FastDateParser parser, Calendar calendar, String source, ParsePosition pos, int maxWidth);
515 abstract boolean parse(FastDateParser parser, Calendar calendar, String source, ParsePosition pos,
516 int maxWidth);
502517 }
503518
504519 /**
506521 */
507522 private abstract static class PatternStrategy extends Strategy {
508523
509 private Pattern pattern;
524 Pattern pattern;
510525
511526 void createPattern(final StringBuilder regex) {
512527 createPattern(regex.toString());
517532 }
518533
519534 /**
520 * Is this field a number?
521 * The default implementation returns false.
535 * Is this field a number? The default implementation returns false.
522536 *
523537 * @return true, if field is a number
524538 */
528542 }
529543
530544 @Override
531 boolean parse(final FastDateParser parser, final Calendar calendar, final String source, final ParsePosition pos, final int maxWidth) {
545 boolean parse(final FastDateParser parser, final Calendar calendar, final String source,
546 final ParsePosition pos, final int maxWidth) {
532547 final Matcher matcher = pattern.matcher(source.substring(pos.getIndex()));
533548 if (!matcher.lookingAt()) {
534549 pos.setErrorIndex(pos.getIndex());
539554 return true;
540555 }
541556
542 abstract void setCalendar(FastDateParser parser, Calendar cal, String value);
543 }
544
545 /**
546 * Obtain a Strategy given a field from a SimpleDateFormat pattern
557 abstract void setCalendar(FastDateParser parser, Calendar calendar, String value);
558
559 /**
560 * Converts this instance to a handy debug string.
561 *
562 * @since 3.12.0
563 */
564 @Override
565 public String toString() {
566 return getClass().getSimpleName() + " [pattern=" + pattern + "]";
567 }
568
569 }
570
571 /**
572 * Gets a Strategy given a field from a SimpleDateFormat pattern
547573 * @param f A sub-sequence of the SimpleDateFormat pattern
548574 * @param definingCalendar The calendar to obtain the short and long values
549575 * @return The Strategy that will handle parsing for the field
550576 */
551577 private Strategy getStrategy(final char f, final int width, final Calendar definingCalendar) {
552 switch(f) {
578 switch (f) {
553579 default:
554 throw new IllegalArgumentException("Format '"+f+"' not supported");
580 throw new IllegalArgumentException("Format '" + f + "' not supported");
555581 case 'D':
556582 return DAY_OF_YEAR_STRATEGY;
557583 case 'E':
560586 return DAY_OF_WEEK_IN_MONTH_STRATEGY;
561587 case 'G':
562588 return getLocaleSpecificStrategy(Calendar.ERA, definingCalendar);
563 case 'H': // Hour in day (0-23)
589 case 'H': // Hour in day (0-23)
564590 return HOUR_OF_DAY_STRATEGY;
565 case 'K': // Hour in am/pm (0-11)
591 case 'K': // Hour in am/pm (0-11)
566592 return HOUR_STRATEGY;
567593 case 'M':
568 return width>=3 ?getLocaleSpecificStrategy(Calendar.MONTH, definingCalendar) :NUMBER_MONTH_STRATEGY;
594 return width >= 3 ? getLocaleSpecificStrategy(Calendar.MONTH, definingCalendar) : NUMBER_MONTH_STRATEGY;
569595 case 'S':
570596 return MILLISECOND_STRATEGY;
571597 case 'W':
574600 return getLocaleSpecificStrategy(Calendar.AM_PM, definingCalendar);
575601 case 'd':
576602 return DAY_OF_MONTH_STRATEGY;
577 case 'h': // Hour in am/pm (1-12), i.e. midday/midnight is 12, not 0
603 case 'h': // Hour in am/pm (1-12), i.e. midday/midnight is 12, not 0
578604 return HOUR12_STRATEGY;
579 case 'k': // Hour in day (1-24), i.e. midnight is 24, not 0
605 case 'k': // Hour in day (1-24), i.e. midnight is 24, not 0
580606 return HOUR24_OF_DAY_STRATEGY;
581607 case 'm':
582608 return MINUTE_STRATEGY;
588614 return WEEK_OF_YEAR_STRATEGY;
589615 case 'y':
590616 case 'Y':
591 return width>2 ?LITERAL_YEAR_STRATEGY :ABBREVIATED_YEAR_STRATEGY;
617 return width > 2 ? LITERAL_YEAR_STRATEGY : ABBREVIATED_YEAR_STRATEGY;
592618 case 'X':
593619 return ISO8601TimeZoneStrategy.getStrategy(width);
594620 case 'Z':
595 if (width==2) {
621 if (width == 2) {
596622 return ISO8601TimeZoneStrategy.ISO_8601_3_STRATEGY;
597623 }
598624 //$FALL-THROUGH$
628654 final ConcurrentMap<Locale, Strategy> cache = getCache(field);
629655 Strategy strategy = cache.get(locale);
630656 if (strategy == null) {
631 strategy = field == Calendar.ZONE_OFFSET
632 ? new TimeZoneStrategy(locale)
633 : new CaseInsensitiveTextStrategy(field, definingCalendar, locale);
657 strategy = field == Calendar.ZONE_OFFSET ? new TimeZoneStrategy(locale)
658 : new CaseInsensitiveTextStrategy(field, definingCalendar, locale);
634659 final Strategy inCache = cache.putIfAbsent(locale, strategy);
635660 if (inCache != null) {
636661 return inCache;
648673
649674 /**
650675 * Constructs a Strategy that ensures the formatField has literal text
676 *
651677 * @param formatField The literal text to match
652678 */
653679 CopyQuotedStrategy(final String formatField) {
663689 }
664690
665691 @Override
666 boolean parse(final FastDateParser parser, final Calendar calendar, final String source, final ParsePosition pos, final int maxWidth) {
692 boolean parse(final FastDateParser parser, final Calendar calendar, final String source,
693 final ParsePosition pos, final int maxWidth) {
667694 for (int idx = 0; idx < formatField.length(); ++idx) {
668695 final int sIdx = idx + pos.getIndex();
669696 if (sIdx == source.length()) {
678705 pos.setIndex(formatField.length() + pos.getIndex());
679706 return true;
680707 }
708
709 /**
710 * Converts this instance to a handy debug string.
711 *
712 * @since 3.12.0
713 */
714 @Override
715 public String toString() {
716 return "CopyQuotedStrategy [formatField=" + formatField + "]";
717 }
681718 }
682719
683720 /**
684721 * A strategy that handles a text field in the parsing pattern
685722 */
686 private static class CaseInsensitiveTextStrategy extends PatternStrategy {
723 private static class CaseInsensitiveTextStrategy extends PatternStrategy {
687724 private final int field;
688725 final Locale locale;
689726 private final Map<String, Integer> lKeyValues;
690727
691728 /**
692729 * Constructs a Strategy that parses a Text field
693 * @param field The Calendar field
694 * @param definingCalendar The Calendar to use
695 * @param locale The Locale to use
730 *
731 * @param field The Calendar field
732 * @param definingCalendar The Calendar to use
733 * @param locale The Locale to use
696734 */
697735 CaseInsensitiveTextStrategy(final int field, final Calendar definingCalendar, final Locale locale) {
698736 this.field = field;
699 this.locale = locale;
737 this.locale = LocaleUtils.toLocale(locale);
700738
701739 final StringBuilder regex = new StringBuilder();
702740 regex.append("((?iu)");
703741 lKeyValues = appendDisplayNames(definingCalendar, locale, field, regex);
704 regex.setLength(regex.length()-1);
742 regex.setLength(regex.length() - 1);
705743 regex.append(")");
706744 createPattern(regex);
707745 }
710748 * {@inheritDoc}
711749 */
712750 @Override
713 void setCalendar(final FastDateParser parser, final Calendar cal, final String value) {
751 void setCalendar(final FastDateParser parser, final Calendar calendar, final String value) {
714752 final String lowerCase = value.toLowerCase(locale);
715753 Integer iVal = lKeyValues.get(lowerCase);
716754 if (iVal == null) {
717755 // match missing the optional trailing period
718756 iVal = lKeyValues.get(lowerCase + '.');
719757 }
720 cal.set(field, iVal.intValue());
758 //LANG-1669: Mimic fix done in OpenJDK 17 to resolve issue with parsing newly supported day periods added in OpenJDK 16
759 if (Calendar.AM_PM != this.field || iVal <= 1) {
760 calendar.set(field, iVal.intValue());
761 }
762 }
763
764 /**
765 * Converts this instance to a handy debug string.
766 *
767 * @since 3.12.0
768 */
769 @Override
770 public String toString() {
771 return "CaseInsensitiveTextStrategy [field=" + field + ", locale=" + locale + ", lKeyValues=" + lKeyValues
772 + ", pattern=" + pattern + "]";
721773 }
722774 }
723775
726778 * A strategy that handles a number field in the parsing pattern
727779 */
728780 private static class NumberStrategy extends Strategy {
781
729782 private final int field;
730783
731784 /**
732785 * Constructs a Strategy that parses a Number field
786 *
733787 * @param field The Calendar field
734788 */
735789 NumberStrategy(final int field) {
736 this.field= field;
790 this.field = field;
737791 }
738792
739793 /**
745799 }
746800
747801 @Override
748 boolean parse(final FastDateParser parser, final Calendar calendar, final String source, final ParsePosition pos, final int maxWidth) {
802 boolean parse(final FastDateParser parser, final Calendar calendar, final String source,
803 final ParsePosition pos, final int maxWidth) {
749804 int idx = pos.getIndex();
750805 int last = source.length();
751806
786841
787842 /**
788843 * Make any modifications to parsed integer
844 *
789845 * @param parser The parser
790846 * @param iValue The parsed integer
791847 * @return The modified value
794850 return iValue;
795851 }
796852
853 /**
854 * Converts this instance to a handy debug string.
855 *
856 * @since 3.12.0
857 */
858 @Override
859 public String toString() {
860 return "NumberStrategy [field=" + field + "]";
861 }
797862 }
798863
799864 private static final Strategy ABBREVIATED_YEAR_STRATEGY = new NumberStrategy(Calendar.YEAR) {
807872 };
808873
809874 /**
810 * A strategy that handles a timezone field in the parsing pattern
875 * A strategy that handles a time zone field in the parsing pattern
811876 */
812877 static class TimeZoneStrategy extends PatternStrategy {
813878 private static final String RFC_822_TIME_ZONE = "[+-]\\d{4}";
814879 private static final String GMT_OPTION = TimeZones.GMT_ID + "[+-]\\d{1,2}:\\d{2}";
815880
816881 private final Locale locale;
817 private final Map<String, TzInfo> tzNames= new HashMap<>();
882 private final Map<String, TzInfo> tzNames = new HashMap<>();
818883
819884 private static class TzInfo {
820 TimeZone zone;
821 int dstOffset;
885 final TimeZone zone;
886 final int dstOffset;
822887
823888 TzInfo(final TimeZone tz, final boolean useDst) {
824889 zone = tz;
825 dstOffset = useDst ?tz.getDSTSavings() :0;
890 dstOffset = useDst ? tz.getDSTSavings() : 0;
826891 }
827892 }
828893
833898
834899 /**
835900 * Constructs a Strategy that parses a TimeZone
901 *
836902 * @param locale The Locale
837903 */
838904 TimeZoneStrategy(final Locale locale) {
839 this.locale = locale;
905 this.locale = LocaleUtils.toLocale(locale);
840906
841907 final StringBuilder sb = new StringBuilder();
842 sb.append("((?iu)" + RFC_822_TIME_ZONE + "|" + GMT_OPTION );
908 sb.append("((?iu)" + RFC_822_TIME_ZONE + "|" + GMT_OPTION);
843909
844910 final Set<String> sorted = new TreeSet<>(LONGER_FIRST_LOWERCASE);
845911
890956 * {@inheritDoc}
891957 */
892958 @Override
893 void setCalendar(final FastDateParser parser, final Calendar cal, final String timeZone) {
959 void setCalendar(final FastDateParser parser, final Calendar calendar, final String timeZone) {
894960 final TimeZone tz = FastTimeZone.getGmtTimeZone(timeZone);
895961 if (tz != null) {
896 cal.setTimeZone(tz);
962 calendar.setTimeZone(tz);
897963 } else {
898964 final String lowerCase = timeZone.toLowerCase(locale);
899965 TzInfo tzInfo = tzNames.get(lowerCase);
901967 // match missing the optional trailing period
902968 tzInfo = tzNames.get(lowerCase + '.');
903969 }
904 cal.set(Calendar.DST_OFFSET, tzInfo.dstOffset);
905 cal.set(Calendar.ZONE_OFFSET, tzInfo.zone.getRawOffset());
906 }
907 }
970 calendar.set(Calendar.DST_OFFSET, tzInfo.dstOffset);
971 calendar.set(Calendar.ZONE_OFFSET, tzInfo.zone.getRawOffset());
972 }
973 }
974
975 /**
976 * Converts this instance to a handy debug string.
977 *
978 * @since 3.12.0
979 */
980 @Override
981 public String toString() {
982 return "TimeZoneStrategy [locale=" + locale + ", tzNames=" + tzNames + ", pattern=" + pattern + "]";
983 }
984
908985 }
909986
910987 private static class ISO8601TimeZoneStrategy extends PatternStrategy {
922999 * {@inheritDoc}
9231000 */
9241001 @Override
925 void setCalendar(final FastDateParser parser, final Calendar cal, final String value) {
926 cal.setTimeZone(FastTimeZone.getGmtTimeZone(value));
1002 void setCalendar(final FastDateParser parser, final Calendar calendar, final String value) {
1003 calendar.setTimeZone(FastTimeZone.getGmtTimeZone(value));
9271004 }
9281005
9291006 private static final Strategy ISO_8601_1_STRATEGY = new ISO8601TimeZoneStrategy("(Z|(?:[+-]\\d{2}))");
3030 import java.util.concurrent.ConcurrentHashMap;
3131 import java.util.concurrent.ConcurrentMap;
3232
33 import org.apache.commons.lang3.LocaleUtils;
3334 import org.apache.commons.lang3.exception.ExceptionUtils;
3435
3536 /**
8990 // taking the value and adding (mathematically) the ASCII value for '0'.
9091 // So, don't change this code! It works and is very fast.
9192
93 /** Empty array. */
94 private static final Rule[] EMPTY_RULE_ARRAY = {};
95
9296 /**
9397 * Required for serialization support.
9498 *
135139 private transient int mMaxLengthEstimate;
136140
137141 // Constructor
138 //-----------------------------------------------------------------------
139142 /**
140143 * <p>Constructs a new FastDatePrinter.</p>
141144 * Use {@link FastDateFormat#getInstance(String, TimeZone, Locale)} or another variation of the
149152 protected FastDatePrinter(final String pattern, final TimeZone timeZone, final Locale locale) {
150153 mPattern = pattern;
151154 mTimeZone = timeZone;
152 mLocale = locale;
155 mLocale = LocaleUtils.toLocale(locale);
153156
154157 init();
155158 }
159162 */
160163 private void init() {
161164 final List<Rule> rulesList = parsePattern();
162 mRules = rulesList.toArray(new Rule[0]);
165 mRules = rulesList.toArray(EMPTY_RULE_ARRAY);
163166
164167 int len = 0;
165168 for (int i=mRules.length; --i >= 0; ) {
170173 }
171174
172175 // Parse the pattern
173 //-----------------------------------------------------------------------
174176 /**
175177 * <p>Returns a list of Rules given a pattern.</p>
176178 *
333335
334336 while (i + 1 < length) {
335337 final char peek = pattern.charAt(i + 1);
336 if (peek == c) {
337 buf.append(c);
338 i++;
339 } else {
338 if (peek != c) {
340339 break;
341340 }
341 buf.append(c);
342 i++;
342343 }
343344 } else {
344345 // This will identify token as text.
390391 }
391392
392393 // Format methods
393 //-----------------------------------------------------------------------
394394 /**
395395 * <p>Formats a {@code Date}, {@code Calendar} or
396396 * {@code Long} (milliseconds) object.</p>
405405 public StringBuffer format(final Object obj, final StringBuffer toAppendTo, final FieldPosition pos) {
406406 if (obj instanceof Date) {
407407 return format((Date) obj, toAppendTo);
408 } else if (obj instanceof Calendar) {
408 }
409 if (obj instanceof Calendar) {
409410 return format((Calendar) obj, toAppendTo);
410 } else if (obj instanceof Long) {
411 }
412 if (obj instanceof Long) {
411413 return format(((Long) obj).longValue(), toAppendTo);
412 } else {
413 throw new IllegalArgumentException("Unknown class: " +
414 (obj == null ? "<null>" : obj.getClass().getName()));
415 }
414 }
415 throw new IllegalArgumentException("Unknown class: " +
416 (obj == null ? "<null>" : obj.getClass().getName()));
416417 }
417418
418419 /**
425426 String format(final Object obj) {
426427 if (obj instanceof Date) {
427428 return format((Date) obj);
428 } else if (obj instanceof Calendar) {
429 }
430 if (obj instanceof Calendar) {
429431 return format((Calendar) obj);
430 } else if (obj instanceof Long) {
432 }
433 if (obj instanceof Long) {
431434 return format(((Long) obj).longValue());
432 } else {
433 throw new IllegalArgumentException("Unknown class: " +
434 (obj == null ? "<null>" : obj.getClass().getName()));
435 }
435 }
436 throw new IllegalArgumentException("Unknown class: " +
437 (obj == null ? "<null>" : obj.getClass().getName()));
436438 }
437439
438440 /* (non-Javadoc)
578580 }
579581
580582 // Accessors
581 //-----------------------------------------------------------------------
582583 /* (non-Javadoc)
583584 * @see org.apache.commons.lang3.time.DatePrinter#getPattern()
584585 */
617618 }
618619
619620 // Basics
620 //-----------------------------------------------------------------------
621621 /**
622622 * <p>Compares two objects for equality.</p>
623623 *
656656 }
657657
658658 // Serializing
659 //-----------------------------------------------------------------------
660659 /**
661660 * Create the object after serialization. This implementation reinitializes the
662661 * transient properties.
756755 }
757756
758757 // Rules
759 //-----------------------------------------------------------------------
760758 /**
761759 * <p>Inner class defining a rule.</p>
762760 */
773771 *
774772 * @param buf the output buffer
775773 * @param calendar calendar to be appended
776 * @throws IOException if an I/O error occurs
774 * @throws IOException if an I/O error occurs.
777775 */
778776 void appendTo(Appendable buf, Calendar calendar) throws IOException;
779777 }
787785 *
788786 * @param buffer the output buffer
789787 * @param value the value to be appended
790 * @throws IOException if an I/O error occurs
788 * @throws IOException if an I/O error occurs.
791789 */
792790 void appendTo(Appendable buffer, int value) throws IOException;
793791 }
958956 *
959957 */
960958 UnpaddedMonthField() {
961 super();
962959 }
963960
964961 /**
10911088 * Constructs an instance of {@code TwoDigitYearField}.
10921089 */
10931090 TwoDigitYearField() {
1094 super();
10951091 }
10961092
10971093 /**
11151111 */
11161112 @Override
11171113 public final void appendTo(final Appendable buffer, final int value) throws IOException {
1118 appendDigits(buffer, value);
1114 appendDigits(buffer, value % 100);
11191115 }
11201116 }
11211117
11291125 * Constructs an instance of {@code TwoDigitMonthField}.
11301126 */
11311127 TwoDigitMonthField() {
1132 super();
11331128 }
11341129
11351130 /**
13001295 }
13011296 }
13021297
1303 //-----------------------------------------------------------------------
13041298
13051299 private static final ConcurrentMap<TimeZoneDisplayKey, String> cTimeZoneDisplayCache =
13061300 new ConcurrentHashMap<>(7);
13441338 * @param style the style
13451339 */
13461340 TimeZoneNameRule(final TimeZone timeZone, final Locale locale, final int style) {
1347 mLocale = locale;
1341 mLocale = LocaleUtils.toLocale(locale);
13481342 mStyle = style;
13491343
13501344 mStandard = getTimeZoneDisplay(timeZone, false, style, locale);
15301524 *
15311525 * @param timeZone the time zone
15321526 * @param daylight adjust the style for daylight saving time if {@code true}
1533 * @param style the timezone style
1534 * @param locale the timezone locale
1527 * @param style the time zone style
1528 * @param locale the time zone locale
15351529 */
15361530 TimeZoneDisplayKey(final TimeZone timeZone,
15371531 final boolean daylight, final int style, final Locale locale) {
15411535 } else {
15421536 mStyle = style;
15431537 }
1544 mLocale = locale;
1538 mLocale = LocaleUtils.toLocale(locale);
15451539 }
15461540
15471541 /**
6969 * i.e. <em>[GMT] (+|-) Hours [[:] Minutes]</em>
7070 *
7171 * @param id A GMT custom id (or Olson id
72 * @return A timezone
72 * @return A time zone
7373 */
7474 public static TimeZone getTimeZone(final String id) {
7575 final TimeZone tz = getGmtTimeZone(id);
2424 import java.util.concurrent.ConcurrentHashMap;
2525 import java.util.concurrent.ConcurrentMap;
2626
27 import org.apache.commons.lang3.LocaleUtils;
2728 import org.apache.commons.lang3.Validate;
2829
2930 /**
30 * <p>FormatCache is a cache and factory for {@link Format}s.</p>
31 * FormatCache is a cache and factory for {@link Format}s.
3132 *
3233 * @since 3.0
3334 */
3738 /**
3839 * No date or no time. Used in same parameters as DateFormat.SHORT or DateFormat.LONG
3940 */
40 static final int NONE= -1;
41
42 private final ConcurrentMap<MultipartKey, F> cInstanceCache
43 = new ConcurrentHashMap<>(7);
44
45 private static final ConcurrentMap<MultipartKey, String> cDateTimeInstanceCache
46 = new ConcurrentHashMap<>(7);
47
48 /**
49 * <p>Gets a formatter instance using the default pattern in the
50 * default timezone and locale.</p>
41 static final int NONE = -1;
42
43 private final ConcurrentMap<ArrayKey, F> cInstanceCache = new ConcurrentHashMap<>(7);
44
45 private static final ConcurrentMap<ArrayKey, String> cDateTimeInstanceCache = new ConcurrentHashMap<>(7);
46
47 /**
48 * Gets a formatter instance using the default pattern in the
49 * default time zone and locale.
5150 *
5251 * @return a date/time formatter
5352 */
5655 }
5756
5857 /**
59 * <p>Gets a formatter instance using the specified pattern, time zone
60 * and locale.</p>
58 * Gets a formatter instance using the specified pattern, time zone
59 * and locale.
6160 *
6261 * @param pattern {@link java.text.SimpleDateFormat} compatible
6362 * pattern, non-null
6867 * @throws IllegalArgumentException if pattern is invalid
6968 */
7069 public F getInstance(final String pattern, TimeZone timeZone, Locale locale) {
71 Validate.notNull(pattern, "pattern must not be null");
70 Validate.notNull(pattern, "pattern");
7271 if (timeZone == null) {
7372 timeZone = TimeZone.getDefault();
7473 }
75 if (locale == null) {
76 locale = Locale.getDefault();
77 }
78 final MultipartKey key = new MultipartKey(pattern, timeZone, locale);
74 locale = LocaleUtils.toLocale(locale);
75 final ArrayKey key = new ArrayKey(pattern, timeZone, locale);
7976 F format = cInstanceCache.get(key);
8077 if (format == null) {
8178 format = createInstance(pattern, timeZone, locale);
82 final F previousValue= cInstanceCache.putIfAbsent(key, format);
79 final F previousValue = cInstanceCache.putIfAbsent(key, format);
8380 if (previousValue != null) {
8481 // another thread snuck in and did the same work
8582 // we should return the instance that is in ConcurrentMap
86 format= previousValue;
83 format = previousValue;
8784 }
8885 }
8986 return format;
9087 }
9188
9289 /**
93 * <p>Create a format instance using the specified pattern, time zone
94 * and locale.</p>
90 * Create a format instance using the specified pattern, time zone
91 * and locale.
9592 *
9693 * @param pattern {@link java.text.SimpleDateFormat} compatible pattern, this will not be null.
9794 * @param timeZone time zone, this will not be null.
103100 protected abstract F createInstance(String pattern, TimeZone timeZone, Locale locale);
104101
105102 /**
106 * <p>Gets a date/time formatter instance using the specified style,
107 * time zone and locale.</p>
103 * Gets a date/time formatter instance using the specified style,
104 * time zone and locale.
108105 *
109106 * @param dateStyle date style: FULL, LONG, MEDIUM, or SHORT, null indicates no date in format
110107 * @param timeStyle time style: FULL, LONG, MEDIUM, or SHORT, null indicates no time in format
117114 */
118115 // This must remain private, see LANG-884
119116 private F getDateTimeInstance(final Integer dateStyle, final Integer timeStyle, final TimeZone timeZone, Locale locale) {
120 if (locale == null) {
121 locale = Locale.getDefault();
122 }
117 locale = LocaleUtils.toLocale(locale);
123118 final String pattern = getPatternForStyle(dateStyle, timeStyle, locale);
124119 return getInstance(pattern, timeZone, locale);
125120 }
126121
127122 /**
128 * <p>Gets a date/time formatter instance using the specified style,
129 * time zone and locale.</p>
123 * Gets a date/time formatter instance using the specified style,
124 * time zone and locale.
130125 *
131126 * @param dateStyle date style: FULL, LONG, MEDIUM, or SHORT
132127 * @param timeStyle time style: FULL, LONG, MEDIUM, or SHORT
143138 }
144139
145140 /**
146 * <p>Gets a date formatter instance using the specified style,
147 * time zone and locale.</p>
141 * Gets a date formatter instance using the specified style,
142 * time zone and locale.
148143 *
149144 * @param dateStyle date style: FULL, LONG, MEDIUM, or SHORT
150145 * @param timeZone optional time zone, overrides time zone of
160155 }
161156
162157 /**
163 * <p>Gets a time formatter instance using the specified style,
164 * time zone and locale.</p>
158 * Gets a time formatter instance using the specified style,
159 * time zone and locale.
165160 *
166161 * @param timeStyle time style: FULL, LONG, MEDIUM, or SHORT
167162 * @param timeZone optional time zone, overrides time zone of
177172 }
178173
179174 /**
180 * <p>Gets a date/time format for the specified styles and locale.</p>
175 * Gets a date/time format for the specified styles and locale.
181176 *
182177 * @param dateStyle date style: FULL, LONG, MEDIUM, or SHORT, null indicates no date in format
183178 * @param timeStyle time style: FULL, LONG, MEDIUM, or SHORT, null indicates no time in format
187182 */
188183 // package protected, for access from test code; do not make public or protected
189184 static String getPatternForStyle(final Integer dateStyle, final Integer timeStyle, final Locale locale) {
190 final MultipartKey key = new MultipartKey(dateStyle, timeStyle, locale);
185 final Locale safeLocale = LocaleUtils.toLocale(locale);
186 final ArrayKey key = new ArrayKey(dateStyle, timeStyle, safeLocale);
191187
192188 String pattern = cDateTimeInstanceCache.get(key);
193189 if (pattern == null) {
194190 try {
195 DateFormat formatter;
191 final DateFormat formatter;
196192 if (dateStyle == null) {
197 formatter = DateFormat.getTimeInstance(timeStyle.intValue(), locale);
193 formatter = DateFormat.getTimeInstance(timeStyle.intValue(), safeLocale);
198194 } else if (timeStyle == null) {
199 formatter = DateFormat.getDateInstance(dateStyle.intValue(), locale);
195 formatter = DateFormat.getDateInstance(dateStyle.intValue(), safeLocale);
200196 } else {
201 formatter = DateFormat.getDateTimeInstance(dateStyle.intValue(), timeStyle.intValue(), locale);
197 formatter = DateFormat.getDateTimeInstance(dateStyle.intValue(), timeStyle.intValue(), safeLocale);
202198 }
203199 pattern = ((SimpleDateFormat) formatter).toPattern();
204200 final String previous = cDateTimeInstanceCache.putIfAbsent(key, pattern);
206202 // even though it doesn't matter if another thread put the pattern
207203 // it's still good practice to return the String instance that is
208204 // actually in the ConcurrentMap
209 pattern= previous;
205 pattern = previous;
210206 }
211207 } catch (final ClassCastException ex) {
212 throw new IllegalArgumentException("No date time pattern for locale: " + locale);
208 throw new IllegalArgumentException("No date time pattern for locale: " + safeLocale);
213209 }
214210 }
215211 return pattern;
216212 }
217213
218 // ----------------------------------------------------------------------
219 /**
220 * <p>Helper class to hold multi-part Map keys</p>
221 */
222 private static class MultipartKey {
214 /**
215 * Helper class to hold multi-part Map keys as arrays.
216 */
217 private static final class ArrayKey {
218
219 private static int computeHashCode(final Object[] keys) {
220 final int prime = 31;
221 int result = 1;
222 result = prime * result + Arrays.hashCode(keys);
223 return result;
224 }
225
223226 private final Object[] keys;
224 private int hashCode;
227 private final int hashCode;
225228
226229 /**
227230 * Constructs an instance of {@code MultipartKey} to hold the specified objects.
231 *
228232 * @param keys the set of objects that make up the key. Each key may be null.
229233 */
230 MultipartKey(final Object... keys) {
234 ArrayKey(final Object... keys) {
231235 this.keys = keys;
232 }
233
234 /**
235 * {@inheritDoc}
236 */
236 this.hashCode = computeHashCode(keys);
237 }
238
239 @Override
240 public int hashCode() {
241 return hashCode;
242 }
243
237244 @Override
238245 public boolean equals(final Object obj) {
239 // Eliminate the usual boilerplate because
240 // this inner static class is only used in a generic ConcurrentHashMap
241 // which will not compare against other Object types
242 return Arrays.equals(keys, ((MultipartKey) obj).keys);
243 }
244
245 /**
246 * {@inheritDoc}
247 */
248 @Override
249 public int hashCode() {
250 if (hashCode==0) {
251 int rc= 0;
252 for (final Object key : keys) {
253 if (key!=null) {
254 rc= rc*7 + key.hashCode();
255 }
256 }
257 hashCode= rc;
258 }
259 return hashCode;
260 }
246 if (this == obj) {
247 return true;
248 }
249 if (obj == null) {
250 return false;
251 }
252 if (getClass() != obj.getClass()) {
253 return false;
254 }
255 final ArrayKey other = (ArrayKey) obj;
256 return Arrays.deepEquals(keys, other.keys);
257 }
258
259
261260 }
262261
263262 }
1919 import java.util.TimeZone;
2020
2121 /**
22 * Custom timezone that contains offset from GMT.
22 * Custom time zone that contains offset from GMT.
2323 *
2424 * @since 3.7
2525 */
204204 private SplitState splitState = SplitState.UNSPLIT;
205205
206206 /**
207 * The start time.
208 */
209 private long startTime;
210
211 /**
212 * The start time in Millis - nanoTime is only for elapsed time so we
207 * The start time in nanoseconds.
208 */
209 private long startTimeNanos;
210
211 /**
212 * The start time in milliseconds - nanoTime is only for elapsed time so we
213213 * need to also store the currentTimeMillis to maintain the old
214214 * getStartTime API.
215215 */
216216 private long startTimeMillis;
217217
218218 /**
219 * The stop time.
220 */
221 private long stopTime;
219 * The end time in milliseconds - nanoTime is only for elapsed time so we
220 * need to also store the currentTimeMillis to maintain the old
221 * getStartTime API.
222 */
223 private long stopTimeMillis;
224
225 /**
226 * The stop time in nanoseconds.
227 */
228 private long stopTimeNanos;
222229
223230 /**
224231 * <p>
241248 }
242249
243250 /**
251 * Returns the split time formatted by {@link DurationFormatUtils#formatDurationHMS}.
252 *
253 * @return the split time formatted by {@link DurationFormatUtils#formatDurationHMS}.
254 * @since 3.10
255 */
256 public String formatSplitTime() {
257 return DurationFormatUtils.formatDurationHMS(getSplitTime());
258 }
259
260 /**
244261 * Returns the time formatted by {@link DurationFormatUtils#formatDurationHMS}.
245262 *
246263 * @return the time formatted by {@link DurationFormatUtils#formatDurationHMS}.
247264 * @since 3.10
248265 */
249 public String formatSplitTime() {
250 return DurationFormatUtils.formatDurationHMS(getSplitTime());
251 }
252
253 /**
254 * Returns the split time formatted by {@link DurationFormatUtils#formatDurationHMS}.
255 *
256 * @return the split time formatted by {@link DurationFormatUtils#formatDurationHMS}.
257 * @since 3.10
258 */
259266 public String formatTime() {
260267 return DurationFormatUtils.formatDurationHMS(getTime());
261268 }
272279
273280 /**
274281 * <p>
275 * Gets the time on the stopwatch in nanoseconds.
282 * Gets the <em>elapsed</em> time in nanoseconds.
276283 * </p>
277284 *
278285 * <p>
280287 * start and stop.
281288 * </p>
282289 *
283 * @return the time in nanoseconds
290 * @return the <em>elapsed</em> time in nanoseconds.
291 * @see System#nanoTime()
284292 * @since 3.0
285293 */
286294 public long getNanoTime() {
287295 if (this.runningState == State.STOPPED || this.runningState == State.SUSPENDED) {
288 return this.stopTime - this.startTime;
289 } else if (this.runningState == State.UNSTARTED) {
296 return this.stopTimeNanos - this.startTimeNanos;
297 }
298 if (this.runningState == State.UNSTARTED) {
290299 return 0;
291 } else if (this.runningState == State.RUNNING) {
292 return System.nanoTime() - this.startTime;
293 }
294 throw new RuntimeException("Illegal running state has occurred.");
295 }
296
297 /**
298 * <p>
299 * Gets the split time on the stopwatch in nanoseconds.
300 }
301 if (this.runningState == State.RUNNING) {
302 return System.nanoTime() - this.startTimeNanos;
303 }
304 throw new IllegalStateException("Illegal running state has occurred.");
305 }
306
307 /**
308 * <p>
309 * Gets the split time in nanoseconds.
300310 * </p>
301311 *
302312 * <p>
311321 */
312322 public long getSplitNanoTime() {
313323 if (this.splitState != SplitState.SPLIT) {
314 throw new IllegalStateException("Stopwatch must be split to get the split time. ");
315 }
316 return this.stopTime - this.startTime;
324 throw new IllegalStateException("Stopwatch must be split to get the split time.");
325 }
326 return this.stopTimeNanos - this.startTimeNanos;
317327 }
318328
319329 /**
336346 }
337347
338348 /**
339 * Gets the time this stopwatch was started.
340 *
341 * @return the time this stopwatch was started
342 * @throws IllegalStateException
343 * if this StopWatch has not been started
349 * Gets the time this stopwatch was started in milliseconds, between the current time and midnight, January 1, 1970
350 * UTC.
351 *
352 * @return the time this stopwatch was started in milliseconds, between the current time and midnight, January 1,
353 * 1970 UTC.
354 * @throws IllegalStateException if this StopWatch has not been started
344355 * @since 2.4
345356 */
346357 public long getStartTime() {
352363 }
353364
354365 /**
366 * Gets the time this stopwatch was stopped in milliseconds, between the current time and midnight, January 1, 1970
367 * UTC.
368 *
369 * @return the time this stopwatch was started in milliseconds, between the current time and midnight, January 1,
370 * 1970 UTC.
371 * @throws IllegalStateException if this StopWatch has not been started
372 * @since 3.12.0
373 */
374 public long getStopTime() {
375 if (this.runningState == State.UNSTARTED) {
376 throw new IllegalStateException("Stopwatch has not been started");
377 }
378 // System.nanoTime is for elapsed time
379 return this.stopTimeMillis;
380 }
381
382 /**
355383 * <p>
356384 * Gets the time on the stopwatch.
357385 * </p>
369397
370398 /**
371399 * <p>
372 * Gets the time on the stopwatch in the specified TimeUnit.
400 * Gets the time in the specified TimeUnit.
373401 * </p>
374402 *
375403 * <p>
438466 this.runningState = State.UNSTARTED;
439467 this.splitState = SplitState.UNSPLIT;
440468 }
469
441470 /**
442471 * <p>
443472 * Resumes the stopwatch after a suspend.
455484 if (this.runningState != State.SUSPENDED) {
456485 throw new IllegalStateException("Stopwatch must be suspended to resume. ");
457486 }
458 this.startTime += System.nanoTime() - this.stopTime;
487 this.startTimeNanos += System.nanoTime() - this.stopTimeNanos;
459488 this.runningState = State.RUNNING;
460489 }
461490
476505 if (this.runningState != State.RUNNING) {
477506 throw new IllegalStateException("Stopwatch is not running. ");
478507 }
479 this.stopTime = System.nanoTime();
508 this.stopTimeNanos = System.nanoTime();
480509 this.splitState = SplitState.SPLIT;
481510 }
482511
499528 if (this.runningState != State.UNSTARTED) {
500529 throw new IllegalStateException("Stopwatch already started. ");
501530 }
502 this.startTime = System.nanoTime();
531 this.startTimeNanos = System.nanoTime();
503532 this.startTimeMillis = System.currentTimeMillis();
504533 this.runningState = State.RUNNING;
505534 }
521550 throw new IllegalStateException("Stopwatch is not running. ");
522551 }
523552 if (this.runningState == State.RUNNING) {
524 this.stopTime = System.nanoTime();
553 this.stopTimeNanos = System.nanoTime();
554 this.stopTimeMillis = System.currentTimeMillis();
525555 }
526556 this.runningState = State.STOPPED;
527557 }
543573 if (this.runningState != State.RUNNING) {
544574 throw new IllegalStateException("Stopwatch must be running to suspend. ");
545575 }
546 this.stopTime = System.nanoTime();
576 this.stopTimeNanos = System.nanoTime();
577 this.stopTimeMillis = System.currentTimeMillis();
547578 this.runningState = State.SUSPENDED;
548579 }
549580
166166 * @param right the right value, may be null
167167 */
168168 public ImmutablePair(final L left, final R right) {
169 super();
170169 this.left = left;
171170 this.right = right;
172171 }
114114 * @param right the right value, may be null
115115 */
116116 public ImmutableTriple(final L left, final M middle, final R right) {
117 super();
118117 this.left = left;
119118 this.middle = middle;
120119 this.right = right;
121120 }
122121
123 //-----------------------------------------------------------------------
124122 /**
125123 * {@inheritDoc}
126124 */
106106 * Create a new pair instance of two nulls.
107107 */
108108 public MutablePair() {
109 super();
110109 }
111110
112111 /**
116115 * @param right the right value, may be null
117116 */
118117 public MutablePair(final L left, final R right) {
119 super();
120118 this.left = left;
121119 this.right = right;
122120 }
123121
124 //-----------------------------------------------------------------------
125122 /**
126123 * {@inheritDoc}
127124 */
8585 * Create a new triple instance of three nulls.
8686 */
8787 public MutableTriple() {
88 super();
8988 }
9089
9190 /**
9695 * @param right the right value, may be null
9796 */
9897 public MutableTriple(final L left, final M middle, final R right) {
99 super();
10098 this.left = left;
10199 this.middle = middle;
102100 this.right = right;
103101 }
104102
105 //-----------------------------------------------------------------------
106103 /**
107104 * {@inheritDoc}
108105 */
119119 return ImmutablePair.of(pair);
120120 }
121121
122 //-----------------------------------------------------------------------
123122 /**
124123 * <p>Compares the pair based on the left element followed by the right element.
125124 * The types must be {@code Comparable}.</p>
165164 return getLeft();
166165 }
167166
168 //-----------------------------------------------------------------------
169167 /**
170168 * <p>Gets the left element from this pair.</p>
171169 *
105105 return new ImmutableTriple<>(left, middle, right);
106106 }
107107
108 //-----------------------------------------------------------------------
109108 /**
110109 * <p>Compares the triple based on the left element, followed by the middle element,
111110 * finally the right element.
141140 return false;
142141 }
143142
144 //-----------------------------------------------------------------------
145143 /**
146144 * <p>Gets the left element from this triple.</p>
147145 *
1414 See the License for the specific language governing permissions and
1515 limitations under the License.
1616 -->
17 <!DOCTYPE suppressions PUBLIC "-//Puppy Crawl//DTD Suppressions 1.1//EN" "http://www.puppycrawl.com/dtds/suppressions_1_1.dtd">
17 <!DOCTYPE suppressions PUBLIC "-//Checkstyle//DTD SuppressionFilter Configuration 1.0//EN" "https://checkstyle.org/dtds/suppressions_1_0.dtd">
1818 <suppressions>
1919 <suppress checks="JavadocMethod" files=".*[/\\]test[/\\].*"/>
2020 <suppress checks="JavadocPackage" files=".*[/\\]test[/\\].*"/>
2121 <!-- exclude generated JMH classes from all checks -->
2222 <suppress checks="[a-zA-Z0-9]*" files=".*[/\\]generated-test-sources[/\\].*"/>
2323 <suppress checks="RedundantModifier" files="ConstructorUtilsTest" lines="0-99999"/>
24 <!-- Windows-only workaround -->
25 <suppress checks="NewlineAtEndOfFile" files="target[/\\]maven-archiver[/\\]pom.properties"/>
2426 </suppressions>
1616 -->
1717
1818 <!DOCTYPE module PUBLIC
19 "-//Puppy Crawl//DTD Check Configuration 1.1//EN"
20 "http://www.puppycrawl.com/dtds/configuration_1_1.dtd">
19 "-//Checkstyle//DTD Checkstyle Configuration 1.2//EN"
20 "https://checkstyle.org/dtds/configuration_1_2.dtd">
2121
2222 <!-- Apache Commons Lang customization of default Checkstyle behavior -->
2323 <module name="Checker">
4444 <module name="UnusedImports"/>
4545 <module name="NeedBraces"/>
4646 <module name="JavadocMethod">
47 <property name="scope" value="public" />
47 <property name="accessModifiers" value="public" />
4848 </module>
4949 <module name="ModifierOrder"/>
5050 <module name="RedundantModifier"/>
8686 <a href="userguide.html" title="Users guide">Users guide</a>
8787 </li>
8888 <li class="none">
89 <a href="release-history.html" title="Release History">Release History</a>
89 <a href="changes-report.html" title="Release History">Release History</a>
9090 </li>
9191 <li class="none">
9292 <a href="api-release/index.html" title="Javadoc (3.0 release)">Javadoc (3.0 release)</a>
2323
2424 <body>
2525 <menu name="Lang">
26 <item name="Overview" href="/index.html"/>
27 <item name="Download" href="/download_lang.cgi"/>
28 <item name="Users guide" href="/userguide.html"/>
29 <item name="Release History" href="/release-history.html"/>
30 <item name="Javadoc (Latest release)" href="javadocs/api-release/index.html"/>
26 <item name="Overview" href="/index.html" />
27 <item name="Download" href="/download_lang.cgi" />
28 <item name="Users guide" href="/userguide.html" />
29 <item name="Release History" href="/changes-report.html" />
30 <item name="Javadoc" href="/apidocs/index.html" />
31 <item name="Javadoc Archive" href="https://javadoc.io/doc/org.apache.commons/commons-lang3" />
3132 </menu>
3233
3334 <menu name="Development">
34 <item name="Building" href="/building.html"/>
35 <item name="Mailing Lists" href="/mail-lists.html"/>
36 <item name="Issue Tracking" href="/issue-tracking.html"/>
37 <item name="Proposal" href="/proposal.html"/>
38 <item name="Developer guide" href="/developerguide.html"/>
39 <item name="Source Repository" href="/scm.html"/>
40 <item name="Javadoc (GIT latest)" href="apidocs/index.html"/>
35 <item name="Building" href="/building.html" />
36 <item name="Mailing Lists" href="/mail-lists.html" />
37 <item name="Issue Tracking" href="/issue-tracking.html" />
38 <item name="Proposal" href="/proposal.html" />
39 <item name="Developer guide" href="/developerguide.html" />
40 <item name="Source Repository" href="/scm.html" />
4141 </menu>
4242
4343 </body>
112112 </p>
113113 </subsection>
114114 </section>
115 <section name="Apache Commons Lang 3.11 (Java 8+)">
115 <section name="Apache Commons Lang 3.12.0 (Java 8+)">
116116 <subsection name="Binaries">
117117 <table>
118118 <tr>
119 <td><a href="[preferred]/commons/lang/binaries/commons-lang3-3.11-bin.tar.gz">commons-lang3-3.11-bin.tar.gz</a></td>
120 <td><a href="https://www.apache.org/dist/commons/lang/binaries/commons-lang3-3.11-bin.tar.gz.sha512">sha512</a></td>
121 <td><a href="https://www.apache.org/dist/commons/lang/binaries/commons-lang3-3.11-bin.tar.gz.asc">pgp</a></td>
119 <td><a href="[preferred]/commons/lang/binaries/commons-lang3-3.12.0-bin.tar.gz">commons-lang3-3.12.0-bin.tar.gz</a></td>
120 <td><a href="https://www.apache.org/dist/commons/lang/binaries/commons-lang3-3.12.0-bin.tar.gz.sha512">sha512</a></td>
121 <td><a href="https://www.apache.org/dist/commons/lang/binaries/commons-lang3-3.12.0-bin.tar.gz.asc">pgp</a></td>
122122 </tr>
123123 <tr>
124 <td><a href="[preferred]/commons/lang/binaries/commons-lang3-3.11-bin.zip">commons-lang3-3.11-bin.zip</a></td>
125 <td><a href="https://www.apache.org/dist/commons/lang/binaries/commons-lang3-3.11-bin.zip.sha512">sha512</a></td>
126 <td><a href="https://www.apache.org/dist/commons/lang/binaries/commons-lang3-3.11-bin.zip.asc">pgp</a></td>
124 <td><a href="[preferred]/commons/lang/binaries/commons-lang3-3.12.0-bin.zip">commons-lang3-3.12.0-bin.zip</a></td>
125 <td><a href="https://www.apache.org/dist/commons/lang/binaries/commons-lang3-3.12.0-bin.zip.sha512">sha512</a></td>
126 <td><a href="https://www.apache.org/dist/commons/lang/binaries/commons-lang3-3.12.0-bin.zip.asc">pgp</a></td>
127127 </tr>
128128 </table>
129129 </subsection>
130130 <subsection name="Source">
131131 <table>
132132 <tr>
133 <td><a href="[preferred]/commons/lang/source/commons-lang3-3.11-src.tar.gz">commons-lang3-3.11-src.tar.gz</a></td>
134 <td><a href="https://www.apache.org/dist/commons/lang/source/commons-lang3-3.11-src.tar.gz.sha512">sha512</a></td>
135 <td><a href="https://www.apache.org/dist/commons/lang/source/commons-lang3-3.11-src.tar.gz.asc">pgp</a></td>
133 <td><a href="[preferred]/commons/lang/source/commons-lang3-3.12.0-src.tar.gz">commons-lang3-3.12.0-src.tar.gz</a></td>
134 <td><a href="https://www.apache.org/dist/commons/lang/source/commons-lang3-3.12.0-src.tar.gz.sha512">sha512</a></td>
135 <td><a href="https://www.apache.org/dist/commons/lang/source/commons-lang3-3.12.0-src.tar.gz.asc">pgp</a></td>
136136 </tr>
137137 <tr>
138 <td><a href="[preferred]/commons/lang/source/commons-lang3-3.11-src.zip">commons-lang3-3.11-src.zip</a></td>
139 <td><a href="https://www.apache.org/dist/commons/lang/source/commons-lang3-3.11-src.zip.sha512">sha512</a></td>
140 <td><a href="https://www.apache.org/dist/commons/lang/source/commons-lang3-3.11-src.zip.asc">pgp</a></td>
138 <td><a href="[preferred]/commons/lang/source/commons-lang3-3.12.0-src.zip">commons-lang3-3.12.0-src.zip</a></td>
139 <td><a href="https://www.apache.org/dist/commons/lang/source/commons-lang3-3.12.0-src.zip.sha512">sha512</a></td>
140 <td><a href="https://www.apache.org/dist/commons/lang/source/commons-lang3-3.12.0-src.zip.asc">pgp</a></td>
141141 </tr>
142142 </table>
143143 </subsection>
3030 </p>
3131
3232 <p>
33 Lang provides a host of helper utilities for the java.lang API, notably
33 Apache Commons Lang provides a host of helper utilities for the java.lang API, notably
3434 String manipulation methods, basic numerical methods, object reflection, concurrency, creation and serialization
3535 and System properties. Additionally it contains basic enhancements to java.util.Date and a series of utilities dedicated to help with
3636 building methods, such as hashCode, toString and equals.
3737 </p>
3838 <p>
39 Note that Lang 3.0 (and subsequent versions) use a different package (<em>org.apache.commons.lang3</em>) than the previous versions (<em>org.apache.commons.lang</em>), allowing it to be used at the same time as an earlier version.
39 Note that Commons Lang 3.0 (and subsequent versions) use a different package (<em>org.apache.commons.lang3</em>) than the previous versions (<em>org.apache.commons.lang</em>),
40 allowing Commons Lang 3 to be used at the same time as Commons Lang 2.
4041 </p>
4142 </section>
4243 <!-- ================================================== -->
4950 The Javadoc API documents are available online:
5051 </p>
5152 <ul>
52 <li>The <a href="javadocs/api-3.11/index.html">current stable release 3.11</a> [Java 8 and up]</li>
53 <li>The <a href="javadocs/api-release/index.html">current release</a> [Java 8 and up]</li>
5354 <li>The <a href="javadocs/api-2.6/index.html">legacy release 2.6</a> [Java 1.2 and up]</li>
54 <li>Older releases - see the <a href="release-history.html">Release History</a> page</li>
55 <li>Older releases - see the <a href="changes-report.html">Release History</a> page</li>
5556 </ul>
5657 <p>
5758 The <a href="scm.html">git repository</a> can be
6061 </section>
6162 <!-- ================================================== -->
6263 <section name="Release Information">
63 <p>The latest stable release of Lang is 3.10. You may: </p>
64 <p>The latest stable release of Lang is 3.12.0: </p>
6465 <ul>
65 <li>Download <a href="https://commons.apache.org/lang/download_lang.cgi">3.10</a></li>
66 <li>Read the <a href="release-notes/RELEASE-NOTES-3.10.txt">3.10 release notes</a></li>
67 <li>Examine the <a href="article3_0.html">2.x to 3.0 upgrade notes</a></li>
68 <li>Compare major versions via the <a href="lang2-lang3-clirr-report.html">Lang2 to Lang3 Clirr report</a></li>
66 <li>Pull it using a build tool like Maven using a <a href="dependency-info.html">dependency management reference</a>.</li>
67 <li>Download the latest release from a <a href="https://commons.apache.org/lang/download_lang.cgi">mirror</a>.</li>
68 <li>Read the <a href="release-notes/RELEASE-NOTES-3.12.txt">release notes</a>.</li>
69 <li>Examine the <a href="article3_0.html">2.x to 3.0 upgrade notes</a>.</li>
70 <li>Compare major versions via the <a href="lang2-lang3-clirr-report.html">Lang2 to Lang3 Clirr report</a>.</li>
6971 </ul>
70 <p>
71 Alternatively you can pull it from the central Maven repositories:
72 <pre>
73 &lt;dependency&gt;
74 &lt;groupId&gt;org.apache.commons&lt;/groupId&gt;
75 &lt;artifactId&gt;commons-lang3&lt;/artifactId&gt;
76 &lt;version&gt;3.10&lt;/version&gt;
77 &lt;/dependency&gt;
78 </pre>
79 </p>
8072
8173 <p>
82 For information on previous releases see the <a href="release-history.html">Release History</a>, and to download previous releases see the <a href="https://archive.apache.org/dist/commons/lang/">Commons Lang Archive</a>.
74 For information on previous releases see the <a href="changes-report.html">Release History</a>, and to download previous releases see the <a href="https://archive.apache.org/dist/commons/lang/">Commons Lang Archive</a>.
8375 </p>
8476 </section>
8577 <!-- ================================================== -->
+0
-131
src/site/xdoc/release-history.xml less more
0 <?xml version="1.0"?>
1 <!--
2 Licensed to the Apache Software Foundation (ASF) under one or more
3 contributor license agreements. See the NOTICE file distributed with
4 this work for additional information regarding copyright ownership.
5 The ASF licenses this file to You under the Apache License, Version 2.0
6 (the "License"); you may not use this file except in compliance with
7 the License. You may obtain a copy of the License at
8
9 http://www.apache.org/licenses/LICENSE-2.0
10
11 Unless required by applicable law or agreed to in writing, software
12 distributed under the License is distributed on an "AS IS" BASIS,
13 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 See the License for the specific language governing permissions and
15 limitations under the License.
16 -->
17 <document>
18 <properties>
19 <title>Release History</title>
20 <author email="dev@commons.apache.org">Commons Documentation Team</author>
21 </properties>
22 <body>
23 <!-- ================================================== -->
24 <section name="Release History">
25
26 This page contains information about all Apache Commons Lang releases.
27
28 <subsection name="org.apache.commons:commons-lang3:3.x">
29 <table>
30 <tr>
31 <th>Version</th><th>Release date</th><th>Required Java Version</th><th>Javadoc</th><th>Release notes</th>
32 </tr>
33 <tr>
34 <td>3.10</td><td>2020-03-22</td><td>8</td><td><a href="javadocs/api-3.10/">api-3.10</a></td><td><a href="release-notes/RELEASE-NOTES-3.10.txt">release notes for 3.10</a></td>
35 </tr>
36 <tr>
37 <td>3.9</td><td>2019-04-09</td><td>8</td><td><a href="javadocs/api-3.9/">api-3.9</a></td><td><a href="release-notes/RELEASE-NOTES-3.9.txt">release notes for 3.9</a></td>
38 </tr>
39 <tr>
40 <td>3.8.1</td><td>2018-09-19</td><td>7</td><td><a href="javadocs/api-3.8.1/">api-3.8.1</a></td><td><a href="release-notes/RELEASE-NOTES-3.8.1.txt">release notes for 3.8.1</a></td>
41 </tr>
42 <tr>
43 <td>3.8</td><td>2018-08-15</td><td>7</td><td><a href="javadocs/api-3.8/">api-3.8</a></td><td><a href="release-notes/RELEASE-NOTES-3.8.txt">release notes for 3.8</a></td>
44 </tr>
45 <tr>
46 <td>3.7</td><td>2017-10-04</td><td>7</td><td><a href="javadocs/api-3.7/">api-3.7</a></td><td><a href="release-notes/RELEASE-NOTES-3.7.txt">release notes for 3.7</a></td>
47 </tr>
48 <tr>
49 <td>3.6</td><td>2016-04-17</td><td>7</td><td><a href="javadocs/api-3.6/">api-3.6</a></td><td><a href="release-notes/RELEASE-NOTES-3.6.txt">release notes for 3.6</a></td>
50 </tr>
51 <tr>
52 <td>3.5</td><td>2016-10-02</td><td>6</td><td><a href="javadocs/api-3.5/">api-3.5</a></td><td><a href="release-notes/RELEASE-NOTES-3.5.txt">release notes for 3.5</a></td>
53 </tr>
54 <tr>
55 <td>3.4</td><td>2014-04-06</td><td>6</td><td><a href="javadocs/api-3.4/">api-3.4</a></td><td><a href="release-notes/RELEASE-NOTES-3.4.txt">release notes for 3.4</a></td>
56 </tr>
57 <tr>
58 <td>3.3.2</td><td>2014-04-09</td><td>6</td><td><a href="javadocs/api-3.3.2/">api-3.3.2</a></td><td><a href="release-notes/RELEASE-NOTES-3.3.2.txt">release notes for 3.3.2</a></td>
59 </tr>
60 <tr>
61 <td>3.3.1</td><td>2014-03-18</td><td>6</td><td><a href="javadocs/api-3.3.1/">api-3.3.1</a></td><td><a href="release-notes/RELEASE-NOTES-3.3.1.txt">release notes for 3.3.1</a></td>
62 </tr>
63 <tr>
64 <td>3.3</td><td>2014-03-04</td><td>6</td><td><a href="javadocs/api-3.3/">api-3.3</a></td><td><a href="release-notes/RELEASE-NOTES-3.3.txt">release notes for 3.3</a></td>
65 </tr>
66 <tr>
67 <td>3.2.1</td><td>2014-01-05</td><td>6</td><td><a href="javadocs/api-3.2.1/">api-3.2.1</a></td><td><a href="release-notes/RELEASE-NOTES-3.2.1.txt">release notes for 3.2.1</a></td>
68 </tr>
69 <tr>
70 <td>3.2</td><td>2014-01-01</td><td>6</td><td><a href="javadocs/api-3.2/">api-3.2</a></td><td><a href="release-notes/RELEASE-NOTES-3.2.txt">release notes for 3.2</a></td>
71 </tr>
72 <tr>
73 <td>3.1</td><td>2011-11-14</td><td>5.0</td><td><a href="javadocs/api-3.1/">api-3.1</a></td><td><a href="release-notes/RELEASE-NOTES-3.1.txt">release notes for 3.1</a></td>
74 </tr>
75 <tr>
76 <td>3.0.1</td><td>2011-08-09</td><td>5.0</td><td><a href="javadocs/api-3.0.1/">api-3.0.1</a></td><td><a href="release-notes/RELEASE-NOTES-3.0.1.txt">release notes for 3.0.1</a></td>
77 </tr>
78 <tr>
79 <td>3.0</td><td>2011-07-18</td><td>5.0</td><td><a href="javadocs/api-3.0/">api-3.0</a></td><td><a href="release-notes/RELEASE-NOTES-3.0.txt">release notes for 3.0</a></td>
80 </tr>
81 </table>
82 </subsection>
83
84 <subsection name="commons-lang:commons-lang:2.x">
85 <table>
86 <tr>
87 <th>Version</th><th>Release date</th><th>Required Java Version</th><th>Javadoc</th><th>Release notes</th>
88 </tr>
89 <tr>
90 <td>2.6</td><td>2011-01-16</td><td>1.3</td><td><a href="javadocs/api-2.6/">api-2.6</a></td><td><a href="release-notes/RELEASE-NOTES-2.6.txt">release notes for 2.6</a></td>
91 </tr>
92 <tr>
93 <td>2.5</td><td>2010-02-23</td><td>1.3</td><td><a href="javadocs/api-2.5/">api-2.5</a></td><td><a href="release-notes/RELEASE-NOTES-2.5.txt">release notes for 2.5</a></td>
94 </tr>
95 <tr>
96 <td>2.4</td><td>2008-03-18</td><td>1.2</td><td><a href="javadocs/api-2.4/">api-2.4</a></td><td><a href="release-notes/RELEASE-NOTES-2.4.txt">release notes for 2.4</a></td>
97 </tr>
98 <tr>
99 <td>2.3</td><td>2007-02-13</td><td>1.1</td><td><a href="javadocs/api-2.3/">api-2.3</a></td><td><a href="release-notes/RELEASE-NOTES-2.3.txt">release notes for 2.3</a></td>
100 </tr>
101 <tr>
102 <td>2.2</td><td>2006-10-04</td><td>1.1</td><td><a href="javadocs/api-2.2/">api-2.2</a></td><td><a href="release-notes/RELEASE-NOTES-2.2.txt">release notes for 2.2</a></td>
103 </tr>
104 <tr>
105 <td>2.1</td><td>2006-06-13</td><td>1.1</td><td><a href="javadocs/api-2.1/">api-2.1</a></td><td><a href="release-notes/RELEASE-NOTES-2.1.txt">release notes for 2.1</a></td>
106 </tr>
107 <tr>
108 <td>2.0</td><td>2003-09-02</td><td>1.1</td><td><a href="javadocs/api-2.0/">api-2.0</a></td><td><a href="release-notes/RELEASE-NOTES-2.0.txt">release notes for 2.0</a></td>
109 </tr>
110 </table>
111 </subsection>
112
113 <subsection name="commons-lang:commons-lang:1.x">
114 <table>
115 <tr>
116 <th>Version</th><th>Release date</th><th>Required Java Version</th><th>Javadoc</th><th>Release notes</th>
117 </tr>
118 <tr>
119 <td>1.0.1</td><td>2002-11-25</td><td>1.1</td><td><a href="javadocs/api-1.0.1/">api-1.0.1</a></td><td><a href="release-notes/RELEASE-NOTES-1.0.1.txt">release notes for 1.0.1</a></td>
120 </tr>
121 <tr>
122 <td>1.0</td><td>2002-10-04</td><td>1.1</td><td><a href="javadocs/api-1.0/">api-1.0</a></td><td><a href="release-notes/RELEASE-NOTES-1.0.txt">release notes for 1.0</a></td>
123 </tr>
124 </table>
125 </subsection>
126
127 </section>
128 <!-- ================================================== -->
129 </body>
130 </document>
2525 <body>
2626
2727 <section name='User guide for Commons "Lang"'>
28 Looking for the User Guide? It has been moved to the package <a href="javadocs/api-release/index.html">Javadoc</a>
28 Looking for the User Guide? It has been moved to the package <a href="javadocs/api-release/index.html">Javadoc</a>.
2929 </section>
3030
3131 </body>
0 /*
1 * Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package org.apache.commons.lang3;
18
19 import static org.junit.jupiter.api.Assertions.assertArrayEquals;
20
21 import java.util.Arrays;
22
23 import org.junit.jupiter.api.Test;
24
25 public class ArraySorterTest {
26
27 @Test
28 public void testSortByteArray() {
29 final byte[] array1 = {2, 1};
30 final byte[] array2 = array1.clone();
31 Arrays.sort(array1);
32 assertArrayEquals(array1, ArraySorter.sort(array2));
33 }
34
35 @Test
36 public void testSortCharArray() {
37 final char[] array1 = {2, 1};
38 final char[] array2 = array1.clone();
39 Arrays.sort(array1);
40 assertArrayEquals(array1, ArraySorter.sort(array2));
41 }
42
43 @Test
44 public void testSortComparable() {
45 final String[] array1 = ArrayUtils.toArray("foo", "bar");
46 final String[] array2 = array1.clone();
47 Arrays.sort(array1);
48 assertArrayEquals(array1, ArraySorter.sort(array2, String::compareTo));
49 }
50
51 @Test
52 public void testSortDoubleArray() {
53 final double[] array1 = {2, 1};
54 final double[] array2 = array1.clone();
55 Arrays.sort(array1);
56 assertArrayEquals(array1, ArraySorter.sort(array2));
57 }
58
59 @Test
60 public void testSortFloatArray() {
61 final float[] array1 = {2, 1};
62 final float[] array2 = array1.clone();
63 Arrays.sort(array1);
64 assertArrayEquals(array1, ArraySorter.sort(array2));
65 }
66
67 @Test
68 public void testSortIntArray() {
69 final int[] array1 = {2, 1};
70 final int[] array2 = array1.clone();
71 Arrays.sort(array1);
72 assertArrayEquals(array1, ArraySorter.sort(array2));
73 }
74
75 @Test
76 public void testSortLongArray() {
77 final long[] array1 = {2, 1};
78 final long[] array2 = array1.clone();
79 Arrays.sort(array1);
80 assertArrayEquals(array1, ArraySorter.sort(array2));
81 }
82
83 @Test
84 public void testSortObjects() {
85 final String[] array1 = ArrayUtils.toArray("foo", "bar");
86 final String[] array2 = array1.clone();
87 Arrays.sort(array1);
88 assertArrayEquals(array1, ArraySorter.sort(array2));
89 }
90
91 @Test
92 public void testSortShortArray() {
93 final short[] array1 = {2, 1};
94 final short[] array2 = array1.clone();
95 Arrays.sort(array1);
96 assertArrayEquals(array1, ArraySorter.sort(array2));
97 }
98
99 }
3939 newArray = ArrayUtils.addFirst(null, true);
4040 assertArrayEquals(new boolean[]{true}, newArray);
4141 assertEquals(Boolean.TYPE, newArray.getClass().getComponentType());
42 final boolean[] array1 = new boolean[]{true, false, true};
42 final boolean[] array1 = {true, false, true};
4343 newArray = ArrayUtils.addFirst(array1, false);
4444 assertArrayEquals(new boolean[]{false, true, false, true}, newArray);
4545 assertEquals(Boolean.TYPE, newArray.getClass().getComponentType());
5454 newArray = ArrayUtils.addFirst((byte[]) null, (byte) 1);
5555 assertArrayEquals(new byte[]{1}, newArray);
5656 assertEquals(Byte.TYPE, newArray.getClass().getComponentType());
57 final byte[] array1 = new byte[]{1, 2, 3};
57 final byte[] array1 = {1, 2, 3};
5858 newArray = ArrayUtils.addFirst(array1, (byte) 0);
5959 assertArrayEquals(new byte[]{0, 1, 2, 3}, newArray);
6060 assertEquals(Byte.TYPE, newArray.getClass().getComponentType());
7272 newArray = ArrayUtils.addFirst((char[]) null, (char) 1);
7373 assertArrayEquals(new char[]{1}, newArray);
7474 assertEquals(Character.TYPE, newArray.getClass().getComponentType());
75 final char[] array1 = new char[]{1, 2, 3};
75 final char[] array1 = {1, 2, 3};
7676 newArray = ArrayUtils.addFirst(array1, (char) 0);
7777 assertArrayEquals(new char[]{0, 1, 2, 3}, newArray);
7878 assertEquals(Character.TYPE, newArray.getClass().getComponentType());
9090 newArray = ArrayUtils.addFirst((double[]) null, 1);
9191 assertArrayEquals(new double[]{1}, newArray);
9292 assertEquals(Double.TYPE, newArray.getClass().getComponentType());
93 final double[] array1 = new double[]{1, 2, 3};
93 final double[] array1 = {1, 2, 3};
9494 newArray = ArrayUtils.addFirst(array1, 0);
9595 assertArrayEquals(new double[]{0, 1, 2, 3}, newArray);
9696 assertEquals(Double.TYPE, newArray.getClass().getComponentType());
108108 newArray = ArrayUtils.addFirst((float[]) null, 1);
109109 assertArrayEquals(new float[]{1}, newArray);
110110 assertEquals(Float.TYPE, newArray.getClass().getComponentType());
111 final float[] array1 = new float[]{1, 2, 3};
111 final float[] array1 = {1, 2, 3};
112112 newArray = ArrayUtils.addFirst(array1, 0);
113113 assertArrayEquals(new float[]{0, 1, 2, 3}, newArray);
114114 assertEquals(Float.TYPE, newArray.getClass().getComponentType());
126126 newArray = ArrayUtils.addFirst((int[]) null, 1);
127127 assertArrayEquals(new int[]{1}, newArray);
128128 assertEquals(Integer.TYPE, newArray.getClass().getComponentType());
129 final int[] array1 = new int[]{1, 2, 3};
129 final int[] array1 = {1, 2, 3};
130130 newArray = ArrayUtils.addFirst(array1, 0);
131131 assertArrayEquals(new int[]{0, 1, 2, 3}, newArray);
132132 assertEquals(Integer.TYPE, newArray.getClass().getComponentType());
144144 newArray = ArrayUtils.addFirst((long[]) null, 1);
145145 assertArrayEquals(new long[]{1}, newArray);
146146 assertEquals(Long.TYPE, newArray.getClass().getComponentType());
147 final long[] array1 = new long[]{1, 2, 3};
147 final long[] array1 = {1, 2, 3};
148148 newArray = ArrayUtils.addFirst(array1, 0);
149149 assertArrayEquals(new long[]{0, 1, 2, 3}, newArray);
150150 assertEquals(Long.TYPE, newArray.getClass().getComponentType());
169169 assertArrayEquals(new Object[]{"a"}, newStringArray);
170170 assertEquals(String.class, newStringArray.getClass().getComponentType());
171171
172 final String[] stringArray1 = new String[] { "a", "b", "c" };
172 final String[] stringArray1 = { "a", "b", "c" };
173173 newArray = ArrayUtils.addFirst(stringArray1, null);
174174 assertArrayEquals(new String[] { null, "a", "b", "c" }, newArray);
175175 assertEquals(String.class, newArray.getClass().getComponentType());
178178 assertArrayEquals(new String[] { "d", "a", "b", "c" }, newArray);
179179 assertEquals(String.class, newArray.getClass().getComponentType());
180180
181 Number[] numberArray1 = new Number[] { Integer.valueOf(1), Double.valueOf(2) };
181 Number[] numberArray1 = { Integer.valueOf(1), Double.valueOf(2) };
182182 newArray = ArrayUtils.addFirst(numberArray1, Float.valueOf(3));
183183 assertArrayEquals(new Number[] { Float.valueOf(3), Integer.valueOf(1), Double.valueOf(2) }, newArray);
184184 assertEquals(Number.class, newArray.getClass().getComponentType());
198198 newArray = ArrayUtils.addFirst((short[]) null, (short) 1);
199199 assertArrayEquals(new short[]{1}, newArray);
200200 assertEquals(Short.TYPE, newArray.getClass().getComponentType());
201 final short[] array1 = new short[]{1, 2, 3};
201 final short[] array1 = {1, 2, 3};
202202 newArray = ArrayUtils.addFirst(array1, (short) 0);
203203 assertArrayEquals(new short[]{0, 1, 2, 3}, newArray);
204204 assertEquals(Short.TYPE, newArray.getClass().getComponentType());
216216 newArray = ArrayUtils.add(null, true);
217217 assertArrayEquals(new boolean[]{true}, newArray);
218218 assertEquals(Boolean.TYPE, newArray.getClass().getComponentType());
219 final boolean[] array1 = new boolean[]{true, false, true};
219 final boolean[] array1 = {true, false, true};
220220 newArray = ArrayUtils.add(array1, false);
221221 assertArrayEquals(new boolean[]{true, false, true, false}, newArray);
222222 assertEquals(Boolean.TYPE, newArray.getClass().getComponentType());
231231 newArray = ArrayUtils.add((byte[]) null, (byte) 1);
232232 assertArrayEquals(new byte[]{1}, newArray);
233233 assertEquals(Byte.TYPE, newArray.getClass().getComponentType());
234 final byte[] array1 = new byte[]{1, 2, 3};
234 final byte[] array1 = {1, 2, 3};
235235 newArray = ArrayUtils.add(array1, (byte) 0);
236236 assertArrayEquals(new byte[]{1, 2, 3, 0}, newArray);
237237 assertEquals(Byte.TYPE, newArray.getClass().getComponentType());
249249 newArray = ArrayUtils.add((char[]) null, (char) 1);
250250 assertArrayEquals(new char[]{1}, newArray);
251251 assertEquals(Character.TYPE, newArray.getClass().getComponentType());
252 final char[] array1 = new char[]{1, 2, 3};
252 final char[] array1 = {1, 2, 3};
253253 newArray = ArrayUtils.add(array1, (char) 0);
254254 assertArrayEquals(new char[]{1, 2, 3, 0}, newArray);
255255 assertEquals(Character.TYPE, newArray.getClass().getComponentType());
267267 newArray = ArrayUtils.add((double[]) null, 1);
268268 assertArrayEquals(new double[]{1}, newArray);
269269 assertEquals(Double.TYPE, newArray.getClass().getComponentType());
270 final double[] array1 = new double[]{1, 2, 3};
270 final double[] array1 = {1, 2, 3};
271271 newArray = ArrayUtils.add(array1, 0);
272272 assertArrayEquals(new double[]{1, 2, 3, 0}, newArray);
273273 assertEquals(Double.TYPE, newArray.getClass().getComponentType());
285285 newArray = ArrayUtils.add((float[]) null, 1);
286286 assertArrayEquals(new float[]{1}, newArray);
287287 assertEquals(Float.TYPE, newArray.getClass().getComponentType());
288 final float[] array1 = new float[]{1, 2, 3};
288 final float[] array1 = {1, 2, 3};
289289 newArray = ArrayUtils.add(array1, 0);
290290 assertArrayEquals(new float[]{1, 2, 3, 0}, newArray);
291291 assertEquals(Float.TYPE, newArray.getClass().getComponentType());
303303 newArray = ArrayUtils.add((int[]) null, 1);
304304 assertArrayEquals(new int[]{1}, newArray);
305305 assertEquals(Integer.TYPE, newArray.getClass().getComponentType());
306 final int[] array1 = new int[]{1, 2, 3};
306 final int[] array1 = {1, 2, 3};
307307 newArray = ArrayUtils.add(array1, 0);
308308 assertArrayEquals(new int[]{1, 2, 3, 0}, newArray);
309309 assertEquals(Integer.TYPE, newArray.getClass().getComponentType());
321321 newArray = ArrayUtils.add((long[]) null, 1);
322322 assertArrayEquals(new long[]{1}, newArray);
323323 assertEquals(Long.TYPE, newArray.getClass().getComponentType());
324 final long[] array1 = new long[]{1, 2, 3};
324 final long[] array1 = {1, 2, 3};
325325 newArray = ArrayUtils.add(array1, 0);
326326 assertArrayEquals(new long[]{1, 2, 3, 0}, newArray);
327327 assertEquals(Long.TYPE, newArray.getClass().getComponentType());
346346 assertArrayEquals(new Object[]{"a"}, newStringArray);
347347 assertEquals(String.class, newStringArray.getClass().getComponentType());
348348
349 final String[] stringArray1 = new String[]{"a", "b", "c"};
349 final String[] stringArray1 = {"a", "b", "c"};
350350 newArray = ArrayUtils.add(stringArray1, null);
351351 assertArrayEquals(new String[]{"a", "b", "c", null}, newArray);
352352 assertEquals(String.class, newArray.getClass().getComponentType());
355355 assertArrayEquals(new String[]{"a", "b", "c", "d"}, newArray);
356356 assertEquals(String.class, newArray.getClass().getComponentType());
357357
358 Number[] numberArray1 = new Number[]{Integer.valueOf(1), Double.valueOf(2)};
358 Number[] numberArray1 = {Integer.valueOf(1), Double.valueOf(2)};
359359 newArray = ArrayUtils.add(numberArray1, Float.valueOf(3));
360360 assertArrayEquals(new Number[]{Integer.valueOf(1), Double.valueOf(2), Float.valueOf(3)}, newArray);
361361 assertEquals(Number.class, newArray.getClass().getComponentType());
375375 newArray = ArrayUtils.add((short[]) null, (short) 1);
376376 assertArrayEquals(new short[]{1}, newArray);
377377 assertEquals(Short.TYPE, newArray.getClass().getComponentType());
378 final short[] array1 = new short[]{1, 2, 3};
378 final short[] array1 = {1, 2, 3};
379379 newArray = ArrayUtils.add(array1, (short) 0);
380380 assertArrayEquals(new short[]{1, 2, 3, 0}, newArray);
381381 assertEquals(Short.TYPE, newArray.getClass().getComponentType());
388388 public void testAddObjectArrayToObjectArray() {
389389 assertNull(ArrayUtils.addAll(null, (Object[]) null));
390390 Object[] newArray;
391 final String[] stringArray1 = new String[]{"a", "b", "c"};
392 final String[] stringArray2 = new String[]{"1", "2", "3"};
391 final String[] stringArray1 = {"a", "b", "c"};
392 final String[] stringArray2 = {"1", "2", "3"};
393393 newArray = ArrayUtils.addAll(stringArray1, (String[]) null);
394394 assertNotSame(stringArray1, newArray);
395395 assertArrayEquals(stringArray1, newArray);
415415 assertArrayEquals(ArrayUtils.EMPTY_STRING_ARRAY, newArray);
416416 assertArrayEquals(new String[]{}, newArray);
417417 assertEquals(String.class, newArray.getClass().getComponentType());
418 final String[] stringArrayNull = new String []{null};
418 final String[] stringArrayNull = {null};
419419 newArray = ArrayUtils.addAll(stringArrayNull, stringArrayNull);
420420 assertArrayEquals(new String[]{null, null}, newArray);
421421 assertEquals(String.class, newArray.getClass().getComponentType());
486486 assertArrayEquals(new String[]{"a"}, newArray);
487487 assertArrayEquals(new Object[]{"a"}, newArray);
488488 assertEquals(String.class, newArray.getClass().getComponentType());
489 final String[] stringArray1 = new String[]{"a", "b", "c"};
489 final String[] stringArray1 = {"a", "b", "c"};
490490 newArray = ArrayUtils.add(stringArray1, 0, null);
491491 assertArrayEquals(new String[]{null, "a", "b", "c"}, newArray);
492492 assertEquals(String.class, newArray.getClass().getComponentType());
501501 assertEquals(String.class, newArray.getClass().getComponentType());
502502 assertEquals(String.class, newArray.getClass().getComponentType());
503503
504 final Object[] o = new Object[] {"1", "2", "4"};
504 final Object[] o = {"1", "2", "4"};
505505 final Object[] result = ArrayUtils.add(o, 2, "3");
506506 final Object[] result2 = ArrayUtils.add(o, 3, "5");
507507
102102
103103 @Test
104104 public void testRemoveAllBooleanArrayRemoveNone() {
105 final boolean[] array1 = new boolean[] { true, false };
105 final boolean[] array1 = { true, false };
106106 final boolean[] array2 = ArrayUtils.removeAll(array1);
107107 assertNotSame(array1, array2);
108108 assertArrayEquals(array1, array2);
174174
175175 @Test
176176 public void testRemoveAllByteArrayRemoveNone() {
177 final byte[] array1 = new byte[] { 1, 2 };
177 final byte[] array1 = { 1, 2 };
178178 final byte[] array2 = ArrayUtils.removeAll(array1);
179179 assertNotSame(array1, array2);
180180 assertArrayEquals(array1, array2);
246246
247247 @Test
248248 public void testRemoveAllCharArrayRemoveNone() {
249 final char[] array1 = new char[] { 'a', 'b' };
249 final char[] array1 = { 'a', 'b' };
250250 final char[] array2 = ArrayUtils.removeAll(array1);
251251 assertNotSame(array1, array2);
252252 assertArrayEquals(array1, array2);
318318
319319 @Test
320320 public void testRemoveAllDoubleArrayRemoveNone() {
321 final double[] array1 = new double[] { 1, 2 };
321 final double[] array1 = { 1, 2 };
322322 final double[] array2 = ArrayUtils.removeAll(array1);
323323 assertNotSame(array1, array2);
324324 assertArrayEquals(array1, array2);
390390
391391 @Test
392392 public void testRemoveAllFloatArrayRemoveNone() {
393 final float[] array1 = new float[] { 1, 2 };
393 final float[] array1 = { 1, 2 };
394394 final float[] array2 = ArrayUtils.removeAll(array1);
395395 assertNotSame(array1, array2);
396396 assertArrayEquals(array1, array2);
468468
469469 @Test
470470 public void testRemoveAllIntArrayRemoveNone() {
471 final int[] array1 = new int[] { 1, 2 };
471 final int[] array1 = { 1, 2 };
472472 final int[] array2 = ArrayUtils.removeAll(array1);
473473 assertNotSame(array1, array2);
474474 assertArrayEquals(array1, array2);
540540
541541 @Test
542542 public void testRemoveAllLongArrayRemoveNone() {
543 final long[] array1 = new long[] { 1, 2 };
543 final long[] array1 = { 1, 2 };
544544 final long[] array2 = ArrayUtils.removeAll(array1);
545545 assertNotSame(array1, array2);
546546 assertArrayEquals(array1, array2);
684684
685685 @Test
686686 public void testRemoveAllObjectArrayRemoveNone() {
687 final Object[] array1 = new Object[] { "foo", "bar", "baz" };
687 final Object[] array1 = { "foo", "bar", "baz" };
688688 final Object[] array2 = ArrayUtils.removeAll(array1);
689689 assertNotSame(array1, array2);
690690 assertArrayEquals(array1, array2);
756756
757757 @Test
758758 public void testRemoveAllShortArrayRemoveNone() {
759 final short[] array1 = new short[] { 1, 2 };
759 final short[] array1 = { 1, 2 };
760760 final short[] array2 = ArrayUtils.removeAll(array1);
761761 assertNotSame(array1, array2);
762762 assertArrayEquals(array1, array2);
0 /*
1 * Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package org.apache.commons.lang3;
18
19 import static org.junit.jupiter.api.Assertions.assertArrayEquals;
20 import static org.junit.jupiter.api.Assertions.assertEquals;
21 import static org.junit.jupiter.api.Assertions.assertNull;
22 import static org.junit.jupiter.api.Assertions.assertSame;
23
24 import java.util.function.IntFunction;
25 import java.util.function.Supplier;
26
27 import org.junit.jupiter.api.Test;
28
29 public class ArrayUtilsSetTest {
30
31 @Test
32 public void testSetAll_IntFunction() {
33 final IntFunction<?> nullIntFunction = null;
34 assertNull(ArrayUtils.setAll(null, nullIntFunction));
35 assertArrayEquals(null, ArrayUtils.setAll(null, nullIntFunction));
36 assertArrayEquals(ArrayUtils.EMPTY_BOOLEAN_OBJECT_ARRAY, ArrayUtils.setAll(ArrayUtils.EMPTY_BOOLEAN_OBJECT_ARRAY, nullIntFunction));
37 assertArrayEquals(ArrayUtils.EMPTY_OBJECT_ARRAY, ArrayUtils.setAll(ArrayUtils.EMPTY_OBJECT_ARRAY, nullIntFunction));
38 Integer[] array = new Integer[10];
39 final Integer[] array2 = ArrayUtils.setAll(array, Integer::valueOf);
40 assertSame(array, array2);
41 for (int i = 0; i < array.length; i++) {
42 assertEquals(i, array[i].intValue());
43 }
44 }
45
46 @Test
47 public void testSetAll_Suppiler() {
48 final Supplier<?> nullSupplier = null;
49 assertNull(ArrayUtils.setAll(null, nullSupplier));
50 assertArrayEquals(null, ArrayUtils.setAll(null, nullSupplier));
51 assertArrayEquals(ArrayUtils.EMPTY_BOOLEAN_OBJECT_ARRAY, ArrayUtils.setAll(ArrayUtils.EMPTY_BOOLEAN_OBJECT_ARRAY, nullSupplier));
52 assertArrayEquals(ArrayUtils.EMPTY_OBJECT_ARRAY, ArrayUtils.setAll(ArrayUtils.EMPTY_OBJECT_ARRAY, nullSupplier));
53 String[] array = new String[10];
54 final String[] array2 = ArrayUtils.setAll(array, () -> StringUtils.EMPTY);
55 assertSame(array, array2);
56 for (String s : array) {
57 assertEquals(StringUtils.EMPTY, s);
58 }
59 }
60 }
4545 public class ArrayUtilsTest {
4646
4747 private class TestClass {
48 // empty
4849 }
4950
5051 /** A predefined seed used to initialize {@link Random} in order to get predictable results */
7778 assertEquals("foo", array[0]);
7879 assertEquals("bar", array[1]);
7980 }
80
8181 /**
8282 * Tests generic array creation with parameters of common base type.
8383 */
101101 @Test
102102 public void testClone() {
103103 assertArrayEquals(null, ArrayUtils.clone((Object[]) null));
104 Object[] original1 = new Object[0];
104 Object[] original1 = {};
105105 Object[] cloned1 = ArrayUtils.clone(original1);
106106 assertArrayEquals(original1, cloned1);
107107 assertNotSame(original1, cloned1);
119119 @Test
120120 public void testCloneBoolean() {
121121 assertNull(ArrayUtils.clone((boolean[]) null));
122 final boolean[] original = new boolean[]{true, false};
122 final boolean[] original = {true, false};
123123 final boolean[] cloned = ArrayUtils.clone(original);
124124 assertArrayEquals(original, cloned);
125125 assertNotSame(original, cloned);
128128 @Test
129129 public void testCloneByte() {
130130 assertNull(ArrayUtils.clone((byte[]) null));
131 final byte[] original = new byte[]{1, 6};
131 final byte[] original = {1, 6};
132132 final byte[] cloned = ArrayUtils.clone(original);
133133 assertArrayEquals(original, cloned);
134134 assertNotSame(original, cloned);
137137 @Test
138138 public void testCloneChar() {
139139 assertNull(ArrayUtils.clone((char[]) null));
140 final char[] original = new char[]{'a', '4'};
140 final char[] original = {'a', '4'};
141141 final char[] cloned = ArrayUtils.clone(original);
142142 assertArrayEquals(original, cloned);
143143 assertNotSame(original, cloned);
146146 @Test
147147 public void testCloneDouble() {
148148 assertNull(ArrayUtils.clone((double[]) null));
149 final double[] original = new double[]{2.4d, 5.7d};
149 final double[] original = {2.4d, 5.7d};
150150 final double[] cloned = ArrayUtils.clone(original);
151151 assertArrayEquals(original, cloned);
152152 assertNotSame(original, cloned);
155155 @Test
156156 public void testCloneFloat() {
157157 assertNull(ArrayUtils.clone((float[]) null));
158 final float[] original = new float[]{2.6f, 6.4f};
158 final float[] original = {2.6f, 6.4f};
159159 final float[] cloned = ArrayUtils.clone(original);
160160 assertArrayEquals(original, cloned);
161161 assertNotSame(original, cloned);
164164 @Test
165165 public void testCloneInt() {
166166 assertNull(ArrayUtils.clone((int[]) null));
167 final int[] original = new int[]{5, 8};
167 final int[] original = {5, 8};
168168 final int[] cloned = ArrayUtils.clone(original);
169169 assertArrayEquals(original, cloned);
170170 assertNotSame(original, cloned);
173173 @Test
174174 public void testCloneLong() {
175175 assertNull(ArrayUtils.clone((long[]) null));
176 final long[] original = new long[]{0L, 1L};
176 final long[] original = {0L, 1L};
177177 final long[] cloned = ArrayUtils.clone(original);
178178 assertArrayEquals(original, cloned);
179179 assertNotSame(original, cloned);
182182 @Test
183183 public void testCloneShort() {
184184 assertNull(ArrayUtils.clone((short[]) null));
185 final short[] original = new short[]{1, 4};
185 final short[] original = {1, 4};
186186 final short[] cloned = ArrayUtils.clone(original);
187187 assertArrayEquals(original, cloned);
188188 assertNotSame(original, cloned);
200200
201201 @Test
202202 public void testContains() {
203 final Object[] array = new Object[]{"0", "1", "2", "3", null, "0"};
203 final Object[] array = {"0", "1", "2", "3", null, "0"};
204204 assertFalse(ArrayUtils.contains(null, null));
205205 assertFalse(ArrayUtils.contains(null, "1"));
206206 assertTrue(ArrayUtils.contains(array, "0"));
213213
214214 @Test
215215 public void testContains_LANG_1261() {
216
216217 class LANG1261ParentObject {
217218 @Override
218219 public boolean equals(final Object o) {
219220 return true;
220221 }
221222 }
223
222224 class LANG1261ChildObject extends LANG1261ParentObject {
225 // empty.
223226 }
224227
225228 final Object[] array = new LANG1261ChildObject[]{new LANG1261ChildObject()};
276279 assertFalse(ArrayUtils.contains(array, (double) 99));
277280 }
278281
282 @Test
283 public void testContainsDoubleNaN() {
284 final double[] a = { Double.NEGATIVE_INFINITY, Double.NaN, Double.POSITIVE_INFINITY };
285 assertTrue(ArrayUtils.contains(a, Double.POSITIVE_INFINITY));
286 assertTrue(ArrayUtils.contains(a, Double.NEGATIVE_INFINITY));
287 assertTrue(ArrayUtils.contains(a, Double.NaN));
288 }
289
279290 @SuppressWarnings("cast")
280291 @Test
281292 public void testContainsDoubleTolerance() {
302313 }
303314
304315 @Test
316 public void testContainsFloatNaN() {
317 final float[] array = { Float.NEGATIVE_INFINITY, Float.NaN, Float.POSITIVE_INFINITY };
318 assertTrue(ArrayUtils.contains(array, Float.POSITIVE_INFINITY));
319 assertTrue(ArrayUtils.contains(array, Float.NEGATIVE_INFINITY));
320 assertTrue(ArrayUtils.contains(array, Float.NaN));
321 }
322
323 @Test
305324 public void testContainsInt() {
306325 int[] array = null;
307326 assertFalse(ArrayUtils.contains(array, 1));
340359 @Test
341360 public void testCreatePrimitiveArray() {
342361 assertNull(ArrayUtils.toPrimitive((Object[]) null));
362 assertArrayEquals(new boolean[]{true}, ArrayUtils.toPrimitive(new Boolean[]{true}));
363 assertArrayEquals(new char[]{'a'}, ArrayUtils.toPrimitive(new Character[]{'a'}));
364 assertArrayEquals(new byte[]{1}, ArrayUtils.toPrimitive(new Byte[]{1}));
343365 assertArrayEquals(new int[]{}, ArrayUtils.toPrimitive(new Integer[]{}));
344366 assertArrayEquals(new short[]{2}, ArrayUtils.toPrimitive(new Short[]{2}));
345367 assertArrayEquals(new long[]{2, 3}, ArrayUtils.toPrimitive(new Long[]{2L, 3L}));
346368 assertArrayEquals(new float[]{3.14f}, ArrayUtils.toPrimitive(new Float[]{3.14f}), 0.1f);
347369 assertArrayEquals(new double[]{2.718}, ArrayUtils.toPrimitive(new Double[]{2.718}), 0.1);
370 }
371
372 @Test
373 public void testCreatePrimitiveArrayViaObjectArray() {
374 assertNull(ArrayUtils.toPrimitive((Object) null));
375 assertArrayEquals(new boolean[]{true}, (boolean[]) ArrayUtils.toPrimitive((Object) new Boolean[]{true}));
376 assertArrayEquals(new char[]{'a'}, (char[]) ArrayUtils.toPrimitive((Object) new Character[]{'a'}));
377 assertArrayEquals(new byte[]{1}, (byte[]) ArrayUtils.toPrimitive((Object) new Byte[]{1}));
378 assertArrayEquals(new int[]{}, (int[]) ArrayUtils.toPrimitive((Object) new Integer[]{}));
379 assertArrayEquals(new short[]{2}, (short[]) ArrayUtils.toPrimitive((Object) new Short[]{2}));
380 assertArrayEquals(new long[]{2, 3}, (long[]) ArrayUtils.toPrimitive((Object) new Long[]{2L, 3L}));
381 assertArrayEquals(new float[]{3.14f}, (float[]) ArrayUtils.toPrimitive((Object) new Float[]{3.14f}), 0.1f);
382 assertArrayEquals(new double[]{2.718}, (double[]) ArrayUtils.toPrimitive((Object) new Double[]{2.718}), 0.1);
348383 }
349384
350385 /**
369404 assertEquals(null, ArrayUtils.get(array1, -1));
370405 assertEquals(StringUtils.EMPTY, ArrayUtils.get(array1, 0));
371406 assertEquals(null, ArrayUtils.get(array1, 1));
407 }
408
409 @Test
410 public void testGetComponentType() {
411 final TestClass[] newArray = {};
412 // No type-cast required.
413 final Class<TestClass> componentType = ArrayUtils.getComponentType(newArray);
414 assertEquals(TestClass.class, componentType);
415 assertNull(ArrayUtils.getComponentType(null));
372416 }
373417
374418 @Test
401445 public void testGetLength() {
402446 assertEquals(0, ArrayUtils.getLength(null));
403447
404 final Object[] emptyObjectArray = new Object[0];
405 final Object[] notEmptyObjectArray = new Object[]{"aValue"};
448 final Object[] emptyObjectArray = {};
449 final Object[] notEmptyObjectArray = {"aValue"};
406450 assertEquals(0, ArrayUtils.getLength(null));
407451 assertEquals(0, ArrayUtils.getLength(emptyObjectArray));
408452 assertEquals(1, ArrayUtils.getLength(notEmptyObjectArray));
409453
410 final int[] emptyIntArray = new int[]{};
411 final int[] notEmptyIntArray = new int[]{1};
454 final int[] emptyIntArray = {};
455 final int[] notEmptyIntArray = {1};
412456 assertEquals(0, ArrayUtils.getLength(null));
413457 assertEquals(0, ArrayUtils.getLength(emptyIntArray));
414458 assertEquals(1, ArrayUtils.getLength(notEmptyIntArray));
415459
416 final short[] emptyShortArray = new short[]{};
417 final short[] notEmptyShortArray = new short[]{1};
460 final short[] emptyShortArray = {};
461 final short[] notEmptyShortArray = {1};
418462 assertEquals(0, ArrayUtils.getLength(null));
419463 assertEquals(0, ArrayUtils.getLength(emptyShortArray));
420464 assertEquals(1, ArrayUtils.getLength(notEmptyShortArray));
421465
422 final char[] emptyCharArray = new char[]{};
423 final char[] notEmptyCharArray = new char[]{1};
466 final char[] emptyCharArray = {};
467 final char[] notEmptyCharArray = {1};
424468 assertEquals(0, ArrayUtils.getLength(null));
425469 assertEquals(0, ArrayUtils.getLength(emptyCharArray));
426470 assertEquals(1, ArrayUtils.getLength(notEmptyCharArray));
427471
428 final byte[] emptyByteArray = new byte[]{};
429 final byte[] notEmptyByteArray = new byte[]{1};
472 final byte[] emptyByteArray = {};
473 final byte[] notEmptyByteArray = {1};
430474 assertEquals(0, ArrayUtils.getLength(null));
431475 assertEquals(0, ArrayUtils.getLength(emptyByteArray));
432476 assertEquals(1, ArrayUtils.getLength(notEmptyByteArray));
433477
434 final double[] emptyDoubleArray = new double[]{};
435 final double[] notEmptyDoubleArray = new double[]{1.0};
478 final double[] emptyDoubleArray = {};
479 final double[] notEmptyDoubleArray = {1.0};
436480 assertEquals(0, ArrayUtils.getLength(null));
437481 assertEquals(0, ArrayUtils.getLength(emptyDoubleArray));
438482 assertEquals(1, ArrayUtils.getLength(notEmptyDoubleArray));
439483
440 final float[] emptyFloatArray = new float[]{};
441 final float[] notEmptyFloatArray = new float[]{1.0F};
484 final float[] emptyFloatArray = {};
485 final float[] notEmptyFloatArray = {1.0F};
442486 assertEquals(0, ArrayUtils.getLength(null));
443487 assertEquals(0, ArrayUtils.getLength(emptyFloatArray));
444488 assertEquals(1, ArrayUtils.getLength(notEmptyFloatArray));
445489
446 final boolean[] emptyBooleanArray = new boolean[]{};
447 final boolean[] notEmptyBooleanArray = new boolean[]{true};
490 final boolean[] emptyBooleanArray = {};
491 final boolean[] notEmptyBooleanArray = {true};
448492 assertEquals(0, ArrayUtils.getLength(null));
449493 assertEquals(0, ArrayUtils.getLength(emptyBooleanArray));
450494 assertEquals(1, ArrayUtils.getLength(notEmptyBooleanArray));
454498
455499 @Test
456500 public void testHashCode() {
457 final long[][] array1 = new long[][]{{2, 5}, {4, 5}};
458 final long[][] array2 = new long[][]{{2, 5}, {4, 6}};
501 final long[][] array1 = {{2, 5}, {4, 5}};
502 final long[][] array2 = {{2, 5}, {4, 6}};
459503 assertEquals(ArrayUtils.hashCode(array1), ArrayUtils.hashCode(array1));
460504 assertNotEquals(ArrayUtils.hashCode(array1), ArrayUtils.hashCode(array2));
461505
462 final Object[] array3 = new Object[]{new String(new char[]{'A', 'B'})};
463 final Object[] array4 = new Object[]{"AB"};
506 final Object[] array3 = {new String(new char[]{'A', 'B'})};
507 final Object[] array4 = {"AB"};
464508 assertEquals(ArrayUtils.hashCode(array3), ArrayUtils.hashCode(array3));
465509 assertEquals(ArrayUtils.hashCode(array3), ArrayUtils.hashCode(array4));
466510
467 final Object[] arrayA = new Object[]{new boolean[]{true, false}, new int[]{6, 7}};
468 final Object[] arrayB = new Object[]{new boolean[]{true, false}, new int[]{6, 7}};
511 final Object[] arrayA = {new boolean[]{true, false}, new int[]{6, 7}};
512 final Object[] arrayB = {new boolean[]{true, false}, new int[]{6, 7}};
469513 assertEquals(ArrayUtils.hashCode(arrayB), ArrayUtils.hashCode(arrayA));
470514 }
471515
472516 @Test
473517 public void testIndexesOf() {
474 final Object[] array = new Object[]{"0", "1", "2", "3", null, "0"};
518 final Object[] array = {"0", "1", "2", "3", null, "0"};
475519 final BitSet emptySet = new BitSet();
476520 final BitSet testSet = new BitSet();
477521 assertEquals(emptySet, ArrayUtils.indexesOf((Object[]) null, null));
624668 assertEquals(emptySet, ArrayUtils.indexesOf(array, 'e', 0));
625669 }
626670
627 @SuppressWarnings("cast")
628671 @Test
629672 public void testIndexesOfDouble() {
630673 double[] array = null;
668711 assertEquals(testSet, ArrayUtils.indexesOf(array, 1.00001324, 0.0001));
669712 }
670713
671 @SuppressWarnings("cast")
672714 @Test
673715 public void testIndexesOfDoubleWithStartIndex() {
674716 double[] array = null;
721763 assertEquals(testSet, ArrayUtils.indexesOf(array, 1.00001324, 0, 0.0001));
722764 }
723765
724 @SuppressWarnings("cast")
725766 @Test
726767 public void testIndexesOfFloat() {
727768 float[] array = null;
744785 assertEquals(emptySet, ArrayUtils.indexesOf(array, 99));
745786 }
746787
747 @SuppressWarnings("cast")
748788 @Test
749789 public void testIndexesOfFloatWithStartIndex() {
750790 float[] array = null;
795835
796836 @Test
797837 public void testIndexesOfLong() {
798 final long[] array = new long[]{0, 1, 2, 3};
838 final long[] array = {0, 1, 2, 3};
799839 final BitSet emptySet = new BitSet();
800840 final BitSet testSet = new BitSet();
801841 assertEquals(emptySet, ArrayUtils.indexesOf((long[]) null, 0));
815855
816856 @Test
817857 public void testIndexesOfLongWithStartIndex() {
818 final long[] array = new long[]{0, 1, 2, 3, 2, 1, 0, 1};
858 final long[] array = {0, 1, 2, 3, 2, 1, 0, 1};
819859 final BitSet emptySet = new BitSet();
820860 final BitSet testSet = new BitSet();
821861 assertEquals(emptySet, ArrayUtils.indexesOf((long[]) null, 0, 0));
887927
888928 @Test
889929 public void testIndexesOfWithStartIndex() {
890 final Object[] array = new Object[]{"0", "1", "2", "3", "2", "3", "1", null, "0"};
930 final Object[] array = {"0", "1", "2", "3", "2", "3", "1", null, "0"};
891931 final BitSet emptySet = new BitSet();
892932 final BitSet testSet = new BitSet();
893933 assertEquals(emptySet, ArrayUtils.indexesOf(null, null, 2));
919959
920960 @Test
921961 public void testIndexOf() {
922 final Object[] array = new Object[]{"0", "1", "2", "3", null, "0"};
962 final Object[] array = {"0", "1", "2", "3", null, "0"};
923963 assertEquals(-1, ArrayUtils.indexOf(null, null));
924964 assertEquals(-1, ArrayUtils.indexOf(null, "0"));
925965 assertEquals(-1, ArrayUtils.indexOf(new Object[0], "0"));
10261066 assertEquals(3, ArrayUtils.indexOf(array, (double) 3));
10271067 assertEquals(3, ArrayUtils.indexOf(array, (double) 3, -1));
10281068 assertEquals(-1, ArrayUtils.indexOf(array, (double) 99));
1069 }
1070
1071 @Test
1072 public void testIndexOfDoubleNaN() {
1073 final double[] array = { Double.NEGATIVE_INFINITY, Double.NaN, Double.POSITIVE_INFINITY, Double.NaN };
1074 assertEquals(0, ArrayUtils.indexOf(array, Double.NEGATIVE_INFINITY));
1075 assertEquals(1, ArrayUtils.indexOf(array, Double.NaN));
1076 assertEquals(2, ArrayUtils.indexOf(array, Double.POSITIVE_INFINITY));
1077
10291078 }
10301079
10311080 @SuppressWarnings("cast")
10911140 assertEquals(-1, ArrayUtils.indexOf(array, (float) 99));
10921141 }
10931142
1143 @Test
1144 public void testIndexOfFloatNaN() {
1145 final float[] array = { Float.NEGATIVE_INFINITY, Float.NaN, Float.POSITIVE_INFINITY, Float.NaN };
1146 assertEquals(0, ArrayUtils.indexOf(array, Float.NEGATIVE_INFINITY));
1147 assertEquals(1, ArrayUtils.indexOf(array, Float.NaN));
1148 assertEquals(2, ArrayUtils.indexOf(array, Float.POSITIVE_INFINITY));
1149 }
1150
10941151 @SuppressWarnings("cast")
10951152 @Test
10961153 public void testIndexOfFloatWithStartIndex() {
11881245
11891246 @Test
11901247 public void testIndexOfWithStartIndex() {
1191 final Object[] array = new Object[]{"0", "1", "2", "3", null, "0"};
1248 final Object[] array = {"0", "1", "2", "3", null, "0"};
11921249 assertEquals(-1, ArrayUtils.indexOf(null, null, 2));
11931250 assertEquals(-1, ArrayUtils.indexOf(new Object[0], "0", 0));
11941251 assertEquals(-1, ArrayUtils.indexOf(null, "0", 2));
12441301 */
12451302 @Test
12461303 public void testIsEmptyObject() {
1247 final Object[] emptyArray = new Object[]{};
1248 final Object[] notEmptyArray = new Object[]{new String("Value")};
1304 final Object[] emptyArray = {};
1305 final Object[] notEmptyArray = {"Value"};
12491306 assertTrue(ArrayUtils.isEmpty((Object[]) null));
12501307 assertTrue(ArrayUtils.isEmpty(emptyArray));
12511308 assertFalse(ArrayUtils.isEmpty(notEmptyArray));
12631320 */
12641321 @Test
12651322 public void testIsEmptyPrimitives() {
1266 final long[] emptyLongArray = new long[]{};
1267 final long[] notEmptyLongArray = new long[]{1L};
1323 final long[] emptyLongArray = {};
1324 final long[] notEmptyLongArray = {1L};
12681325 assertTrue(ArrayUtils.isEmpty((long[]) null));
12691326 assertTrue(ArrayUtils.isEmpty(emptyLongArray));
12701327 assertFalse(ArrayUtils.isEmpty(notEmptyLongArray));
12711328
1272 final int[] emptyIntArray = new int[]{};
1273 final int[] notEmptyIntArray = new int[]{1};
1329 final int[] emptyIntArray = {};
1330 final int[] notEmptyIntArray = {1};
12741331 assertTrue(ArrayUtils.isEmpty((int[]) null));
12751332 assertTrue(ArrayUtils.isEmpty(emptyIntArray));
12761333 assertFalse(ArrayUtils.isEmpty(notEmptyIntArray));
12771334
1278 final short[] emptyShortArray = new short[]{};
1279 final short[] notEmptyShortArray = new short[]{1};
1335 final short[] emptyShortArray = {};
1336 final short[] notEmptyShortArray = {1};
12801337 assertTrue(ArrayUtils.isEmpty((short[]) null));
12811338 assertTrue(ArrayUtils.isEmpty(emptyShortArray));
12821339 assertFalse(ArrayUtils.isEmpty(notEmptyShortArray));
12831340
1284 final char[] emptyCharArray = new char[]{};
1285 final char[] notEmptyCharArray = new char[]{1};
1341 final char[] emptyCharArray = {};
1342 final char[] notEmptyCharArray = {1};
12861343 assertTrue(ArrayUtils.isEmpty((char[]) null));
12871344 assertTrue(ArrayUtils.isEmpty(emptyCharArray));
12881345 assertFalse(ArrayUtils.isEmpty(notEmptyCharArray));
12891346
1290 final byte[] emptyByteArray = new byte[]{};
1291 final byte[] notEmptyByteArray = new byte[]{1};
1347 final byte[] emptyByteArray = {};
1348 final byte[] notEmptyByteArray = {1};
12921349 assertTrue(ArrayUtils.isEmpty((byte[]) null));
12931350 assertTrue(ArrayUtils.isEmpty(emptyByteArray));
12941351 assertFalse(ArrayUtils.isEmpty(notEmptyByteArray));
12951352
1296 final double[] emptyDoubleArray = new double[]{};
1297 final double[] notEmptyDoubleArray = new double[]{1.0};
1353 final double[] emptyDoubleArray = {};
1354 final double[] notEmptyDoubleArray = {1.0};
12981355 assertTrue(ArrayUtils.isEmpty((double[]) null));
12991356 assertTrue(ArrayUtils.isEmpty(emptyDoubleArray));
13001357 assertFalse(ArrayUtils.isEmpty(notEmptyDoubleArray));
13011358
1302 final float[] emptyFloatArray = new float[]{};
1303 final float[] notEmptyFloatArray = new float[]{1.0F};
1359 final float[] emptyFloatArray = {};
1360 final float[] notEmptyFloatArray = {1.0F};
13041361 assertTrue(ArrayUtils.isEmpty((float[]) null));
13051362 assertTrue(ArrayUtils.isEmpty(emptyFloatArray));
13061363 assertFalse(ArrayUtils.isEmpty(notEmptyFloatArray));
13071364
1308 final boolean[] emptyBooleanArray = new boolean[]{};
1309 final boolean[] notEmptyBooleanArray = new boolean[]{true};
1365 final boolean[] emptyBooleanArray = {};
1366 final boolean[] notEmptyBooleanArray = {true};
13101367 assertTrue(ArrayUtils.isEmpty((boolean[]) null));
13111368 assertTrue(ArrayUtils.isEmpty(emptyBooleanArray));
13121369 assertFalse(ArrayUtils.isEmpty(notEmptyBooleanArray));
13141371
13151372 @Test
13161373 public void testIsEquals() {
1317 final long[][] larray1 = new long[][]{{2, 5}, {4, 5}};
1318 final long[][] larray2 = new long[][]{{2, 5}, {4, 6}};
1319 final long[] larray3 = new long[]{2, 5};
1374 final long[][] larray1 = {{2, 5}, {4, 5}};
1375 final long[][] larray2 = {{2, 5}, {4, 6}};
1376 final long[] larray3 = {2, 5};
13201377 this.assertIsEquals(larray1, larray2, larray3);
13211378
1322 final int[][] iarray1 = new int[][]{{2, 5}, {4, 5}};
1323 final int[][] iarray2 = new int[][]{{2, 5}, {4, 6}};
1324 final int[] iarray3 = new int[]{2, 5};
1379 final int[][] iarray1 = {{2, 5}, {4, 5}};
1380 final int[][] iarray2 = {{2, 5}, {4, 6}};
1381 final int[] iarray3 = {2, 5};
13251382 this.assertIsEquals(iarray1, iarray2, iarray3);
13261383
1327 final short[][] sarray1 = new short[][]{{2, 5}, {4, 5}};
1328 final short[][] sarray2 = new short[][]{{2, 5}, {4, 6}};
1329 final short[] sarray3 = new short[]{2, 5};
1384 final short[][] sarray1 = {{2, 5}, {4, 5}};
1385 final short[][] sarray2 = {{2, 5}, {4, 6}};
1386 final short[] sarray3 = {2, 5};
13301387 this.assertIsEquals(sarray1, sarray2, sarray3);
13311388
1332 final float[][] farray1 = new float[][]{{2, 5}, {4, 5}};
1333 final float[][] farray2 = new float[][]{{2, 5}, {4, 6}};
1334 final float[] farray3 = new float[]{2, 5};
1389 final float[][] farray1 = {{2, 5}, {4, 5}};
1390 final float[][] farray2 = {{2, 5}, {4, 6}};
1391 final float[] farray3 = {2, 5};
13351392 this.assertIsEquals(farray1, farray2, farray3);
13361393
1337 final double[][] darray1 = new double[][]{{2, 5}, {4, 5}};
1338 final double[][] darray2 = new double[][]{{2, 5}, {4, 6}};
1339 final double[] darray3 = new double[]{2, 5};
1394 final double[][] darray1 = {{2, 5}, {4, 5}};
1395 final double[][] darray2 = {{2, 5}, {4, 6}};
1396 final double[] darray3 = {2, 5};
13401397 this.assertIsEquals(darray1, darray2, darray3);
13411398
1342 final byte[][] byteArray1 = new byte[][]{{2, 5}, {4, 5}};
1343 final byte[][] byteArray2 = new byte[][]{{2, 5}, {4, 6}};
1344 final byte[] byteArray3 = new byte[]{2, 5};
1399 final byte[][] byteArray1 = {{2, 5}, {4, 5}};
1400 final byte[][] byteArray2 = {{2, 5}, {4, 6}};
1401 final byte[] byteArray3 = {2, 5};
13451402 this.assertIsEquals(byteArray1, byteArray2, byteArray3);
13461403
1347 final char[][] charArray1 = new char[][]{{2, 5}, {4, 5}};
1348 final char[][] charArray2 = new char[][]{{2, 5}, {4, 6}};
1349 final char[] charArray3 = new char[]{2, 5};
1404 final char[][] charArray1 = {{2, 5}, {4, 5}};
1405 final char[][] charArray2 = {{2, 5}, {4, 6}};
1406 final char[] charArray3 = {2, 5};
13501407 this.assertIsEquals(charArray1, charArray2, charArray3);
13511408
1352 final boolean[][] barray1 = new boolean[][]{{true, false}, {true, true}};
1353 final boolean[][] barray2 = new boolean[][]{{true, false}, {true, false}};
1354 final boolean[] barray3 = new boolean[]{false, true};
1409 final boolean[][] barray1 = {{true, false}, {true, true}};
1410 final boolean[][] barray2 = {{true, false}, {true, false}};
1411 final boolean[] barray3 = {false, true};
13551412 this.assertIsEquals(barray1, barray2, barray3);
13561413
1357 final Object[] array3 = new Object[]{new String(new char[]{'A', 'B'})};
1358 final Object[] array4 = new Object[]{"AB"};
1414 final Object[] array3 = {new String(new char[]{'A', 'B'})};
1415 final Object[] array4 = {"AB"};
13591416 assertTrue(ArrayUtils.isEquals(array3, array3));
13601417 assertTrue(ArrayUtils.isEquals(array3, array4));
13611418
13681425 */
13691426 @Test
13701427 public void testIsNotEmptyObject() {
1371 final Object[] emptyArray = new Object[]{};
1372 final Object[] notEmptyArray = new Object[]{new String("Value")};
1428 final Object[] emptyArray = {};
1429 final Object[] notEmptyArray = {"Value"};
13731430 assertFalse(ArrayUtils.isNotEmpty((Object[]) null));
13741431 assertFalse(ArrayUtils.isNotEmpty(emptyArray));
13751432 assertTrue(ArrayUtils.isNotEmpty(notEmptyArray));
13871444 */
13881445 @Test
13891446 public void testIsNotEmptyPrimitives() {
1390 final long[] emptyLongArray = new long[]{};
1391 final long[] notEmptyLongArray = new long[]{1L};
1447 final long[] emptyLongArray = {};
1448 final long[] notEmptyLongArray = {1L};
13921449 assertFalse(ArrayUtils.isNotEmpty((long[]) null));
13931450 assertFalse(ArrayUtils.isNotEmpty(emptyLongArray));
13941451 assertTrue(ArrayUtils.isNotEmpty(notEmptyLongArray));
13951452
1396 final int[] emptyIntArray = new int[]{};
1397 final int[] notEmptyIntArray = new int[]{1};
1453 final int[] emptyIntArray = {};
1454 final int[] notEmptyIntArray = {1};
13981455 assertFalse(ArrayUtils.isNotEmpty((int[]) null));
13991456 assertFalse(ArrayUtils.isNotEmpty(emptyIntArray));
14001457 assertTrue(ArrayUtils.isNotEmpty(notEmptyIntArray));
14011458
1402 final short[] emptyShortArray = new short[]{};
1403 final short[] notEmptyShortArray = new short[]{1};
1459 final short[] emptyShortArray = {};
1460 final short[] notEmptyShortArray = {1};
14041461 assertFalse(ArrayUtils.isNotEmpty((short[]) null));
14051462 assertFalse(ArrayUtils.isNotEmpty(emptyShortArray));
14061463 assertTrue(ArrayUtils.isNotEmpty(notEmptyShortArray));
14071464
1408 final char[] emptyCharArray = new char[]{};
1409 final char[] notEmptyCharArray = new char[]{1};
1465 final char[] emptyCharArray = {};
1466 final char[] notEmptyCharArray = {1};
14101467 assertFalse(ArrayUtils.isNotEmpty((char[]) null));
14111468 assertFalse(ArrayUtils.isNotEmpty(emptyCharArray));
14121469 assertTrue(ArrayUtils.isNotEmpty(notEmptyCharArray));
14131470
1414 final byte[] emptyByteArray = new byte[]{};
1415 final byte[] notEmptyByteArray = new byte[]{1};
1471 final byte[] emptyByteArray = {};
1472 final byte[] notEmptyByteArray = {1};
14161473 assertFalse(ArrayUtils.isNotEmpty((byte[]) null));
14171474 assertFalse(ArrayUtils.isNotEmpty(emptyByteArray));
14181475 assertTrue(ArrayUtils.isNotEmpty(notEmptyByteArray));
14191476
1420 final double[] emptyDoubleArray = new double[]{};
1421 final double[] notEmptyDoubleArray = new double[]{1.0};
1477 final double[] emptyDoubleArray = {};
1478 final double[] notEmptyDoubleArray = {1.0};
14221479 assertFalse(ArrayUtils.isNotEmpty((double[]) null));
14231480 assertFalse(ArrayUtils.isNotEmpty(emptyDoubleArray));
14241481 assertTrue(ArrayUtils.isNotEmpty(notEmptyDoubleArray));
14251482
1426 final float[] emptyFloatArray = new float[]{};
1427 final float[] notEmptyFloatArray = new float[]{1.0F};
1483 final float[] emptyFloatArray = {};
1484 final float[] notEmptyFloatArray = {1.0F};
14281485 assertFalse(ArrayUtils.isNotEmpty((float[]) null));
14291486 assertFalse(ArrayUtils.isNotEmpty(emptyFloatArray));
14301487 assertTrue(ArrayUtils.isNotEmpty(notEmptyFloatArray));
14311488
1432 final boolean[] emptyBooleanArray = new boolean[]{};
1433 final boolean[] notEmptyBooleanArray = new boolean[]{true};
1489 final boolean[] emptyBooleanArray = {};
1490 final boolean[] notEmptyBooleanArray = {true};
14341491 assertFalse(ArrayUtils.isNotEmpty((boolean[]) null));
14351492 assertFalse(ArrayUtils.isNotEmpty(emptyBooleanArray));
14361493 assertTrue(ArrayUtils.isNotEmpty(notEmptyBooleanArray));
15951652
15961653 @Test
15971654 public void testLastIndexOf() {
1598 final Object[] array = new Object[]{"0", "1", "2", "3", null, "0"};
1655 final Object[] array = {"0", "1", "2", "3", null, "0"};
15991656 assertEquals(-1, ArrayUtils.lastIndexOf(null, null));
16001657 assertEquals(-1, ArrayUtils.lastIndexOf(null, "0"));
16011658 assertEquals(5, ArrayUtils.lastIndexOf(array, "0"));
18631920
18641921 @Test
18651922 public void testLastIndexOfWithStartIndex() {
1866 final Object[] array = new Object[]{"0", "1", "2", "3", null, "0"};
1923 final Object[] array = {"0", "1", "2", "3", null, "0"};
18671924 assertEquals(-1, ArrayUtils.lastIndexOf(null, null, 2));
18681925 assertEquals(-1, ArrayUtils.lastIndexOf(null, "0", 2));
18691926 assertEquals(0, ArrayUtils.lastIndexOf(array, "0", 2));
18811938
18821939 @Test
18831940 public void testNullToEmptyBoolean() {
1884 final boolean[] original = new boolean[]{true, false};
1941 final boolean[] original = {true, false};
18851942 assertEquals(original, ArrayUtils.nullToEmpty(original));
18861943 }
18871944
18881945 @Test
18891946 public void testNullToEmptyBooleanEmptyArray() {
1890 final boolean[] empty = new boolean[]{};
1947 final boolean[] empty = {};
18911948 final boolean[] result = ArrayUtils.nullToEmpty(empty);
18921949 assertEquals(ArrayUtils.EMPTY_BOOLEAN_ARRAY, result);
18931950 assertNotSame(empty, result);
19001957
19011958 @Test
19021959 public void testNullToEmptyBooleanObject() {
1903 final Boolean[] original = new Boolean[]{Boolean.TRUE, Boolean.FALSE};
1960 final Boolean[] original = {Boolean.TRUE, Boolean.FALSE};
19041961 assertArrayEquals(original, ArrayUtils.nullToEmpty(original));
19051962 }
19061963
19071964 @Test
19081965 public void testNullToEmptyBooleanObjectEmptyArray() {
1909 final Boolean[] empty = new Boolean[]{};
1966 final Boolean[] empty = {};
19101967 final Boolean[] result = ArrayUtils.nullToEmpty(empty);
19111968 assertArrayEquals(ArrayUtils.EMPTY_BOOLEAN_OBJECT_ARRAY, result);
19121969 assertNotSame(empty, result);
19191976
19201977 @Test
19211978 public void testNullToEmptyByte() {
1922 final byte[] original = new byte[]{0x0F, 0x0E};
1979 final byte[] original = {0x0F, 0x0E};
19231980 assertEquals(original, ArrayUtils.nullToEmpty(original));
19241981 }
19251982
19261983 @Test
19271984 public void testNullToEmptyByteEmptyArray() {
1928 final byte[] empty = new byte[]{};
1985 final byte[] empty = {};
19291986 final byte[] result = ArrayUtils.nullToEmpty(empty);
19301987 assertEquals(ArrayUtils.EMPTY_BYTE_ARRAY, result);
19311988 assertNotSame(empty, result);
19381995
19391996 @Test
19401997 public void testNullToEmptyByteObject() {
1941 final Byte[] original = new Byte[]{0x0F, 0x0E};
1998 final Byte[] original = {0x0F, 0x0E};
19421999 assertArrayEquals(original, ArrayUtils.nullToEmpty(original));
19432000 }
19442001
19452002 @Test
19462003 public void testNullToEmptyByteObjectEmptyArray() {
1947 final Byte[] empty = new Byte[]{};
2004 final Byte[] empty = {};
19482005 final Byte[] result = ArrayUtils.nullToEmpty(empty);
19492006 assertArrayEquals(ArrayUtils.EMPTY_BYTE_OBJECT_ARRAY, result);
19502007 assertNotSame(empty, result);
19572014
19582015 @Test
19592016 public void testNullToEmptyChar() {
1960 final char[] original = new char[]{'a', 'b'};
2017 final char[] original = {'a', 'b'};
19612018 assertEquals(original, ArrayUtils.nullToEmpty(original));
19622019 }
19632020
19642021 @Test
19652022 public void testNullToEmptyCharEmptyArray() {
1966 final char[] empty = new char[]{};
2023 final char[] empty = {};
19672024 final char[] result = ArrayUtils.nullToEmpty(empty);
19682025 assertEquals(ArrayUtils.EMPTY_CHAR_ARRAY, result);
19692026 assertNotSame(empty, result);
19762033
19772034 @Test
19782035 public void testNullToEmptyCharObject() {
1979 final Character[] original = new Character[]{'a', 'b'};
2036 final Character[] original = {'a', 'b'};
19802037 assertArrayEquals(original, ArrayUtils.nullToEmpty(original));
19812038 }
19822039
19832040 @Test
19842041 public void testNullToEmptyCharObjectEmptyArray() {
1985 final Character[] empty = new Character[]{};
2042 final Character[] empty = {};
19862043 final Character[] result = ArrayUtils.nullToEmpty(empty);
19872044 assertArrayEquals(ArrayUtils.EMPTY_CHARACTER_OBJECT_ARRAY, result);
19882045 assertNotSame(empty, result);
20142071
20152072 @Test
20162073 public void testNullToEmptyDouble() {
2017 final double[] original = new double[]{1L, 2L};
2074 final double[] original = {1L, 2L};
20182075 assertEquals(original, ArrayUtils.nullToEmpty(original));
20192076 }
20202077
20212078 @Test
20222079 public void testNullToEmptyDoubleEmptyArray() {
2023 final double[] empty = new double[]{};
2080 final double[] empty = {};
20242081 final double[] result = ArrayUtils.nullToEmpty(empty);
20252082 assertEquals(ArrayUtils.EMPTY_DOUBLE_ARRAY, result);
20262083 assertNotSame(empty, result);
20332090
20342091 @Test
20352092 public void testNullToEmptyDoubleObject() {
2036 final Double[] original = new Double[]{1D, 2D};
2093 final Double[] original = {1D, 2D};
20372094 assertArrayEquals(original, ArrayUtils.nullToEmpty(original));
20382095 }
20392096
20402097 @Test
20412098 public void testNullToEmptyDoubleObjectEmptyArray() {
2042 final Double[] empty = new Double[]{};
2099 final Double[] empty = {};
20432100 final Double[] result = ArrayUtils.nullToEmpty(empty);
20442101 assertArrayEquals(ArrayUtils.EMPTY_DOUBLE_OBJECT_ARRAY, result);
20452102 assertNotSame(empty, result);
20522109
20532110 @Test
20542111 public void testNullToEmptyFloat() {
2055 final float[] original = new float[]{2.6f, 3.8f};
2112 final float[] original = {2.6f, 3.8f};
20562113 assertEquals(original, ArrayUtils.nullToEmpty(original));
20572114 }
20582115
20592116 @Test
20602117 public void testNullToEmptyFloatEmptyArray() {
2061 final float[] empty = new float[]{};
2118 final float[] empty = {};
20622119 final float[] result = ArrayUtils.nullToEmpty(empty);
20632120 assertEquals(ArrayUtils.EMPTY_FLOAT_ARRAY, result);
20642121 assertNotSame(empty, result);
20712128
20722129 @Test
20732130 public void testNullToEmptyFloatObject() {
2074 final Float[] original = new Float[]{2.6f, 3.8f};
2131 final Float[] original = {2.6f, 3.8f};
20752132 assertArrayEquals(original, ArrayUtils.nullToEmpty(original));
20762133 }
20772134
20782135 @Test
20792136 public void testNullToEmptyFloatObjectEmptyArray() {
2080 final Float[] empty = new Float[]{};
2137 final Float[] empty = {};
20812138 final Float[] result = ArrayUtils.nullToEmpty(empty);
20822139 assertArrayEquals(ArrayUtils.EMPTY_FLOAT_OBJECT_ARRAY, result);
20832140 assertNotSame(empty, result);
20902147
20912148 @Test
20922149 public void testNullToEmptyGeneric() {
2093 final TestClass[] input = new TestClass[]{new TestClass(), new TestClass()};
2150 final TestClass[] input = {new TestClass(), new TestClass()};
20942151 final TestClass[] output = ArrayUtils.nullToEmpty(input, TestClass[].class);
20952152
20962153 assertSame(input, output);
20982155
20992156 @Test
21002157 public void testNullToEmptyGenericEmpty() {
2101 final TestClass[] input = new TestClass[]{};
2158 final TestClass[] input = {};
21022159 final TestClass[] output = ArrayUtils.nullToEmpty(input, TestClass[].class);
21032160
21042161 assertSame(input, output);
21142171
21152172 @Test
21162173 public void testNullToEmptyGenericNullType() {
2117 final TestClass[] input = new TestClass[]{};
2174 final TestClass[] input = {};
21182175 assertThrows(IllegalArgumentException.class, () -> ArrayUtils.nullToEmpty(input, null));
21192176 }
21202177
21212178 @Test
21222179 public void testNullToEmptyInt() {
2123 final int[] original = new int[]{1, 2};
2180 final int[] original = {1, 2};
21242181 assertEquals(original, ArrayUtils.nullToEmpty(original));
21252182 }
21262183
21272184 @Test
21282185 public void testNullToEmptyIntEmptyArray() {
2129 final int[] empty = new int[]{};
2186 final int[] empty = {};
21302187 final int[] result = ArrayUtils.nullToEmpty(empty);
21312188 assertEquals(ArrayUtils.EMPTY_INT_ARRAY, result);
21322189 assertNotSame(empty, result);
21392196
21402197 @Test
21412198 public void testNullToEmptyIntObject() {
2142 final Integer[] original = new Integer[]{1, 2};
2199 final Integer[] original = {1, 2};
21432200 assertArrayEquals(original, ArrayUtils.nullToEmpty(original));
21442201 }
21452202
21462203 @Test
21472204 public void testNullToEmptyIntObjectEmptyArray() {
2148 final Integer[] empty = new Integer[]{};
2205 final Integer[] empty = {};
21492206 final Integer[] result = ArrayUtils.nullToEmpty(empty);
21502207 assertArrayEquals(ArrayUtils.EMPTY_INTEGER_OBJECT_ARRAY, result);
21512208 assertNotSame(empty, result);
21582215
21592216 @Test
21602217 public void testNullToEmptyLong() {
2161 final long[] original = new long[]{1L, 2L};
2218 final long[] original = {1L, 2L};
21622219 assertEquals(original, ArrayUtils.nullToEmpty(original));
21632220 }
21642221
21652222 @Test
21662223 public void testNullToEmptyLongEmptyArray() {
2167 final long[] empty = new long[]{};
2224 final long[] empty = {};
21682225 final long[] result = ArrayUtils.nullToEmpty(empty);
21692226 assertEquals(ArrayUtils.EMPTY_LONG_ARRAY, result);
21702227 assertNotSame(empty, result);
21772234
21782235 @Test
21792236 public void testNullToEmptyLongObject() {
2180 @SuppressWarnings("boxing") final Long[] original = new Long[]{1L, 2L};
2237 @SuppressWarnings("boxing") final Long[] original = {1L, 2L};
21812238 assertArrayEquals(original, ArrayUtils.nullToEmpty(original));
21822239 }
21832240
21842241 @Test
21852242 public void testNullToEmptyLongObjectEmptyArray() {
2186 final Long[] empty = new Long[]{};
2243 final Long[] empty = {};
21872244 final Long[] result = ArrayUtils.nullToEmpty(empty);
21882245 assertArrayEquals(ArrayUtils.EMPTY_LONG_OBJECT_ARRAY, result);
21892246 assertNotSame(empty, result);
21962253
21972254 @Test
21982255 public void testNullToEmptyObject() {
2199 final Object[] original = new Object[]{Boolean.TRUE, Boolean.FALSE};
2256 final Object[] original = {Boolean.TRUE, Boolean.FALSE};
22002257 assertArrayEquals(original, ArrayUtils.nullToEmpty(original));
22012258 }
22022259
22032260 @Test
22042261 public void testNullToEmptyObjectEmptyArray() {
2205 final Object[] empty = new Object[]{};
2262 final Object[] empty = {};
22062263 final Object[] result = ArrayUtils.nullToEmpty(empty);
22072264 assertArrayEquals(ArrayUtils.EMPTY_OBJECT_ARRAY, result);
22082265 assertNotSame(empty, result);
22152272
22162273 @Test
22172274 public void testNullToEmptyShort() {
2218 final short[] original = new short[]{1, 2};
2275 final short[] original = {1, 2};
22192276 assertEquals(original, ArrayUtils.nullToEmpty(original));
22202277 }
22212278
22222279 @Test
22232280 public void testNullToEmptyShortEmptyArray() {
2224 final short[] empty = new short[]{};
2281 final short[] empty = {};
22252282 final short[] result = ArrayUtils.nullToEmpty(empty);
22262283 assertEquals(ArrayUtils.EMPTY_SHORT_ARRAY, result);
22272284 assertNotSame(empty, result);
22342291
22352292 @Test
22362293 public void testNullToEmptyShortObject() {
2237 @SuppressWarnings("boxing") final Short[] original = new Short[]{1, 2};
2294 @SuppressWarnings("boxing") final Short[] original = {1, 2};
22382295 assertArrayEquals(original, ArrayUtils.nullToEmpty(original));
22392296 }
22402297
22412298 @Test
22422299 public void testNullToEmptyShortObjectEmptyArray() {
2243 final Short[] empty = new Short[]{};
2300 final Short[] empty = {};
22442301 final Short[] result = ArrayUtils.nullToEmpty(empty);
22452302 assertArrayEquals(ArrayUtils.EMPTY_SHORT_OBJECT_ARRAY, result);
22462303 assertNotSame(empty, result);
22532310
22542311 @Test
22552312 public void testNullToEmptyString() {
2256 final String[] original = new String[]{"abc", "def"};
2313 final String[] original = {"abc", "def"};
22572314 assertArrayEquals(original, ArrayUtils.nullToEmpty(original));
22582315 }
22592316
22602317 @Test
22612318 public void testNullToEmptyStringEmptyArray() {
2262 final String[] empty = new String[]{};
2319 final String[] empty = {};
22632320 final String[] result = ArrayUtils.nullToEmpty(empty);
22642321 assertArrayEquals(ArrayUtils.EMPTY_STRING_ARRAY, result);
22652322 assertNotSame(empty, result);
22742331 public void testReverse() {
22752332 final StringBuffer str1 = new StringBuffer("pick");
22762333 final String str2 = "a";
2277 final String[] str3 = new String[]{"stick"};
2334 final String[] str3 = {"stick"};
22782335 final String str4 = "up";
22792336
2280 Object[] array = new Object[]{str1, str2, str3};
2337 Object[] array = {str1, str2, str3};
22812338 ArrayUtils.reverse(array);
22822339 assertEquals(array[0], str3);
22832340 assertEquals(array[1], str2);
22972354
22982355 @Test
22992356 public void testReverseBoolean() {
2300 boolean[] array = new boolean[]{false, false, true};
2357 boolean[] array = {false, false, true};
23012358 ArrayUtils.reverse(array);
23022359 assertTrue(array[0]);
23032360 assertFalse(array[1]);
23102367
23112368 @Test
23122369 public void testReverseBooleanRange() {
2313 boolean[] array = new boolean[]{false, false, true};
2370 boolean[] array = {false, false, true};
23142371 // The whole array
23152372 ArrayUtils.reverse(array, 0, 3);
23162373 assertTrue(array[0]);
23422399
23432400 @Test
23442401 public void testReverseByte() {
2345 byte[] array = new byte[]{2, 3, 4};
2402 byte[] array = {2, 3, 4};
23462403 ArrayUtils.reverse(array);
23472404 assertEquals(array[0], 4);
23482405 assertEquals(array[1], 3);
23552412
23562413 @Test
23572414 public void testReverseByteRange() {
2358 byte[] array = new byte[]{1, 2, 3};
2415 byte[] array = {1, 2, 3};
23592416 // The whole array
23602417 ArrayUtils.reverse(array, 0, 3);
23612418 assertEquals(3, array[0]);
23872444
23882445 @Test
23892446 public void testReverseChar() {
2390 char[] array = new char[]{'a', 'f', 'C'};
2447 char[] array = {'a', 'f', 'C'};
23912448 ArrayUtils.reverse(array);
23922449 assertEquals(array[0], 'C');
23932450 assertEquals(array[1], 'f');
24002457
24012458 @Test
24022459 public void testReverseCharRange() {
2403 char[] array = new char[]{1, 2, 3};
2460 char[] array = {1, 2, 3};
24042461 // The whole array
24052462 ArrayUtils.reverse(array, 0, 3);
24062463 assertEquals(3, array[0]);
24322489
24332490 @Test
24342491 public void testReverseDouble() {
2435 double[] array = new double[]{0.3d, 0.4d, 0.5d};
2492 double[] array = {0.3d, 0.4d, 0.5d};
24362493 ArrayUtils.reverse(array);
24372494 assertEquals(0.5d, array[0]);
24382495 assertEquals(0.4d, array[1]);
24452502
24462503 @Test
24472504 public void testReverseDoubleRange() {
2448 double[] array = new double[]{1, 2, 3};
2505 double[] array = {1, 2, 3};
24492506 // The whole array
24502507 ArrayUtils.reverse(array, 0, 3);
24512508 assertEquals(3, array[0]);
24772534
24782535 @Test
24792536 public void testReverseFloat() {
2480 float[] array = new float[]{0.3f, 0.4f, 0.5f};
2537 float[] array = {0.3f, 0.4f, 0.5f};
24812538 ArrayUtils.reverse(array);
24822539 assertEquals(0.5f, array[0]);
24832540 assertEquals(0.4f, array[1]);
24902547
24912548 @Test
24922549 public void testReverseFloatRange() {
2493 float[] array = new float[]{1, 2, 3};
2550 float[] array = {1, 2, 3};
24942551 // The whole array
24952552 ArrayUtils.reverse(array, 0, 3);
24962553 assertEquals(3, array[0]);
25222579
25232580 @Test
25242581 public void testReverseInt() {
2525 int[] array = new int[]{1, 2, 3};
2582 int[] array = {1, 2, 3};
25262583 ArrayUtils.reverse(array);
25272584 assertEquals(array[0], 3);
25282585 assertEquals(array[1], 2);
25352592
25362593 @Test
25372594 public void testReverseIntRange() {
2538 int[] array = new int[]{1, 2, 3};
2595 int[] array = {1, 2, 3};
25392596 // The whole array
25402597 ArrayUtils.reverse(array, 0, 3);
25412598 assertEquals(3, array[0]);
25672624
25682625 @Test
25692626 public void testReverseLong() {
2570 long[] array = new long[]{1L, 2L, 3L};
2627 long[] array = {1L, 2L, 3L};
25712628 ArrayUtils.reverse(array);
25722629 assertEquals(array[0], 3L);
25732630 assertEquals(array[1], 2L);
25802637
25812638 @Test
25822639 public void testReverseLongRange() {
2583 long[] array = new long[]{1, 2, 3};
2640 long[] array = {1, 2, 3};
25842641 // The whole array
25852642 ArrayUtils.reverse(array, 0, 3);
25862643 assertEquals(3, array[0]);
26122669
26132670 @Test
26142671 public void testReverseObjectRange() {
2615 String[] array = new String[]{"1", "2", "3"};
2672 String[] array = {"1", "2", "3"};
26162673 // The whole array
26172674 ArrayUtils.reverse(array, 0, 3);
26182675 assertEquals("3", array[0]);
26442701
26452702 @Test
26462703 public void testReverseShort() {
2647 short[] array = new short[]{1, 2, 3};
2704 short[] array = {1, 2, 3};
26482705 ArrayUtils.reverse(array);
26492706 assertEquals(array[0], 3);
26502707 assertEquals(array[1], 2);
26572714
26582715 @Test
26592716 public void testReverseShortRange() {
2660 short[] array = new short[]{1, 2, 3};
2717 short[] array = {1, 2, 3};
26612718 // The whole array
26622719 ArrayUtils.reverse(array, 0, 3);
26632720 assertEquals(3, array[0]);
26902747 @Test
26912748 public void testSameLength() {
26922749 final Object[] nullArray = null;
2693 final Object[] emptyArray = new Object[0];
2694 final Object[] oneArray = new Object[]{"pick"};
2695 final Object[] twoArray = new Object[]{"pick", "stick"};
2750 final Object[] emptyArray = {};
2751 final Object[] oneArray = {"pick"};
2752 final Object[] twoArray = {"pick", "stick"};
26962753
26972754 assertTrue(ArrayUtils.isSameLength(nullArray, nullArray));
26982755 assertTrue(ArrayUtils.isSameLength(nullArray, emptyArray));
27182775 @Test
27192776 public void testSameLengthAll() {
27202777 final Object[] nullArrayObject = null;
2721 final Object[] emptyArrayObject = new Object[0];
2722 final Object[] oneArrayObject = new Object[]{"pick"};
2723 final Object[] twoArrayObject = new Object[]{"pick", "stick"};
2778 final Object[] emptyArrayObject = {};
2779 final Object[] oneArrayObject = {"pick"};
2780 final Object[] twoArrayObject = {"pick", "stick"};
27242781 final boolean[] nullArrayBoolean = null;
2725 final boolean[] emptyArrayBoolean = new boolean[0];
2726 final boolean[] oneArrayBoolean = new boolean[]{true};
2727 final boolean[] twoArrayBoolean = new boolean[]{true, false};
2782 final boolean[] emptyArrayBoolean = {};
2783 final boolean[] oneArrayBoolean = {true};
2784 final boolean[] twoArrayBoolean = {true, false};
27282785 final long[] nullArrayLong = null;
2729 final long[] emptyArrayLong = new long[0];
2730 final long[] oneArrayLong = new long[]{0L};
2731 final long[] twoArrayLong = new long[]{0L, 76L};
2786 final long[] emptyArrayLong = {};
2787 final long[] oneArrayLong = {0L};
2788 final long[] twoArrayLong = {0L, 76L};
27322789 final int[] nullArrayInt = null;
2733 final int[] emptyArrayInt = new int[0];
2734 final int[] oneArrayInt = new int[]{4};
2735 final int[] twoArrayInt = new int[]{5, 7};
2790 final int[] emptyArrayInt = {};
2791 final int[] oneArrayInt = {4};
2792 final int[] twoArrayInt = {5, 7};
27362793 final short[] nullArrayShort = null;
2737 final short[] emptyArrayShort = new short[0];
2738 final short[] oneArrayShort = new short[]{4};
2739 final short[] twoArrayShort = new short[]{6, 8};
2794 final short[] emptyArrayShort = {};
2795 final short[] oneArrayShort = {4};
2796 final short[] twoArrayShort = {6, 8};
27402797 final char[] nullArrayChar = null;
2741 final char[] emptyArrayChar = new char[0];
2742 final char[] oneArrayChar = new char[]{'f'};
2743 final char[] twoArrayChar = new char[]{'d', 't'};
2798 final char[] emptyArrayChar = {};
2799 final char[] oneArrayChar = {'f'};
2800 final char[] twoArrayChar = {'d', 't'};
27442801 final byte[] nullArrayByte = null;
2745 final byte[] emptyArrayByte = new byte[0];
2746 final byte[] oneArrayByte = new byte[]{3};
2747 final byte[] twoArrayByte = new byte[]{4, 6};
2802 final byte[] emptyArrayByte = {};
2803 final byte[] oneArrayByte = {3};
2804 final byte[] twoArrayByte = {4, 6};
27482805 final double[] nullArrayDouble = null;
2749 final double[] emptyArrayDouble = new double[0];
2750 final double[] oneArrayDouble = new double[]{1.3d};
2751 final double[] twoArrayDouble = new double[]{4.5d, 6.3d};
2806 final double[] emptyArrayDouble = {};
2807 final double[] oneArrayDouble = {1.3d};
2808 final double[] twoArrayDouble = {4.5d, 6.3d};
27522809 final float[] nullArrayFloat = null;
2753 final float[] emptyArrayFloat = new float[0];
2754 final float[] oneArrayFloat = new float[]{2.5f};
2755 final float[] twoArrayFloat = new float[]{6.4f, 5.8f};
2810 final float[] emptyArrayFloat = {};
2811 final float[] oneArrayFloat = {2.5f};
2812 final float[] twoArrayFloat = {6.4f, 5.8f};
27562813 assertTrue(ArrayUtils.isSameLength(nullArrayObject, nullArrayObject));
27572814 assertTrue(ArrayUtils.isSameLength(nullArrayObject, nullArrayBoolean));
27582815 assertTrue(ArrayUtils.isSameLength(nullArrayObject, nullArrayLong));
40544111 @Test
40554112 public void testSameLengthBoolean() {
40564113 final boolean[] nullArray = null;
4057 final boolean[] emptyArray = new boolean[0];
4058 final boolean[] oneArray = new boolean[]{true};
4059 final boolean[] twoArray = new boolean[]{true, false};
4114 final boolean[] emptyArray = {};
4115 final boolean[] oneArray = {true};
4116 final boolean[] twoArray = {true, false};
40604117
40614118 assertTrue(ArrayUtils.isSameLength(nullArray, nullArray));
40624119 assertTrue(ArrayUtils.isSameLength(nullArray, emptyArray));
40824139 @Test
40834140 public void testSameLengthByte() {
40844141 final byte[] nullArray = null;
4085 final byte[] emptyArray = new byte[0];
4086 final byte[] oneArray = new byte[]{3};
4087 final byte[] twoArray = new byte[]{4, 6};
4142 final byte[] emptyArray = {};
4143 final byte[] oneArray = {3};
4144 final byte[] twoArray = {4, 6};
40884145
40894146 assertTrue(ArrayUtils.isSameLength(nullArray, nullArray));
40904147 assertTrue(ArrayUtils.isSameLength(nullArray, emptyArray));
41104167 @Test
41114168 public void testSameLengthChar() {
41124169 final char[] nullArray = null;
4113 final char[] emptyArray = new char[0];
4114 final char[] oneArray = new char[]{'f'};
4115 final char[] twoArray = new char[]{'d', 't'};
4170 final char[] emptyArray = {};
4171 final char[] oneArray = {'f'};
4172 final char[] twoArray = {'d', 't'};
41164173
41174174 assertTrue(ArrayUtils.isSameLength(nullArray, nullArray));
41184175 assertTrue(ArrayUtils.isSameLength(nullArray, emptyArray));
41384195 @Test
41394196 public void testSameLengthDouble() {
41404197 final double[] nullArray = null;
4141 final double[] emptyArray = new double[0];
4142 final double[] oneArray = new double[]{1.3d};
4143 final double[] twoArray = new double[]{4.5d, 6.3d};
4198 final double[] emptyArray = {};
4199 final double[] oneArray = {1.3d};
4200 final double[] twoArray = {4.5d, 6.3d};
41444201
41454202 assertTrue(ArrayUtils.isSameLength(nullArray, nullArray));
41464203 assertTrue(ArrayUtils.isSameLength(nullArray, emptyArray));
41664223 @Test
41674224 public void testSameLengthFloat() {
41684225 final float[] nullArray = null;
4169 final float[] emptyArray = new float[0];
4170 final float[] oneArray = new float[]{2.5f};
4171 final float[] twoArray = new float[]{6.4f, 5.8f};
4226 final float[] emptyArray = {};
4227 final float[] oneArray = {2.5f};
4228 final float[] twoArray = {6.4f, 5.8f};
41724229
41734230 assertTrue(ArrayUtils.isSameLength(nullArray, nullArray));
41744231 assertTrue(ArrayUtils.isSameLength(nullArray, emptyArray));
41944251 @Test
41954252 public void testSameLengthInt() {
41964253 final int[] nullArray = null;
4197 final int[] emptyArray = new int[0];
4198 final int[] oneArray = new int[]{4};
4199 final int[] twoArray = new int[]{5, 7};
4254 final int[] emptyArray = {};
4255 final int[] oneArray = {4};
4256 final int[] twoArray = {5, 7};
42004257
42014258 assertTrue(ArrayUtils.isSameLength(nullArray, nullArray));
42024259 assertTrue(ArrayUtils.isSameLength(nullArray, emptyArray));
42224279 @Test
42234280 public void testSameLengthLong() {
42244281 final long[] nullArray = null;
4225 final long[] emptyArray = new long[0];
4226 final long[] oneArray = new long[]{0L};
4227 final long[] twoArray = new long[]{0L, 76L};
4282 final long[] emptyArray = {};
4283 final long[] oneArray = {0L};
4284 final long[] twoArray = {0L, 76L};
42284285
42294286 assertTrue(ArrayUtils.isSameLength(nullArray, nullArray));
42304287 assertTrue(ArrayUtils.isSameLength(nullArray, emptyArray));
42504307 @Test
42514308 public void testSameLengthShort() {
42524309 final short[] nullArray = null;
4253 final short[] emptyArray = new short[0];
4254 final short[] oneArray = new short[]{4};
4255 final short[] twoArray = new short[]{6, 8};
4310 final short[] emptyArray = {};
4311 final short[] oneArray = {4};
4312 final short[] twoArray = {6, 8};
42564313
42574314 assertTrue(ArrayUtils.isSameLength(nullArray, nullArray));
42584315 assertTrue(ArrayUtils.isSameLength(nullArray, emptyArray));
42904347
42914348 @Test
42924349 public void testShiftAllByte() {
4293 final byte[] array = new byte[]{1, 2, 3, 4};
4350 final byte[] array = {1, 2, 3, 4};
42944351 ArrayUtils.shift(array, 4);
42954352 assertEquals(1, array[0]);
42964353 assertEquals(2, array[1]);
43054362
43064363 @Test
43074364 public void testShiftAllChar() {
4308 final char[] array = new char[]{1, 2, 3, 4};
4365 final char[] array = {1, 2, 3, 4};
43094366 ArrayUtils.shift(array, 4);
43104367 assertEquals(1, array[0]);
43114368 assertEquals(2, array[1]);
43204377
43214378 @Test
43224379 public void testShiftAllDouble() {
4323 final double[] array = new double[]{1, 2, 3, 4};
4380 final double[] array = {1, 2, 3, 4};
43244381 ArrayUtils.shift(array, 4);
43254382 assertEquals(1, array[0]);
43264383 assertEquals(2, array[1]);
43354392
43364393 @Test
43374394 public void testShiftAllFloat() {
4338 final float[] array = new float[]{1, 2, 3, 4};
4395 final float[] array = {1, 2, 3, 4};
43394396 ArrayUtils.shift(array, 4);
43404397 assertEquals(1, array[0]);
43414398 assertEquals(2, array[1]);
43504407
43514408 @Test
43524409 public void testShiftAllInt() {
4353 final int[] array = new int[]{1, 2, 3, 4};
4410 final int[] array = {1, 2, 3, 4};
43544411 ArrayUtils.shift(array, 4);
43554412 assertEquals(1, array[0]);
43564413 assertEquals(2, array[1]);
43654422
43664423 @Test
43674424 public void testShiftAllLong() {
4368 final long[] array = new long[]{1, 2, 3, 4};
4425 final long[] array = {1, 2, 3, 4};
43694426 ArrayUtils.shift(array, 4);
43704427 assertEquals(1, array[0]);
43714428 assertEquals(2, array[1]);
43804437
43814438 @Test
43824439 public void testShiftAllObject() {
4383 final String[] array = new String[]{"1", "2", "3", "4"};
4440 final String[] array = {"1", "2", "3", "4"};
43844441 ArrayUtils.shift(array, 4);
43854442 assertEquals("1", array[0]);
43864443 assertEquals("2", array[1]);
43954452
43964453 @Test
43974454 public void testShiftAllShort() {
4398 final short[] array = new short[]{1, 2, 3, 4};
4455 final short[] array = {1, 2, 3, 4};
43994456 ArrayUtils.shift(array, 4);
44004457 assertEquals(1, array[0]);
44014458 assertEquals(2, array[1]);
44104467
44114468 @Test
44124469 public void testShiftBoolean() {
4413 final boolean[] array = new boolean[]{true, true, false, false};
4470 final boolean[] array = {true, true, false, false};
44144471
44154472 ArrayUtils.shift(array, 1);
44164473 assertFalse(array[0]);
44394496
44404497 @Test
44414498 public void testShiftByte() {
4442 final byte[] array = new byte[]{1, 2, 3, 4};
4499 final byte[] array = {1, 2, 3, 4};
44434500 ArrayUtils.shift(array, 1);
44444501 assertEquals(4, array[0]);
44454502 assertEquals(1, array[1]);
44644521
44654522 @Test
44664523 public void testShiftChar() {
4467 final char[] array = new char[]{1, 2, 3, 4};
4524 final char[] array = {1, 2, 3, 4};
44684525 ArrayUtils.shift(array, 1);
44694526 assertEquals(4, array[0]);
44704527 assertEquals(1, array[1]);
44894546
44904547 @Test
44914548 public void testShiftDouble() {
4492 final double[] array = new double[]{1, 2, 3, 4};
4549 final double[] array = {1, 2, 3, 4};
44934550 ArrayUtils.shift(array, 1);
44944551 assertEquals(4, array[0]);
44954552 assertEquals(1, array[1]);
45124569 assertEquals(2, array[3]);
45134570 }
45144571
4515
45164572 @Test
45174573 public void testShiftFloat() {
4518 final float[] array = new float[]{1, 2, 3, 4};
4574 final float[] array = {1, 2, 3, 4};
45194575 ArrayUtils.shift(array, 1);
45204576 assertEquals(4, array[0]);
45214577 assertEquals(1, array[1]);
45384594 assertEquals(2, array[3]);
45394595 }
45404596
4597
45414598 @Test
45424599 public void testShiftInt() {
4543 final int[] array = new int[]{1, 2, 3, 4};
4600 final int[] array = {1, 2, 3, 4};
45444601 ArrayUtils.shift(array, 1);
45454602 assertEquals(4, array[0]);
45464603 assertEquals(1, array[1]);
45654622
45664623 @Test
45674624 public void testShiftLong() {
4568 final long[] array = new long[]{1, 2, 3, 4};
4625 final long[] array = {1, 2, 3, 4};
45694626 ArrayUtils.shift(array, 1);
45704627 assertEquals(4, array[0]);
45714628 assertEquals(1, array[1]);
46464703
46474704 @Test
46484705 public void testShiftObject() {
4649 final String[] array = new String[]{"1", "2", "3", "4"};
4706 final String[] array = {"1", "2", "3", "4"};
46504707 ArrayUtils.shift(array, 1);
46514708 assertEquals("4", array[0]);
46524709 assertEquals("1", array[1]);
46714728
46724729 @Test
46734730 public void testShiftRangeByte() {
4674 final byte[] array = new byte[]{1, 2, 3, 4, 5};
4731 final byte[] array = {1, 2, 3, 4, 5};
46754732 ArrayUtils.shift(array, 1, 3, 1);
46764733 assertEquals(1, array[0]);
46774734 assertEquals(3, array[1]);
46884745
46894746 @Test
46904747 public void testShiftRangeChar() {
4691 final char[] array = new char[]{1, 2, 3, 4, 5};
4748 final char[] array = {1, 2, 3, 4, 5};
46924749 ArrayUtils.shift(array, 1, 3, 1);
46934750 assertEquals(1, array[0]);
46944751 assertEquals(3, array[1]);
47054762
47064763 @Test
47074764 public void testShiftRangeDouble() {
4708 final double[] array = new double[]{1, 2, 3, 4, 5};
4765 final double[] array = {1, 2, 3, 4, 5};
47094766 ArrayUtils.shift(array, 1, 3, 1);
47104767 assertEquals(1, array[0]);
47114768 assertEquals(3, array[1]);
47224779
47234780 @Test
47244781 public void testShiftRangeFloat() {
4725 final float[] array = new float[]{1, 2, 3, 4, 5};
4782 final float[] array = {1, 2, 3, 4, 5};
47264783 ArrayUtils.shift(array, 1, 3, 1);
47274784 assertEquals(1, array[0]);
47284785 assertEquals(3, array[1]);
47394796
47404797 @Test
47414798 public void testShiftRangeInt() {
4742 final int[] array = new int[]{1, 2, 3, 4, 5};
4799 final int[] array = {1, 2, 3, 4, 5};
47434800 ArrayUtils.shift(array, 1, 3, 1);
47444801 assertEquals(1, array[0]);
47454802 assertEquals(3, array[1]);
47564813
47574814 @Test
47584815 public void testShiftRangeLong() {
4759 final long[] array = new long[]{1, 2, 3, 4, 5};
4816 final long[] array = {1, 2, 3, 4, 5};
47604817 ArrayUtils.shift(array, 1, 3, 1);
47614818 assertEquals(1, array[0]);
47624819 assertEquals(3, array[1]);
47734830
47744831 @Test
47754832 public void testShiftRangeNoElemByte() {
4776 final byte[] array = new byte[]{1, 2, 3, 4};
4833 final byte[] array = {1, 2, 3, 4};
47774834 ArrayUtils.shift(array, 1, 1, 1);
47784835 assertEquals(1, array[0]);
47794836 assertEquals(2, array[1]);
47834840
47844841 @Test
47854842 public void testShiftRangeNoElemChar() {
4786 final char[] array = new char[]{1, 2, 3, 4};
4843 final char[] array = {1, 2, 3, 4};
47874844 ArrayUtils.shift(array, 1, 1, 1);
47884845 assertEquals(1, array[0]);
47894846 assertEquals(2, array[1]);
47934850
47944851 @Test
47954852 public void testShiftRangeNoElemDouble() {
4796 final double[] array = new double[]{1, 2, 3, 4};
4853 final double[] array = {1, 2, 3, 4};
47974854 ArrayUtils.shift(array, 1, 1, 1);
47984855 assertEquals(1, array[0]);
47994856 assertEquals(2, array[1]);
48034860
48044861 @Test
48054862 public void testShiftRangeNoElemFloat() {
4806 final float[] array = new float[]{1, 2, 3, 4};
4863 final float[] array = {1, 2, 3, 4};
48074864 ArrayUtils.shift(array, 1, 1, 1);
48084865 assertEquals(1, array[0]);
48094866 assertEquals(2, array[1]);
48134870
48144871 @Test
48154872 public void testShiftRangeNoElemInt() {
4816 final int[] array = new int[]{1, 2, 3, 4};
4873 final int[] array = {1, 2, 3, 4};
48174874 ArrayUtils.shift(array, 1, 1, 1);
48184875 assertEquals(1, array[0]);
48194876 assertEquals(2, array[1]);
48234880
48244881 @Test
48254882 public void testShiftRangeNoElemLong() {
4826 final long[] array = new long[]{1, 2, 3, 4};
4883 final long[] array = {1, 2, 3, 4};
48274884 ArrayUtils.shift(array, 1, 1, 1);
48284885 assertEquals(1, array[0]);
48294886 assertEquals(2, array[1]);
48334890
48344891 @Test
48354892 public void testShiftRangeNoElemObject() {
4836 final String[] array = new String[]{"1", "2", "3", "4"};
4893 final String[] array = {"1", "2", "3", "4"};
48374894 ArrayUtils.shift(array, 1, 1, 1);
48384895 assertEquals("1", array[0]);
48394896 assertEquals("2", array[1]);
48434900
48444901 @Test
48454902 public void testShiftRangeNoElemShort() {
4846 final short[] array = new short[]{1, 2, 3, 4};
4903 final short[] array = {1, 2, 3, 4};
48474904 ArrayUtils.shift(array, 1, 1, 1);
48484905 assertEquals(1, array[0]);
48494906 assertEquals(2, array[1]);
49104967
49114968 @Test
49124969 public void testShiftRangeObject() {
4913 final String[] array = new String[]{"1", "2", "3", "4", "5"};
4970 final String[] array = {"1", "2", "3", "4", "5"};
49144971 ArrayUtils.shift(array, 1, 3, 1);
49154972 assertEquals("1", array[0]);
49164973 assertEquals("3", array[1]);
49274984
49284985 @Test
49294986 public void testShiftRangeShort() {
4930 final short[] array = new short[]{1, 2, 3, 4, 5};
4987 final short[] array = {1, 2, 3, 4, 5};
49314988 ArrayUtils.shift(array, 1, 3, 1);
49324989 assertEquals(1, array[0]);
49334990 assertEquals(3, array[1]);
49445001
49455002 @Test
49465003 public void testShiftShort() {
4947 short[] array = new short[]{1, 2, 3, 4};
5004 short[] array = {1, 2, 3, 4};
49485005 ArrayUtils.shift(array, 1);
49495006 assertEquals(4, array[0]);
49505007 assertEquals(1, array[1]);
49765033
49775034 @Test
49785035 public void testShuffle() {
4979 final String[] array1 = new String[]{"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"};
5036 final String[] array1 = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"};
49805037 final String[] array2 = ArrayUtils.clone(array1);
49815038
49825039 ArrayUtils.shuffle(array1, new Random(SEED));
49885045
49895046 @Test
49905047 public void testShuffleBoolean() {
4991 final boolean[] array1 = new boolean[]{true, false, true, true, false, false, true, false, false, true};
5048 final boolean[] array1 = {true, false, true, true, false, false, true, false, false, true};
49925049 final boolean[] array2 = ArrayUtils.clone(array1);
49935050
49945051 ArrayUtils.shuffle(array1, new Random(SEED));
49985055
49995056 @Test
50005057 public void testShuffleByte() {
5001 final byte[] array1 = new byte[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
5058 final byte[] array1 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
50025059 final byte[] array2 = ArrayUtils.clone(array1);
50035060
50045061 ArrayUtils.shuffle(array1, new Random(SEED));
50105067
50115068 @Test
50125069 public void testShuffleChar() {
5013 final char[] array1 = new char[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
5070 final char[] array1 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
50145071 final char[] array2 = ArrayUtils.clone(array1);
50155072
50165073 ArrayUtils.shuffle(array1, new Random(SEED));
50225079
50235080 @Test
50245081 public void testShuffleDouble() {
5025 final double[] array1 = new double[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
5082 final double[] array1 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
50265083 final double[] array2 = ArrayUtils.clone(array1);
50275084
50285085 ArrayUtils.shuffle(array1, new Random(SEED));
50345091
50355092 @Test
50365093 public void testShuffleFloat() {
5037 final float[] array1 = new float[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
5094 final float[] array1 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
50385095 final float[] array2 = ArrayUtils.clone(array1);
50395096
50405097 ArrayUtils.shuffle(array1, new Random(SEED));
50465103
50475104 @Test
50485105 public void testShuffleInt() {
5049 final int[] array1 = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
5106 final int[] array1 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
50505107 final int[] array2 = ArrayUtils.clone(array1);
50515108
50525109 ArrayUtils.shuffle(array1, new Random(SEED));
50585115
50595116 @Test
50605117 public void testShuffleLong() {
5061 final long[] array1 = new long[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
5118 final long[] array1 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
50625119 final long[] array2 = ArrayUtils.clone(array1);
50635120
50645121 ArrayUtils.shuffle(array1, new Random(SEED));
50705127
50715128 @Test
50725129 public void testShuffleShort() {
5073 final short[] array1 = new short[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
5130 final short[] array1 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
50745131 final short[] array2 = ArrayUtils.clone(array1);
50755132
50765133 ArrayUtils.shuffle(array1, new Random(SEED));
54665523
54675524 @Test
54685525 public void testSwapBoolean() {
5469 final boolean[] array = new boolean[]{true, false, false};
5526 final boolean[] array = {true, false, false};
54705527 ArrayUtils.swap(array, 0, 2);
54715528 assertFalse(array[0]);
54725529 assertFalse(array[1]);
54755532
54765533 @Test
54775534 public void testSwapBooleanRange() {
5478 boolean[] array = new boolean[]{false, false, true, true};
5535 boolean[] array = {false, false, true, true};
54795536 ArrayUtils.swap(array, 0, 2, 2);
54805537 assertTrue(array[0]);
54815538 assertTrue(array[1]);
55155572
55165573 @Test
55175574 public void testSwapByte() {
5518 final byte[] array = new byte[]{1, 2, 3};
5575 final byte[] array = {1, 2, 3};
55195576 ArrayUtils.swap(array, 0, 2);
55205577 assertEquals(3, array[0]);
55215578 assertEquals(2, array[1]);
55245581
55255582 @Test
55265583 public void testSwapByteRange() {
5527 byte[] array = new byte[]{1, 2, 3, 4};
5584 byte[] array = {1, 2, 3, 4};
55285585 ArrayUtils.swap(array, 0, 2, 2);
55295586 assertEquals(3, array[0]);
55305587 assertEquals(4, array[1]);
55645621
55655622 @Test
55665623 public void testSwapChar() {
5567 char[] array = new char[]{1, 2, 3};
5624 char[] array = {1, 2, 3};
55685625 ArrayUtils.swap(array, 0, 2);
55695626 assertArrayEquals(new char[]{3, 2, 1}, array);
55705627
55795636
55805637 @Test
55815638 public void testSwapCharRange() {
5582 char[] array = new char[]{1, 2, 3, 4};
5639 char[] array = {1, 2, 3, 4};
55835640 ArrayUtils.swap(array, 0, 2, 2);
55845641 assertEquals(3, array[0]);
55855642 assertEquals(4, array[1]);
56195676
56205677 @Test
56215678 public void testSwapDouble() {
5622 final double[] array = new double[]{1, 2, 3};
5679 final double[] array = {1, 2, 3};
56235680 ArrayUtils.swap(array, 0, 2);
56245681 assertEquals(3, array[0]);
56255682 assertEquals(2, array[1]);
56285685
56295686 @Test
56305687 public void testSwapDoubleRange() {
5631 double[] array = new double[]{1, 2, 3, 4};
5688 double[] array = {1, 2, 3, 4};
56325689 ArrayUtils.swap(array, 0, 2, 2);
56335690 assertEquals(3, array[0]);
56345691 assertEquals(4, array[1]);
56685725
56695726 @Test
56705727 public void testSwapEmptyBooleanArray() {
5671 final boolean[] array = new boolean[0];
5728 final boolean[] array = {};
56725729 ArrayUtils.swap(array, 0, 2);
56735730 assertEquals(0, array.length);
56745731 }
56755732
56765733 @Test
56775734 public void testSwapEmptyByteArray() {
5678 final byte[] array = new byte[0];
5735 final byte[] array = {};
56795736 ArrayUtils.swap(array, 0, 2);
56805737 assertEquals(0, array.length);
56815738 }
56825739
56835740 @Test
56845741 public void testSwapEmptyCharArray() {
5685 final char[] array = new char[0];
5742 final char[] array = {};
56865743 ArrayUtils.swap(array, 0, 2);
56875744 assertEquals(0, array.length);
56885745 }
56895746
56905747 @Test
56915748 public void testSwapEmptyDoubleArray() {
5692 final double[] array = new double[0];
5749 final double[] array = {};
56935750 ArrayUtils.swap(array, 0, 2);
56945751 assertEquals(0, array.length);
56955752 }
56965753
56975754 @Test
56985755 public void testSwapEmptyFloatArray() {
5699 final float[] array = new float[0];
5756 final float[] array = {};
57005757 ArrayUtils.swap(array, 0, 2);
57015758 assertEquals(0, array.length);
57025759 }
57035760
57045761 @Test
57055762 public void testSwapEmptyIntArray() {
5706 final int[] array = new int[0];
5763 final int[] array = {};
57075764 ArrayUtils.swap(array, 0, 2);
57085765 assertEquals(0, array.length);
57095766 }
57105767
57115768 @Test
57125769 public void testSwapEmptyLongArray() {
5713 final long[] array = new long[0];
5770 final long[] array = {};
57145771 ArrayUtils.swap(array, 0, 2);
57155772 assertEquals(0, array.length);
57165773 }
57175774
57185775 @Test
57195776 public void testSwapEmptyObjectArray() {
5720 final String[] array = new String[0];
5777 final String[] array = {};
57215778 ArrayUtils.swap(array, 0, 2);
57225779 assertEquals(0, array.length);
57235780 }
57245781
57255782 @Test
57265783 public void testSwapEmptyShortArray() {
5727 final short[] array = new short[0];
5784 final short[] array = {};
57285785 ArrayUtils.swap(array, 0, 2);
57295786 assertEquals(0, array.length);
57305787 }
57315788
57325789 @Test
57335790 public void testSwapFloat() {
5734 final float[] array = new float[]{1, 2, 3};
5791 final float[] array = {1, 2, 3};
57355792 ArrayUtils.swap(array, 0, 2);
57365793 assertEquals(3, array[0]);
57375794 assertEquals(2, array[1]);
57405797
57415798 @Test
57425799 public void testSwapFloatRange() {
5743 float[] array = new float[]{1, 2, 3, 4};
5800 float[] array = {1, 2, 3, 4};
57445801 ArrayUtils.swap(array, 0, 2, 2);
57455802 assertEquals(3, array[0]);
57465803 assertEquals(4, array[1]);
57805837
57815838 @Test
57825839 public void testSwapInt() {
5783 final int[] array = new int[]{1, 2, 3};
5840 final int[] array = {1, 2, 3};
57845841 ArrayUtils.swap(array, 0, 2);
57855842 assertEquals(3, array[0]);
57865843 assertEquals(2, array[1]);
58015858
58025859 @Test
58035860 public void testSwapIntRange() {
5804 int[] array = new int[]{1, 2, 3, 4};
5861 int[] array = {1, 2, 3, 4};
58055862 ArrayUtils.swap(array, 0, 2, 2);
58065863 assertEquals(3, array[0]);
58075864 assertEquals(4, array[1]);
58415898
58425899 @Test
58435900 public void testSwapLong() {
5844 final long[] array = new long[]{1, 2, 3};
5901 final long[] array = {1, 2, 3};
58455902 ArrayUtils.swap(array, 0, 2);
58465903 assertEquals(3, array[0]);
58475904 assertEquals(2, array[1]);
58505907
58515908 @Test
58525909 public void testSwapLongRange() {
5853 long[] array = new long[]{1, 2, 3, 4};
5910 long[] array = {1, 2, 3, 4};
58545911 ArrayUtils.swap(array, 0, 2, 2);
58555912 assertEquals(3, array[0]);
58565913 assertEquals(4, array[1]);
59536010
59546011 @Test
59556012 public void testSwapObject() {
5956 final String[] array = new String[]{"1", "2", "3"};
6013 final String[] array = {"1", "2", "3"};
59576014 ArrayUtils.swap(array, 0, 2);
59586015 assertEquals("3", array[0]);
59596016 assertEquals("2", array[1]);
59626019
59636020 @Test
59646021 public void testSwapObjectRange() {
5965 String[] array = new String[]{"1", "2", "3", "4"};
6022 String[] array = {"1", "2", "3", "4"};
59666023 ArrayUtils.swap(array, 0, 2, 2);
59676024 assertEquals("3", array[0]);
59686025 assertEquals("4", array[1]);
60036060
60046061 @Test
60056062 public void testSwapShort() {
6006 final short[] array = new short[]{1, 2, 3};
6063 final short[] array = {1, 2, 3};
60076064 ArrayUtils.swap(array, 0, 2);
60086065 assertEquals(3, array[0]);
60096066 assertEquals(2, array[1]);
60126069
60136070 @Test
60146071 public void testSwapShortRange() {
6015 short[] array = new short[]{1, 2, 3, 4};
6072 short[] array = {1, 2, 3, 4};
60166073 ArrayUtils.swap(array, 0, 2, 2);
60176074 assertEquals(3, array[0]);
60186075 assertEquals(4, array[1]);
64816538
64826539 assertArrayEquals(new String[0], ArrayUtils.toStringArray(new Object[0]));
64836540
6484 final Object[] array = new Object[]{1, 2, 3, "array", "test"};
6541 final Object[] array = {1, 2, 3, "array", "test"};
64856542 assertArrayEquals(new String[]{"1", "2", "3", "array", "test"}, ArrayUtils.toStringArray(array));
64866543
64876544 assertThrows(NullPointerException.class, () -> ArrayUtils.toStringArray(new Object[]{null}));
64936550
64946551 assertArrayEquals(new String[0], ArrayUtils.toStringArray(new Object[0], ""));
64956552
6496 final Object[] array = new Object[]{1, null, "test"};
6553 final Object[] array = {1, null, "test"};
64976554 assertArrayEquals(new String[]{"1", "valueForNullElements", "test"},
64986555 ArrayUtils.toStringArray(array, "valueForNullElements"));
64996556 }
1515 */
1616 package org.apache.commons.lang3;
1717
18 import static org.apache.commons.lang3.ArraySorter.sort;
19 import static org.junit.jupiter.api.Assertions.assertArrayEquals;
1820 import static org.junit.jupiter.api.Assertions.assertEquals;
1921 import static org.junit.jupiter.api.Assertions.assertFalse;
2022 import static org.junit.jupiter.api.Assertions.assertNotNull;
3335 */
3436 public class BooleanUtilsTest {
3537
36 //-----------------------------------------------------------------------
37 @Test
38 public void testConstructor() {
39 assertNotNull(new BooleanUtils());
40 final Constructor<?>[] cons = BooleanUtils.class.getDeclaredConstructors();
41 assertEquals(1, cons.length);
42 assertTrue(Modifier.isPublic(cons[0].getModifiers()));
43 assertTrue(Modifier.isPublic(BooleanUtils.class.getModifiers()));
44 assertFalse(Modifier.isFinal(BooleanUtils.class.getModifiers()));
45 }
46
47 //-----------------------------------------------------------------------
38 @Test
39 public void test_booleanValues() {
40 final Boolean[] expected = {false, true};
41 assertArrayEquals(sort(expected), BooleanUtils.booleanValues());
42 }
43
44 @Test
45 public void test_isFalse_Boolean() {
46 assertFalse(BooleanUtils.isFalse(Boolean.TRUE));
47 assertTrue(BooleanUtils.isFalse(Boolean.FALSE));
48 assertFalse(BooleanUtils.isFalse(null));
49 }
50
51 @Test
52 public void test_isNotFalse_Boolean() {
53 assertTrue(BooleanUtils.isNotFalse(Boolean.TRUE));
54 assertFalse(BooleanUtils.isNotFalse(Boolean.FALSE));
55 assertTrue(BooleanUtils.isNotFalse(null));
56 }
57
58 @Test
59 public void test_isNotTrue_Boolean() {
60 assertFalse(BooleanUtils.isNotTrue(Boolean.TRUE));
61 assertTrue(BooleanUtils.isNotTrue(Boolean.FALSE));
62 assertTrue(BooleanUtils.isNotTrue(null));
63 }
64
65 @Test
66 public void test_isTrue_Boolean() {
67 assertTrue(BooleanUtils.isTrue(Boolean.TRUE));
68 assertFalse(BooleanUtils.isTrue(Boolean.FALSE));
69 assertFalse(BooleanUtils.isTrue(null));
70 }
71
4872 @Test
4973 public void test_negate_Boolean() {
5074 assertSame(null, BooleanUtils.negate(null));
5276 assertSame(Boolean.FALSE, BooleanUtils.negate(Boolean.TRUE));
5377 }
5478
55 //-----------------------------------------------------------------------
56 @Test
57 public void test_isTrue_Boolean() {
58 assertTrue(BooleanUtils.isTrue(Boolean.TRUE));
59 assertFalse(BooleanUtils.isTrue(Boolean.FALSE));
60 assertFalse(BooleanUtils.isTrue(null));
61 }
62
63 @Test
64 public void test_isNotTrue_Boolean() {
65 assertFalse(BooleanUtils.isNotTrue(Boolean.TRUE));
66 assertTrue(BooleanUtils.isNotTrue(Boolean.FALSE));
67 assertTrue(BooleanUtils.isNotTrue(null));
68 }
69
70 //-----------------------------------------------------------------------
71 @Test
72 public void test_isFalse_Boolean() {
73 assertFalse(BooleanUtils.isFalse(Boolean.TRUE));
74 assertTrue(BooleanUtils.isFalse(Boolean.FALSE));
75 assertFalse(BooleanUtils.isFalse(null));
76 }
77
78 @Test
79 public void test_isNotFalse_Boolean() {
80 assertTrue(BooleanUtils.isNotFalse(Boolean.TRUE));
81 assertFalse(BooleanUtils.isNotFalse(Boolean.FALSE));
82 assertTrue(BooleanUtils.isNotFalse(null));
83 }
84
85 //-----------------------------------------------------------------------
79 @Test
80 public void test_primitiveValues() {
81 assertArrayEquals(new boolean[] {false, true}, BooleanUtils.primitiveValues());
82 }
83
8684 @Test
8785 public void test_toBoolean_Boolean() {
8886 assertTrue(BooleanUtils.toBoolean(Boolean.TRUE));
9189 }
9290
9391 @Test
94 public void test_toBooleanDefaultIfNull_Boolean_boolean() {
95 assertTrue(BooleanUtils.toBooleanDefaultIfNull(Boolean.TRUE, true));
96 assertTrue(BooleanUtils.toBooleanDefaultIfNull(Boolean.TRUE, false));
97 assertFalse(BooleanUtils.toBooleanDefaultIfNull(Boolean.FALSE, true));
98 assertFalse(BooleanUtils.toBooleanDefaultIfNull(Boolean.FALSE, false));
99 assertTrue(BooleanUtils.toBooleanDefaultIfNull(null, true));
100 assertFalse(BooleanUtils.toBooleanDefaultIfNull(null, false));
101 }
102
103 //-----------------------------------------------------------------------
104 //-----------------------------------------------------------------------
105 @Test
10692 public void test_toBoolean_int() {
10793 assertTrue(BooleanUtils.toBoolean(1));
10894 assertTrue(BooleanUtils.toBoolean(-1));
11096 }
11197
11298 @Test
113 public void test_toBooleanObject_int() {
114 assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject(1));
115 assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject(-1));
116 assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject(0));
117 }
118
119 @Test
120 public void test_toBooleanObject_Integer() {
121 assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject(Integer.valueOf(1)));
122 assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject(Integer.valueOf(-1)));
123 assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject(Integer.valueOf(0)));
124 assertNull(BooleanUtils.toBooleanObject((Integer) null));
125 }
126
127 //-----------------------------------------------------------------------
128 @Test
12999 public void test_toBoolean_int_int_int() {
130100 assertTrue(BooleanUtils.toBoolean(6, 6, 7));
131101 assertFalse(BooleanUtils.toBoolean(7, 6, 7));
149119 }
150120
151121 @Test
122 public void test_toBoolean_Integer_Integer_Integer_noMatch() {
123 assertThrows(IllegalArgumentException.class,
124 () -> BooleanUtils.toBoolean(Integer.valueOf(8), Integer.valueOf(6), Integer.valueOf(7)));
125 }
126
127 @Test
152128 public void test_toBoolean_Integer_Integer_Integer_nullValue() {
153129 assertThrows(IllegalArgumentException.class,
154130 () -> BooleanUtils.toBoolean(null, Integer.valueOf(6), Integer.valueOf(7)));
155131 }
156132
157 @Test
158 public void test_toBoolean_Integer_Integer_Integer_noMatch() {
159 assertThrows(IllegalArgumentException.class,
160 () -> BooleanUtils.toBoolean(Integer.valueOf(8), Integer.valueOf(6), Integer.valueOf(7)));
161 }
162
163 //-----------------------------------------------------------------------
164 @Test
165 public void test_toBooleanObject_int_int_int() {
166 assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject(6, 6, 7, 8));
167 assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject(7, 6, 7, 8));
168 assertNull(BooleanUtils.toBooleanObject(8, 6, 7, 8));
169 }
170
171 @Test
172 public void test_toBooleanObject_int_int_int_noMatch() {
173 assertThrows(IllegalArgumentException.class, () -> BooleanUtils.toBooleanObject(9, 6, 7, 8));
174 }
175
176 @Test
177 public void test_toBooleanObject_Integer_Integer_Integer_Integer() {
178 final Integer six = Integer.valueOf(6);
179 final Integer seven = Integer.valueOf(7);
180 final Integer eight = Integer.valueOf(8);
181
182 assertSame(Boolean.TRUE, BooleanUtils.toBooleanObject(null, null, seven, eight));
183 assertSame(Boolean.FALSE, BooleanUtils.toBooleanObject(null, six, null, eight));
184 assertSame(null, BooleanUtils.toBooleanObject(null, six, seven, null));
185
186 assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject(Integer.valueOf(6), six, seven, eight));
187 assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject(Integer.valueOf(7), six, seven, eight));
188 assertNull(BooleanUtils.toBooleanObject(Integer.valueOf(8), six, seven, eight));
189 }
190
191 @Test
192 public void test_toBooleanObject_Integer_Integer_Integer_Integer_nullValue() {
193 assertThrows(IllegalArgumentException.class,
194 () -> BooleanUtils.toBooleanObject(null, Integer.valueOf(6), Integer.valueOf(7), Integer.valueOf(8)));
195 }
196
197 @Test
198 public void test_toBooleanObject_Integer_Integer_Integer_Integer_noMatch() {
199 assertThrows(IllegalArgumentException.class,
200 () -> BooleanUtils.toBooleanObject(Integer.valueOf(9), Integer.valueOf(6), Integer.valueOf(7), Integer.valueOf(8)));
201 }
202
203 //-----------------------------------------------------------------------
204 @Test
205 public void test_toInteger_boolean() {
206 assertEquals(1, BooleanUtils.toInteger(true));
207 assertEquals(0, BooleanUtils.toInteger(false));
208 }
209
210 @Test
211 public void test_toIntegerObject_boolean() {
212 assertEquals(Integer.valueOf(1), BooleanUtils.toIntegerObject(true));
213 assertEquals(Integer.valueOf(0), BooleanUtils.toIntegerObject(false));
214 }
215
216 @Test
217 public void test_toIntegerObject_Boolean() {
218 assertEquals(Integer.valueOf(1), BooleanUtils.toIntegerObject(Boolean.TRUE));
219 assertEquals(Integer.valueOf(0), BooleanUtils.toIntegerObject(Boolean.FALSE));
220 assertNull(BooleanUtils.toIntegerObject(null));
221 }
222
223 //-----------------------------------------------------------------------
224 @Test
225 public void test_toInteger_boolean_int_int() {
226 assertEquals(6, BooleanUtils.toInteger(true, 6, 7));
227 assertEquals(7, BooleanUtils.toInteger(false, 6, 7));
228 }
229
230 @Test
231 public void test_toInteger_Boolean_int_int_int() {
232 assertEquals(6, BooleanUtils.toInteger(Boolean.TRUE, 6, 7, 8));
233 assertEquals(7, BooleanUtils.toInteger(Boolean.FALSE, 6, 7, 8));
234 assertEquals(8, BooleanUtils.toInteger(null, 6, 7, 8));
235 }
236
237 @Test
238 public void test_toIntegerObject_boolean_Integer_Integer() {
239 final Integer six = Integer.valueOf(6);
240 final Integer seven = Integer.valueOf(7);
241 assertEquals(six, BooleanUtils.toIntegerObject(true, six, seven));
242 assertEquals(seven, BooleanUtils.toIntegerObject(false, six, seven));
243 }
244
245 @Test
246 public void test_toIntegerObject_Boolean_Integer_Integer_Integer() {
247 final Integer six = Integer.valueOf(6);
248 final Integer seven = Integer.valueOf(7);
249 final Integer eight = Integer.valueOf(8);
250 assertEquals(six, BooleanUtils.toIntegerObject(Boolean.TRUE, six, seven, eight));
251 assertEquals(seven, BooleanUtils.toIntegerObject(Boolean.FALSE, six, seven, eight));
252 assertEquals(eight, BooleanUtils.toIntegerObject(null, six, seven, eight));
253 assertNull(BooleanUtils.toIntegerObject(null, six, seven, null));
254 }
255
256 //-----------------------------------------------------------------------
257 //-----------------------------------------------------------------------
258 @Test
259 public void test_toBooleanObject_String() {
260 assertNull(BooleanUtils.toBooleanObject((String) null));
261 assertNull(BooleanUtils.toBooleanObject(""));
262 assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject("false"));
263 assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject("no"));
264 assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject("off"));
265 assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject("FALSE"));
266 assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject("NO"));
267 assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject("OFF"));
268 assertNull(BooleanUtils.toBooleanObject("oof"));
269 assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject("true"));
270 assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject("yes"));
271 assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject("on"));
272 assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject("TRUE"));
273 assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject("ON"));
274 assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject("YES"));
275 assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject("TruE"));
276 assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject("TruE"));
277
278 assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject("y")); // yes
279 assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject("Y"));
280 assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject("t")); // true
281 assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject("T"));
282 assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject("1"));
283 assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject("f")); // false
284 assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject("F"));
285 assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject("n")); // No
286 assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject("N"));
287 assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject("0"));
288 assertNull(BooleanUtils.toBooleanObject("z"));
289
290 assertNull(BooleanUtils.toBooleanObject("ab"));
291 assertNull(BooleanUtils.toBooleanObject("yoo"));
292 assertNull(BooleanUtils.toBooleanObject("true "));
293 assertNull(BooleanUtils.toBooleanObject("ono"));
294 }
295
296 @Test
297 public void test_toBooleanObject_String_String_String_String() {
298 assertSame(Boolean.TRUE, BooleanUtils.toBooleanObject(null, null, "N", "U"));
299 assertSame(Boolean.FALSE, BooleanUtils.toBooleanObject(null, "Y", null, "U"));
300 assertSame(null, BooleanUtils.toBooleanObject(null, "Y", "N", null));
301
302 assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject("Y", "Y", "N", "U"));
303 assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject("N", "Y", "N", "U"));
304 assertNull(BooleanUtils.toBooleanObject("U", "Y", "N", "U"));
305 }
306
307 @Test
308 public void test_toBooleanObject_String_String_String_String_nullValue() {
309 assertThrows(IllegalArgumentException.class, () -> BooleanUtils.toBooleanObject(null, "Y", "N", "U"));
310 }
311
312 @Test
313 public void test_toBooleanObject_String_String_String_String_noMatch() {
314 assertThrows(IllegalArgumentException.class, () -> BooleanUtils.toBooleanObject("X", "Y", "N", "U"));
315 }
316
317 //-----------------------------------------------------------------------
318133 @Test
319134 public void test_toBoolean_String() {
320135 assertFalse(BooleanUtils.toBoolean((String) null));
369184 assertTrue(BooleanUtils.toBoolean(null, null, "N"));
370185 assertFalse(BooleanUtils.toBoolean(null, "Y", null));
371186 assertTrue(BooleanUtils.toBoolean("Y", "Y", "N"));
372 assertTrue(BooleanUtils.toBoolean("Y", new String("Y"), new String("N")));
187 assertTrue(BooleanUtils.toBoolean("Y", "Y", "N"));
373188 assertFalse(BooleanUtils.toBoolean("N", "Y", "N"));
374 assertFalse(BooleanUtils.toBoolean("N", new String("Y"), new String("N")));
189 assertFalse(BooleanUtils.toBoolean("N", "Y", "N"));
375190 assertTrue(BooleanUtils.toBoolean((String) null, null, null));
376191 assertTrue(BooleanUtils.toBoolean("Y", "Y", "Y"));
377 assertTrue(BooleanUtils.toBoolean("Y", new String("Y"), new String("Y")));
192 assertTrue(BooleanUtils.toBoolean("Y", "Y", "Y"));
193 }
194
195 @Test
196 public void test_toBoolean_String_String_String_noMatch() {
197 assertThrows(IllegalArgumentException.class, () -> BooleanUtils.toBoolean("X", "Y", "N"));
378198 }
379199
380200 @Test
383203 }
384204
385205 @Test
386 public void test_toBoolean_String_String_String_noMatch() {
387 assertThrows(IllegalArgumentException.class, () -> BooleanUtils.toBoolean("X", "Y", "N"));
388 }
389
390 //-----------------------------------------------------------------------
206 public void test_toBooleanDefaultIfNull_Boolean_boolean() {
207 assertTrue(BooleanUtils.toBooleanDefaultIfNull(Boolean.TRUE, true));
208 assertTrue(BooleanUtils.toBooleanDefaultIfNull(Boolean.TRUE, false));
209 assertFalse(BooleanUtils.toBooleanDefaultIfNull(Boolean.FALSE, true));
210 assertFalse(BooleanUtils.toBooleanDefaultIfNull(Boolean.FALSE, false));
211 assertTrue(BooleanUtils.toBooleanDefaultIfNull(null, true));
212 assertFalse(BooleanUtils.toBooleanDefaultIfNull(null, false));
213 }
214
215 @Test
216 public void test_toBooleanObject_int() {
217 assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject(1));
218 assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject(-1));
219 assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject(0));
220 }
221
222 @Test
223 public void test_toBooleanObject_int_int_int() {
224 assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject(6, 6, 7, 8));
225 assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject(7, 6, 7, 8));
226 assertNull(BooleanUtils.toBooleanObject(8, 6, 7, 8));
227 }
228
229 @Test
230 public void test_toBooleanObject_int_int_int_noMatch() {
231 assertThrows(IllegalArgumentException.class, () -> BooleanUtils.toBooleanObject(9, 6, 7, 8));
232 }
233
234 @Test
235 public void test_toBooleanObject_Integer() {
236 assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject(Integer.valueOf(1)));
237 assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject(Integer.valueOf(-1)));
238 assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject(Integer.valueOf(0)));
239 assertNull(BooleanUtils.toBooleanObject((Integer) null));
240 }
241
242 @Test
243 public void test_toBooleanObject_Integer_Integer_Integer_Integer() {
244 final Integer six = Integer.valueOf(6);
245 final Integer seven = Integer.valueOf(7);
246 final Integer eight = Integer.valueOf(8);
247
248 assertSame(Boolean.TRUE, BooleanUtils.toBooleanObject(null, null, seven, eight));
249 assertSame(Boolean.FALSE, BooleanUtils.toBooleanObject(null, six, null, eight));
250 assertSame(null, BooleanUtils.toBooleanObject(null, six, seven, null));
251
252 assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject(Integer.valueOf(6), six, seven, eight));
253 assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject(Integer.valueOf(7), six, seven, eight));
254 assertNull(BooleanUtils.toBooleanObject(Integer.valueOf(8), six, seven, eight));
255 }
256
257 @Test
258 public void test_toBooleanObject_Integer_Integer_Integer_Integer_noMatch() {
259 assertThrows(IllegalArgumentException.class,
260 () -> BooleanUtils.toBooleanObject(Integer.valueOf(9), Integer.valueOf(6), Integer.valueOf(7), Integer.valueOf(8)));
261 }
262
263 @Test
264 public void test_toBooleanObject_Integer_Integer_Integer_Integer_nullValue() {
265 assertThrows(IllegalArgumentException.class,
266 () -> BooleanUtils.toBooleanObject(null, Integer.valueOf(6), Integer.valueOf(7), Integer.valueOf(8)));
267 }
268
269 @Test
270 public void test_toBooleanObject_String() {
271 assertNull(BooleanUtils.toBooleanObject((String) null));
272 assertNull(BooleanUtils.toBooleanObject(""));
273 assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject("false"));
274 assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject("no"));
275 assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject("off"));
276 assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject("FALSE"));
277 assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject("NO"));
278 assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject("OFF"));
279 assertNull(BooleanUtils.toBooleanObject("oof"));
280 assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject("true"));
281 assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject("yes"));
282 assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject("on"));
283 assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject("TRUE"));
284 assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject("ON"));
285 assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject("YES"));
286 assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject("TruE"));
287 assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject("TruE"));
288
289 assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject("y")); // yes
290 assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject("Y"));
291 assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject("t")); // true
292 assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject("T"));
293 assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject("1"));
294 assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject("f")); // false
295 assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject("F"));
296 assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject("n")); // No
297 assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject("N"));
298 assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject("0"));
299 assertNull(BooleanUtils.toBooleanObject("z"));
300
301 assertNull(BooleanUtils.toBooleanObject("ab"));
302 assertNull(BooleanUtils.toBooleanObject("yoo"));
303 assertNull(BooleanUtils.toBooleanObject("true "));
304 assertNull(BooleanUtils.toBooleanObject("ono"));
305 }
306
307 @Test
308 public void test_toBooleanObject_String_String_String_String() {
309 assertSame(Boolean.TRUE, BooleanUtils.toBooleanObject(null, null, "N", "U"));
310 assertSame(Boolean.FALSE, BooleanUtils.toBooleanObject(null, "Y", null, "U"));
311 assertSame(null, BooleanUtils.toBooleanObject(null, "Y", "N", null));
312
313 assertEquals(Boolean.TRUE, BooleanUtils.toBooleanObject("Y", "Y", "N", "U"));
314 assertEquals(Boolean.FALSE, BooleanUtils.toBooleanObject("N", "Y", "N", "U"));
315 assertNull(BooleanUtils.toBooleanObject("U", "Y", "N", "U"));
316 }
317
318 @Test
319 public void test_toBooleanObject_String_String_String_String_noMatch() {
320 assertThrows(IllegalArgumentException.class, () -> BooleanUtils.toBooleanObject("X", "Y", "N", "U"));
321 }
322
323 @Test
324 public void test_toBooleanObject_String_String_String_String_nullValue() {
325 assertThrows(IllegalArgumentException.class, () -> BooleanUtils.toBooleanObject(null, "Y", "N", "U"));
326 }
327
328 @Test
329 public void test_toInteger_boolean() {
330 assertEquals(1, BooleanUtils.toInteger(true));
331 assertEquals(0, BooleanUtils.toInteger(false));
332 }
333
334 @Test
335 public void test_toInteger_boolean_int_int() {
336 assertEquals(6, BooleanUtils.toInteger(true, 6, 7));
337 assertEquals(7, BooleanUtils.toInteger(false, 6, 7));
338 }
339
340 @Test
341 public void test_toInteger_Boolean_int_int_int() {
342 assertEquals(6, BooleanUtils.toInteger(Boolean.TRUE, 6, 7, 8));
343 assertEquals(7, BooleanUtils.toInteger(Boolean.FALSE, 6, 7, 8));
344 assertEquals(8, BooleanUtils.toInteger(null, 6, 7, 8));
345 }
346
347 @Test
348 public void test_toIntegerObject_boolean() {
349 assertEquals(Integer.valueOf(1), BooleanUtils.toIntegerObject(true));
350 assertEquals(Integer.valueOf(0), BooleanUtils.toIntegerObject(false));
351 }
352
353 @Test
354 public void test_toIntegerObject_Boolean() {
355 assertEquals(Integer.valueOf(1), BooleanUtils.toIntegerObject(Boolean.TRUE));
356 assertEquals(Integer.valueOf(0), BooleanUtils.toIntegerObject(Boolean.FALSE));
357 assertNull(BooleanUtils.toIntegerObject(null));
358 }
359
360 @Test
361 public void test_toIntegerObject_boolean_Integer_Integer() {
362 final Integer six = Integer.valueOf(6);
363 final Integer seven = Integer.valueOf(7);
364 assertEquals(six, BooleanUtils.toIntegerObject(true, six, seven));
365 assertEquals(seven, BooleanUtils.toIntegerObject(false, six, seven));
366 }
367
368 @Test
369 public void test_toIntegerObject_Boolean_Integer_Integer_Integer() {
370 final Integer six = Integer.valueOf(6);
371 final Integer seven = Integer.valueOf(7);
372 final Integer eight = Integer.valueOf(8);
373 assertEquals(six, BooleanUtils.toIntegerObject(Boolean.TRUE, six, seven, eight));
374 assertEquals(seven, BooleanUtils.toIntegerObject(Boolean.FALSE, six, seven, eight));
375 assertEquals(eight, BooleanUtils.toIntegerObject(null, six, seven, eight));
376 assertNull(BooleanUtils.toIntegerObject(null, six, seven, null));
377 }
378
379 @Test
380 public void test_toString_boolean_String_String_String() {
381 assertEquals("Y", BooleanUtils.toString(true, "Y", "N"));
382 assertEquals("N", BooleanUtils.toString(false, "Y", "N"));
383 }
384
385 @Test
386 public void test_toString_Boolean_String_String_String() {
387 assertEquals("U", BooleanUtils.toString(null, "Y", "N", "U"));
388 assertEquals("Y", BooleanUtils.toString(Boolean.TRUE, "Y", "N", "U"));
389 assertEquals("N", BooleanUtils.toString(Boolean.FALSE, "Y", "N", "U"));
390 }
391
392 @Test
393 public void test_toStringOnOff_boolean() {
394 assertEquals("on", BooleanUtils.toStringOnOff(true));
395 assertEquals("off", BooleanUtils.toStringOnOff(false));
396 }
397
398 @Test
399 public void test_toStringOnOff_Boolean() {
400 assertNull(BooleanUtils.toStringOnOff(null));
401 assertEquals("on", BooleanUtils.toStringOnOff(Boolean.TRUE));
402 assertEquals("off", BooleanUtils.toStringOnOff(Boolean.FALSE));
403 }
404
405 @Test
406 public void test_toStringTrueFalse_boolean() {
407 assertEquals("true", BooleanUtils.toStringTrueFalse(true));
408 assertEquals("false", BooleanUtils.toStringTrueFalse(false));
409 }
410
391411 @Test
392412 public void test_toStringTrueFalse_Boolean() {
393413 assertNull(BooleanUtils.toStringTrueFalse(null));
396416 }
397417
398418 @Test
399 public void test_toStringOnOff_Boolean() {
400 assertNull(BooleanUtils.toStringOnOff(null));
401 assertEquals("on", BooleanUtils.toStringOnOff(Boolean.TRUE));
402 assertEquals("off", BooleanUtils.toStringOnOff(Boolean.FALSE));
419 public void test_toStringYesNo_boolean() {
420 assertEquals("yes", BooleanUtils.toStringYesNo(true));
421 assertEquals("no", BooleanUtils.toStringYesNo(false));
403422 }
404423
405424 @Test
410429 }
411430
412431 @Test
413 public void test_toString_Boolean_String_String_String() {
414 assertEquals("U", BooleanUtils.toString(null, "Y", "N", "U"));
415 assertEquals("Y", BooleanUtils.toString(Boolean.TRUE, "Y", "N", "U"));
416 assertEquals("N", BooleanUtils.toString(Boolean.FALSE, "Y", "N", "U"));
417 }
418
419 //-----------------------------------------------------------------------
420 @Test
421 public void test_toStringTrueFalse_boolean() {
422 assertEquals("true", BooleanUtils.toStringTrueFalse(true));
423 assertEquals("false", BooleanUtils.toStringTrueFalse(false));
424 }
425
426 @Test
427 public void test_toStringOnOff_boolean() {
428 assertEquals("on", BooleanUtils.toStringOnOff(true));
429 assertEquals("off", BooleanUtils.toStringOnOff(false));
430 }
431
432 @Test
433 public void test_toStringYesNo_boolean() {
434 assertEquals("yes", BooleanUtils.toStringYesNo(true));
435 assertEquals("no", BooleanUtils.toStringYesNo(false));
436 }
437
438 @Test
439 public void test_toString_boolean_String_String_String() {
440 assertEquals("Y", BooleanUtils.toString(true, "Y", "N"));
441 assertEquals("N", BooleanUtils.toString(false, "Y", "N"));
442 }
443
444 // testXor
445 // -----------------------------------------------------------------------
446 @Test
447 public void testXor_primitive_nullInput() {
448 assertThrows(IllegalArgumentException.class, () -> BooleanUtils.xor((boolean[]) null));
449 }
450
451 @Test
452 public void testXor_primitive_emptyInput() {
453 assertThrows(IllegalArgumentException.class, () -> BooleanUtils.xor(new boolean[] {}));
454 }
455
456 @Test
457 public void testXor_primitive_validInput_2items() {
458 assertEquals(
459 true ^ true,
460 BooleanUtils.xor(new boolean[] { true, true }),
461 "true ^ true");
462
463 assertEquals(
464 false ^ false,
465 BooleanUtils.xor(new boolean[] { false, false }),
466 "false ^ false");
467
468 assertEquals(
469 true ^ false,
470 BooleanUtils.xor(new boolean[] { true, false }),
471 "true ^ false");
472
473 assertEquals(
474 false ^ true,
475 BooleanUtils.xor(new boolean[] { false, true }),
476 "false ^ true");
477 }
478
479 @Test
480 public void testXor_primitive_validInput_3items() {
481 assertEquals(
482 false ^ false ^ false,
483 BooleanUtils.xor(new boolean[] { false, false, false }),
484 "false ^ false ^ false");
485
486 assertEquals(
487 false ^ false ^ true,
488 BooleanUtils.xor(new boolean[] { false, false, true }),
489 "false ^ false ^ true");
490
491 assertEquals(
492 false ^ true ^ false,
493 BooleanUtils.xor(new boolean[] { false, true, false }),
494 "false ^ true ^ false");
495
496 assertEquals(
497 false ^ true ^ true,
498 BooleanUtils.xor(new boolean[] { false, true, true }),
499 "false ^ true ^ true");
500
501 assertEquals(
502 true ^ false ^ false,
503 BooleanUtils.xor(new boolean[] { true, false, false }),
504 "true ^ false ^ false");
505
506 assertEquals(
507 true ^ false ^ true,
508 BooleanUtils.xor(new boolean[] { true, false, true }),
509 "true ^ false ^ true");
510
511 assertEquals(
512 true ^ true ^ false,
513 BooleanUtils.xor(new boolean[] { true, true, false }),
514 "true ^ true ^ false");
515
516 assertEquals(
517 true ^ true ^ true,
518 BooleanUtils.xor(new boolean[] { true, true, true }),
519 "true ^ true ^ true");
520 }
521
522 @Test
523 public void testXor_object_nullInput() {
524 assertThrows(IllegalArgumentException.class, () -> BooleanUtils.xor((Boolean[]) null));
432 public void testAnd_object_emptyInput() {
433 assertThrows(IllegalArgumentException.class, () -> BooleanUtils.and(new Boolean[] {}));
434 }
435
436 @Test
437 public void testAnd_object_nullElementInput() {
438 assertThrows(IllegalArgumentException.class, () -> BooleanUtils.and(new Boolean[] {null}));
439 }
440
441 @Test
442 public void testAnd_object_nullInput() {
443 assertThrows(NullPointerException.class, () -> BooleanUtils.and((Boolean[]) null));
444 }
445
446 @Test
447 public void testAnd_object_validInput_2items() {
448 assertTrue(
449 BooleanUtils
450 .and(new Boolean[] { Boolean.TRUE, Boolean.TRUE })
451 .booleanValue(),
452 "False result for (true, true)");
453
454 assertTrue(
455 ! BooleanUtils
456 .and(new Boolean[] { Boolean.FALSE, Boolean.FALSE })
457 .booleanValue(),
458 "True result for (false, false)");
459
460 assertTrue(
461 ! BooleanUtils
462 .and(new Boolean[] { Boolean.TRUE, Boolean.FALSE })
463 .booleanValue(),
464 "True result for (true, false)");
465
466 assertTrue(
467 ! BooleanUtils
468 .and(new Boolean[] { Boolean.FALSE, Boolean.TRUE })
469 .booleanValue(),
470 "True result for (false, true)");
471 }
472
473 @Test
474 public void testAnd_object_validInput_3items() {
475 assertTrue(
476 ! BooleanUtils
477 .and(
478 new Boolean[] {
479 Boolean.FALSE,
480 Boolean.FALSE,
481 Boolean.TRUE })
482 .booleanValue(),
483 "True result for (false, false, true)");
484
485 assertTrue(
486 ! BooleanUtils
487 .and(
488 new Boolean[] {
489 Boolean.FALSE,
490 Boolean.TRUE,
491 Boolean.FALSE })
492 .booleanValue(),
493 "True result for (false, true, false)");
494
495 assertTrue(
496 ! BooleanUtils
497 .and(
498 new Boolean[] {
499 Boolean.TRUE,
500 Boolean.FALSE,
501 Boolean.FALSE })
502 .booleanValue(),
503 "True result for (true, false, false)");
504
505 assertTrue(
506 BooleanUtils
507 .and(new Boolean[] { Boolean.TRUE, Boolean.TRUE, Boolean.TRUE })
508 .booleanValue(),
509 "False result for (true, true, true)");
510
511 assertTrue(
512 ! BooleanUtils.and(
513 new Boolean[] {
514 Boolean.FALSE,
515 Boolean.FALSE,
516 Boolean.FALSE })
517 .booleanValue(),
518 "True result for (false, false)");
519
520 assertTrue(
521 ! BooleanUtils.and(
522 new Boolean[] {
523 Boolean.TRUE,
524 Boolean.TRUE,
525 Boolean.FALSE })
526 .booleanValue(),
527 "True result for (true, true, false)");
528
529 assertTrue(
530 ! BooleanUtils.and(
531 new Boolean[] {
532 Boolean.TRUE,
533 Boolean.FALSE,
534 Boolean.TRUE })
535 .booleanValue(),
536 "True result for (true, false, true)");
537
538 assertTrue(
539 ! BooleanUtils.and(
540 new Boolean[] {
541 Boolean.FALSE,
542 Boolean.TRUE,
543 Boolean.TRUE })
544 .booleanValue(),
545 "True result for (false, true, true)");
546 }
547
548 @Test
549 public void testAnd_primitive_emptyInput() {
550 assertThrows(IllegalArgumentException.class, () -> BooleanUtils.and(new boolean[] {}));
551 }
552
553 @Test
554 public void testAnd_primitive_nullInput() {
555 assertThrows(NullPointerException.class, () -> BooleanUtils.and((boolean[]) null));
556 }
557
558 @Test
559 public void testAnd_primitive_validInput_2items() {
560 assertTrue(
561 BooleanUtils.and(new boolean[] { true, true }),
562 "False result for (true, true)");
563
564 assertTrue(
565 ! BooleanUtils.and(new boolean[] { false, false }),
566 "True result for (false, false)");
567
568 assertTrue(
569 ! BooleanUtils.and(new boolean[] { true, false }),
570 "True result for (true, false)");
571
572 assertTrue(
573 ! BooleanUtils.and(new boolean[] { false, true }),
574 "True result for (false, true)");
575 }
576
577 @Test
578 public void testAnd_primitive_validInput_3items() {
579 assertTrue(
580 ! BooleanUtils.and(new boolean[] { false, false, true }),
581 "True result for (false, false, true)");
582
583 assertTrue(
584 ! BooleanUtils.and(new boolean[] { false, true, false }),
585 "True result for (false, true, false)");
586
587 assertTrue(
588 ! BooleanUtils.and(new boolean[] { true, false, false }),
589 "True result for (true, false, false)");
590
591 assertTrue(
592 BooleanUtils.and(new boolean[] { true, true, true }),
593 "False result for (true, true, true)");
594
595 assertTrue(
596 ! BooleanUtils.and(new boolean[] { false, false, false }),
597 "True result for (false, false)");
598
599 assertTrue(
600 ! BooleanUtils.and(new boolean[] { true, true, false }),
601 "True result for (true, true, false)");
602
603 assertTrue(
604 ! BooleanUtils.and(new boolean[] { true, false, true }),
605 "True result for (true, false, true)");
606
607 assertTrue(
608 ! BooleanUtils.and(new boolean[] { false, true, true }),
609 "True result for (false, true, true)");
610 }
611
612 @Test
613 public void testCompare() {
614 assertTrue(BooleanUtils.compare(true, false) > 0);
615 assertEquals(0, BooleanUtils.compare(true, true));
616 assertEquals(0, BooleanUtils.compare(false, false));
617 assertTrue(BooleanUtils.compare(false, true) < 0);
618 }
619
620 @Test
621 public void testConstructor() {
622 assertNotNull(new BooleanUtils());
623 final Constructor<?>[] cons = BooleanUtils.class.getDeclaredConstructors();
624 assertEquals(1, cons.length);
625 assertTrue(Modifier.isPublic(cons[0].getModifiers()));
626 assertTrue(Modifier.isPublic(BooleanUtils.class.getModifiers()));
627 assertFalse(Modifier.isFinal(BooleanUtils.class.getModifiers()));
628 }
629
630 @Test
631 public void testOr_object_emptyInput() {
632 assertThrows(IllegalArgumentException.class, () -> BooleanUtils.or(new Boolean[] {}));
633 }
634
635 @Test
636 public void testOr_object_nullElementInput() {
637 assertThrows(IllegalArgumentException.class, () -> BooleanUtils.or(new Boolean[] {null}));
638 }
639
640 @Test
641 public void testOr_object_nullInput() {
642 assertThrows(NullPointerException.class, () -> BooleanUtils.or((Boolean[]) null));
643 }
644
645 @Test
646 public void testOr_object_validInput_2items() {
647 assertTrue(
648 BooleanUtils
649 .or(new Boolean[] { Boolean.TRUE, Boolean.TRUE })
650 .booleanValue(),
651 "False result for (true, true)");
652
653 assertTrue(
654 ! BooleanUtils
655 .or(new Boolean[] { Boolean.FALSE, Boolean.FALSE })
656 .booleanValue(),
657 "True result for (false, false)");
658
659 assertTrue(
660 BooleanUtils
661 .or(new Boolean[] { Boolean.TRUE, Boolean.FALSE })
662 .booleanValue(),
663 "False result for (true, false)");
664
665 assertTrue(
666 BooleanUtils
667 .or(new Boolean[] { Boolean.FALSE, Boolean.TRUE })
668 .booleanValue(),
669 "False result for (false, true)");
670 }
671
672 @Test
673 public void testOr_object_validInput_3items() {
674 assertTrue(
675 BooleanUtils
676 .or(
677 new Boolean[] {
678 Boolean.FALSE,
679 Boolean.FALSE,
680 Boolean.TRUE })
681 .booleanValue(),
682 "False result for (false, false, true)");
683
684 assertTrue(
685 BooleanUtils
686 .or(
687 new Boolean[] {
688 Boolean.FALSE,
689 Boolean.TRUE,
690 Boolean.FALSE })
691 .booleanValue(),
692 "False result for (false, true, false)");
693
694 assertTrue(
695 BooleanUtils
696 .or(
697 new Boolean[] {
698 Boolean.TRUE,
699 Boolean.FALSE,
700 Boolean.FALSE })
701 .booleanValue(),
702 "False result for (true, false, false)");
703
704 assertTrue(
705 BooleanUtils
706 .or(new Boolean[] { Boolean.TRUE, Boolean.TRUE, Boolean.TRUE })
707 .booleanValue(),
708 "False result for (true, true, true)");
709
710 assertTrue(
711 ! BooleanUtils.or(
712 new Boolean[] {
713 Boolean.FALSE,
714 Boolean.FALSE,
715 Boolean.FALSE })
716 .booleanValue(),
717 "True result for (false, false)");
718
719 assertTrue(
720 BooleanUtils.or(
721 new Boolean[] {
722 Boolean.TRUE,
723 Boolean.TRUE,
724 Boolean.FALSE })
725 .booleanValue(),
726 "False result for (true, true, false)");
727
728 assertTrue(
729 BooleanUtils.or(
730 new Boolean[] {
731 Boolean.TRUE,
732 Boolean.FALSE,
733 Boolean.TRUE })
734 .booleanValue(),
735 "False result for (true, false, true)");
736
737 assertTrue(
738 BooleanUtils.or(
739 new Boolean[] {
740 Boolean.FALSE,
741 Boolean.TRUE,
742 Boolean.TRUE })
743 .booleanValue(),
744 "False result for (false, true, true)");
745 }
746
747 @Test
748 public void testOr_primitive_emptyInput() {
749 assertThrows(IllegalArgumentException.class, () -> BooleanUtils.or(new boolean[] {}));
750 }
751
752 @Test
753 public void testOr_primitive_nullInput() {
754 assertThrows(NullPointerException.class, () -> BooleanUtils.or((boolean[]) null));
755 }
756
757 @Test
758 public void testOr_primitive_validInput_2items() {
759 assertTrue(
760 BooleanUtils.or(new boolean[] { true, true }),
761 "False result for (true, true)");
762
763 assertTrue(
764 ! BooleanUtils.or(new boolean[] { false, false }),
765 "True result for (false, false)");
766
767 assertTrue(
768 BooleanUtils.or(new boolean[] { true, false }),
769 "False result for (true, false)");
770
771 assertTrue(
772 BooleanUtils.or(new boolean[] { false, true }),
773 "False result for (false, true)");
774 }
775
776 @Test
777 public void testOr_primitive_validInput_3items() {
778 assertTrue(
779 BooleanUtils.or(new boolean[] { false, false, true }),
780 "False result for (false, false, true)");
781
782 assertTrue(
783 BooleanUtils.or(new boolean[] { false, true, false }),
784 "False result for (false, true, false)");
785
786 assertTrue(
787 BooleanUtils.or(new boolean[] { true, false, false }),
788 "False result for (true, false, false)");
789
790 assertTrue(
791 BooleanUtils.or(new boolean[] { true, true, true }),
792 "False result for (true, true, true)");
793
794 assertTrue(
795 ! BooleanUtils.or(new boolean[] { false, false, false }),
796 "True result for (false, false)");
797
798 assertTrue(
799 BooleanUtils.or(new boolean[] { true, true, false }),
800 "False result for (true, true, false)");
801
802 assertTrue(
803 BooleanUtils.or(new boolean[] { true, false, true }),
804 "False result for (true, false, true)");
805
806 assertTrue(
807 BooleanUtils.or(new boolean[] { false, true, true }),
808 "False result for (false, true, true)");
809
525810 }
526811
527812 @Test
534819 assertThrows(IllegalArgumentException.class, () -> BooleanUtils.xor(new Boolean[] {null}));
535820 }
536821
822 @Test
823 public void testXor_object_nullInput() {
824 assertThrows(NullPointerException.class, () -> BooleanUtils.xor((Boolean[]) null));
825 }
537826 @Test
538827 public void testXor_object_validInput_2items() {
539828 assertEquals(
643932 "true ^ true ^ true");
644933 }
645934
646 // testAnd
647 // -----------------------------------------------------------------------
648 @Test
649 public void testAnd_primitive_nullInput() {
650 assertThrows(IllegalArgumentException.class, () -> BooleanUtils.and((boolean[]) null));
651 }
652
653 @Test
654 public void testAnd_primitive_emptyInput() {
655 assertThrows(IllegalArgumentException.class, () -> BooleanUtils.and(new boolean[] {}));
656 }
657
658 @Test
659 public void testAnd_primitive_validInput_2items() {
660 assertTrue(
661 BooleanUtils.and(new boolean[] { true, true }),
662 "False result for (true, true)");
663
664 assertTrue(
665 ! BooleanUtils.and(new boolean[] { false, false }),
666 "True result for (false, false)");
667
668 assertTrue(
669 ! BooleanUtils.and(new boolean[] { true, false }),
670 "True result for (true, false)");
671
672 assertTrue(
673 ! BooleanUtils.and(new boolean[] { false, true }),
674 "True result for (false, true)");
675 }
676
677 @Test
678 public void testAnd_primitive_validInput_3items() {
679 assertTrue(
680 ! BooleanUtils.and(new boolean[] { false, false, true }),
681 "True result for (false, false, true)");
682
683 assertTrue(
684 ! BooleanUtils.and(new boolean[] { false, true, false }),
685 "True result for (false, true, false)");
686
687 assertTrue(
688 ! BooleanUtils.and(new boolean[] { true, false, false }),
689 "True result for (true, false, false)");
690
691 assertTrue(
692 BooleanUtils.and(new boolean[] { true, true, true }),
693 "False result for (true, true, true)");
694
695 assertTrue(
696 ! BooleanUtils.and(new boolean[] { false, false, false }),
697 "True result for (false, false)");
698
699 assertTrue(
700 ! BooleanUtils.and(new boolean[] { true, true, false }),
701 "True result for (true, true, false)");
702
703 assertTrue(
704 ! BooleanUtils.and(new boolean[] { true, false, true }),
705 "True result for (true, false, true)");
706
707 assertTrue(
708 ! BooleanUtils.and(new boolean[] { false, true, true }),
709 "True result for (false, true, true)");
710 }
711
712 @Test
713 public void testAnd_object_nullInput() {
714 assertThrows(IllegalArgumentException.class, () -> BooleanUtils.and((Boolean[]) null));
715 }
716
717 @Test
718 public void testAnd_object_emptyInput() {
719 assertThrows(IllegalArgumentException.class, () -> BooleanUtils.and(new Boolean[] {}));
720 }
721
722 @Test
723 public void testAnd_object_nullElementInput() {
724 assertThrows(IllegalArgumentException.class, () -> BooleanUtils.and(new Boolean[] {null}));
725 }
726
727 @Test
728 public void testAnd_object_validInput_2items() {
729 assertTrue(
730 BooleanUtils
731 .and(new Boolean[] { Boolean.TRUE, Boolean.TRUE })
732 .booleanValue(),
733 "False result for (true, true)");
734
735 assertTrue(
736 ! BooleanUtils
737 .and(new Boolean[] { Boolean.FALSE, Boolean.FALSE })
738 .booleanValue(),
739 "True result for (false, false)");
740
741 assertTrue(
742 ! BooleanUtils
743 .and(new Boolean[] { Boolean.TRUE, Boolean.FALSE })
744 .booleanValue(),
745 "True result for (true, false)");
746
747 assertTrue(
748 ! BooleanUtils
749 .and(new Boolean[] { Boolean.FALSE, Boolean.TRUE })
750 .booleanValue(),
751 "True result for (false, true)");
752 }
753
754 @Test
755 public void testAnd_object_validInput_3items() {
756 assertTrue(
757 ! BooleanUtils
758 .and(
759 new Boolean[] {
760 Boolean.FALSE,
761 Boolean.FALSE,
762 Boolean.TRUE })
763 .booleanValue(),
764 "True result for (false, false, true)");
765
766 assertTrue(
767 ! BooleanUtils
768 .and(
769 new Boolean[] {
770 Boolean.FALSE,
771 Boolean.TRUE,
772 Boolean.FALSE })
773 .booleanValue(),
774 "True result for (false, true, false)");
775
776 assertTrue(
777 ! BooleanUtils
778 .and(
779 new Boolean[] {
780 Boolean.TRUE,
781 Boolean.FALSE,
782 Boolean.FALSE })
783 .booleanValue(),
784 "True result for (true, false, false)");
785
786 assertTrue(
787 BooleanUtils
788 .and(new Boolean[] { Boolean.TRUE, Boolean.TRUE, Boolean.TRUE })
789 .booleanValue(),
790 "False result for (true, true, true)");
791
792 assertTrue(
793 ! BooleanUtils.and(
794 new Boolean[] {
795 Boolean.FALSE,
796 Boolean.FALSE,
797 Boolean.FALSE })
798 .booleanValue(),
799 "True result for (false, false)");
800
801 assertTrue(
802 ! BooleanUtils.and(
803 new Boolean[] {
804 Boolean.TRUE,
805 Boolean.TRUE,
806 Boolean.FALSE })
807 .booleanValue(),
808 "True result for (true, true, false)");
809
810 assertTrue(
811 ! BooleanUtils.and(
812 new Boolean[] {
813 Boolean.TRUE,
814 Boolean.FALSE,
815 Boolean.TRUE })
816 .booleanValue(),
817 "True result for (true, false, true)");
818
819 assertTrue(
820 ! BooleanUtils.and(
821 new Boolean[] {
822 Boolean.FALSE,
823 Boolean.TRUE,
824 Boolean.TRUE })
825 .booleanValue(),
826 "True result for (false, true, true)");
827 }
828
829 // testOr
830 // -----------------------------------------------------------------------
831 @Test
832 public void testOr_primitive_nullInput() {
833 assertThrows(IllegalArgumentException.class, () -> BooleanUtils.or((boolean[]) null));
834 }
835
836 @Test
837 public void testOr_primitive_emptyInput() {
838 assertThrows(IllegalArgumentException.class, () -> BooleanUtils.or(new boolean[] {}));
839 }
840
841 @Test
842 public void testOr_primitive_validInput_2items() {
843 assertTrue(
844 BooleanUtils.or(new boolean[] { true, true }),
845 "False result for (true, true)");
846
847 assertTrue(
848 ! BooleanUtils.or(new boolean[] { false, false }),
849 "True result for (false, false)");
850
851 assertTrue(
852 BooleanUtils.or(new boolean[] { true, false }),
853 "False result for (true, false)");
854
855 assertTrue(
856 BooleanUtils.or(new boolean[] { false, true }),
857 "False result for (false, true)");
858 }
859
860 @Test
861 public void testOr_primitive_validInput_3items() {
862 assertTrue(
863 BooleanUtils.or(new boolean[] { false, false, true }),
864 "False result for (false, false, true)");
865
866 assertTrue(
867 BooleanUtils.or(new boolean[] { false, true, false }),
868 "False result for (false, true, false)");
869
870 assertTrue(
871 BooleanUtils.or(new boolean[] { true, false, false }),
872 "False result for (true, false, false)");
873
874 assertTrue(
875 BooleanUtils.or(new boolean[] { true, true, true }),
876 "False result for (true, true, true)");
877
878 assertTrue(
879 ! BooleanUtils.or(new boolean[] { false, false, false }),
880 "True result for (false, false)");
881
882 assertTrue(
883 BooleanUtils.or(new boolean[] { true, true, false }),
884 "False result for (true, true, false)");
885
886 assertTrue(
887 BooleanUtils.or(new boolean[] { true, false, true }),
888 "False result for (true, false, true)");
889
890 assertTrue(
891 BooleanUtils.or(new boolean[] { false, true, true }),
892 "False result for (false, true, true)");
893
894 }
895 @Test
896 public void testOr_object_nullInput() {
897 assertThrows(IllegalArgumentException.class, () -> BooleanUtils.or((Boolean[]) null));
898 }
899
900 @Test
901 public void testOr_object_emptyInput() {
902 assertThrows(IllegalArgumentException.class, () -> BooleanUtils.or(new Boolean[] {}));
903 }
904
905 @Test
906 public void testOr_object_nullElementInput() {
907 assertThrows(IllegalArgumentException.class, () -> BooleanUtils.or(new Boolean[] {null}));
908 }
909
910 @Test
911 public void testOr_object_validInput_2items() {
912 assertTrue(
913 BooleanUtils
914 .or(new Boolean[] { Boolean.TRUE, Boolean.TRUE })
915 .booleanValue(),
916 "False result for (true, true)");
917
918 assertTrue(
919 ! BooleanUtils
920 .or(new Boolean[] { Boolean.FALSE, Boolean.FALSE })
921 .booleanValue(),
922 "True result for (false, false)");
923
924 assertTrue(
925 BooleanUtils
926 .or(new Boolean[] { Boolean.TRUE, Boolean.FALSE })
927 .booleanValue(),
928 "False result for (true, false)");
929
930 assertTrue(
931 BooleanUtils
932 .or(new Boolean[] { Boolean.FALSE, Boolean.TRUE })
933 .booleanValue(),
934 "False result for (false, true)");
935 }
936
937 @Test
938 public void testOr_object_validInput_3items() {
939 assertTrue(
940 BooleanUtils
941 .or(
942 new Boolean[] {
943 Boolean.FALSE,
944 Boolean.FALSE,
945 Boolean.TRUE })
946 .booleanValue(),
947 "False result for (false, false, true)");
948
949 assertTrue(
950 BooleanUtils
951 .or(
952 new Boolean[] {
953 Boolean.FALSE,
954 Boolean.TRUE,
955 Boolean.FALSE })
956 .booleanValue(),
957 "False result for (false, true, false)");
958
959 assertTrue(
960 BooleanUtils
961 .or(
962 new Boolean[] {
963 Boolean.TRUE,
964 Boolean.FALSE,
965 Boolean.FALSE })
966 .booleanValue(),
967 "False result for (true, false, false)");
968
969 assertTrue(
970 BooleanUtils
971 .or(new Boolean[] { Boolean.TRUE, Boolean.TRUE, Boolean.TRUE })
972 .booleanValue(),
973 "False result for (true, true, true)");
974
975 assertTrue(
976 ! BooleanUtils.or(
977 new Boolean[] {
978 Boolean.FALSE,
979 Boolean.FALSE,
980 Boolean.FALSE })
981 .booleanValue(),
982 "True result for (false, false)");
983
984 assertTrue(
985 BooleanUtils.or(
986 new Boolean[] {
987 Boolean.TRUE,
988 Boolean.TRUE,
989 Boolean.FALSE })
990 .booleanValue(),
991 "False result for (true, true, false)");
992
993 assertTrue(
994 BooleanUtils.or(
995 new Boolean[] {
996 Boolean.TRUE,
997 Boolean.FALSE,
998 Boolean.TRUE })
999 .booleanValue(),
1000 "False result for (true, false, true)");
1001
1002 assertTrue(
1003 BooleanUtils.or(
1004 new Boolean[] {
1005 Boolean.FALSE,
1006 Boolean.TRUE,
1007 Boolean.TRUE })
1008 .booleanValue(),
1009 "False result for (false, true, true)");
1010 }
1011
1012 @Test
1013 public void testCompare() {
1014 assertTrue(BooleanUtils.compare(true, false) > 0);
1015 assertEquals(0, BooleanUtils.compare(true, true));
1016 assertEquals(0, BooleanUtils.compare(false, false));
1017 assertTrue(BooleanUtils.compare(false, true) < 0);
935 @Test
936 public void testXor_primitive_emptyInput() {
937 assertThrows(IllegalArgumentException.class, () -> BooleanUtils.xor(new boolean[] {}));
938 }
939
940 @Test
941 public void testXor_primitive_nullInput() {
942 assertThrows(NullPointerException.class, () -> BooleanUtils.xor((boolean[]) null));
943 }
944
945 @Test
946 public void testXor_primitive_validInput_2items() {
947 assertEquals(
948 true ^ true,
949 BooleanUtils.xor(new boolean[] { true, true }),
950 "true ^ true");
951
952 assertEquals(
953 false ^ false,
954 BooleanUtils.xor(new boolean[] { false, false }),
955 "false ^ false");
956
957 assertEquals(
958 true ^ false,
959 BooleanUtils.xor(new boolean[] { true, false }),
960 "true ^ false");
961
962 assertEquals(
963 false ^ true,
964 BooleanUtils.xor(new boolean[] { false, true }),
965 "false ^ true");
966 }
967
968 @Test
969 public void testXor_primitive_validInput_3items() {
970 assertEquals(
971 false ^ false ^ false,
972 BooleanUtils.xor(new boolean[] { false, false, false }),
973 "false ^ false ^ false");
974
975 assertEquals(
976 false ^ false ^ true,
977 BooleanUtils.xor(new boolean[] { false, false, true }),
978 "false ^ false ^ true");
979
980 assertEquals(
981 false ^ true ^ false,
982 BooleanUtils.xor(new boolean[] { false, true, false }),
983 "false ^ true ^ false");
984
985 assertEquals(
986 false ^ true ^ true,
987 BooleanUtils.xor(new boolean[] { false, true, true }),
988 "false ^ true ^ true");
989
990 assertEquals(
991 true ^ false ^ false,
992 BooleanUtils.xor(new boolean[] { true, false, false }),
993 "true ^ false ^ false");
994
995 assertEquals(
996 true ^ false ^ true,
997 BooleanUtils.xor(new boolean[] { true, false, true }),
998 "true ^ false ^ true");
999
1000 assertEquals(
1001 true ^ true ^ false,
1002 BooleanUtils.xor(new boolean[] { true, true, false }),
1003 "true ^ true ^ false");
1004
1005 assertEquals(
1006 true ^ true ^ true,
1007 BooleanUtils.xor(new boolean[] { true, true, true }),
1008 "true ^ true ^ true");
10181009 }
10191010
10201011 }
3535 */
3636 public class CharRangeTest {
3737
38 //-----------------------------------------------------------------------
3938 @Test
4039 public void testClass() {
4140 // class changed to non-public in 3.0
4342 assertTrue(Modifier.isFinal(CharRange.class.getModifiers()));
4443 }
4544
46 //-----------------------------------------------------------------------
4745 @Test
4846 public void testConstructorAccessors_is() {
4947 final CharRange rangea = CharRange.is('a');
116114 assertEquals("^a-e", rangea.toString());
117115 }
118116
119 //-----------------------------------------------------------------------
120117 @Test
121118 public void testEquals_Object() {
122119 final CharRange rangea = CharRange.is('a');
161158 assertNotEquals(rangenotbf.hashCode(), rangeae.hashCode());
162159 }
163160
164 //-----------------------------------------------------------------------
165161 @Test
166162 public void testContains_Char() {
167163 CharRange range = CharRange.is('c');
191187 assertTrue(range.contains(Character.MAX_VALUE));
192188 }
193189
194 //-----------------------------------------------------------------------
195190 @Test
196191 public void testContains_Charrange() {
197192 final CharRange a = CharRange.is('a');
311306 public void testContainsNullArg() {
312307 final CharRange range = CharRange.is('a');
313308 final NullPointerException e = assertThrows(NullPointerException.class, () -> range.contains(null));
314 assertEquals("The Range must not be null", e.getMessage());
309 assertEquals("range", e.getMessage());
315310 }
316311
317312 @Test
366361 assertThrows(NoSuchElementException.class, notLastIt::next);
367362 }
368363
369 //-----------------------------------------------------------------------
370364 @Test
371365 public void testSerialization() {
372366 CharRange range = CharRange.is('a');
377371 assertEquals(range, SerializationUtils.clone(range));
378372 }
379373
380 //-----------------------------------------------------------------------
381374 @Test
382375 public void testIteratorRemove() {
383376 final CharRange a = CharRange.is('a');
2222 import static org.junit.jupiter.api.Assertions.assertNull;
2323 import static org.junit.jupiter.api.Assertions.assertThrows;
2424 import static org.junit.jupiter.api.Assertions.assertTrue;
25 import static org.junit.jupiter.params.provider.Arguments.arguments;
2526
2627 import java.lang.reflect.Constructor;
2728 import java.lang.reflect.Modifier;
2829 import java.util.Random;
2930 import java.util.stream.IntStream;
31 import java.util.stream.Stream;
3032
3133 import org.junit.jupiter.api.Test;
34 import org.junit.jupiter.params.ParameterizedTest;
35 import org.junit.jupiter.params.provider.Arguments;
36 import org.junit.jupiter.params.provider.MethodSource;
3237
3338 /**
3439 * Tests CharSequenceUtils
3540 */
3641 public class CharSequenceUtilsTest {
3742
38 //-----------------------------------------------------------------------
3943 @Test
4044 public void testConstructor() {
4145 assertNotNull(new CharSequenceUtils());
4650 assertFalse(Modifier.isFinal(CharSequenceUtils.class.getModifiers()));
4751 }
4852
49 //-----------------------------------------------------------------------
5053 @Test
5154 public void testSubSequence() {
5255 //
260263 }
261264 }
262265
266 @ParameterizedTest
267 @MethodSource("lastIndexWithStandardCharSequence")
268 public void testLastIndexOfWithDifferentCharSequences(final CharSequence cs, final CharSequence search, final int start,
269 final int expected) {
270 assertEquals(expected, CharSequenceUtils.lastIndexOf(cs, search, start));
271 }
272
273 static Stream<Arguments> lastIndexWithStandardCharSequence() {
274 return Stream.of(
275 arguments("abc", "b", 2, 1),
276 arguments(new StringBuilder("abc"), "b", 2, 1),
277 arguments(new StringBuffer("abc"), "b", 2, 1),
278 arguments("abc", new StringBuilder("b"), 2, 1),
279 arguments(new StringBuilder("abc"), new StringBuilder("b"), 2, 1),
280 arguments(new StringBuffer("abc"), new StringBuffer("b"), 2, 1),
281 arguments(new StringBuilder("abc"), new StringBuffer("b"), 2, 1)
282 );
283 }
284
263285 private void testNewLastIndexOfSingle(final CharSequence a, final CharSequence b) {
264286 final int maxa = Math.max(a.length(), b.length());
265287 for (int i = -maxa - 10; i <= maxa + 10; i++) {
3333 */
3434 public class CharSetTest {
3535
36 //-----------------------------------------------------------------------
3736 @Test
3837 public void testClass() {
3938 assertTrue(Modifier.isPublic(CharSet.class.getModifiers()));
4039 assertFalse(Modifier.isFinal(CharSet.class.getModifiers()));
4140 }
4241
43 //-----------------------------------------------------------------------
4442 @Test
4543 public void testGetInstance() {
4644 assertSame(CharSet.EMPTY, CharSet.getInstance( (String) null));
5250 assertSame(CharSet.ASCII_NUMERIC, CharSet.getInstance("0-9"));
5351 }
5452
55 //-----------------------------------------------------------------------
5653 @Test
5754 public void testGetInstance_Stringarray() {
5855 assertNull(CharSet.getInstance((String[]) null));
6158 assertEquals("[a-e]", CharSet.getInstance(new String[] {"a-e"}).toString());
6259 }
6360
64 //-----------------------------------------------------------------------
6561 @Test
6662 public void testConstructor_String_simple() {
6763 CharSet set;
293289 @Test
294290 public void testConstructor_String_oddCombinations() {
295291 CharSet set;
296 CharRange[] array = null;
292 CharRange[] array;
297293
298294 set = CharSet.getInstance("a-^c");
299295 array = set.getCharRanges();
339335 assertFalse(set.contains('c'));
340336 }
341337
342 //-----------------------------------------------------------------------
343338 @Test
344339 public void testEquals_Object() {
345340 final CharSet abc = CharSet.getInstance("abc");
384379 assertEquals(notatoc.hashCode(), notatoc2.hashCode());
385380 }
386381
387 //-----------------------------------------------------------------------
388382 @Test
389383 public void testContains_Char() {
390384 final CharSet btod = CharSet.getInstance("b-d");
428422 assertEquals(1, array.length);
429423 }
430424
431 //-----------------------------------------------------------------------
432425 @Test
433426 public void testSerialization() {
434427 CharSet set = CharSet.getInstance("a");
439432 assertEquals(set, SerializationUtils.clone(set));
440433 }
441434
442 //-----------------------------------------------------------------------
443435 @Test
444436 public void testStatics() {
445437 CharRange[] array;
3131 */
3232 public class CharSetUtilsTest {
3333
34 //-----------------------------------------------------------------------
3534 @Test
3635 public void testConstructor() {
3736 assertNotNull(new CharSetUtils());
4241 assertFalse(Modifier.isFinal(CharSetUtils.class.getModifiers()));
4342 }
4443
45 //-----------------------------------------------------------------------
4644 @Test
4745 public void testSqueeze_StringString() {
4846 assertNull(CharSetUtils.squeeze(null, (String) null));
8381 assertEquals("fof", CharSetUtils.squeeze("fooooff", "fo"));
8482 }
8583
86 //-----------------------------------------------------------------------
8784 @Test
8885 public void testContainsAny_StringString() {
8986 assertFalse(CharSetUtils.containsAny(null, (String) null));
123120 assertFalse(CharSetUtils.containsAny("hello", ""));
124121 }
125122
126 //-----------------------------------------------------------------------
127123 @Test
128124 public void testCount_StringString() {
129125 assertEquals(0, CharSetUtils.count(null, (String) null));
163159 assertEquals(0, CharSetUtils.count("hello", ""));
164160 }
165161
166 //-----------------------------------------------------------------------
167162 @Test
168163 public void testKeep_StringString() {
169164 assertNull(CharSetUtils.keep(null, (String) null));
206201 assertEquals("ll", CharSetUtils.keep("hello", "l"));
207202 }
208203
209 //-----------------------------------------------------------------------
210204 @Test
211205 public void testDelete_StringString() {
212206 assertNull(CharSetUtils.delete(null, (String) null));
9898
9999 private void run() {
100100 this.printSysInfo();
101 long start;
102 start = System.currentTimeMillis();
103 this.printlnTotal("Do nothing", start);
101 long startMillis;
102 startMillis = System.currentTimeMillis();
103 this.printlnTotal("Do nothing", startMillis);
104104 run_CharUtils_isAsciiNumeric(WARM_UP);
105 start = System.currentTimeMillis();
105 startMillis = System.currentTimeMillis();
106106 run_CharUtils_isAsciiNumeric(COUNT);
107 this.printlnTotal("run_CharUtils_isAsciiNumeric", start);
107 this.printlnTotal("run_CharUtils_isAsciiNumeric", startMillis);
108108 run_inlined_CharUtils_isAsciiNumeric(WARM_UP);
109 start = System.currentTimeMillis();
109 startMillis = System.currentTimeMillis();
110110 run_inlined_CharUtils_isAsciiNumeric(COUNT);
111 this.printlnTotal("run_inlined_CharUtils_isAsciiNumeric", start);
111 this.printlnTotal("run_inlined_CharUtils_isAsciiNumeric", startMillis);
112112 run_CharSet(WARM_UP);
113 start = System.currentTimeMillis();
113 startMillis = System.currentTimeMillis();
114114 run_CharSet(COUNT);
115 this.printlnTotal("run_CharSet", start);
115 this.printlnTotal("run_CharSet", startMillis);
116116 }
117117
118118 private int run_CharSet(final int loopCount) {
148148 return t;
149149 }
150150
151 private void printlnTotal(final String prefix, final long start) {
152 final long total = System.currentTimeMillis() - start;
153 System.out.println(prefix + ": " + NumberFormat.getInstance().format(total) + " milliseconds.");
151 private void printlnTotal(final String prefix, final long startMillis) {
152 final long totalMillis = System.currentTimeMillis() - startMillis;
153 System.out.println(prefix + ": " + NumberFormat.getInstance().format(totalMillis) + " milliseconds.");
154154 }
155155 }
3535 import java.util.List;
3636 import java.util.Map;
3737 import java.util.Set;
38 import java.util.TreeMap;
3839
3940 import org.apache.commons.lang3.ClassUtils.Interfaces;
4041 import org.apache.commons.lang3.reflect.testbed.GenericConsumer;
130131 assertNull(ClassUtils.convertClassesToClassNames(null));
131132 }
132133
133 // -------------------------------------------------------------------------
134134 @Test
135135 public void test_convertClassNamesToClasses_List() {
136136 final List<String> list = new ArrayList<>();
155155 assertNull(ClassUtils.convertClassNamesToClasses(null));
156156 }
157157
158 // -------------------------------------------------------------------------
159158 @Test
160159 public void test_getAbbreviatedName_Class() {
161160 assertEquals("", ClassUtils.getAbbreviatedName((Class<?>) null, 1));
165164 assertEquals("j.lang.String", ClassUtils.getAbbreviatedName(String.class, 13));
166165 assertEquals("j.lang.String", ClassUtils.getAbbreviatedName(String.class, 15));
167166 assertEquals("java.lang.String", ClassUtils.getAbbreviatedName(String.class, 20));
168 }
169
170 /**
171 * Test that in case the required length is larger than the name and thus there is no need for any shortening
172 * then the returned string object is the same as the one passed as argument. Note, however, that this is
173 * tested as an internal implementation detail, but it is not a guaranteed feature of the implementation.
174 */
175 @Test
176 @DisplayName("When the length hint is longer than the actual length then the same String object is returned")
177 public void test_getAbbreviatedName_TooLongHint(){
178 final String className = "java.lang.String";
179 Assertions.assertSame(className, ClassUtils.getAbbreviatedName(className, className.length()+1));
180 Assertions.assertSame(className, ClassUtils.getAbbreviatedName(className, className.length()));
181167 }
182168
183169 @Test
216202 assertEquals("j.l.String", ClassUtils.getAbbreviatedName("java.lang.String", "j.l.String".length() - 1));
217203 }
218204
205 /**
206 * Test that in case the required length is larger than the name and thus there is no need for any shortening
207 * then the returned string object is the same as the one passed as argument. Note, however, that this is
208 * tested as an internal implementation detail, but it is not a guaranteed feature of the implementation.
209 */
210 @Test
211 @DisplayName("When the length hint is longer than the actual length then the same String object is returned")
212 public void test_getAbbreviatedName_TooLongHint(){
213 final String className = "java.lang.String";
214 Assertions.assertSame(className, ClassUtils.getAbbreviatedName(className, className.length()+1));
215 Assertions.assertSame(className, ClassUtils.getAbbreviatedName(className, className.length()));
216 }
217
219218 @Test
220219 public void test_getAllInterfaces_Class() {
221220 final List<?> list = ClassUtils.getAllInterfaces(CY.class);
230229 assertNull(ClassUtils.getAllInterfaces(null));
231230 }
232231
233 // -------------------------------------------------------------------------
234232 @Test
235233 public void test_getAllSuperclasses_Class() {
236234 final List<?> list = ClassUtils.getAllSuperclasses(CY.class);
490488 assertEquals("org.apache.commons.lang3", ClassUtils.getPackageName(Named.class));
491489 }
492490
493 // -------------------------------------------------------------------------
494491 @Test
495492 public void test_getPackageName_Object() {
496493 assertEquals("org.apache.commons.lang3", ClassUtils.getPackageName(new ClassUtils(), "<null>"));
630627 assertEquals("ClassUtilsTest.Inner", ClassUtils.getShortClassName(Inner.class));
631628 }
632629
633 // -------------------------------------------------------------------------
634630 @Test
635631 public void test_getShortClassName_Object() {
636632 assertEquals("ClassUtils", ClassUtils.getShortClassName(new ClassUtils(), "<null>"));
772768 assertTrue(ClassUtils.isAssignable(Boolean.class, Boolean.class, true));
773769 }
774770
775 // -------------------------------------------------------------------------
776771 @Test
777772 public void test_isAssignable_ClassArray_ClassArray() {
778773 final Class<?>[] array2 = new Class[] {Object.class, Object.class};
11301125 assertTrue(ClassUtils.isAssignable(Boolean.TYPE, Boolean.TYPE), "boolean -> boolean");
11311126 }
11321127
1133 // -------------------------------------------------------------------------
11341128 @Test
11351129 public void test_isInnerClass_Class() {
11361130 assertTrue(ClassUtils.isInnerClass(Inner.class));
11431137 assertFalse(ClassUtils.isInnerClass(null));
11441138 }
11451139
1146 //-----------------------------------------------------------------------
1140 @Test
1141 public void testComparable() {
1142 final TreeMap<Class<?>, String> map = new TreeMap<>(ClassUtils.comparator());
1143 map.put(String.class, "lastEntry");
1144 map.toString();
1145 map.put(Character.class, "firstEntry");
1146 map.toString();
1147 assertEquals("firstEntry", map.firstEntry().getValue());
1148 assertEquals(Character.class, map.firstEntry().getKey());
1149 //
1150 assertEquals("lastEntry", map.lastEntry().getValue());
1151 assertEquals(String.class, map.lastEntry().getKey());
1152 //
1153 map.put(null, "null");
1154 map.toString();
1155 assertEquals("null", map.get(null));
1156 }
1157
11471158 @Test
11481159 public void testConstructor() {
11491160 assertNotNull(new ClassUtils());
12421253 }
12431254
12441255 @Test
1256 public void testGetComponentType() {
1257 final CX[] newArray = {};
1258 @SuppressWarnings("unchecked")
1259 final Class<CX[]> classCxArray = (Class<CX[]>) newArray.getClass();
1260 // No type-cast required.
1261 final Class<CX> componentType = ClassUtils.getComponentType(classCxArray);
1262 assertEquals(CX.class, componentType);
1263 assertNull(ClassUtils.getComponentType(null));
1264 }
1265
1266 @Test
12451267 public void testGetInnerClass() throws ClassNotFoundException {
12461268 assertEquals( Inner.DeeplyNested.class, ClassUtils.getClass( "org.apache.commons.lang3.ClassUtilsTest.Inner.DeeplyNested" ) );
12471269 assertEquals( Inner.DeeplyNested.class, ClassUtils.getClass( "org.apache.commons.lang3.ClassUtilsTest.Inner$DeeplyNested" ) );
226226 */
227227 @Test
228228 public void testBinaryToHexDigit_2args() {
229 final boolean[] shortArray = new boolean[]{false, true, true};
229 final boolean[] shortArray = {false, true, true};
230230 assertEquals('6', Conversion.binaryToHexDigit(shortArray, 0));
231231 assertEquals('3', Conversion.binaryToHexDigit(shortArray, 1));
232232 assertEquals('1', Conversion.binaryToHexDigit(shortArray, 2));
233 final boolean[] longArray = new boolean[]{true, false, true, false, false, true, true};
233 final boolean[] longArray = {true, false, true, false, false, true, true};
234234 assertEquals('5', Conversion.binaryToHexDigit(longArray, 0));
235235 assertEquals('2', Conversion.binaryToHexDigit(longArray, 1));
236236 assertEquals('9', Conversion.binaryToHexDigit(longArray, 2));
294294 // assertEquals('6', Conversion.BinaryToHexDigitMsb0(shortArray, 0));
295295 // assertEquals('3', Conversion.BinaryToHexDigitMsb0(shortArray, 1));
296296 // assertEquals('1', Conversion.BinaryToHexDigitMsb0(shortArray, 2));
297 final boolean[] shortArray = new boolean[]{true, true, false, true};
297 final boolean[] shortArray = {true, true, false, true};
298298 assertEquals('d', Conversion.binaryToHexDigitMsb0_4bits(shortArray, 0));
299 final boolean[] longArray = new boolean[]{true, false, true, false, false, true, true};
299 final boolean[] longArray = {true, false, true, false, false, true, true};
300300 assertEquals('a', Conversion.binaryToHexDigitMsb0_4bits(longArray, 0));
301301 assertEquals('4', Conversion.binaryToHexDigitMsb0_4bits(longArray, 1));
302302 assertEquals('9', Conversion.binaryToHexDigitMsb0_4bits(longArray, 2));
304304 // assertEquals('6', Conversion.BinaryToHexDigitMsb0(longArray, 4));
305305 // assertEquals('3', Conversion.BinaryToHexDigitMsb0(longArray, 5));
306306 // assertEquals('1', Conversion.BinaryToHexDigitMsb0(longArray, 6));
307 final boolean[] maxLengthArray = new boolean[]{
307 final boolean[] maxLengthArray = {
308308 true, false, true, false, false, true, true, true};
309309 assertEquals('a', Conversion.binaryToHexDigitMsb0_4bits(maxLengthArray, 0));
310310 assertEquals('4', Conversion.binaryToHexDigitMsb0_4bits(maxLengthArray, 1));
314314 // assertEquals('7', Conversion.BinaryToHexDigitMsb0(longArray, 5));
315315 // assertEquals('3', Conversion.BinaryToHexDigitMsb0(longArray, 6));
316316 // assertEquals('1', Conversion.BinaryToHexDigitMsb0(longArray, 7));
317 final boolean[] javaDocCheck = new boolean[]{
317 final boolean[] javaDocCheck = {
318318 true, false, false, true, true, false, true, false};
319319 assertEquals('d', Conversion.binaryToHexDigitMsb0_4bits(javaDocCheck, 3));
320320
376376 true, false, false, false, false, false, false, false, false, false, false,
377377 true, false, true, false, false}, 2));
378378
379 final boolean[] shortArray = new boolean[]{true, true, false};
379 final boolean[] shortArray = {true, true, false};
380380 assertEquals('6', Conversion.binaryBeMsb0ToHexDigit(shortArray, 0));
381381 assertEquals('3', Conversion.binaryBeMsb0ToHexDigit(shortArray, 1));
382382 assertEquals('1', Conversion.binaryBeMsb0ToHexDigit(shortArray, 2));
383 final boolean[] shortArray2 = new boolean[]{true, true, true, false, false, true, false, true};
383 final boolean[] shortArray2 = {true, true, true, false, false, true, false, true};
384384 assertEquals('5', Conversion.binaryBeMsb0ToHexDigit(shortArray2, 0));
385385 assertEquals('2', Conversion.binaryBeMsb0ToHexDigit(shortArray2, 1));
386386 assertEquals('9', Conversion.binaryBeMsb0ToHexDigit(shortArray2, 2));
389389 assertEquals('7', Conversion.binaryBeMsb0ToHexDigit(shortArray2, 5));
390390 assertEquals('3', Conversion.binaryBeMsb0ToHexDigit(shortArray2, 6));
391391 assertEquals('1', Conversion.binaryBeMsb0ToHexDigit(shortArray2, 7));
392 final boolean[] multiBytesArray = new boolean[]{
392 final boolean[] multiBytesArray = {
393393 true, true, false, false, true, false, true, false, true, true, true, false, false,
394394 true, false, true};
395395 assertEquals('5', Conversion.binaryBeMsb0ToHexDigit(multiBytesArray, 0));
478478 */
479479 @Test
480480 public void testIntArrayToLong() {
481 final int[] src = new int[]{0xCDF1F0C1, 0x0F123456, 0x78000000};
481 final int[] src = {0xCDF1F0C1, 0x0F123456, 0x78000000};
482482 assertEquals(0x0000000000000000L, Conversion.intArrayToLong(src, 0, 0L, 0, 0));
483483 assertEquals(0x0000000000000000L, Conversion.intArrayToLong(src, 1, 0L, 0, 0));
484484 assertEquals(0x00000000CDF1F0C1L, Conversion.intArrayToLong(src, 0, 0L, 0, 1));
496496 */
497497 @Test
498498 public void testShortArrayToLong() {
499 final short[] src = new short[]{
499 final short[] src = {
500500 (short) 0xCDF1, (short) 0xF0C1, (short) 0x0F12, (short) 0x3456, (short) 0x7800};
501501 assertEquals(0x0000000000000000L, Conversion.shortArrayToLong(src, 0, 0L, 0, 0));
502502 assertEquals(0x000000000000CDF1L, Conversion.shortArrayToLong(src, 0, 0L, 0, 1));
517517 */
518518 @Test
519519 public void testByteArrayToLong() {
520 final byte[] src = new byte[]{
520 final byte[] src = {
521521 (byte) 0xCD, (byte) 0xF1, (byte) 0xF0, (byte) 0xC1, (byte) 0x0F, (byte) 0x12, (byte) 0x34,
522522 (byte) 0x56, (byte) 0x78};
523523 assertEquals(0x0000000000000000L, Conversion.byteArrayToLong(src, 0, 0L, 0, 0));
537537 */
538538 @Test
539539 public void testShortArrayToInt() {
540 final short[] src = new short[]{
540 final short[] src = {
541541 (short) 0xCDF1, (short) 0xF0C1, (short) 0x0F12, (short) 0x3456, (short) 0x7800};
542542 assertEquals(0x00000000, Conversion.shortArrayToInt(src, 0, 0, 0, 0));
543543 assertEquals(0x0000CDF1, Conversion.shortArrayToInt(src, 0, 0, 0, 1));
553553 */
554554 @Test
555555 public void testByteArrayToInt() {
556 final byte[] src = new byte[]{
556 final byte[] src = {
557557 (byte) 0xCD, (byte) 0xF1, (byte) 0xF0, (byte) 0xC1, (byte) 0x0F, (byte) 0x12, (byte) 0x34,
558558 (byte) 0x56, (byte) 0x78};
559559 assertEquals(0x00000000, Conversion.byteArrayToInt(src, 0, 0, 0, 0));
570570 */
571571 @Test
572572 public void testByteArrayToShort() {
573 final byte[] src = new byte[]{
573 final byte[] src = {
574574 (byte) 0xCD, (byte) 0xF1, (byte) 0xF0, (byte) 0xC1, (byte) 0x0F, (byte) 0x12, (byte) 0x34,
575575 (byte) 0x56, (byte) 0x78};
576576 assertEquals((short) 0x0000, Conversion.byteArrayToShort(src, 0, (short) 0, 0, 0));
646646 */
647647 @Test
648648 public void testBinaryToLong() {
649 final boolean[] src = new boolean[]{
649 final boolean[] src = {
650650 false, false, true, true, true, false, true, true, true, true, true, true, true,
651651 false, false, false, true, true, true, true, false, false, false, false, false,
652652 false, true, true, true, false, false, false, false, false, false, false, true,
670670 */
671671 @Test
672672 public void testBinaryToInt() {
673 final boolean[] src = new boolean[]{
673 final boolean[] src = {
674674 false, false, true, true, true, false, true, true, true, true, true, true, true,
675675 false, false, false, true, true, true, true, false, false, false, false, false,
676676 false, true, true, true, false, false, false, false, false, false, false, true,
691691 */
692692 @Test
693693 public void testBinaryToShort() {
694 final boolean[] src = new boolean[]{
694 final boolean[] src = {
695695 false, false, true, true, true, false, true, true, true, true, true, true, true,
696696 false, false, false, true, true, true, true, false, false, false, false, false,
697697 false, true, true, true, false, false, false, false, false, false, false, true,
714714 */
715715 @Test
716716 public void testBinaryToByte() {
717 final boolean[] src = new boolean[]{
717 final boolean[] src = {
718718 false, false, true, true, true, false, true, true, true, true, true, true, true,
719719 false, false, false, true, true, true, true, false, false, false, false, false,
720720 false, true, true, true, false, false, false, false, false, false, false, true,
2828 import java.util.EnumSet;
2929 import java.util.List;
3030 import java.util.Map;
31 import java.util.function.Function;
3132
3233 import org.junit.jupiter.api.Assertions;
3334 import org.junit.jupiter.api.Test;
35
36 enum Enum64 {
37 A00, A01, A02, A03, A04, A05, A06, A07, A08, A09, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19, A20, A21, A22,
38 A23, A24, A25, A26, A27, A28, A29, A30, A31, A32, A33, A34, A35, A36, A37, A38, A39, A40, A41, A42, A43, A44, A45,
39 A46, A47, A48, A49, A50, A51, A52, A53, A54, A55, A56, A57, A58, A59, A60, A61, A62, A63
40 }
3441
3542 /**
3643 *
3744 */
3845 public class EnumUtilsTest {
3946
40 @Test
41 public void testConstructable() {
42 // enforce public constructor
43 new EnumUtils();
47 private void assertArrayEquals(final long[] actual, final long... expected) {
48 Assertions.assertArrayEquals(expected, actual);
49 }
50
51 @Test
52 public void test_generateBitVector() {
53 assertEquals(0L, EnumUtils.generateBitVector(Traffic.class, EnumSet.noneOf(Traffic.class)));
54 assertEquals(1L, EnumUtils.generateBitVector(Traffic.class, EnumSet.of(Traffic.RED)));
55 assertEquals(2L, EnumUtils.generateBitVector(Traffic.class, EnumSet.of(Traffic.AMBER)));
56 assertEquals(4L, EnumUtils.generateBitVector(Traffic.class, EnumSet.of(Traffic.GREEN)));
57 assertEquals(3L, EnumUtils.generateBitVector(Traffic.class, EnumSet.of(Traffic.RED, Traffic.AMBER)));
58 assertEquals(5L, EnumUtils.generateBitVector(Traffic.class, EnumSet.of(Traffic.RED, Traffic.GREEN)));
59 assertEquals(6L, EnumUtils.generateBitVector(Traffic.class, EnumSet.of(Traffic.AMBER, Traffic.GREEN)));
60 assertEquals(7L,
61 EnumUtils.generateBitVector(Traffic.class, EnumSet.of(Traffic.RED, Traffic.AMBER, Traffic.GREEN)));
62
63 // 64 values Enum (to test whether no int<->long jdk conversion issue exists)
64 assertEquals((1L << 31), EnumUtils.generateBitVector(Enum64.class, EnumSet.of(Enum64.A31)));
65 assertEquals((1L << 32), EnumUtils.generateBitVector(Enum64.class, EnumSet.of(Enum64.A32)));
66 assertEquals((1L << 63), EnumUtils.generateBitVector(Enum64.class, EnumSet.of(Enum64.A63)));
67 assertEquals(Long.MIN_VALUE, EnumUtils.generateBitVector(Enum64.class, EnumSet.of(Enum64.A63)));
68 }
69
70 @Test
71 public void test_generateBitVector_longClass() {
72 assertThrows(IllegalArgumentException.class,
73 () -> EnumUtils.generateBitVector(TooMany.class, EnumSet.of(TooMany.A1)));
74 }
75
76 @Test
77 public void test_generateBitVector_longClassWithArray() {
78 assertThrows(IllegalArgumentException.class, () -> EnumUtils.generateBitVector(TooMany.class, TooMany.A1));
79 }
80
81 @SuppressWarnings("unchecked")
82 @Test
83 public void test_generateBitVector_nonEnumClass() {
84 @SuppressWarnings("rawtypes")
85 final Class rawType = Object.class;
86 @SuppressWarnings("rawtypes")
87 final List rawList = new ArrayList();
88 assertThrows(IllegalArgumentException.class, () -> EnumUtils.generateBitVector(rawType, rawList));
89 }
90
91 @SuppressWarnings("unchecked")
92 @Test
93 public void test_generateBitVector_nonEnumClassWithArray() {
94 @SuppressWarnings("rawtypes")
95 final Class rawType = Object.class;
96 assertThrows(IllegalArgumentException.class, () -> EnumUtils.generateBitVector(rawType));
97 }
98
99 @Test
100 public void test_generateBitVector_nullArray() {
101 assertThrows(NullPointerException.class, () -> EnumUtils.generateBitVector(Traffic.class, (Traffic[]) null));
102 }
103
104 @Test
105 public void test_generateBitVector_nullArrayElement() {
106 assertThrows(IllegalArgumentException.class,
107 () -> EnumUtils.generateBitVector(Traffic.class, Traffic.RED, null));
108 }
109
110 @Test
111 public void test_generateBitVector_nullClass() {
112 assertThrows(NullPointerException.class, () -> EnumUtils.generateBitVector(null, EnumSet.of(Traffic.RED)));
113 }
114
115 @Test
116 public void test_generateBitVector_nullClassWithArray() {
117 assertThrows(NullPointerException.class, () -> EnumUtils.generateBitVector(null, Traffic.RED));
118 }
119
120 @Test
121 public void test_generateBitVector_nullElement() {
122 assertThrows(NullPointerException.class,
123 () -> EnumUtils.generateBitVector(Traffic.class, Arrays.asList(Traffic.RED, null)));
124 }
125
126 @Test
127 public void test_generateBitVector_nullIterable() {
128 assertThrows(NullPointerException.class,
129 () -> EnumUtils.generateBitVector(Traffic.class, (Iterable<Traffic>) null));
130 }
131
132 @Test
133 public void test_generateBitVectorFromArray() {
134 assertEquals(0L, EnumUtils.generateBitVector(Traffic.class));
135 assertEquals(1L, EnumUtils.generateBitVector(Traffic.class, Traffic.RED));
136 assertEquals(2L, EnumUtils.generateBitVector(Traffic.class, Traffic.AMBER));
137 assertEquals(4L, EnumUtils.generateBitVector(Traffic.class, Traffic.GREEN));
138 assertEquals(3L, EnumUtils.generateBitVector(Traffic.class, Traffic.RED, Traffic.AMBER));
139 assertEquals(5L, EnumUtils.generateBitVector(Traffic.class, Traffic.RED, Traffic.GREEN));
140 assertEquals(6L, EnumUtils.generateBitVector(Traffic.class, Traffic.AMBER, Traffic.GREEN));
141 assertEquals(7L, EnumUtils.generateBitVector(Traffic.class, Traffic.RED, Traffic.AMBER, Traffic.GREEN));
142 // gracefully handles duplicates:
143 assertEquals(7L,
144 EnumUtils.generateBitVector(Traffic.class, Traffic.RED, Traffic.AMBER, Traffic.GREEN, Traffic.GREEN));
145
146 // 64 values Enum (to test whether no int<->long jdk conversion issue exists)
147 assertEquals((1L << 31), EnumUtils.generateBitVector(Enum64.class, Enum64.A31));
148 assertEquals((1L << 32), EnumUtils.generateBitVector(Enum64.class, Enum64.A32));
149 assertEquals((1L << 63), EnumUtils.generateBitVector(Enum64.class, Enum64.A63));
150 assertEquals(Long.MIN_VALUE, EnumUtils.generateBitVector(Enum64.class, Enum64.A63));
151 }
152
153 @Test
154 public void test_generateBitVectors() {
155 assertArrayEquals(EnumUtils.generateBitVectors(Traffic.class, EnumSet.noneOf(Traffic.class)), 0L);
156 assertArrayEquals(EnumUtils.generateBitVectors(Traffic.class, EnumSet.of(Traffic.RED)), 1L);
157 assertArrayEquals(EnumUtils.generateBitVectors(Traffic.class, EnumSet.of(Traffic.AMBER)), 2L);
158 assertArrayEquals(EnumUtils.generateBitVectors(Traffic.class, EnumSet.of(Traffic.GREEN)), 4L);
159 assertArrayEquals(EnumUtils.generateBitVectors(Traffic.class, EnumSet.of(Traffic.RED, Traffic.AMBER)), 3L);
160 assertArrayEquals(EnumUtils.generateBitVectors(Traffic.class, EnumSet.of(Traffic.RED, Traffic.GREEN)), 5L);
161 assertArrayEquals(EnumUtils.generateBitVectors(Traffic.class, EnumSet.of(Traffic.AMBER, Traffic.GREEN)), 6L);
162 assertArrayEquals(
163 EnumUtils.generateBitVectors(Traffic.class, EnumSet.of(Traffic.RED, Traffic.AMBER, Traffic.GREEN)), 7L);
164
165 // 64 values Enum (to test whether no int<->long jdk conversion issue exists)
166 assertArrayEquals(EnumUtils.generateBitVectors(Enum64.class, EnumSet.of(Enum64.A31)), (1L << 31));
167 assertArrayEquals(EnumUtils.generateBitVectors(Enum64.class, EnumSet.of(Enum64.A32)), (1L << 32));
168 assertArrayEquals(EnumUtils.generateBitVectors(Enum64.class, EnumSet.of(Enum64.A63)), (1L << 63));
169 assertArrayEquals(EnumUtils.generateBitVectors(Enum64.class, EnumSet.of(Enum64.A63)), Long.MIN_VALUE);
170
171 // More than 64 values Enum
172 assertArrayEquals(EnumUtils.generateBitVectors(TooMany.class, EnumSet.of(TooMany.M2)), 1L, 0L);
173 assertArrayEquals(EnumUtils.generateBitVectors(TooMany.class, EnumSet.of(TooMany.L2, TooMany.M2)), 1L,
174 (1L << 63));
175 }
176
177 @SuppressWarnings("unchecked")
178 @Test
179 public void test_generateBitVectors_nonEnumClass() {
180 @SuppressWarnings("rawtypes")
181 final Class rawType = Object.class;
182 @SuppressWarnings("rawtypes")
183 final List rawList = new ArrayList();
184 assertThrows(IllegalArgumentException.class, () -> EnumUtils.generateBitVectors(rawType, rawList));
185 }
186
187 @SuppressWarnings("unchecked")
188 @Test
189 public void test_generateBitVectors_nonEnumClassWithArray() {
190 @SuppressWarnings("rawtypes")
191 final Class rawType = Object.class;
192 assertThrows(IllegalArgumentException.class, () -> EnumUtils.generateBitVectors(rawType));
193 }
194
195 @Test
196 public void test_generateBitVectors_nullArray() {
197 assertThrows(NullPointerException.class, () -> EnumUtils.generateBitVectors(Traffic.class, (Traffic[]) null));
198 }
199
200 @Test
201 public void test_generateBitVectors_nullArrayElement() {
202 assertThrows(IllegalArgumentException.class,
203 () -> EnumUtils.generateBitVectors(Traffic.class, Traffic.RED, null));
204 }
205
206 @Test
207 public void test_generateBitVectors_nullClass() {
208 assertThrows(NullPointerException.class, () -> EnumUtils.generateBitVectors(null, EnumSet.of(Traffic.RED)));
209 }
210
211 @Test
212 public void test_generateBitVectors_nullClassWithArray() {
213 assertThrows(NullPointerException.class, () -> EnumUtils.generateBitVectors(null, Traffic.RED));
214 }
215
216 @Test
217 public void test_generateBitVectors_nullElement() {
218 assertThrows(NullPointerException.class,
219 () -> EnumUtils.generateBitVectors(Traffic.class, Arrays.asList(Traffic.RED, null)));
220 }
221
222 @Test
223 public void test_generateBitVectors_nullIterable() {
224 assertThrows(NullPointerException.class, () -> EnumUtils.generateBitVectors(null, (Iterable<Traffic>) null));
225 }
226
227 @Test
228 public void test_generateBitVectorsFromArray() {
229 assertArrayEquals(EnumUtils.generateBitVectors(Traffic.class), 0L);
230 assertArrayEquals(EnumUtils.generateBitVectors(Traffic.class, Traffic.RED), 1L);
231 assertArrayEquals(EnumUtils.generateBitVectors(Traffic.class, Traffic.AMBER), 2L);
232 assertArrayEquals(EnumUtils.generateBitVectors(Traffic.class, Traffic.GREEN), 4L);
233 assertArrayEquals(EnumUtils.generateBitVectors(Traffic.class, Traffic.RED, Traffic.AMBER), 3L);
234 assertArrayEquals(EnumUtils.generateBitVectors(Traffic.class, Traffic.RED, Traffic.GREEN), 5L);
235 assertArrayEquals(EnumUtils.generateBitVectors(Traffic.class, Traffic.AMBER, Traffic.GREEN), 6L);
236 assertArrayEquals(EnumUtils.generateBitVectors(Traffic.class, Traffic.RED, Traffic.AMBER, Traffic.GREEN), 7L);
237 // gracefully handles duplicates:
238 assertArrayEquals(
239 EnumUtils.generateBitVectors(Traffic.class, Traffic.RED, Traffic.AMBER, Traffic.GREEN, Traffic.GREEN), 7L);
240
241 // 64 values Enum (to test whether no int<->long jdk conversion issue exists)
242 assertArrayEquals(EnumUtils.generateBitVectors(Enum64.class, Enum64.A31), (1L << 31));
243 assertArrayEquals(EnumUtils.generateBitVectors(Enum64.class, Enum64.A32), (1L << 32));
244 assertArrayEquals(EnumUtils.generateBitVectors(Enum64.class, Enum64.A63), (1L << 63));
245 assertArrayEquals(EnumUtils.generateBitVectors(Enum64.class, Enum64.A63), Long.MIN_VALUE);
246
247 // More than 64 values Enum
248 assertArrayEquals(EnumUtils.generateBitVectors(TooMany.class, TooMany.M2), 1L, 0L);
249 assertArrayEquals(EnumUtils.generateBitVectors(TooMany.class, TooMany.L2, TooMany.M2), 1L, (1L << 63));
250
251 }
252
253 @Test
254 public void test_getEnum() {
255 assertEquals(Traffic.RED, EnumUtils.getEnum(Traffic.class, "RED"));
256 assertEquals(Traffic.AMBER, EnumUtils.getEnum(Traffic.class, "AMBER"));
257 assertEquals(Traffic.GREEN, EnumUtils.getEnum(Traffic.class, "GREEN"));
258 assertNull(EnumUtils.getEnum(Traffic.class, "PURPLE"));
259 assertNull(EnumUtils.getEnum(Traffic.class, null));
260 }
261
262 @Test
263 public void test_getEnum_defaultEnum() {
264 assertEquals(Traffic.RED, EnumUtils.getEnum(Traffic.class, "RED", Traffic.AMBER));
265 assertEquals(Traffic.AMBER, EnumUtils.getEnum(Traffic.class, "AMBER", Traffic.GREEN));
266 assertEquals(Traffic.GREEN, EnumUtils.getEnum(Traffic.class, "GREEN", Traffic.RED));
267 assertEquals(Traffic.AMBER, EnumUtils.getEnum(Traffic.class, "PURPLE", Traffic.AMBER));
268 assertEquals(Traffic.GREEN, EnumUtils.getEnum(Traffic.class, "PURPLE", Traffic.GREEN));
269 assertEquals(Traffic.RED, EnumUtils.getEnum(Traffic.class, "PURPLE", Traffic.RED));
270 assertEquals(Traffic.AMBER, EnumUtils.getEnum(Traffic.class, null, Traffic.AMBER));
271 assertEquals(Traffic.GREEN, EnumUtils.getEnum(Traffic.class, null, Traffic.GREEN));
272 assertEquals(Traffic.RED, EnumUtils.getEnum(Traffic.class, null, Traffic.RED));
273 assertNull(EnumUtils.getEnum(Traffic.class, "PURPLE", null));
274 }
275
276 @Test
277 public void test_getEnum_nonEnumClass() {
278 final Class rawType = Object.class;
279 assertNull(EnumUtils.getEnum(rawType, "rawType"));
280 }
281
282 @Test
283 public void test_getEnum_nullClass() {
284 assertThrows(NullPointerException.class, () -> EnumUtils.getEnum((Class<Traffic>) null, "PURPLE"));
285 }
286
287 @Test
288 public void test_getEnumIgnoreCase() {
289 assertEquals(Traffic.RED, EnumUtils.getEnumIgnoreCase(Traffic.class, "red"));
290 assertEquals(Traffic.AMBER, EnumUtils.getEnumIgnoreCase(Traffic.class, "Amber"));
291 assertEquals(Traffic.GREEN, EnumUtils.getEnumIgnoreCase(Traffic.class, "grEEn"));
292 assertNull(EnumUtils.getEnumIgnoreCase(Traffic.class, "purple"));
293 assertNull(EnumUtils.getEnumIgnoreCase(Traffic.class, null));
294 }
295
296 @Test
297 public void test_getEnumIgnoreCase_defaultEnum() {
298 assertEquals(Traffic.RED, EnumUtils.getEnumIgnoreCase(Traffic.class, "red", Traffic.AMBER));
299 assertEquals(Traffic.AMBER, EnumUtils.getEnumIgnoreCase(Traffic.class, "Amber", Traffic.GREEN));
300 assertEquals(Traffic.GREEN, EnumUtils.getEnumIgnoreCase(Traffic.class, "grEEn", Traffic.RED));
301 assertEquals(Traffic.AMBER, EnumUtils.getEnumIgnoreCase(Traffic.class, "PURPLE", Traffic.AMBER));
302 assertEquals(Traffic.GREEN, EnumUtils.getEnumIgnoreCase(Traffic.class, "purple", Traffic.GREEN));
303 assertEquals(Traffic.RED, EnumUtils.getEnumIgnoreCase(Traffic.class, "pUrPlE", Traffic.RED));
304 assertEquals(Traffic.AMBER, EnumUtils.getEnumIgnoreCase(Traffic.class, null, Traffic.AMBER));
305 assertEquals(Traffic.GREEN, EnumUtils.getEnumIgnoreCase(Traffic.class, null, Traffic.GREEN));
306 assertEquals(Traffic.RED, EnumUtils.getEnumIgnoreCase(Traffic.class, null, Traffic.RED));
307 assertNull(EnumUtils.getEnumIgnoreCase(Traffic.class, "PURPLE", null));
308 }
309
310 @Test
311 public void test_getEnumIgnoreCase_nonEnumClass() {
312 final Class rawType = Object.class;
313 assertNull(EnumUtils.getEnumIgnoreCase(rawType, "rawType"));
314 }
315
316 @Test
317 public void test_getEnumIgnoreCase_nullClass() {
318 assertThrows(NullPointerException.class, () -> EnumUtils.getEnumIgnoreCase((Class<Traffic>) null, "PURPLE"));
319 }
320
321 @Test
322 public void test_getEnumList() {
323 final List<Traffic> test = EnumUtils.getEnumList(Traffic.class);
324 assertEquals(3, test.size());
325 assertEquals(Traffic.RED, test.get(0));
326 assertEquals(Traffic.AMBER, test.get(1));
327 assertEquals(Traffic.GREEN, test.get(2));
44328 }
45329
46330 @Test
58342 }
59343
60344 @Test
61 public void test_getEnumList() {
62 final List<Traffic> test = EnumUtils.getEnumList(Traffic.class);
63 assertEquals(3, test.size());
64 assertEquals(Traffic.RED, test.get(0));
65 assertEquals(Traffic.AMBER, test.get(1));
66 assertEquals(Traffic.GREEN, test.get(2));
345 public void test_getEnumSystemProperty() {
346 final String key = getClass().getName();
347 System.setProperty(key, Traffic.RED.toString());
348 try {
349 assertEquals(Traffic.RED, EnumUtils.getEnumSystemProperty(Traffic.class, key, null));
350 assertEquals(Traffic.RED, EnumUtils.getEnumSystemProperty(Traffic.class, "?", Traffic.RED));
351 assertEquals(Traffic.RED, EnumUtils.getEnumSystemProperty(null, null, Traffic.RED));
352 assertEquals(Traffic.RED, EnumUtils.getEnumSystemProperty(null, "?", Traffic.RED));
353 assertEquals(Traffic.RED, EnumUtils.getEnumSystemProperty(Traffic.class, null, Traffic.RED));
354 } finally {
355 System.getProperties().remove(key);
356 }
357 }
358
359 @Test
360 public void test_getFirstEnumIgnoreCase_defaultEnum() {
361 final Function<Traffic2, String> f = Traffic2::getLabel;
362 assertEquals(Traffic2.RED, EnumUtils.getFirstEnumIgnoreCase(Traffic2.class, "***red***", f, Traffic2.AMBER));
363 assertEquals(Traffic2.AMBER, EnumUtils.getFirstEnumIgnoreCase(Traffic2.class, "**Amber**", f, Traffic2.GREEN));
364 assertEquals(Traffic2.GREEN, EnumUtils.getFirstEnumIgnoreCase(Traffic2.class, "*grEEn*", f, Traffic2.RED));
365 assertEquals(Traffic2.AMBER, EnumUtils.getFirstEnumIgnoreCase(Traffic2.class, "PURPLE", f, Traffic2.AMBER));
366 assertEquals(Traffic2.GREEN, EnumUtils.getFirstEnumIgnoreCase(Traffic2.class, "purple", f, Traffic2.GREEN));
367 assertEquals(Traffic2.RED, EnumUtils.getFirstEnumIgnoreCase(Traffic2.class, "pUrPlE", f, Traffic2.RED));
368 assertEquals(Traffic2.AMBER, EnumUtils.getFirstEnumIgnoreCase(Traffic2.class, null, f, Traffic2.AMBER));
369 assertEquals(Traffic2.GREEN, EnumUtils.getFirstEnumIgnoreCase(Traffic2.class, null, f, Traffic2.GREEN));
370 assertEquals(Traffic2.RED, EnumUtils.getFirstEnumIgnoreCase(Traffic2.class, null, f, Traffic2.RED));
371 assertNull(EnumUtils.getFirstEnumIgnoreCase(Traffic2.class, "PURPLE", f, null));
67372 }
68373
69374 @Test
92397 @Test
93398 public void test_isValidEnumIgnoreCase_nullClass() {
94399 assertThrows(NullPointerException.class, () -> EnumUtils.isValidEnumIgnoreCase(null, "PURPLE"));
95 }
96
97 @Test
98 public void test_getEnum() {
99 assertEquals(Traffic.RED, EnumUtils.getEnum(Traffic.class, "RED"));
100 assertEquals(Traffic.AMBER, EnumUtils.getEnum(Traffic.class, "AMBER"));
101 assertEquals(Traffic.GREEN, EnumUtils.getEnum(Traffic.class, "GREEN"));
102 assertNull(EnumUtils.getEnum(Traffic.class, "PURPLE"));
103 assertNull(EnumUtils.getEnum(Traffic.class, null));
104 }
105
106 @Test
107 public void test_getEnum_nonEnumClass() {
108 final Class rawType = Object.class;
109 assertNull(EnumUtils.getEnum(rawType, "rawType"));
110 }
111
112 @Test
113 public void test_getEnum_nullClass() {
114 assertThrows(NullPointerException.class, () -> EnumUtils.getEnum((Class<Traffic>) null, "PURPLE"));
115 }
116
117 @Test
118 public void test_getEnum_defaultEnum() {
119 assertEquals(Traffic.RED, EnumUtils.getEnum(Traffic.class, "RED", Traffic.AMBER));
120 assertEquals(Traffic.AMBER, EnumUtils.getEnum(Traffic.class, "AMBER", Traffic.GREEN));
121 assertEquals(Traffic.GREEN, EnumUtils.getEnum(Traffic.class, "GREEN", Traffic.RED));
122 assertEquals(Traffic.AMBER, EnumUtils.getEnum(Traffic.class, "PURPLE", Traffic.AMBER));
123 assertEquals(Traffic.GREEN, EnumUtils.getEnum(Traffic.class, "PURPLE", Traffic.GREEN));
124 assertEquals(Traffic.RED, EnumUtils.getEnum(Traffic.class, "PURPLE", Traffic.RED));
125 assertEquals(Traffic.AMBER, EnumUtils.getEnum(Traffic.class, null, Traffic.AMBER));
126 assertEquals(Traffic.GREEN, EnumUtils.getEnum(Traffic.class, null, Traffic.GREEN));
127 assertEquals(Traffic.RED, EnumUtils.getEnum(Traffic.class, null, Traffic.RED));
128 assertNull(EnumUtils.getEnum(Traffic.class, "PURPLE", null));
129 }
130
131 @Test
132 public void test_getEnumIgnoreCase() {
133 assertEquals(Traffic.RED, EnumUtils.getEnumIgnoreCase(Traffic.class, "red"));
134 assertEquals(Traffic.AMBER, EnumUtils.getEnumIgnoreCase(Traffic.class, "Amber"));
135 assertEquals(Traffic.GREEN, EnumUtils.getEnumIgnoreCase(Traffic.class, "grEEn"));
136 assertNull(EnumUtils.getEnumIgnoreCase(Traffic.class, "purple"));
137 assertNull(EnumUtils.getEnumIgnoreCase(Traffic.class, null));
138 }
139
140 @Test
141 public void test_getEnumIgnoreCase_nonEnumClass() {
142 final Class rawType = Object.class;
143 assertNull(EnumUtils.getEnumIgnoreCase(rawType, "rawType"));
144 }
145
146 @Test
147 public void test_getEnumIgnoreCase_nullClass() {
148 assertThrows(NullPointerException.class, () -> EnumUtils.getEnumIgnoreCase((Class<Traffic>) null, "PURPLE"));
149 }
150
151 @Test
152 public void test_getEnumIgnoreCase_defaultEnum() {
153 assertEquals(Traffic.RED, EnumUtils.getEnumIgnoreCase(Traffic.class, "red", Traffic.AMBER));
154 assertEquals(Traffic.AMBER, EnumUtils.getEnumIgnoreCase(Traffic.class, "Amber", Traffic.GREEN));
155 assertEquals(Traffic.GREEN, EnumUtils.getEnumIgnoreCase(Traffic.class, "grEEn", Traffic.RED));
156 assertEquals(Traffic.AMBER, EnumUtils.getEnumIgnoreCase(Traffic.class, "PURPLE", Traffic.AMBER));
157 assertEquals(Traffic.GREEN, EnumUtils.getEnumIgnoreCase(Traffic.class, "purple", Traffic.GREEN));
158 assertEquals(Traffic.RED, EnumUtils.getEnumIgnoreCase(Traffic.class, "pUrPlE", Traffic.RED));
159 assertEquals(Traffic.AMBER, EnumUtils.getEnumIgnoreCase(Traffic.class, null, Traffic.AMBER));
160 assertEquals(Traffic.GREEN, EnumUtils.getEnumIgnoreCase(Traffic.class, null, Traffic.GREEN));
161 assertEquals(Traffic.RED, EnumUtils.getEnumIgnoreCase(Traffic.class, null, Traffic.RED));
162 assertNull(EnumUtils.getEnumIgnoreCase(Traffic.class, "PURPLE", null));
163 }
164
165 @Test
166 public void test_generateBitVector_nullClass() {
167 assertThrows(NullPointerException.class, () -> EnumUtils.generateBitVector(null, EnumSet.of(Traffic.RED)));
168 }
169
170 @Test
171 public void test_generateBitVectors_nullClass() {
172 assertThrows(NullPointerException.class, () -> EnumUtils.generateBitVectors(null, EnumSet.of(Traffic.RED)));
173 }
174
175 @Test
176 public void test_generateBitVector_nullIterable() {
177 assertThrows(NullPointerException.class,
178 () -> EnumUtils.generateBitVector(Traffic.class, (Iterable<Traffic>) null));
179 }
180
181 @Test
182 public void test_generateBitVectors_nullIterable() {
183 assertThrows(NullPointerException.class, () -> EnumUtils.generateBitVectors(null, (Iterable<Traffic>) null));
184 }
185
186 @Test
187 public void test_generateBitVector_nullElement() {
188 assertThrows(NullPointerException.class,
189 () -> EnumUtils.generateBitVector(Traffic.class, Arrays.asList(Traffic.RED, null)));
190 }
191
192 @Test
193 public void test_generateBitVectors_nullElement() {
194 assertThrows(NullPointerException.class,
195 () -> EnumUtils.generateBitVectors(Traffic.class, Arrays.asList(Traffic.RED, null)));
196 }
197
198 @Test
199 public void test_generateBitVector_nullClassWithArray() {
200 assertThrows(NullPointerException.class, () -> EnumUtils.generateBitVector(null, Traffic.RED));
201 }
202
203 @Test
204 public void test_generateBitVectors_nullClassWithArray() {
205 assertThrows(NullPointerException.class, () -> EnumUtils.generateBitVectors(null, Traffic.RED));
206 }
207
208 @Test
209 public void test_generateBitVector_nullArray() {
210 assertThrows(NullPointerException.class, () -> EnumUtils.generateBitVector(Traffic.class, (Traffic[]) null));
211 }
212
213 @Test
214 public void test_generateBitVectors_nullArray() {
215 assertThrows(NullPointerException.class, () -> EnumUtils.generateBitVectors(Traffic.class, (Traffic[]) null));
216 }
217
218 @Test
219 public void test_generateBitVector_nullArrayElement() {
220 assertThrows(IllegalArgumentException.class,
221 () -> EnumUtils.generateBitVector(Traffic.class, Traffic.RED, null));
222 }
223
224 @Test
225 public void test_generateBitVectors_nullArrayElement() {
226 assertThrows(IllegalArgumentException.class,
227 () -> EnumUtils.generateBitVectors(Traffic.class, Traffic.RED, null));
228 }
229
230 @Test
231 public void test_generateBitVector_longClass() {
232 assertThrows(IllegalArgumentException.class,
233 () -> EnumUtils.generateBitVector(TooMany.class, EnumSet.of(TooMany.A1)));
234 }
235
236 @Test
237 public void test_generateBitVector_longClassWithArray() {
238 assertThrows(IllegalArgumentException.class, () -> EnumUtils.generateBitVector(TooMany.class, TooMany.A1));
239 }
240
241 @SuppressWarnings("unchecked")
242 @Test
243 public void test_generateBitVector_nonEnumClass() {
244 @SuppressWarnings("rawtypes")
245 final
246 Class rawType = Object.class;
247 @SuppressWarnings("rawtypes")
248 final
249 List rawList = new ArrayList();
250 assertThrows(IllegalArgumentException.class, () -> EnumUtils.generateBitVector(rawType, rawList));
251 }
252
253 @SuppressWarnings("unchecked")
254 @Test
255 public void test_generateBitVectors_nonEnumClass() {
256 @SuppressWarnings("rawtypes")
257 final
258 Class rawType = Object.class;
259 @SuppressWarnings("rawtypes")
260 final
261 List rawList = new ArrayList();
262 assertThrows(IllegalArgumentException.class, () -> EnumUtils.generateBitVectors(rawType, rawList));
263 }
264
265 @SuppressWarnings("unchecked")
266 @Test
267 public void test_generateBitVector_nonEnumClassWithArray() {
268 @SuppressWarnings("rawtypes")
269 final
270 Class rawType = Object.class;
271 assertThrows(IllegalArgumentException.class, () -> EnumUtils.generateBitVector(rawType));
272 }
273
274 @SuppressWarnings("unchecked")
275 @Test
276 public void test_generateBitVectors_nonEnumClassWithArray() {
277 @SuppressWarnings("rawtypes")
278 final
279 Class rawType = Object.class;
280 assertThrows(IllegalArgumentException.class, () -> EnumUtils.generateBitVectors(rawType));
281 }
282
283 @Test
284 public void test_generateBitVector() {
285 assertEquals(0L, EnumUtils.generateBitVector(Traffic.class, EnumSet.noneOf(Traffic.class)));
286 assertEquals(1L, EnumUtils.generateBitVector(Traffic.class, EnumSet.of(Traffic.RED)));
287 assertEquals(2L, EnumUtils.generateBitVector(Traffic.class, EnumSet.of(Traffic.AMBER)));
288 assertEquals(4L, EnumUtils.generateBitVector(Traffic.class, EnumSet.of(Traffic.GREEN)));
289 assertEquals(3L, EnumUtils.generateBitVector(Traffic.class, EnumSet.of(Traffic.RED, Traffic.AMBER)));
290 assertEquals(5L, EnumUtils.generateBitVector(Traffic.class, EnumSet.of(Traffic.RED, Traffic.GREEN)));
291 assertEquals(6L, EnumUtils.generateBitVector(Traffic.class, EnumSet.of(Traffic.AMBER, Traffic.GREEN)));
292 assertEquals(7L, EnumUtils.generateBitVector(Traffic.class, EnumSet.of(Traffic.RED, Traffic.AMBER, Traffic.GREEN)));
293
294 // 64 values Enum (to test whether no int<->long jdk conversion issue exists)
295 assertEquals((1L << 31), EnumUtils.generateBitVector(Enum64.class, EnumSet.of(Enum64.A31)));
296 assertEquals((1L << 32), EnumUtils.generateBitVector(Enum64.class, EnumSet.of(Enum64.A32)));
297 assertEquals((1L << 63), EnumUtils.generateBitVector(Enum64.class, EnumSet.of(Enum64.A63)));
298 assertEquals(Long.MIN_VALUE, EnumUtils.generateBitVector(Enum64.class, EnumSet.of(Enum64.A63)));
299 }
300
301 @Test
302 public void test_generateBitVectors() {
303 assertArrayEquals(EnumUtils.generateBitVectors(Traffic.class, EnumSet.noneOf(Traffic.class)), 0L);
304 assertArrayEquals(EnumUtils.generateBitVectors(Traffic.class, EnumSet.of(Traffic.RED)), 1L);
305 assertArrayEquals(EnumUtils.generateBitVectors(Traffic.class, EnumSet.of(Traffic.AMBER)), 2L);
306 assertArrayEquals(EnumUtils.generateBitVectors(Traffic.class, EnumSet.of(Traffic.GREEN)), 4L);
307 assertArrayEquals(EnumUtils.generateBitVectors(Traffic.class, EnumSet.of(Traffic.RED, Traffic.AMBER)), 3L);
308 assertArrayEquals(EnumUtils.generateBitVectors(Traffic.class, EnumSet.of(Traffic.RED, Traffic.GREEN)), 5L);
309 assertArrayEquals(EnumUtils.generateBitVectors(Traffic.class, EnumSet.of(Traffic.AMBER, Traffic.GREEN)), 6L);
310 assertArrayEquals(EnumUtils.generateBitVectors(Traffic.class, EnumSet.of(Traffic.RED, Traffic.AMBER, Traffic.GREEN)), 7L);
311
312 // 64 values Enum (to test whether no int<->long jdk conversion issue exists)
313 assertArrayEquals(EnumUtils.generateBitVectors(Enum64.class, EnumSet.of(Enum64.A31)), (1L << 31));
314 assertArrayEquals(EnumUtils.generateBitVectors(Enum64.class, EnumSet.of(Enum64.A32)), (1L << 32));
315 assertArrayEquals(EnumUtils.generateBitVectors(Enum64.class, EnumSet.of(Enum64.A63)), (1L << 63));
316 assertArrayEquals(EnumUtils.generateBitVectors(Enum64.class, EnumSet.of(Enum64.A63)), Long.MIN_VALUE);
317
318 // More than 64 values Enum
319 assertArrayEquals(EnumUtils.generateBitVectors(TooMany.class, EnumSet.of(TooMany.M2)), 1L, 0L);
320 assertArrayEquals(EnumUtils.generateBitVectors(TooMany.class, EnumSet.of(TooMany.L2, TooMany.M2)), 1L, (1L << 63));
321 }
322
323 @Test
324 public void test_generateBitVectorFromArray() {
325 assertEquals(0L, EnumUtils.generateBitVector(Traffic.class));
326 assertEquals(1L, EnumUtils.generateBitVector(Traffic.class, Traffic.RED));
327 assertEquals(2L, EnumUtils.generateBitVector(Traffic.class, Traffic.AMBER));
328 assertEquals(4L, EnumUtils.generateBitVector(Traffic.class, Traffic.GREEN));
329 assertEquals(3L, EnumUtils.generateBitVector(Traffic.class, Traffic.RED, Traffic.AMBER));
330 assertEquals(5L, EnumUtils.generateBitVector(Traffic.class, Traffic.RED, Traffic.GREEN));
331 assertEquals(6L, EnumUtils.generateBitVector(Traffic.class, Traffic.AMBER, Traffic.GREEN));
332 assertEquals(7L, EnumUtils.generateBitVector(Traffic.class, Traffic.RED, Traffic.AMBER, Traffic.GREEN));
333 //gracefully handles duplicates:
334 assertEquals(7L, EnumUtils.generateBitVector(Traffic.class, Traffic.RED, Traffic.AMBER, Traffic.GREEN, Traffic.GREEN));
335
336 // 64 values Enum (to test whether no int<->long jdk conversion issue exists)
337 assertEquals((1L << 31), EnumUtils.generateBitVector(Enum64.class, Enum64.A31));
338 assertEquals((1L << 32), EnumUtils.generateBitVector(Enum64.class, Enum64.A32));
339 assertEquals((1L << 63), EnumUtils.generateBitVector(Enum64.class, Enum64.A63));
340 assertEquals(Long.MIN_VALUE, EnumUtils.generateBitVector(Enum64.class, Enum64.A63));
341 }
342
343 @Test
344 public void test_generateBitVectorsFromArray() {
345 assertArrayEquals(EnumUtils.generateBitVectors(Traffic.class), 0L);
346 assertArrayEquals(EnumUtils.generateBitVectors(Traffic.class, Traffic.RED), 1L);
347 assertArrayEquals(EnumUtils.generateBitVectors(Traffic.class, Traffic.AMBER), 2L);
348 assertArrayEquals(EnumUtils.generateBitVectors(Traffic.class, Traffic.GREEN), 4L);
349 assertArrayEquals(EnumUtils.generateBitVectors(Traffic.class, Traffic.RED, Traffic.AMBER), 3L);
350 assertArrayEquals(EnumUtils.generateBitVectors(Traffic.class, Traffic.RED, Traffic.GREEN), 5L);
351 assertArrayEquals(EnumUtils.generateBitVectors(Traffic.class, Traffic.AMBER, Traffic.GREEN), 6L);
352 assertArrayEquals(EnumUtils.generateBitVectors(Traffic.class, Traffic.RED, Traffic.AMBER, Traffic.GREEN), 7L);
353 //gracefully handles duplicates:
354 assertArrayEquals(EnumUtils.generateBitVectors(Traffic.class, Traffic.RED, Traffic.AMBER, Traffic.GREEN, Traffic.GREEN), 7L);
355
356 // 64 values Enum (to test whether no int<->long jdk conversion issue exists)
357 assertArrayEquals(EnumUtils.generateBitVectors(Enum64.class, Enum64.A31), (1L << 31));
358 assertArrayEquals(EnumUtils.generateBitVectors(Enum64.class, Enum64.A32), (1L << 32));
359 assertArrayEquals(EnumUtils.generateBitVectors(Enum64.class, Enum64.A63), (1L << 63));
360 assertArrayEquals(EnumUtils.generateBitVectors(Enum64.class, Enum64.A63), Long.MIN_VALUE);
361
362 // More than 64 values Enum
363 assertArrayEquals(EnumUtils.generateBitVectors(TooMany.class, TooMany.M2), 1L, 0L);
364 assertArrayEquals(EnumUtils.generateBitVectors(TooMany.class, TooMany.L2, TooMany.M2), 1L, (1L << 63));
365
366 }
367
368 private void assertArrayEquals(final long[] actual, final long... expected) {
369 Assertions.assertArrayEquals(expected, actual);
370 }
371
372 @Test
373 public void test_processBitVector_nullClass() {
374 final Class<Traffic> empty = null;
375 assertThrows(NullPointerException.class, () -> EnumUtils.processBitVector(empty, 0L));
376 }
377
378 @Test
379 public void test_processBitVectors_nullClass() {
380 final Class<Traffic> empty = null;
381 assertThrows(NullPointerException.class, () -> EnumUtils.processBitVectors(empty, 0L));
382400 }
383401
384402 @Test
390408 assertEquals(EnumSet.of(Traffic.GREEN), EnumUtils.processBitVector(Traffic.class, 4L));
391409 assertEquals(EnumSet.of(Traffic.RED, Traffic.GREEN), EnumUtils.processBitVector(Traffic.class, 5L));
392410 assertEquals(EnumSet.of(Traffic.AMBER, Traffic.GREEN), EnumUtils.processBitVector(Traffic.class, 6L));
393 assertEquals(EnumSet.of(Traffic.RED, Traffic.AMBER, Traffic.GREEN), EnumUtils.processBitVector(Traffic.class, 7L));
411 assertEquals(EnumSet.of(Traffic.RED, Traffic.AMBER, Traffic.GREEN),
412 EnumUtils.processBitVector(Traffic.class, 7L));
394413
395414 // 64 values Enum (to test whether no int<->long jdk conversion issue exists)
396415 assertEquals(EnumSet.of(Enum64.A31), EnumUtils.processBitVector(Enum64.class, (1L << 31)));
397416 assertEquals(EnumSet.of(Enum64.A32), EnumUtils.processBitVector(Enum64.class, (1L << 32)));
398417 assertEquals(EnumSet.of(Enum64.A63), EnumUtils.processBitVector(Enum64.class, (1L << 63)));
399418 assertEquals(EnumSet.of(Enum64.A63), EnumUtils.processBitVector(Enum64.class, Long.MIN_VALUE));
419 }
420
421 @Test
422 public void test_processBitVector_longClass() {
423 assertThrows(IllegalArgumentException.class, () -> EnumUtils.processBitVector(TooMany.class, 0L));
424 }
425
426 @Test
427 public void test_processBitVector_nullClass() {
428 final Class<Traffic> empty = null;
429 assertThrows(NullPointerException.class, () -> EnumUtils.processBitVector(empty, 0L));
400430 }
401431
402432 @Test
408438 assertEquals(EnumSet.of(Traffic.GREEN), EnumUtils.processBitVectors(Traffic.class, 4L));
409439 assertEquals(EnumSet.of(Traffic.RED, Traffic.GREEN), EnumUtils.processBitVectors(Traffic.class, 5L));
410440 assertEquals(EnumSet.of(Traffic.AMBER, Traffic.GREEN), EnumUtils.processBitVectors(Traffic.class, 6L));
411 assertEquals(EnumSet.of(Traffic.RED, Traffic.AMBER, Traffic.GREEN), EnumUtils.processBitVectors(Traffic.class, 7L));
441 assertEquals(EnumSet.of(Traffic.RED, Traffic.AMBER, Traffic.GREEN),
442 EnumUtils.processBitVectors(Traffic.class, 7L));
412443
413444 assertEquals(EnumSet.noneOf(Traffic.class), EnumUtils.processBitVectors(Traffic.class, 0L, 0L));
414445 assertEquals(EnumSet.of(Traffic.RED), EnumUtils.processBitVectors(Traffic.class, 0L, 1L));
417448 assertEquals(EnumSet.of(Traffic.GREEN), EnumUtils.processBitVectors(Traffic.class, 0L, 4L));
418449 assertEquals(EnumSet.of(Traffic.RED, Traffic.GREEN), EnumUtils.processBitVectors(Traffic.class, 0L, 5L));
419450 assertEquals(EnumSet.of(Traffic.AMBER, Traffic.GREEN), EnumUtils.processBitVectors(Traffic.class, 0L, 6L));
420 assertEquals(EnumSet.of(Traffic.RED, Traffic.AMBER, Traffic.GREEN), EnumUtils.processBitVectors(Traffic.class, 0L, 7L));
451 assertEquals(EnumSet.of(Traffic.RED, Traffic.AMBER, Traffic.GREEN),
452 EnumUtils.processBitVectors(Traffic.class, 0L, 7L));
421453
422454 // demonstrate tolerance of irrelevant high-order digits:
423455 assertEquals(EnumSet.noneOf(Traffic.class), EnumUtils.processBitVectors(Traffic.class, 666L, 0L));
427459 assertEquals(EnumSet.of(Traffic.GREEN), EnumUtils.processBitVectors(Traffic.class, 666L, 4L));
428460 assertEquals(EnumSet.of(Traffic.RED, Traffic.GREEN), EnumUtils.processBitVectors(Traffic.class, 666L, 5L));
429461 assertEquals(EnumSet.of(Traffic.AMBER, Traffic.GREEN), EnumUtils.processBitVectors(Traffic.class, 666L, 6L));
430 assertEquals(EnumSet.of(Traffic.RED, Traffic.AMBER, Traffic.GREEN), EnumUtils.processBitVectors(Traffic.class, 666L, 7L));
462 assertEquals(EnumSet.of(Traffic.RED, Traffic.AMBER, Traffic.GREEN),
463 EnumUtils.processBitVectors(Traffic.class, 666L, 7L));
431464
432465 // 64 values Enum (to test whether no int<->long jdk conversion issue exists)
433466 assertEquals(EnumSet.of(Enum64.A31), EnumUtils.processBitVectors(Enum64.class, (1L << 31)));
434467 assertEquals(EnumSet.of(Enum64.A32), EnumUtils.processBitVectors(Enum64.class, (1L << 32)));
435468 assertEquals(EnumSet.of(Enum64.A63), EnumUtils.processBitVectors(Enum64.class, (1L << 63)));
436469 assertEquals(EnumSet.of(Enum64.A63), EnumUtils.processBitVectors(Enum64.class, Long.MIN_VALUE));
437 }
438
439 @Test
440 public void test_processBitVector_longClass() {
441 assertThrows(IllegalArgumentException.class, () -> EnumUtils.processBitVector(TooMany.class, 0L));
442470 }
443471
444472 @Test
469497 assertEquals(EnumSet.of(TooMany.C, TooMany.M2), EnumUtils.processBitVectors(TooMany.class, 1L, 4L));
470498 assertEquals(EnumSet.of(TooMany.A, TooMany.C, TooMany.M2), EnumUtils.processBitVectors(TooMany.class, 1L, 5L));
471499 assertEquals(EnumSet.of(TooMany.B, TooMany.C, TooMany.M2), EnumUtils.processBitVectors(TooMany.class, 1L, 6L));
472 assertEquals(EnumSet.of(TooMany.A, TooMany.B, TooMany.C, TooMany.M2), EnumUtils.processBitVectors(TooMany.class, 1L, 7L));
473 assertEquals(EnumSet.of(TooMany.A, TooMany.B, TooMany.C, TooMany.M2), EnumUtils.processBitVectors(TooMany.class, 1L, 7L));
500 assertEquals(EnumSet.of(TooMany.A, TooMany.B, TooMany.C, TooMany.M2),
501 EnumUtils.processBitVectors(TooMany.class, 1L, 7L));
502 assertEquals(EnumSet.of(TooMany.A, TooMany.B, TooMany.C, TooMany.M2),
503 EnumUtils.processBitVectors(TooMany.class, 1L, 7L));
474504
475505 // demonstrate tolerance of irrelevant high-order digits:
476506 assertEquals(EnumSet.of(TooMany.M2), EnumUtils.processBitVectors(TooMany.class, 9L, 0L));
480510 assertEquals(EnumSet.of(TooMany.C, TooMany.M2), EnumUtils.processBitVectors(TooMany.class, 9L, 4L));
481511 assertEquals(EnumSet.of(TooMany.A, TooMany.C, TooMany.M2), EnumUtils.processBitVectors(TooMany.class, 9L, 5L));
482512 assertEquals(EnumSet.of(TooMany.B, TooMany.C, TooMany.M2), EnumUtils.processBitVectors(TooMany.class, 9L, 6L));
483 assertEquals(EnumSet.of(TooMany.A, TooMany.B, TooMany.C, TooMany.M2), EnumUtils.processBitVectors(TooMany.class, 9L, 7L));
484 assertEquals(EnumSet.of(TooMany.A, TooMany.B, TooMany.C, TooMany.M2), EnumUtils.processBitVectors(TooMany.class, 9L, 7L));
485 }
486
513 assertEquals(EnumSet.of(TooMany.A, TooMany.B, TooMany.C, TooMany.M2),
514 EnumUtils.processBitVectors(TooMany.class, 9L, 7L));
515 assertEquals(EnumSet.of(TooMany.A, TooMany.B, TooMany.C, TooMany.M2),
516 EnumUtils.processBitVectors(TooMany.class, 9L, 7L));
517 }
518
519 @Test
520 public void test_processBitVectors_nullClass() {
521 final Class<Traffic> empty = null;
522 assertThrows(NullPointerException.class, () -> EnumUtils.processBitVectors(empty, 0L));
523 }
524
525 @Test
526 public void testConstructable() {
527 // enforce public constructor
528 new EnumUtils();
529 }
530
531 }
532
533 enum TooMany {
534 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, A1, B1, C1, D1, E1, F1, G1, H1, I1,
535 J1, K1, L1, M1, N1, O1, P1, Q1, R1, S1, T1, U1, V1, W1, X1, Y1, Z1, A2, B2, C2, D2, E2, F2, G2, H2, I2, J2, K2, L2,
536 M2
487537 }
488538
489539 enum Traffic {
490540 RED, AMBER, GREEN
491541 }
492542
493 enum Enum64 {
494 A00, A01, A02, A03, A04, A05, A06, A07, A08, A09, A10, A11, A12, A13, A14, A15,
495 A16, A17, A18, A19, A20, A21, A22, A23, A24, A25, A26, A27, A28, A29, A30, A31,
496 A32, A33, A34, A35, A36, A37, A38, A39, A40, A41, A42, A43, A44, A45, A46, A47,
497 A48, A49, A50, A51, A52, A53, A54, A55, A56, A57, A58, A59, A60, A61, A62, A63
543 enum Traffic2 {
544
545 RED("***Red***"), AMBER("**Amber**"), GREEN("*green*");
546
547 final String label;
548
549 Traffic2(final String label) {
550 this.label = label;
551 }
552
553 public String getLabel() {
554 return label;
555 }
498556 }
499
500 enum TooMany {
501 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,
502 A1, B1, C1, D1, E1, F1, G1, H1, I1, J1, K1, L1, M1, N1, O1, P1, Q1, R1, S1, T1,
503 U1, V1, W1, X1, Y1, Z1, A2, B2, C2, D2, E2, F2, G2, H2, I2, J2, K2, L2, M2
504 }
2525 import static org.apache.commons.lang3.JavaVersion.JAVA_14;
2626 import static org.apache.commons.lang3.JavaVersion.JAVA_15;
2727 import static org.apache.commons.lang3.JavaVersion.JAVA_16;
28 import static org.apache.commons.lang3.JavaVersion.JAVA_17;
2829 import static org.apache.commons.lang3.JavaVersion.JAVA_1_1;
2930 import static org.apache.commons.lang3.JavaVersion.JAVA_1_2;
3031 import static org.apache.commons.lang3.JavaVersion.JAVA_1_3;
6768 assertEquals(JAVA_14, get("14"), "14 failed");
6869 assertEquals(JAVA_15, get("15"), "15 failed");
6970 assertEquals(JAVA_16, get("16"), "16 failed");
71 assertEquals(JAVA_17, get("17"), "17 failed");
7072 assertEquals(JAVA_RECENT, get("1.10"), "1.10 failed");
7173 // assertNull("2.10 unexpectedly worked", get("2.10"));
7274 assertEquals(get("1.5"), getJavaVersion("1.5"), "Wrapper method failed");
73 assertEquals(JAVA_RECENT, get("17"), "Unhandled"); // LANG-1384
75 assertEquals(JAVA_RECENT, get("18"), "Unhandled"); // LANG-1384
7476 }
7577
7678 @Test
5858 LocaleUtils.isAvailableLocale(Locale.getDefault());
5959 }
6060
61 //-----------------------------------------------------------------------
6261 /**
6362 * Test that constructors are public, and work, etc.
6463 */
7271 assertFalse(Modifier.isFinal(LocaleUtils.class.getModifiers()));
7372 }
7473
75 //-----------------------------------------------------------------------
7674 /**
7775 * Pass in a valid language, test toLocale.
7876 *
122120 }
123121
124122 /**
125 * Test toLocale() method.
123 * Test toLocale(Locale) method.
124 */
125 @Test
126 public void testToLocale_Locale_defaults() {
127 assertNull(LocaleUtils.toLocale((String) null));
128 assertEquals(Locale.getDefault(), LocaleUtils.toLocale((Locale) null));
129 assertEquals(Locale.getDefault(), LocaleUtils.toLocale(Locale.getDefault()));
130 }
131
132 /**
133 * Test toLocale(Locale) method.
134 */
135 @ParameterizedTest
136 @MethodSource("java.util.Locale#getAvailableLocales")
137 public void testToLocales(final Locale actualLocale) {
138 assertEquals(actualLocale, LocaleUtils.toLocale(actualLocale));
139 }
140
141 /**
142 * Test toLocale(String) method.
126143 */
127144 @Test
128145 public void testToLocale_1Part() {
129 assertNull(LocaleUtils.toLocale(null));
146 assertNull(LocaleUtils.toLocale((String) null));
130147
131148 assertValidToLocale("us");
132149 assertValidToLocale("fr");
201218 IllegalArgumentException.class, () -> LocaleUtils.toLocale("uu_UU_"), "Must be 3, 5 or 7+ in length");
202219 }
203220
204 //-----------------------------------------------------------------------
205221 /**
206222 * Helper method for local lookups.
207223 *
219235 assertUnmodifiableCollection(localeList);
220236 }
221237
222 //-----------------------------------------------------------------------
223238 /**
224239 * Test localeLookupList() method.
225240 */
294309 LOCALE_EN});
295310 }
296311
297 //-----------------------------------------------------------------------
298312 /**
299313 * Test availableLocaleList() method.
300314 */
311325 assertEquals(jdkLocaleList, list);
312326 }
313327
314 //-----------------------------------------------------------------------
315328 /**
316329 * Test availableLocaleSet() method.
317330 */
329342 assertEquals(jdkLocaleSet, set);
330343 }
331344
332 //-----------------------------------------------------------------------
333345 /**
334346 * Test availableLocaleSet() method.
335347 */
361373 }
362374 }
363375
364 //-----------------------------------------------------------------------
365376 /**
366377 * Make sure the language by country is correct. It checks that
367378 * the LocaleUtils.languagesByCountry(country) call contains the
408419 assertLanguageByCountry("CH", new String[]{"fr", "de", "it"});
409420 }
410421
411 //-----------------------------------------------------------------------
412422 /**
413423 * Make sure the country by language is correct. It checks that
414424 * the LocaleUtils.countryByLanguage(language) call contains the
523533
524534 @ParameterizedTest
525535 @MethodSource("java.util.Locale#getAvailableLocales")
526 public void testParseAllLocales(final Locale l) {
536 public void testParseAllLocales(final Locale actualLocale) {
527537 // Check if it's possible to recreate the Locale using just the standard constructor
528 final Locale locale = new Locale(l.getLanguage(), l.getCountry(), l.getVariant());
529 if (l.equals(locale)) { // it is possible for LocaleUtils.toLocale to handle these Locales
530 final String str = l.toString();
538 final Locale locale = new Locale(actualLocale.getLanguage(), actualLocale.getCountry(), actualLocale.getVariant());
539 if (actualLocale.equals(locale)) { // it is possible for LocaleUtils.toLocale to handle these Locales
540 final String str = actualLocale.toString();
531541 // Look for the script/extension suffix
532542 int suff = str.indexOf("_#");
533543 if (suff == - 1) {
540550 localeStr = str.substring(0, suff);
541551 }
542552 final Locale loc = LocaleUtils.toLocale(localeStr);
543 assertEquals(l, loc);
553 assertEquals(actualLocale, loc);
544554 }
545555 }
546556 }
2929 import java.io.IOException;
3030 import java.lang.reflect.Constructor;
3131 import java.lang.reflect.Modifier;
32 import java.time.Duration;
3233 import java.util.ArrayList;
3334 import java.util.Arrays;
3435 import java.util.Calendar;
5354 */
5455 @SuppressWarnings("deprecation") // deliberate use of deprecated code
5556 public class ObjectUtilsTest {
57 static final class CharSequenceComparator implements Comparator<CharSequence> {
58
59 @Override
60 public int compare(final CharSequence o1, final CharSequence o2) {
61 return o1.toString().compareTo(o2.toString());
62 }
63
64 }
65 /**
66 * String that is cloneable.
67 */
68 static final class CloneableString extends MutableObject<String> implements Cloneable {
69 private static final long serialVersionUID = 1L;
70 CloneableString(final String s) {
71 super(s);
72 }
73
74 @Override
75 public CloneableString clone() throws CloneNotSupportedException {
76 return (CloneableString) super.clone();
77 }
78 }
79 static final class NonComparableCharSequence implements CharSequence {
80 final String value;
81
82 /**
83 * Create a new NonComparableCharSequence instance.
84 *
85 * @param value the CharSequence value
86 */
87 NonComparableCharSequence(final String value) {
88 Validate.notNull(value);
89 this.value = value;
90 }
91
92 @Override
93 public char charAt(final int arg0) {
94 return value.charAt(arg0);
95 }
96
97 @Override
98 public int length() {
99 return value.length();
100 }
101
102 @Override
103 public CharSequence subSequence(final int arg0, final int arg1) {
104 return value.subSequence(arg0, arg1);
105 }
106
107 @Override
108 public String toString() {
109 return value;
110 }
111 }
112 /**
113 * String that is not cloneable.
114 */
115 static final class UncloneableString extends MutableObject<String> implements Cloneable {
116 private static final long serialVersionUID = 1L;
117 UncloneableString(final String s) {
118 super(s);
119 }
120 }
56121 private static final String FOO = "foo";
57122 private static final String BAR = "bar";
58 private static final String[] NON_EMPTY_ARRAY = new String[] { FOO, BAR, };
123 private static final String[] NON_EMPTY_ARRAY = { FOO, BAR, };
124
59125 private static final List<String> NON_EMPTY_LIST = Arrays.asList(NON_EMPTY_ARRAY);
126
60127 private static final Set<String> NON_EMPTY_SET = new HashSet<>(NON_EMPTY_LIST);
128
61129 private static final Map<String, String> NON_EMPTY_MAP = new HashMap<>();
130
62131 static {
63132 NON_EMPTY_MAP.put(FOO, BAR);
64 }
65
66 //-----------------------------------------------------------------------
67 @Test
68 public void testConstructor() {
69 assertNotNull(new ObjectUtils());
70 final Constructor<?>[] cons = ObjectUtils.class.getDeclaredConstructors();
71 assertEquals(1, cons.length);
72 assertTrue(Modifier.isPublic(cons[0].getModifiers()));
73 assertTrue(Modifier.isPublic(ObjectUtils.class.getModifiers()));
74 assertFalse(Modifier.isFinal(ObjectUtils.class.getModifiers()));
75 }
76
77 //-----------------------------------------------------------------------
78 @Test
79 public void testIsEmpty() {
80 assertTrue(ObjectUtils.isEmpty(null));
81 assertTrue(ObjectUtils.isEmpty(""));
82 assertTrue(ObjectUtils.isEmpty(new int[] {}));
83 assertTrue(ObjectUtils.isEmpty(Collections.emptyList()));
84 assertTrue(ObjectUtils.isEmpty(Collections.emptySet()));
85 assertTrue(ObjectUtils.isEmpty(Collections.emptyMap()));
86
87 assertFalse(ObjectUtils.isEmpty(" "));
88 assertFalse(ObjectUtils.isEmpty("ab"));
89 assertFalse(ObjectUtils.isEmpty(NON_EMPTY_ARRAY));
90 assertFalse(ObjectUtils.isEmpty(NON_EMPTY_LIST));
91 assertFalse(ObjectUtils.isEmpty(NON_EMPTY_SET));
92 assertFalse(ObjectUtils.isEmpty(NON_EMPTY_MAP));
93 }
94
95 @Test
96 public void testIsNotEmpty() {
97 assertFalse(ObjectUtils.isNotEmpty(null));
98 assertFalse(ObjectUtils.isNotEmpty(""));
99 assertFalse(ObjectUtils.isNotEmpty(new int[] {}));
100 assertFalse(ObjectUtils.isNotEmpty(Collections.emptyList()));
101 assertFalse(ObjectUtils.isNotEmpty(Collections.emptySet()));
102 assertFalse(ObjectUtils.isNotEmpty(Collections.emptyMap()));
103
104 assertTrue(ObjectUtils.isNotEmpty(" "));
105 assertTrue(ObjectUtils.isNotEmpty("ab"));
106 assertTrue(ObjectUtils.isNotEmpty(NON_EMPTY_ARRAY));
107 assertTrue(ObjectUtils.isNotEmpty(NON_EMPTY_LIST));
108 assertTrue(ObjectUtils.isNotEmpty(NON_EMPTY_SET));
109 assertTrue(ObjectUtils.isNotEmpty(NON_EMPTY_MAP));
110 }
111
112 //-----------------------------------------------------------------------
113 @Test
114 public void testDefaultIfNull() {
115 final Object o = FOO;
116 final Object dflt = BAR;
117 assertSame(dflt, ObjectUtils.defaultIfNull(null, dflt), "dflt was not returned when o was null");
118 assertSame(o, ObjectUtils.defaultIfNull(o, dflt), "dflt was returned when o was not null");
119 assertSame(dflt, ObjectUtils.getIfNull(null, () -> dflt), "dflt was not returned when o was null");
120 assertSame(o, ObjectUtils.getIfNull(o, () -> dflt), "dflt was returned when o was not null");
121 assertSame(o, ObjectUtils.getIfNull(FOO, () -> dflt), "dflt was returned when o was not null");
122 assertSame(o, ObjectUtils.getIfNull("foo", () -> dflt), "dflt was returned when o was not null");
123 final MutableInt callsCounter = new MutableInt(0);
124 final Supplier<Object> countingDefaultSupplier = () -> {
125 callsCounter.increment();
126 return dflt;
127 };
128 ObjectUtils.getIfNull(o, countingDefaultSupplier);
129 assertEquals(0, callsCounter.getValue());
130 ObjectUtils.getIfNull(null, countingDefaultSupplier);
131 assertEquals(1, callsCounter.getValue());
132 }
133
134 @Test
135 public void testFirstNonNull() {
136 assertEquals("", ObjectUtils.firstNonNull(null, ""));
137 final String firstNonNullGenerics = ObjectUtils.firstNonNull(null, null, "123", "456");
138 assertEquals("123", firstNonNullGenerics);
139 assertEquals("123", ObjectUtils.firstNonNull("123", null, "456", null));
140 assertSame(Boolean.TRUE, ObjectUtils.firstNonNull(Boolean.TRUE));
141
142 // Explicitly pass in an empty array of Object type to ensure compiler doesn't complain of unchecked generic array creation
143 assertNull(ObjectUtils.firstNonNull());
144
145 // Cast to Object in line below ensures compiler doesn't complain of unchecked generic array creation
146 assertNull(ObjectUtils.firstNonNull(null, null));
147
148 assertNull(ObjectUtils.firstNonNull((Object) null));
149 assertNull(ObjectUtils.firstNonNull((Object[]) null));
150 }
151
152 @Test
153 public void testGetFirstNonNull() {
154 // first non null
155 assertEquals("", ObjectUtils.getFirstNonNull(() -> null, () -> ""));
156 // first encountered value is used
157 assertEquals("1", ObjectUtils.getFirstNonNull(() -> null, () -> "1", () -> "2", () -> null));
158 assertEquals("123", ObjectUtils.getFirstNonNull(() -> "123", () -> null, () -> "456"));
159 // don't evaluate suppliers after first value is found
160 assertEquals("123", ObjectUtils.getFirstNonNull(() -> null, () -> "123", () -> fail("Supplier after first non-null value should not be evaluated")));
161 // supplier returning null and null supplier both result in null
162 assertNull(ObjectUtils.getFirstNonNull(null, () -> null));
163 // Explicitly pass in an empty array of Object type to ensure compiler doesn't complain of unchecked generic array creation
164 assertNull(ObjectUtils.getFirstNonNull());
165 // supplier is null
166 assertNull(ObjectUtils.getFirstNonNull((Supplier<Object>) null));
167 // varargs array itself is null
168 assertNull(ObjectUtils.getFirstNonNull((Supplier<Object>[]) null));
169 // test different types
170 assertEquals(1, ObjectUtils.getFirstNonNull(() -> null, () -> 1));
171 assertEquals(Boolean.TRUE, ObjectUtils.getFirstNonNull(() -> null, () -> Boolean.TRUE));
172 }
173
174 /**
175 * Tests {@link ObjectUtils#anyNull(Object...)}.
176 */
177 @Test
178 public void testAnyNull() {
179 assertTrue(ObjectUtils.anyNull((Object) null));
180 assertTrue(ObjectUtils.anyNull(null, null, null));
181 assertTrue(ObjectUtils.anyNull(null, FOO, BAR));
182 assertTrue(ObjectUtils.anyNull(FOO, BAR, null));
183 assertTrue(ObjectUtils.anyNull(FOO, BAR, null, FOO, BAR));
184
185 assertFalse(ObjectUtils.anyNull());
186 assertFalse(ObjectUtils.anyNull(FOO));
187 assertFalse(ObjectUtils.anyNull(FOO, BAR, 1, Boolean.TRUE, new Object(), new Object[]{}));
188 }
189
190 /**
191 * Tests {@link ObjectUtils#anyNotNull(Object...)}.
192 */
193 @Test
194 public void testAnyNotNull() {
195 assertFalse(ObjectUtils.anyNotNull());
196 assertFalse(ObjectUtils.anyNotNull((Object) null));
197 assertFalse(ObjectUtils.anyNotNull((Object[]) null));
198 assertFalse(ObjectUtils.anyNotNull(null, null, null));
199
200 assertTrue(ObjectUtils.anyNotNull(FOO));
201 assertTrue(ObjectUtils.anyNotNull(null, FOO, null));
202 assertTrue(ObjectUtils.anyNotNull(null, null, null, null, FOO, BAR));
203 }
204
205 /**
206 * Tests {@link ObjectUtils#allNull(Object...)}.
207 */
208 @Test
209 public void testAllNull() {
210 assertTrue(ObjectUtils.allNull());
211 assertTrue(ObjectUtils.allNull((Object) null));
212 assertTrue(ObjectUtils.allNull((Object[]) null));
213 assertTrue(ObjectUtils.allNull(null, null, null));
214
215 assertFalse(ObjectUtils.allNull(FOO));
216 assertFalse(ObjectUtils.allNull(null, FOO, null));
217 assertFalse(ObjectUtils.allNull(null, null, null, null, FOO, BAR));
218133 }
219134
220135 /**
234149 assertTrue(ObjectUtils.allNotNull(FOO, BAR, 1, Boolean.TRUE, new Object(), new Object[]{}));
235150 }
236151
237 //-----------------------------------------------------------------------
238 @Test
239 public void testEquals() {
240 assertTrue(ObjectUtils.equals(null, null), "ObjectUtils.equals(null, null) returned false");
241 assertTrue(!ObjectUtils.equals(FOO, null), "ObjectUtils.equals(\"foo\", null) returned true");
242 assertTrue(!ObjectUtils.equals(null, BAR), "ObjectUtils.equals(null, \"bar\") returned true");
243 assertTrue(!ObjectUtils.equals(FOO, BAR), "ObjectUtils.equals(\"foo\", \"bar\") returned true");
244 assertTrue(ObjectUtils.equals(FOO, FOO), "ObjectUtils.equals(\"foo\", \"foo\") returned false");
245 }
246
247 @Test
248 public void testNotEqual() {
249 assertFalse(ObjectUtils.notEqual(null, null), "ObjectUtils.notEqual(null, null) returned false");
250 assertTrue(ObjectUtils.notEqual(FOO, null), "ObjectUtils.notEqual(\"foo\", null) returned true");
251 assertTrue(ObjectUtils.notEqual(null, BAR), "ObjectUtils.notEqual(null, \"bar\") returned true");
252 assertTrue(ObjectUtils.notEqual(FOO, BAR), "ObjectUtils.notEqual(\"foo\", \"bar\") returned true");
253 assertFalse(ObjectUtils.notEqual(FOO, FOO), "ObjectUtils.notEqual(\"foo\", \"foo\") returned false");
254 }
255
256 @Test
257 public void testHashCode() {
258 assertEquals(0, ObjectUtils.hashCode(null));
259 assertEquals("a".hashCode(), ObjectUtils.hashCode("a"));
260 }
261
262 @Test
263 public void testHashCodeMulti_multiple_emptyArray() {
264 final Object[] array = new Object[0];
265 assertEquals(1, ObjectUtils.hashCodeMulti(array));
266 }
267
268 @Test
269 public void testHashCodeMulti_multiple_nullArray() {
270 final Object[] array = null;
271 assertEquals(1, ObjectUtils.hashCodeMulti(array));
272 }
273
274 @Test
275 public void testHashCodeMulti_multiple_likeList() {
276 final List<Object> list0 = new ArrayList<>(Collections.emptyList());
277 assertEquals(list0.hashCode(), ObjectUtils.hashCodeMulti());
278
279 final List<Object> list1 = new ArrayList<>(Collections.singletonList("a"));
280 assertEquals(list1.hashCode(), ObjectUtils.hashCodeMulti("a"));
281
282 final List<Object> list2 = new ArrayList<>(Arrays.asList("a", "b"));
283 assertEquals(list2.hashCode(), ObjectUtils.hashCodeMulti("a", "b"));
284
285 final List<Object> list3 = new ArrayList<>(Arrays.asList("a", "b", "c"));
286 assertEquals(list3.hashCode(), ObjectUtils.hashCodeMulti("a", "b", "c"));
287 }
288
289 @Test
290 public void testIdentityToStringStringBuffer() {
291 final Integer i = Integer.valueOf(45);
292 final String expected = "java.lang.Integer@" + Integer.toHexString(System.identityHashCode(i));
293
294 final StringBuffer buffer = new StringBuffer();
295 ObjectUtils.identityToString(buffer, i);
296 assertEquals(expected, buffer.toString());
297
298 assertThrows(NullPointerException.class, () -> ObjectUtils.identityToString((StringBuffer) null, "tmp"));
299 assertThrows(NullPointerException.class, () -> ObjectUtils.identityToString(new StringBuffer(), null));
300 }
301
302 @Test
303 public void testIdentityToStringObjectNull() {
304 assertNull(ObjectUtils.identityToString(null));
305 }
306
307 @Test
308 public void testIdentityToStringInteger() {
309 final Integer i = Integer.valueOf(90);
310 final String expected = "java.lang.Integer@" + Integer.toHexString(System.identityHashCode(i));
311
312 assertEquals(expected, ObjectUtils.identityToString(i));
313 }
314
315 @Test
316 public void testIdentityToStringString() {
317 assertEquals(
318 "java.lang.String@" + Integer.toHexString(System.identityHashCode(FOO)),
319 ObjectUtils.identityToString(FOO));
320 }
321
322 @Test
323 public void testIdentityToStringStringBuilder() {
324 final Integer i = Integer.valueOf(90);
325 final String expected = "java.lang.Integer@" + Integer.toHexString(System.identityHashCode(i));
326
327 final StringBuilder builder = new StringBuilder();
328 ObjectUtils.identityToString(builder, i);
329 assertEquals(expected, builder.toString());
330 }
331
332 @Test
333 public void testIdentityToStringStringBuilderInUse() {
334 final Integer i = Integer.valueOf(90);
335 final String expected = "ABC = java.lang.Integer@" + Integer.toHexString(System.identityHashCode(i));
336
337 final StringBuilder builder = new StringBuilder("ABC = ");
338 ObjectUtils.identityToString(builder, i);
339 assertEquals(expected, builder.toString());
340 }
341
342 @Test
343 public void testIdentityToStringStringBuilderNullValue() {
344 assertThrows(NullPointerException.class, () -> ObjectUtils.identityToString(new StringBuilder(), null));
345 }
346
347 @Test
348 public void testIdentityToStringStringBuilderNullStringBuilder() {
349 assertThrows(NullPointerException.class, () -> ObjectUtils.identityToString((StringBuilder) null, "tmp"));
350 }
351
352 @Test
353 public void testIdentityToStringStrBuilder() {
354 final Integer i = Integer.valueOf(102);
355 final String expected = "java.lang.Integer@" + Integer.toHexString(System.identityHashCode(i));
356
357 final StrBuilder builder = new StrBuilder();
358 ObjectUtils.identityToString(builder, i);
359 assertEquals(expected, builder.toString());
360
361 assertThrows(NullPointerException.class, () -> ObjectUtils.identityToString((StrBuilder) null, "tmp"));
362
363 assertThrows(NullPointerException.class, () -> ObjectUtils.identityToString(new StrBuilder(), null));
364 }
365
366 @Test
367 public void testIdentityToStringAppendable() throws IOException {
368 final Integer i = Integer.valueOf(121);
369 final String expected = "java.lang.Integer@" + Integer.toHexString(System.identityHashCode(i));
370
371 final Appendable appendable = new StringBuilder();
372 ObjectUtils.identityToString(appendable, i);
373 assertEquals(expected, appendable.toString());
374
375 assertThrows(NullPointerException.class, () -> ObjectUtils.identityToString((Appendable) null, "tmp"));
376
377 assertThrows(
378 NullPointerException.class,
379 () -> ObjectUtils.identityToString((Appendable) (new StringBuilder()), null));
380 }
381
382 @Test
383 public void testToString_Object() {
384 assertEquals("", ObjectUtils.toString(null) );
385 assertEquals(Boolean.TRUE.toString(), ObjectUtils.toString(Boolean.TRUE) );
386 }
387
388 @Test
389 public void testToString_ObjectString() {
390 assertEquals(BAR, ObjectUtils.toString(null, BAR) );
391 assertEquals(Boolean.TRUE.toString(), ObjectUtils.toString(Boolean.TRUE, BAR) );
392 }
393
394 @Test
395 public void testToString_SupplierString() {
396 assertEquals(null, ObjectUtils.toString(null, (Supplier<String>) null));
397 assertEquals(null, ObjectUtils.toString(null, () -> null));
398 // Pretend computing BAR is expensive.
399 assertEquals(BAR, ObjectUtils.toString(null, () -> BAR));
400 assertEquals(Boolean.TRUE.toString(), ObjectUtils.toString(Boolean.TRUE, () -> BAR));
401 }
402
403 @SuppressWarnings("cast") // 1 OK, because we are checking for code change
404 @Test
405 public void testNull() {
406 assertNotNull(ObjectUtils.NULL);
407 // 1 Check that NULL really is a Null i.e. the definition has not been changed
408 assertTrue(ObjectUtils.NULL instanceof ObjectUtils.Null);
409 assertSame(ObjectUtils.NULL, SerializationUtils.clone(ObjectUtils.NULL));
410 }
411
412 @Test
413 public void testMax() {
414 final Calendar calendar = Calendar.getInstance();
415 final Date nonNullComparable1 = calendar.getTime();
416 final Date nonNullComparable2 = calendar.getTime();
417 final String[] nullArray = null;
418
419 calendar.set( Calendar.YEAR, calendar.get( Calendar.YEAR ) -1 );
420 final Date minComparable = calendar.getTime();
421
422 assertNotSame( nonNullComparable1, nonNullComparable2 );
423
424 assertNull(ObjectUtils.max( (String) null ) );
425 assertNull(ObjectUtils.max( nullArray ) );
426 assertSame( nonNullComparable1, ObjectUtils.max( null, nonNullComparable1 ) );
427 assertSame( nonNullComparable1, ObjectUtils.max( nonNullComparable1, null ) );
428 assertSame( nonNullComparable1, ObjectUtils.max( null, nonNullComparable1, null ) );
429 assertSame( nonNullComparable1, ObjectUtils.max( nonNullComparable1, nonNullComparable2 ) );
430 assertSame( nonNullComparable2, ObjectUtils.max( nonNullComparable2, nonNullComparable1 ) );
431 assertSame( nonNullComparable1, ObjectUtils.max( nonNullComparable1, minComparable ) );
432 assertSame( nonNullComparable1, ObjectUtils.max( minComparable, nonNullComparable1 ) );
433 assertSame( nonNullComparable1, ObjectUtils.max( null, minComparable, null, nonNullComparable1 ) );
434
435 assertNull( ObjectUtils.max(null, null) );
436 }
437
438 @Test
439 public void testMin() {
440 final Calendar calendar = Calendar.getInstance();
441 final Date nonNullComparable1 = calendar.getTime();
442 final Date nonNullComparable2 = calendar.getTime();
443 final String[] nullArray = null;
444
445 calendar.set( Calendar.YEAR, calendar.get( Calendar.YEAR ) -1 );
446 final Date minComparable = calendar.getTime();
447
448 assertNotSame( nonNullComparable1, nonNullComparable2 );
449
450 assertNull(ObjectUtils.min( (String) null ) );
451 assertNull(ObjectUtils.min( nullArray ) );
452 assertSame( nonNullComparable1, ObjectUtils.min( null, nonNullComparable1 ) );
453 assertSame( nonNullComparable1, ObjectUtils.min( nonNullComparable1, null ) );
454 assertSame( nonNullComparable1, ObjectUtils.min( null, nonNullComparable1, null ) );
455 assertSame( nonNullComparable1, ObjectUtils.min( nonNullComparable1, nonNullComparable2 ) );
456 assertSame( nonNullComparable2, ObjectUtils.min( nonNullComparable2, nonNullComparable1 ) );
457 assertSame( minComparable, ObjectUtils.min( nonNullComparable1, minComparable ) );
458 assertSame( minComparable, ObjectUtils.min( minComparable, nonNullComparable1 ) );
459 assertSame( minComparable, ObjectUtils.min( null, nonNullComparable1, null, minComparable ) );
460
461 assertNull( ObjectUtils.min(null, null) );
462 }
463
464 /**
465 * Tests {@link ObjectUtils#compare(Comparable, Comparable, boolean)}.
466 */
467 @Test
468 public void testCompare() {
469 final Integer one = Integer.valueOf(1);
470 final Integer two = Integer.valueOf(2);
471 final Integer nullValue = null;
472
473 assertEquals(0, ObjectUtils.compare(nullValue, nullValue), "Null Null false");
474 assertEquals(0, ObjectUtils.compare(nullValue, nullValue, true), "Null Null true");
475
476 assertEquals(-1, ObjectUtils.compare(nullValue, one), "Null one false");
477 assertEquals(1, ObjectUtils.compare(nullValue, one, true), "Null one true");
478
479 assertEquals(1, ObjectUtils.compare(one, nullValue), "one Null false");
480 assertEquals(-1, ObjectUtils.compare(one, nullValue, true), "one Null true");
481
482 assertEquals(-1, ObjectUtils.compare(one, two), "one two false");
483 assertEquals(-1, ObjectUtils.compare(one, two, true), "one two true");
484 }
485
486 @Test
487 public void testMedian() {
488 assertEquals("foo", ObjectUtils.median("foo"));
489 assertEquals("bar", ObjectUtils.median("foo", "bar"));
490 assertEquals("baz", ObjectUtils.median("foo", "bar", "baz"));
491 assertEquals("baz", ObjectUtils.median("foo", "bar", "baz", "blah"));
492 assertEquals("blah", ObjectUtils.median("foo", "bar", "baz", "blah", "wah"));
493 assertEquals(Integer.valueOf(5),
494 ObjectUtils.median(Integer.valueOf(1), Integer.valueOf(5), Integer.valueOf(10)));
495 assertEquals(
496 Integer.valueOf(7),
497 ObjectUtils.median(Integer.valueOf(5), Integer.valueOf(6), Integer.valueOf(7), Integer.valueOf(8),
498 Integer.valueOf(9)));
499 assertEquals(Integer.valueOf(6),
500 ObjectUtils.median(Integer.valueOf(5), Integer.valueOf(6), Integer.valueOf(7), Integer.valueOf(8)));
501 }
502
503 @Test
504 public void testMedian_nullItems() {
505 assertThrows(NullPointerException.class, () -> ObjectUtils.median((String[]) null));
506 }
507
508 @Test
509 public void testMedian_emptyItems() {
510 assertThrows(IllegalArgumentException.class, ObjectUtils::<String>median);
152 /**
153 * Tests {@link ObjectUtils#allNull(Object...)}.
154 */
155 @Test
156 public void testAllNull() {
157 assertTrue(ObjectUtils.allNull());
158 assertTrue(ObjectUtils.allNull((Object) null));
159 assertTrue(ObjectUtils.allNull((Object[]) null));
160 assertTrue(ObjectUtils.allNull(null, null, null));
161
162 assertFalse(ObjectUtils.allNull(FOO));
163 assertFalse(ObjectUtils.allNull(null, FOO, null));
164 assertFalse(ObjectUtils.allNull(null, null, null, null, FOO, BAR));
165 }
166
167 /**
168 * Tests {@link ObjectUtils#anyNotNull(Object...)}.
169 */
170 @Test
171 public void testAnyNotNull() {
172 assertFalse(ObjectUtils.anyNotNull());
173 assertFalse(ObjectUtils.anyNotNull((Object) null));
174 assertFalse(ObjectUtils.anyNotNull((Object[]) null));
175 assertFalse(ObjectUtils.anyNotNull(null, null, null));
176
177 assertTrue(ObjectUtils.anyNotNull(FOO));
178 assertTrue(ObjectUtils.anyNotNull(null, FOO, null));
179 assertTrue(ObjectUtils.anyNotNull(null, null, null, null, FOO, BAR));
180 }
181
182 /**
183 * Tests {@link ObjectUtils#anyNull(Object...)}.
184 */
185 @Test
186 public void testAnyNull() {
187 assertTrue(ObjectUtils.anyNull((Object) null));
188 assertTrue(ObjectUtils.anyNull(null, null, null));
189 assertTrue(ObjectUtils.anyNull(null, FOO, BAR));
190 assertTrue(ObjectUtils.anyNull(FOO, BAR, null));
191 assertTrue(ObjectUtils.anyNull(FOO, BAR, null, FOO, BAR));
192
193 assertFalse(ObjectUtils.anyNull());
194 assertFalse(ObjectUtils.anyNull(FOO));
195 assertFalse(ObjectUtils.anyNull(FOO, BAR, 1, Boolean.TRUE, new Object(), new Object[]{}));
196 }
197
198 /**
199 * Tests {@link ObjectUtils#clone(Object)} with a cloneable object.
200 */
201 @Test
202 public void testCloneOfCloneable() {
203 final CloneableString string = new CloneableString("apache");
204 final CloneableString stringClone = ObjectUtils.clone(string);
205 assertEquals("apache", stringClone.getValue());
206 }
207
208 /**
209 * Tests {@link ObjectUtils#clone(Object)} with a not cloneable object.
210 */
211 @Test
212 public void testCloneOfNotCloneable() {
213 final String string = "apache";
214 assertNull(ObjectUtils.clone(string));
215 }
216
217 /**
218 * Tests {@link ObjectUtils#clone(Object)} with an array of primitives.
219 */
220 @Test
221 public void testCloneOfPrimitiveArray() {
222 assertArrayEquals(new int[]{1}, ObjectUtils.clone(new int[]{1}));
223 }
224
225 /**
226 * Tests {@link ObjectUtils#clone(Object)} with an object array.
227 */
228 @Test
229 public void testCloneOfStringArray() {
230 assertTrue(Arrays.deepEquals(
231 new String[]{"string"}, ObjectUtils.clone(new String[]{"string"})));
232 }
233
234 /**
235 * Tests {@link ObjectUtils#clone(Object)} with an uncloneable object.
236 */
237 @Test
238 public void testCloneOfUncloneable() {
239 final UncloneableString string = new UncloneableString("apache");
240 final CloneFailedException e = assertThrows(CloneFailedException.class, () -> ObjectUtils.clone(string));
241 assertEquals(NoSuchMethodException.class, e.getCause().getClass());
511242 }
512243
513244 @Test
526257 }
527258
528259 @Test
260 public void testComparatorMedian_emptyItems() {
261 assertThrows(IllegalArgumentException.class, () -> ObjectUtils.median(new CharSequenceComparator()));
262 }
263
264 @Test
529265 public void testComparatorMedian_nullComparator() {
530266 assertThrows(NullPointerException.class,
531267 () -> ObjectUtils.median((Comparator<CharSequence>) null, new NonComparableCharSequence("foo")));
537273 () -> ObjectUtils.median(new CharSequenceComparator(), (CharSequence[]) null));
538274 }
539275
540 @Test
541 public void testComparatorMedian_emptyItems() {
542 assertThrows(IllegalArgumentException.class, () -> ObjectUtils.median(new CharSequenceComparator()));
543 }
544
545 @Test
546 public void testMode() {
547 assertNull(ObjectUtils.mode((Object[]) null));
548 assertNull(ObjectUtils.mode());
549 assertNull(ObjectUtils.mode("foo", "bar", "baz"));
550 assertNull(ObjectUtils.mode("foo", "bar", "baz", "foo", "bar"));
551 assertEquals("foo", ObjectUtils.mode("foo", "bar", "baz", "foo"));
552 assertEquals(Integer.valueOf(9),
553 ObjectUtils.mode("foo", "bar", "baz", Integer.valueOf(9), Integer.valueOf(10), Integer.valueOf(9)));
554 }
555
556 /**
557 * Tests {@link ObjectUtils#clone(Object)} with a cloneable object.
558 */
559 @Test
560 public void testCloneOfCloneable() {
561 final CloneableString string = new CloneableString("apache");
562 final CloneableString stringClone = ObjectUtils.clone(string);
563 assertEquals("apache", stringClone.getValue());
564 }
565
566 /**
567 * Tests {@link ObjectUtils#clone(Object)} with a not cloneable object.
568 */
569 @Test
570 public void testCloneOfNotCloneable() {
571 final String string = new String("apache");
572 assertNull(ObjectUtils.clone(string));
573 }
574
575 /**
576 * Tests {@link ObjectUtils#clone(Object)} with an uncloneable object.
577 */
578 @Test
579 public void testCloneOfUncloneable() {
580 final UncloneableString string = new UncloneableString("apache");
581 final CloneFailedException e = assertThrows(CloneFailedException.class, () -> ObjectUtils.clone(string));
582 assertEquals(NoSuchMethodException.class, e.getCause().getClass());
583 }
584
585 /**
586 * Tests {@link ObjectUtils#clone(Object)} with an object array.
587 */
588 @Test
589 public void testCloneOfStringArray() {
590 assertTrue(Arrays.deepEquals(
591 new String[]{"string"}, ObjectUtils.clone(new String[]{"string"})));
592 }
593
594 /**
595 * Tests {@link ObjectUtils#clone(Object)} with an array of primitives.
596 */
597 @Test
598 public void testCloneOfPrimitiveArray() {
599 assertArrayEquals(new int[]{1}, ObjectUtils.clone(new int[]{1}));
600 }
601
602 /**
603 * Tests {@link ObjectUtils#cloneIfPossible(Object)} with a cloneable object.
604 */
605 @Test
606 public void testPossibleCloneOfCloneable() {
607 final CloneableString string = new CloneableString("apache");
608 final CloneableString stringClone = ObjectUtils.cloneIfPossible(string);
609 assertEquals("apache", stringClone.getValue());
610 }
611
612 /**
613 * Tests {@link ObjectUtils#cloneIfPossible(Object)} with a not cloneable object.
614 */
615 @Test
616 public void testPossibleCloneOfNotCloneable() {
617 final String string = new String("apache");
618 assertSame(string, ObjectUtils.cloneIfPossible(string));
619 }
620
621 /**
622 * Tests {@link ObjectUtils#cloneIfPossible(Object)} with an uncloneable object.
623 */
624 @Test
625 public void testPossibleCloneOfUncloneable() {
626 final UncloneableString string = new UncloneableString("apache");
627 final CloneFailedException e = assertThrows(CloneFailedException.class, () -> ObjectUtils.cloneIfPossible(string));
628 assertEquals(NoSuchMethodException.class, e.getCause().getClass());
276 /**
277 * Tests {@link ObjectUtils#compare(Comparable, Comparable, boolean)}.
278 */
279 @Test
280 public void testCompare() {
281 final Integer one = Integer.valueOf(1);
282 final Integer two = Integer.valueOf(2);
283 final Integer nullValue = null;
284
285 assertEquals(0, ObjectUtils.compare(nullValue, nullValue), "Null Null false");
286 assertEquals(0, ObjectUtils.compare(nullValue, nullValue, true), "Null Null true");
287
288 assertEquals(-1, ObjectUtils.compare(nullValue, one), "Null one false");
289 assertEquals(1, ObjectUtils.compare(nullValue, one, true), "Null one true");
290
291 assertEquals(1, ObjectUtils.compare(one, nullValue), "one Null false");
292 assertEquals(-1, ObjectUtils.compare(one, nullValue, true), "one Null true");
293
294 assertEquals(-1, ObjectUtils.compare(one, two), "one two false");
295 assertEquals(-1, ObjectUtils.compare(one, two, true), "one two true");
629296 }
630297
631298 @Test
695362 "CONST_SHORT(32768): IllegalArgumentException should have been thrown.");
696363 }
697364
698 /**
699 * String that is cloneable.
700 */
701 static final class CloneableString extends MutableObject<String> implements Cloneable {
702 private static final long serialVersionUID = 1L;
703 CloneableString(final String s) {
704 super(s);
705 }
706
707 @Override
708 public CloneableString clone() throws CloneNotSupportedException {
709 return (CloneableString) super.clone();
710 }
711 }
712
713 /**
714 * String that is not cloneable.
715 */
716 static final class UncloneableString extends MutableObject<String> implements Cloneable {
717 private static final long serialVersionUID = 1L;
718 UncloneableString(final String s) {
719 super(s);
720 }
721 }
722
723 static final class NonComparableCharSequence implements CharSequence {
724 final String value;
725
726 /**
727 * Create a new NonComparableCharSequence instance.
728 *
729 * @param value
730 */
731 NonComparableCharSequence(final String value) {
732 super();
733 Validate.notNull(value);
734 this.value = value;
735 }
736
737 @Override
738 public char charAt(final int arg0) {
739 return value.charAt(arg0);
740 }
741
742 @Override
743 public int length() {
744 return value.length();
745 }
746
747 @Override
748 public CharSequence subSequence(final int arg0, final int arg1) {
749 return value.subSequence(arg0, arg1);
750 }
751
752 @Override
753 public String toString() {
754 return value;
755 }
756 }
757
758 static final class CharSequenceComparator implements Comparator<CharSequence> {
759
760 @Override
761 public int compare(final CharSequence o1, final CharSequence o2) {
762 return o1.toString().compareTo(o2.toString());
763 }
764
365 @Test
366 public void testConstructor() {
367 assertNotNull(new ObjectUtils());
368 final Constructor<?>[] cons = ObjectUtils.class.getDeclaredConstructors();
369 assertEquals(1, cons.length);
370 assertTrue(Modifier.isPublic(cons[0].getModifiers()));
371 assertTrue(Modifier.isPublic(ObjectUtils.class.getModifiers()));
372 assertFalse(Modifier.isFinal(ObjectUtils.class.getModifiers()));
373 }
374
375 @Test
376 public void testDefaultIfNull() {
377 final Object o = FOO;
378 final Object dflt = BAR;
379 assertSame(dflt, ObjectUtils.defaultIfNull(null, dflt), "dflt was not returned when o was null");
380 assertSame(o, ObjectUtils.defaultIfNull(o, dflt), "dflt was returned when o was not null");
381 assertSame(dflt, ObjectUtils.getIfNull(null, () -> dflt), "dflt was not returned when o was null");
382 assertSame(o, ObjectUtils.getIfNull(o, () -> dflt), "dflt was returned when o was not null");
383 assertSame(o, ObjectUtils.getIfNull(FOO, () -> dflt), "dflt was returned when o was not null");
384 assertSame(o, ObjectUtils.getIfNull("foo", () -> dflt), "dflt was returned when o was not null");
385 final MutableInt callsCounter = new MutableInt(0);
386 final Supplier<Object> countingDefaultSupplier = () -> {
387 callsCounter.increment();
388 return dflt;
389 };
390 ObjectUtils.getIfNull(o, countingDefaultSupplier);
391 assertEquals(0, callsCounter.getValue());
392 ObjectUtils.getIfNull(null, countingDefaultSupplier);
393 assertEquals(1, callsCounter.getValue());
394 }
395
396 @Test
397 public void testEquals() {
398 assertTrue(ObjectUtils.equals(null, null), "ObjectUtils.equals(null, null) returned false");
399 assertTrue(!ObjectUtils.equals(FOO, null), "ObjectUtils.equals(\"foo\", null) returned true");
400 assertTrue(!ObjectUtils.equals(null, BAR), "ObjectUtils.equals(null, \"bar\") returned true");
401 assertTrue(!ObjectUtils.equals(FOO, BAR), "ObjectUtils.equals(\"foo\", \"bar\") returned true");
402 assertTrue(ObjectUtils.equals(FOO, FOO), "ObjectUtils.equals(\"foo\", \"foo\") returned false");
403 }
404
405 @Test
406 public void testFirstNonNull() {
407 assertEquals("", ObjectUtils.firstNonNull(null, ""));
408 final String firstNonNullGenerics = ObjectUtils.firstNonNull(null, null, "123", "456");
409 assertEquals("123", firstNonNullGenerics);
410 assertEquals("123", ObjectUtils.firstNonNull("123", null, "456", null));
411 assertSame(Boolean.TRUE, ObjectUtils.firstNonNull(Boolean.TRUE));
412
413 // Explicitly pass in an empty array of Object type to ensure compiler doesn't complain of unchecked generic array creation
414 assertNull(ObjectUtils.firstNonNull());
415
416 // Cast to Object in line below ensures compiler doesn't complain of unchecked generic array creation
417 assertNull(ObjectUtils.firstNonNull(null, null));
418
419 assertNull(ObjectUtils.firstNonNull((Object) null));
420 assertNull(ObjectUtils.firstNonNull((Object[]) null));
421 }
422
423 @Test
424 public void testGetClass() {
425 final String[] newArray = ArrayUtils.EMPTY_STRING_ARRAY;
426 // No type-cast required.
427 final Class<String[]> cls = ObjectUtils.getClass(newArray);
428 assertEquals(String[].class, cls);
429 assertNull(ObjectUtils.getClass(null));
430 }
431
432 @Test
433 public void testGetFirstNonNull() {
434 // first non null
435 assertEquals("", ObjectUtils.getFirstNonNull(() -> null, () -> ""));
436 // first encountered value is used
437 assertEquals("1", ObjectUtils.getFirstNonNull(() -> null, () -> "1", () -> "2", () -> null));
438 assertEquals("123", ObjectUtils.getFirstNonNull(() -> "123", () -> null, () -> "456"));
439 // don't evaluate suppliers after first value is found
440 assertEquals("123", ObjectUtils.getFirstNonNull(() -> null, () -> "123", () -> fail("Supplier after first non-null value should not be evaluated")));
441 // supplier returning null and null supplier both result in null
442 assertNull(ObjectUtils.getFirstNonNull(null, () -> null));
443 // Explicitly pass in an empty array of Object type to ensure compiler doesn't complain of unchecked generic array creation
444 assertNull(ObjectUtils.getFirstNonNull());
445 // supplier is null
446 assertNull(ObjectUtils.getFirstNonNull((Supplier<Object>) null));
447 // varargs array itself is null
448 assertNull(ObjectUtils.getFirstNonNull((Supplier<Object>[]) null));
449 // test different types
450 assertEquals(1, ObjectUtils.getFirstNonNull(() -> null, () -> 1));
451 assertEquals(Boolean.TRUE, ObjectUtils.getFirstNonNull(() -> null, () -> Boolean.TRUE));
452 }
453
454 @Test
455 public void testHashCode() {
456 assertEquals(0, ObjectUtils.hashCode(null));
457 assertEquals("a".hashCode(), ObjectUtils.hashCode("a"));
458 }
459
460 @Test
461 public void testHashCodeMulti_multiple_emptyArray() {
462 final Object[] array = {};
463 assertEquals(1, ObjectUtils.hashCodeMulti(array));
464 }
465
466 @Test
467 public void testHashCodeMulti_multiple_likeList() {
468 final List<Object> list0 = new ArrayList<>(Collections.emptyList());
469 assertEquals(list0.hashCode(), ObjectUtils.hashCodeMulti());
470
471 final List<Object> list1 = new ArrayList<>(Collections.singletonList("a"));
472 assertEquals(list1.hashCode(), ObjectUtils.hashCodeMulti("a"));
473
474 final List<Object> list2 = new ArrayList<>(Arrays.asList("a", "b"));
475 assertEquals(list2.hashCode(), ObjectUtils.hashCodeMulti("a", "b"));
476
477 final List<Object> list3 = new ArrayList<>(Arrays.asList("a", "b", "c"));
478 assertEquals(list3.hashCode(), ObjectUtils.hashCodeMulti("a", "b", "c"));
479 }
480
481 @Test
482 public void testHashCodeMulti_multiple_nullArray() {
483 final Object[] array = null;
484 assertEquals(1, ObjectUtils.hashCodeMulti(array));
485 }
486
487 @Test
488 public void testIdentityToStringAppendable() throws IOException {
489 final Integer i = Integer.valueOf(121);
490 final String expected = "java.lang.Integer@" + Integer.toHexString(System.identityHashCode(i));
491
492 final Appendable appendable = new StringBuilder();
493 ObjectUtils.identityToString(appendable, i);
494 assertEquals(expected, appendable.toString());
495
496 assertThrows(NullPointerException.class, () -> ObjectUtils.identityToString((Appendable) null, "tmp"));
497
498 assertThrows(
499 NullPointerException.class,
500 () -> ObjectUtils.identityToString((Appendable) (new StringBuilder()), null));
501 }
502
503 @Test
504 public void testIdentityToStringInteger() {
505 final Integer i = Integer.valueOf(90);
506 final String expected = "java.lang.Integer@" + Integer.toHexString(System.identityHashCode(i));
507
508 assertEquals(expected, ObjectUtils.identityToString(i));
509 }
510
511 @Test
512 public void testIdentityToStringObjectNull() {
513 assertNull(ObjectUtils.identityToString(null));
514 }
515
516 @Test
517 public void testIdentityToStringStrBuilder() {
518 final Integer i = Integer.valueOf(102);
519 final String expected = "java.lang.Integer@" + Integer.toHexString(System.identityHashCode(i));
520
521 final StrBuilder builder = new StrBuilder();
522 ObjectUtils.identityToString(builder, i);
523 assertEquals(expected, builder.toString());
524
525 assertThrows(NullPointerException.class, () -> ObjectUtils.identityToString((StrBuilder) null, "tmp"));
526
527 assertThrows(NullPointerException.class, () -> ObjectUtils.identityToString(new StrBuilder(), null));
528 }
529
530 @Test
531 public void testIdentityToStringString() {
532 assertEquals(
533 "java.lang.String@" + Integer.toHexString(System.identityHashCode(FOO)),
534 ObjectUtils.identityToString(FOO));
535 }
536
537 @Test
538 public void testIdentityToStringStringBuffer() {
539 final Integer i = Integer.valueOf(45);
540 final String expected = "java.lang.Integer@" + Integer.toHexString(System.identityHashCode(i));
541
542 final StringBuffer buffer = new StringBuffer();
543 ObjectUtils.identityToString(buffer, i);
544 assertEquals(expected, buffer.toString());
545
546 assertThrows(NullPointerException.class, () -> ObjectUtils.identityToString((StringBuffer) null, "tmp"));
547 assertThrows(NullPointerException.class, () -> ObjectUtils.identityToString(new StringBuffer(), null));
548 }
549
550 @Test
551 public void testIdentityToStringStringBuilder() {
552 final Integer i = Integer.valueOf(90);
553 final String expected = "java.lang.Integer@" + Integer.toHexString(System.identityHashCode(i));
554
555 final StringBuilder builder = new StringBuilder();
556 ObjectUtils.identityToString(builder, i);
557 assertEquals(expected, builder.toString());
558 }
559
560 @Test
561 public void testIdentityToStringStringBuilderInUse() {
562 final Integer i = Integer.valueOf(90);
563 final String expected = "ABC = java.lang.Integer@" + Integer.toHexString(System.identityHashCode(i));
564
565 final StringBuilder builder = new StringBuilder("ABC = ");
566 ObjectUtils.identityToString(builder, i);
567 assertEquals(expected, builder.toString());
568 }
569
570 @Test
571 public void testIdentityToStringStringBuilderNullStringBuilder() {
572 assertThrows(NullPointerException.class, () -> ObjectUtils.identityToString((StringBuilder) null, "tmp"));
573 }
574
575 @Test
576 public void testIdentityToStringStringBuilderNullValue() {
577 assertThrows(NullPointerException.class, () -> ObjectUtils.identityToString(new StringBuilder(), null));
578 }
579
580 @Test
581 public void testIsEmpty() {
582 assertTrue(ObjectUtils.isEmpty(null));
583 assertTrue(ObjectUtils.isEmpty(""));
584 assertTrue(ObjectUtils.isEmpty(new int[] {}));
585 assertTrue(ObjectUtils.isEmpty(Collections.emptyList()));
586 assertTrue(ObjectUtils.isEmpty(Collections.emptySet()));
587 assertTrue(ObjectUtils.isEmpty(Collections.emptyMap()));
588
589 assertFalse(ObjectUtils.isEmpty(" "));
590 assertFalse(ObjectUtils.isEmpty("ab"));
591 assertFalse(ObjectUtils.isEmpty(NON_EMPTY_ARRAY));
592 assertFalse(ObjectUtils.isEmpty(NON_EMPTY_LIST));
593 assertFalse(ObjectUtils.isEmpty(NON_EMPTY_SET));
594 assertFalse(ObjectUtils.isEmpty(NON_EMPTY_MAP));
595 }
596
597 @Test
598 public void testIsNotEmpty() {
599 assertFalse(ObjectUtils.isNotEmpty(null));
600 assertFalse(ObjectUtils.isNotEmpty(""));
601 assertFalse(ObjectUtils.isNotEmpty(new int[] {}));
602 assertFalse(ObjectUtils.isNotEmpty(Collections.emptyList()));
603 assertFalse(ObjectUtils.isNotEmpty(Collections.emptySet()));
604 assertFalse(ObjectUtils.isNotEmpty(Collections.emptyMap()));
605
606 assertTrue(ObjectUtils.isNotEmpty(" "));
607 assertTrue(ObjectUtils.isNotEmpty("ab"));
608 assertTrue(ObjectUtils.isNotEmpty(NON_EMPTY_ARRAY));
609 assertTrue(ObjectUtils.isNotEmpty(NON_EMPTY_LIST));
610 assertTrue(ObjectUtils.isNotEmpty(NON_EMPTY_SET));
611 assertTrue(ObjectUtils.isNotEmpty(NON_EMPTY_MAP));
612 }
613
614 @Test
615 public void testMax() {
616 final Calendar calendar = Calendar.getInstance();
617 final Date nonNullComparable1 = calendar.getTime();
618 final Date nonNullComparable2 = calendar.getTime();
619 final String[] nullArray = null;
620
621 calendar.set( Calendar.YEAR, calendar.get( Calendar.YEAR ) -1 );
622 final Date minComparable = calendar.getTime();
623
624 assertNotSame( nonNullComparable1, nonNullComparable2 );
625
626 assertNull(ObjectUtils.max( (String) null ) );
627 assertNull(ObjectUtils.max( nullArray ) );
628 assertSame( nonNullComparable1, ObjectUtils.max( null, nonNullComparable1 ) );
629 assertSame( nonNullComparable1, ObjectUtils.max( nonNullComparable1, null ) );
630 assertSame( nonNullComparable1, ObjectUtils.max( null, nonNullComparable1, null ) );
631 assertSame( nonNullComparable1, ObjectUtils.max( nonNullComparable1, nonNullComparable2 ) );
632 assertSame( nonNullComparable2, ObjectUtils.max( nonNullComparable2, nonNullComparable1 ) );
633 assertSame( nonNullComparable1, ObjectUtils.max( nonNullComparable1, minComparable ) );
634 assertSame( nonNullComparable1, ObjectUtils.max( minComparable, nonNullComparable1 ) );
635 assertSame( nonNullComparable1, ObjectUtils.max( null, minComparable, null, nonNullComparable1 ) );
636
637 assertNull( ObjectUtils.max(null, null) );
638 }
639
640 @Test
641 public void testMedian() {
642 assertEquals("foo", ObjectUtils.median("foo"));
643 assertEquals("bar", ObjectUtils.median("foo", "bar"));
644 assertEquals("baz", ObjectUtils.median("foo", "bar", "baz"));
645 assertEquals("baz", ObjectUtils.median("foo", "bar", "baz", "blah"));
646 assertEquals("blah", ObjectUtils.median("foo", "bar", "baz", "blah", "wah"));
647 assertEquals(Integer.valueOf(5),
648 ObjectUtils.median(Integer.valueOf(1), Integer.valueOf(5), Integer.valueOf(10)));
649 assertEquals(
650 Integer.valueOf(7),
651 ObjectUtils.median(Integer.valueOf(5), Integer.valueOf(6), Integer.valueOf(7), Integer.valueOf(8),
652 Integer.valueOf(9)));
653 assertEquals(Integer.valueOf(6),
654 ObjectUtils.median(Integer.valueOf(5), Integer.valueOf(6), Integer.valueOf(7), Integer.valueOf(8)));
655 }
656
657 @Test
658 public void testMedian_emptyItems() {
659 assertThrows(IllegalArgumentException.class, ObjectUtils::<String>median);
660 }
661
662 @Test
663 public void testMedian_nullItems() {
664 assertThrows(NullPointerException.class, () -> ObjectUtils.median((String[]) null));
665 }
666
667 @Test
668 public void testMin() {
669 final Calendar calendar = Calendar.getInstance();
670 final Date nonNullComparable1 = calendar.getTime();
671 final Date nonNullComparable2 = calendar.getTime();
672 final String[] nullArray = null;
673
674 calendar.set( Calendar.YEAR, calendar.get( Calendar.YEAR ) -1 );
675 final Date minComparable = calendar.getTime();
676
677 assertNotSame( nonNullComparable1, nonNullComparable2 );
678
679 assertNull(ObjectUtils.min( (String) null ) );
680 assertNull(ObjectUtils.min( nullArray ) );
681 assertSame( nonNullComparable1, ObjectUtils.min( null, nonNullComparable1 ) );
682 assertSame( nonNullComparable1, ObjectUtils.min( nonNullComparable1, null ) );
683 assertSame( nonNullComparable1, ObjectUtils.min( null, nonNullComparable1, null ) );
684 assertSame( nonNullComparable1, ObjectUtils.min( nonNullComparable1, nonNullComparable2 ) );
685 assertSame( nonNullComparable2, ObjectUtils.min( nonNullComparable2, nonNullComparable1 ) );
686 assertSame( minComparable, ObjectUtils.min( nonNullComparable1, minComparable ) );
687 assertSame( minComparable, ObjectUtils.min( minComparable, nonNullComparable1 ) );
688 assertSame( minComparable, ObjectUtils.min( null, nonNullComparable1, null, minComparable ) );
689
690 assertNull( ObjectUtils.min(null, null) );
691 }
692
693 @Test
694 public void testMode() {
695 assertNull(ObjectUtils.mode((Object[]) null));
696 assertNull(ObjectUtils.mode());
697 assertNull(ObjectUtils.mode("foo", "bar", "baz"));
698 assertNull(ObjectUtils.mode("foo", "bar", "baz", "foo", "bar"));
699 assertEquals("foo", ObjectUtils.mode("foo", "bar", "baz", "foo"));
700 assertEquals(Integer.valueOf(9),
701 ObjectUtils.mode("foo", "bar", "baz", Integer.valueOf(9), Integer.valueOf(10), Integer.valueOf(9)));
702 }
703
704 @Test
705 public void testNotEqual() {
706 assertFalse(ObjectUtils.notEqual(null, null), "ObjectUtils.notEqual(null, null) returned false");
707 assertTrue(ObjectUtils.notEqual(FOO, null), "ObjectUtils.notEqual(\"foo\", null) returned true");
708 assertTrue(ObjectUtils.notEqual(null, BAR), "ObjectUtils.notEqual(null, \"bar\") returned true");
709 assertTrue(ObjectUtils.notEqual(FOO, BAR), "ObjectUtils.notEqual(\"foo\", \"bar\") returned true");
710 assertFalse(ObjectUtils.notEqual(FOO, FOO), "ObjectUtils.notEqual(\"foo\", \"foo\") returned false");
711 }
712
713 @SuppressWarnings("cast") // 1 OK, because we are checking for code change
714 @Test
715 public void testNull() {
716 assertNotNull(ObjectUtils.NULL);
717 // 1 Check that NULL really is a Null i.e. the definition has not been changed
718 assertTrue(ObjectUtils.NULL instanceof ObjectUtils.Null);
719 assertSame(ObjectUtils.NULL, SerializationUtils.clone(ObjectUtils.NULL));
720 }
721
722 /**
723 * Tests {@link ObjectUtils#cloneIfPossible(Object)} with a cloneable object.
724 */
725 @Test
726 public void testPossibleCloneOfCloneable() {
727 final CloneableString string = new CloneableString("apache");
728 final CloneableString stringClone = ObjectUtils.cloneIfPossible(string);
729 assertEquals("apache", stringClone.getValue());
730 }
731
732 /**
733 * Tests {@link ObjectUtils#cloneIfPossible(Object)} with a not cloneable object.
734 */
735 @Test
736 public void testPossibleCloneOfNotCloneable() {
737 final String string = "apache";
738 assertSame(string, ObjectUtils.cloneIfPossible(string));
739 }
740
741 /**
742 * Tests {@link ObjectUtils#cloneIfPossible(Object)} with an uncloneable object.
743 */
744 @Test
745 public void testPossibleCloneOfUncloneable() {
746 final UncloneableString string = new UncloneableString("apache");
747 final CloneFailedException e = assertThrows(CloneFailedException.class,
748 () -> ObjectUtils.cloneIfPossible(string));
749 assertEquals(NoSuchMethodException.class, e.getCause().getClass());
750 }
751
752 @Test
753 public void testRequireNonEmpty() {
754 assertEquals("foo", ObjectUtils.requireNonEmpty("foo"));
755 assertEquals("foo", ObjectUtils.requireNonEmpty("foo", "foo"));
756 //
757 assertThrows(NullPointerException.class, () -> ObjectUtils.requireNonEmpty(null));
758 assertThrows(NullPointerException.class, () -> ObjectUtils.requireNonEmpty(null, "foo"));
759 //
760 assertThrows(IllegalArgumentException.class, () -> ObjectUtils.requireNonEmpty(""));
761 assertThrows(IllegalArgumentException.class, () -> ObjectUtils.requireNonEmpty("", "foo"));
762 }
763
764 @Test
765 public void testToString_Object() {
766 assertEquals("", ObjectUtils.toString(null) );
767 assertEquals(Boolean.TRUE.toString(), ObjectUtils.toString(Boolean.TRUE) );
768 }
769
770 @Test
771 public void testToString_ObjectString() {
772 assertEquals(BAR, ObjectUtils.toString(null, BAR) );
773 assertEquals(Boolean.TRUE.toString(), ObjectUtils.toString(Boolean.TRUE, BAR) );
774 }
775
776 @Test
777 public void testToString_SupplierString() {
778 assertEquals(null, ObjectUtils.toString(null, (Supplier<String>) null));
779 assertEquals(null, ObjectUtils.toString(null, () -> null));
780 // Pretend computing BAR is expensive.
781 assertEquals(BAR, ObjectUtils.toString(null, () -> BAR));
782 assertEquals(Boolean.TRUE.toString(), ObjectUtils.toString(Boolean.TRUE, () -> BAR));
783 }
784
785 @Test
786 public void testWaitDuration() {
787 assertThrows(IllegalMonitorStateException.class, () -> ObjectUtils.wait(new Object(), Duration.ZERO));
765788 }
766789
767790 }
4040 */
4141 public class RandomStringUtilsTest {
4242
43 //-----------------------------------------------------------------------
4443 @Test
4544 public void testConstructor() {
4645 assertNotNull(new RandomStringUtils());
5150 assertFalse(Modifier.isFinal(RandomStringUtils.class.getModifiers()));
5251 }
5352
54 //-----------------------------------------------------------------------
5553 /**
5654 * Test the implementation
5755 */
141139 assertEquals(50, r2.length(), "random(50) length");
142140 assertTrue(!r1.equals(r2), "!r1.equals(r2)");
143141
144 final long seed = System.currentTimeMillis();
145 r1 = RandomStringUtils.random(50, 0, 0, true, true, null, new Random(seed));
146 r2 = RandomStringUtils.random(50, 0, 0, true, true, null, new Random(seed));
142 final long seedMillis = System.currentTimeMillis();
143 r1 = RandomStringUtils.random(50, 0, 0, true, true, null, new Random(seedMillis));
144 r2 = RandomStringUtils.random(50, 0, 0, true, true, null, new Random(seedMillis));
147145 assertEquals(r1, r2, "r1.equals(r2)");
148146
149147 r1 = RandomStringUtils.random(0);
152150
153151 @Test
154152 public void testLANG805() {
155 final long seed = System.currentTimeMillis();
156 assertEquals("aaa", RandomStringUtils.random(3, 0, 0, false, false, new char[]{'a'}, new Random(seed)));
153 final long seedMillis = System.currentTimeMillis();
154 assertEquals("aaa", RandomStringUtils.random(3, 0, 0, false, false, new char[]{'a'}, new Random(seedMillis)));
157155 }
158156
159157 @Test
167165
168166 @Test
169167 public void testExceptions() {
170 final char[] DUMMY = new char[]{'a'}; // valid char array
168 final char[] DUMMY = {'a'}; // valid char array
171169 assertThrows(IllegalArgumentException.class, () -> RandomStringUtils.random(-1));
172170 assertThrows(IllegalArgumentException.class, () -> RandomStringUtils.random(-1, true, true));
173171 assertThrows(IllegalArgumentException.class, () -> RandomStringUtils.random(-1, DUMMY));
1818 import static org.junit.jupiter.api.Assertions.assertArrayEquals;
1919 import static org.junit.jupiter.api.Assertions.assertEquals;
2020 import static org.junit.jupiter.api.Assertions.assertFalse;
21 import static org.junit.jupiter.api.Assertions.assertNotEquals;
2122 import static org.junit.jupiter.api.Assertions.assertNotNull;
2223 import static org.junit.jupiter.api.Assertions.assertThrows;
2324 import static org.junit.jupiter.api.Assertions.assertTrue;
9899 @Test
99100 public void testBoolean() {
100101 final boolean result = RandomUtils.nextBoolean();
101 assertTrue(result == true || result == false);
102 assertTrue(result || !result);
102103 }
103104
104105 /**
261262 final double result = RandomUtils.nextDouble(0, Double.MAX_VALUE);
262263 assertTrue(result >= 0 && result <= Double.MAX_VALUE);
263264 }
265
266 /**
267 * Test a large value for long. A previous implementation using
268 * {@link RandomUtils#nextDouble(double, double)} could generate a value equal
269 * to the upper limit.
270 *
271 * <pre>
272 * return (long) nextDouble(startInclusive, endExclusive);
273 * </pre>
274 *
275 * <p>See LANG-1592.</p>
276 */
277 @Test
278 public void testLargeValueRangeLong() {
279 final long startInclusive = 12900000000001L;
280 final long endExclusive = 12900000000016L;
281 // Note: The method using 'return (long) nextDouble(startInclusive, endExclusive)'
282 // takes thousands of calls to generate an error. This size loop fails most
283 // of the time with the previous method.
284 final int n = (int) (endExclusive - startInclusive) * 1000;
285 for (int i = 0; i < n; i++) {
286 assertNotEquals(endExclusive, RandomUtils.nextLong(startInclusive, endExclusive));
287 }
288 }
264289 }
9090 }
9191
9292 // -----------------------------------------------------------------------
93 @SuppressWarnings({ "rawtypes", "unchecked" })
93 @SuppressWarnings({"rawtypes", "unchecked"})
9494 @Test
9595 public void testComparableConstructors() {
9696 final Comparable c = other -> 1;
6161 iMap.put("BAR", iInteger);
6262 }
6363
64 //-----------------------------------------------------------------------
6564
6665 @Test
6766 public void testConstructor() {
9594 assertSame(ex, serEx.getCause());
9695 }
9796
98 //-----------------------------------------------------------------------
9997
10098 @Test
10199 public void testSerializeStream() throws Exception {
163161 assertEquals("java.io.IOException: " + SERIALIZE_IO_EXCEPTION_MESSAGE, e.getMessage());
164162 }
165163
166 //-----------------------------------------------------------------------
167164
168165 @Test
169166 public void testDeserializeStream() throws Exception {
242239 assertEquals(iMap, newMap);
243240 }
244241
245 //-----------------------------------------------------------------------
246242
247243 @Test
248244 public void testSerializeBytes() throws Exception {
280276 assertArrayEquals(realBytes, testBytes);
281277 }
282278
283 //-----------------------------------------------------------------------
284279
285280 @Test
286281 public void testDeserializeBytes() throws Exception {
324319 assertThrows(SerializationException.class, () -> SerializationUtils.deserialize(new byte[0]));
325320 }
326321
327 //-----------------------------------------------------------------------
328322
329323 @Test
330324 public void testClone() {
8383
8484 protected <T extends Throwable> FailableConsumer<String, T> asIntConsumer(final T pThrowable) {
8585 return s -> {
86 final Integer i = Integer.valueOf(s);
87 if (i.intValue() == 4) {
86 final int i = Integer.parseInt(s);
87 if (i == 4) {
8888 throw pThrowable;
8989 }
9090 };
144144
145145 protected <T extends Throwable> FailablePredicate<Integer, T> asIntPredicate(final T pThrowable) {
146146 return i -> {
147 if (i.intValue() == 5) {
148 if (pThrowable != null) {
149 throw pThrowable;
150 }
147 if (i.intValue() == 5 && pThrowable != null) {
148 throw pThrowable;
151149 }
152150 return i%2==0;
153151 };
475475 // COUNTING ROD UNIT DIGIT THREE
476476 // in Unicode
477477 // codepoint: U+1D362
478 final byte[] data = new byte[] { (byte) 0xF0, (byte) 0x9D, (byte) 0x8D, (byte) 0xA2 };
478 final byte[] data = { (byte) 0xF0, (byte) 0x9D, (byte) 0x8D, (byte) 0xA2 };
479479
480480 final String original = new String(data, StandardCharsets.UTF_8);
481481
172172 assertTrue(StringUtils.containsAny("zzabyycdxx", "by"));
173173 assertTrue(StringUtils.containsAny("zzabyycdxx", "zy"));
174174 assertFalse(StringUtils.containsAny("ab", "z"));
175 }
176
177 /**
178 * See http://www.oracle.com/technetwork/articles/javase/supplementary-142654.html
179 */
180 @Test
181 public void testContainsAny_StringWithBadSupplementaryChars() {
182 // Test edge case: 1/2 of a (broken) supplementary char
183 assertFalse(StringUtils.containsAny(CharUSuppCharHigh, CharU20001));
184 assertEquals(-1, CharUSuppCharLow.indexOf(CharU20001));
185 assertFalse(StringUtils.containsAny(CharUSuppCharLow, CharU20001));
186 assertFalse(StringUtils.containsAny(CharU20001, CharUSuppCharHigh));
187 assertEquals(0, CharU20001.indexOf(CharUSuppCharLow));
188 assertTrue(StringUtils.containsAny(CharU20001, CharUSuppCharLow));
189 }
190
191 /**
192 * See http://www.oracle.com/technetwork/articles/javase/supplementary-142654.html
193 */
194 @Test
195 public void testContainsAny_StringWithSupplementaryChars() {
196 assertTrue(StringUtils.containsAny(CharU20000 + CharU20001, CharU20000));
197 assertTrue(StringUtils.containsAny(CharU20000 + CharU20001, CharU20001));
198 assertTrue(StringUtils.containsAny(CharU20000, CharU20000));
199 // Sanity check:
200 assertEquals(-1, CharU20000.indexOf(CharU20001));
201 assertEquals(0, CharU20000.indexOf(CharU20001.charAt(0)));
202 assertEquals(-1, CharU20000.indexOf(CharU20001.charAt(1)));
203 // Test:
204 assertFalse(StringUtils.containsAny(CharU20000, CharU20001));
205 assertFalse(StringUtils.containsAny(CharU20001, CharU20000));
206175 }
207176
208177 @Test
226195 assertTrue(StringUtils.containsAny("abc", "d", "abc"));
227196 }
228197
198 @Test
199 public void testContainsAnyIgnoreCase_StringStringArray() {
200 assertFalse(StringUtils.containsAnyIgnoreCase(null, (String[]) null));
201 assertFalse(StringUtils.containsAnyIgnoreCase(null, new String[0]));
202 assertFalse(StringUtils.containsAnyIgnoreCase(null, new String[] { "hello" }));
203 assertFalse(StringUtils.containsAnyIgnoreCase("", (String[]) null));
204 assertFalse(StringUtils.containsAnyIgnoreCase("", new String[0]));
205 assertFalse(StringUtils.containsAnyIgnoreCase("", new String[] { "hello" }));
206 assertFalse(StringUtils.containsAnyIgnoreCase("hello, goodbye", (String[]) null));
207 assertFalse(StringUtils.containsAnyIgnoreCase("hello, goodbye", new String[0]));
208 assertTrue(StringUtils.containsAnyIgnoreCase("hello, goodbye", new String[]{"hello", "goodbye"}));
209 assertTrue(StringUtils.containsAnyIgnoreCase("hello, goodbye", new String[]{"hello", "Goodbye"}));
210 assertTrue(StringUtils.containsAnyIgnoreCase("hello, goodbye", new String[]{"Hello", "Goodbye"}));
211 assertTrue(StringUtils.containsAnyIgnoreCase("hello, goodbye", new String[]{"Hello", null}));
212 assertTrue(StringUtils.containsAnyIgnoreCase("hello, null", new String[] { "Hello", null }));
213 // Javadoc examples:
214 assertTrue(StringUtils.containsAnyIgnoreCase("abcd", "ab", null));
215 assertTrue(StringUtils.containsAnyIgnoreCase("abcd", "ab", "cd"));
216 assertTrue(StringUtils.containsAnyIgnoreCase("abc", "d", "abc"));
217 }
218
219 /**
220 * See http://www.oracle.com/technetwork/articles/javase/supplementary-142654.html
221 */
222 @Test
223 public void testContainsAny_StringWithBadSupplementaryChars() {
224 // Test edge case: 1/2 of a (broken) supplementary char
225 assertFalse(StringUtils.containsAny(CharUSuppCharHigh, CharU20001));
226 assertEquals(-1, CharUSuppCharLow.indexOf(CharU20001));
227 assertFalse(StringUtils.containsAny(CharUSuppCharLow, CharU20001));
228 assertFalse(StringUtils.containsAny(CharU20001, CharUSuppCharHigh));
229 assertEquals(0, CharU20001.indexOf(CharUSuppCharLow));
230 assertTrue(StringUtils.containsAny(CharU20001, CharUSuppCharLow));
231 }
232
233 /**
234 * See http://www.oracle.com/technetwork/articles/javase/supplementary-142654.html
235 */
236 @Test
237 public void testContainsAny_StringWithSupplementaryChars() {
238 assertTrue(StringUtils.containsAny(CharU20000 + CharU20001, CharU20000));
239 assertTrue(StringUtils.containsAny(CharU20000 + CharU20001, CharU20001));
240 assertTrue(StringUtils.containsAny(CharU20000, CharU20000));
241 // Sanity check:
242 assertEquals(-1, CharU20000.indexOf(CharU20001));
243 assertEquals(0, CharU20000.indexOf(CharU20001.charAt(0)));
244 assertEquals(-1, CharU20000.indexOf(CharU20001.charAt(1)));
245 // Test:
246 assertFalse(StringUtils.containsAny(CharU20000, CharU20001));
247 assertFalse(StringUtils.containsAny(CharU20001, CharU20000));
248 }
249
229250 @DefaultLocale(language = "de", country = "DE")
230251 @Test
231252 public void testContainsIgnoreCase_LocaleIndependence() {
292313 final char[] chars1= {'b'};
293314 final char[] chars2= {'.'};
294315 final char[] chars3= {'c', 'd'};
295 final char[] emptyChars = new char[0];
316 final char[] emptyChars = {};
296317 assertTrue(StringUtils.containsNone(null, (char[]) null));
297318 assertTrue(StringUtils.containsNone("", (char[]) null));
298319 assertTrue(StringUtils.containsNone(null, emptyChars));
407428 final char[] chars1= {'b'};
408429 final char[] chars2= {'a'};
409430 final char[] chars3= {'a', 'b'};
410 final char[] emptyChars = new char[0];
431 final char[] emptyChars = {};
411432 assertFalse(StringUtils.containsOnly(null, (char[]) null));
412433 assertFalse(StringUtils.containsOnly("", (char[]) null));
413434 assertFalse(StringUtils.containsOnly(null, emptyChars));
2020 import static org.junit.jupiter.api.Assertions.assertFalse;
2121 import static org.junit.jupiter.api.Assertions.assertTrue;
2222
23 import java.nio.CharBuffer;
2324 import java.util.Locale;
2425
2526 import org.hamcrest.core.IsNot;
4546
4647 private static final String FOOBAR = "foobar";
4748
48 private static final String[] FOOBAR_SUB_ARRAY = new String[] {"ob", "ba"};
49 private static final String[] FOOBAR_SUB_ARRAY = {"ob", "ba"};
4950
5051 // The purpose of this class is to test StringUtils#equals(CharSequence, CharSequence)
5152 // with a CharSequence implementation whose equals(Object) override requires that the
196197 assertTrue(StringUtils.equalsAnyIgnoreCase(FOO, new StringBuilder("fOo")));
197198 }
198199
199 //-----------------------------------------------------------------------
200200 @Test
201201 public void testCompare_StringString() {
202202 assertEquals(0, StringUtils.compare(null, null));
265265 assertTrue(StringUtils.compareIgnoreCase("abc", "AB ", false) > 0);
266266 }
267267
268 //-----------------------------------------------------------------------
269268 @Test
270269 public void testIndexOf_char() {
271270 assertEquals(-1, StringUtils.indexOf(null, ' '));
274273 assertEquals(2, StringUtils.indexOf("aabaabaa", 'b'));
275274
276275 assertEquals(2, StringUtils.indexOf(new StringBuilder("aabaabaa"), 'b'));
276 assertEquals(StringUtils.INDEX_NOT_FOUND, StringUtils.indexOf(new StringBuilder("aabaabaa"), -1738));
277277 }
278278
279279 @Test
563563 assertEquals(1, StringUtils.lastIndexOf(builder, CODE_POINT, 1 ));
564564 assertEquals(-1, StringUtils.lastIndexOf(builder.toString(), CODE_POINT, 0));
565565 assertEquals(1, StringUtils.lastIndexOf(builder.toString(), CODE_POINT, 1));
566 assertEquals(StringUtils.INDEX_NOT_FOUND, StringUtils.lastIndexOf(CharBuffer.wrap("[%{.c.0rro"), -1738, 982));
566567 }
567568
568569 @Test
3232 private static final String BAR = "BAR";
3333 private static final String FOOBAR = "FOOBAR";
3434
35 //-----------------------------------------------------------------------
3635
3736 /**
3837 * Test StringUtils.startsWith()
3131 private static final String FOOBAR = "foobar";
3232 private static final String SENTENCE = "foo bar baz";
3333
34 //-----------------------------------------------------------------------
3534
3635 @Test
3736 public void testSubstring_StringInt() {
126125 assertEquals(FOO, StringUtils.mid(FOOBAR, -1, 3));
127126 }
128127
129 //-----------------------------------------------------------------------
128 @Test
129 public void testSubstringBefore_StringInt() {
130 assertEquals("foo", StringUtils.substringBefore("fooXXbarXXbaz", 'X'));
131
132 assertNull(StringUtils.substringBefore(null, 0));
133 assertNull(StringUtils.substringBefore(null, 'X'));
134 assertEquals("", StringUtils.substringBefore("", 0));
135 assertEquals("", StringUtils.substringBefore("", 'X'));
136
137 assertEquals("foo", StringUtils.substringBefore("foo", 0));
138 assertEquals("foo", StringUtils.substringBefore("foo", 'b'));
139 assertEquals("f", StringUtils.substringBefore("foot", 'o'));
140 assertEquals("", StringUtils.substringBefore("abc", 'a'));
141 assertEquals("a", StringUtils.substringBefore("abcba", 'b'));
142 assertEquals("ab", StringUtils.substringBefore("abc", 'c'));
143 assertEquals("abc", StringUtils.substringBefore("abc", 0));
144 }
145
130146 @Test
131147 public void testSubstringBefore_StringString() {
132148 assertEquals("foo", StringUtils.substringBefore("fooXXbarXXbaz", "XX"));
145161 assertEquals("a", StringUtils.substringBefore("abcba", "b"));
146162 assertEquals("ab", StringUtils.substringBefore("abc", "c"));
147163 assertEquals("", StringUtils.substringBefore("abc", ""));
164 assertEquals("abc", StringUtils.substringBefore("abc", "X"));
148165 }
149166
150167 @Test
243260 assertEquals("", StringUtils.substringAfterLast("", 'd'));
244261 }
245262
246 //-----------------------------------------------------------------------
247263 @Test
248264 public void testSubstringBetween_StringString() {
249265 assertNull(StringUtils.substringBetween(null, "tag"));
332348 assertEquals(0, results.length);
333349 }
334350
335 //-----------------------------------------------------------------------
336351 @Test
337352 public void testCountMatches_String() {
338353 assertEquals(0, StringUtils.countMatches(null, null));
348363 StringUtils.countMatches("one long someone sentence of one", "two"));
349364 assertEquals(4,
350365 StringUtils.countMatches("oooooooooooo", "ooo"));
366 assertEquals(0, StringUtils.countMatches(null, "?"));
367 assertEquals(0, StringUtils.countMatches("", "?"));
368 assertEquals(0, StringUtils.countMatches("abba", null));
369 assertEquals(0, StringUtils.countMatches("abba", ""));
370 assertEquals(2, StringUtils.countMatches("abba", "a"));
371 assertEquals(1, StringUtils.countMatches("abba", "ab"));
372 assertEquals(0, StringUtils.countMatches("abba", "xxx"));
373 assertEquals(1, StringUtils.countMatches("ababa", "aba"));
351374 }
352375
353376 @Test
4343
4444 import org.apache.commons.lang3.mutable.MutableInt;
4545 import org.apache.commons.lang3.text.WordUtils;
46 import org.junit.jupiter.api.Disabled;
4647 import org.junit.jupiter.api.Test;
4748
4849 /**
112113
113114 private static final String SEPARATOR = ",";
114115 private static final char SEPARATOR_CHAR = ';';
116 private static final char COMMA_SEPARATOR_CHAR = ',';
115117
116118 private static final String TEXT_LIST = "foo,bar,baz";
117119 private static final String TEXT_LIST_CHAR = "foo;bar;baz";
122124
123125 private static final String SENTENCE_UNCAP = "foo bar baz";
124126 private static final String SENTENCE_CAP = "Foo Bar Baz";
127
128 private static final boolean[] EMPTY = {};
129 private static final boolean[] ARRAY_FALSE_FALSE = {false, false};
130 private static final boolean[] ARRAY_FALSE_TRUE = {false, true};
131 private static final boolean[] ARRAY_FALSE_TRUE_FALSE = {false, true, false};
125132
126133 private void assertAbbreviateWithAbbrevMarkerAndOffset(final String expected, final String abbrevMarker, final int offset, final int maxWidth) {
127134 final String abcdefghijklmno = "abcdefghijklmno";
234241 assertEquals(str.substring(2), res[1], msg);
235242 }
236243
237 //-----------------------------------------------------------------------
238244 //Fixed LANG-1463
239245 @Test
240246 public void testAbbreviateMarkerWithEmptyString() {
481487 assertEquals("'cat'", StringUtils.capitalize("'cat'"));
482488 }
483489
484 //-----------------------------------------------------------------------
485490 @Test
486491 public void testCenter_StringInt() {
487492 assertNull(StringUtils.center(null, -1));
599604 }
600605 }
601606
602 //-----------------------------------------------------------------------
603607 @Test
604608 public void testConstructor() {
605609 assertNotNull(new StringUtils());
610614 assertFalse(Modifier.isFinal(StringUtils.class.getModifiers()));
611615 }
612616
613 //-----------------------------------------------------------------------
614617 @Test
615618 public void testDefault_String() {
616619 assertEquals("", StringUtils.defaultString(null));
779782 assertEquals("test", StringUtils.deleteWhitespace("\u000Bt \t\n\u0009e\rs\n\n \tt"));
780783 }
781784
782 //-----------------------------------------------------------------------
783785 @Test
784786 public void testDifference_StringString() {
785787 assertNull(StringUtils.difference(null, null));
985987 assertThrows(IllegalArgumentException.class, () -> StringUtils.getLevenshteinDistance("a", null, 0));
986988 }
987989
988 //-----------------------------------------------------------------------
989990 @Test
990991 public void testGetLevenshteinDistance_StringString() {
991992 assertEquals(0, StringUtils.getLevenshteinDistance("", ""));
11531154 assertEquals(StringUtils.EMPTY, StringUtils.join(BYTE_PRIM_LIST, SEPARATOR_CHAR, 1, 0));
11541155 }
11551156
1157
1158 @Test
1159 public void testJoin_ArrayOfBooleans() {
1160 assertNull(StringUtils.join((boolean[]) null, COMMA_SEPARATOR_CHAR));
1161 assertEquals("false;false", StringUtils.join(ARRAY_FALSE_FALSE, SEPARATOR_CHAR));
1162 assertEquals("", StringUtils.join(EMPTY, SEPARATOR_CHAR));
1163 assertEquals("false,true,false", StringUtils.join(ARRAY_FALSE_TRUE_FALSE, COMMA_SEPARATOR_CHAR));
1164 assertEquals("true", StringUtils.join(ARRAY_FALSE_TRUE, SEPARATOR_CHAR, 1, 2));
1165 assertNull(StringUtils.join((boolean[]) null, SEPARATOR_CHAR, 0, 1));
1166 assertEquals(StringUtils.EMPTY, StringUtils.join(ARRAY_FALSE_FALSE, SEPARATOR_CHAR, 0, 0));
1167 assertEquals(StringUtils.EMPTY, StringUtils.join(ARRAY_FALSE_TRUE_FALSE, SEPARATOR_CHAR, 1, 0));
1168 }
1169
11561170 @Test
11571171 public void testJoin_ArrayOfChars() {
11581172 assertNull(StringUtils.join((char[]) null, ','));
13401354 assertEquals("foo2", StringUtils.join(MIXED_TYPE_LIST));
13411355 }
13421356
1343 //-----------------------------------------------------------------------
1357 @Disabled
1358 @Test
1359 public void testLang1593() {
1360 final int[] arr = {1, 2, 3, 4, 5, 6, 7};
1361 final String expected = StringUtils.join(arr, '-');
1362 final String actual = StringUtils.join(arr, "-");
1363 assertEquals(expected, actual);
1364 }
1365
13441366 @Test
13451367 public void testJoin_Objects() {
13461368 assertEquals("abc", StringUtils.join("a", "b", "c"));
13781400 assertEquals("121", StringUtils.stripEnd("121.00", ".0"));
13791401 }
13801402
1381 //-----------------------------------------------------------------------
13821403 @Test
13831404 public void testLeftPad_StringInt() {
13841405 assertNull(StringUtils.leftPad(null, 5));
21982219 StringUtils.replacePattern("Lorem ipsum dolor sit", "( +)([a-z]+)", "_$2"));
21992220 }
22002221
2201 //-----------------------------------------------------------------------
22022222 @Test
22032223 public void testReverse_String() {
22042224 assertNull(StringUtils.reverse(null));
22152235 assertEquals("", StringUtils.reverseDelimited("", '.'));
22162236 }
22172237
2218 //-----------------------------------------------------------------------
22192238 @Test
22202239 public void testRightPad_StringInt() {
22212240 assertNull(StringUtils.rightPad(null, 5));
22522271 assertEquals("abc ", StringUtils.rightPad("abc", 5, ""));
22532272 }
22542273
2255 //-----------------------------------------------------------------------
22562274 @Test
22572275 public void testRotate_StringInt() {
22582276 assertNull(StringUtils.rotate(null, 1));
24132431
24142432 // test whitespace
24152433 String input = "ab de fg";
2416 String[] expected = new String[]{"ab", "", "", "de", "fg"};
2434 String[] expected = {"ab", "", "", "de", "fg"};
24172435
24182436 String[] actual = StringUtils.splitByWholeSeparatorPreserveAllTokens(input, null);
24192437 assertEquals(expected.length, actual.length);
24502468
24512469 // test whitespace
24522470 String input = "ab de fg";
2453 String[] expected = new String[]{"ab", "", "", "de", "fg"};
2471 String[] expected = {"ab", "", "", "de", "fg"};
24542472
24552473 String[] actual = StringUtils.splitByWholeSeparatorPreserveAllTokens(input, null, -1);
24562474 assertEquals(expected.length, actual.length);
29802998 assertEquals(expectedString, StringUtils.toString(expectedBytes, encoding));
29812999 }
29823000
2983 //-----------------------------------------------------------------------
29843001 @Test
29853002 public void testTruncate_StringInt() {
29863003 assertNull(StringUtils.truncate(null, 12));
31633180 assertEquals("abc", StringUtils.unwrap("abc", null));
31643181 assertEquals("abc", StringUtils.unwrap("abc", ""));
31653182 assertEquals("a", StringUtils.unwrap("a", "a"));
3183 assertEquals("ababa", StringUtils.unwrap("ababa", "aba"));
31663184 assertEquals("", StringUtils.unwrap("aa", "a"));
31673185 assertEquals("abc", StringUtils.unwrap("\'abc\'", "\'"));
31683186 assertEquals("abc", StringUtils.unwrap("\"abc\"", "\""));
33093327
33103328 @Test
33113329 public void testGeorgianSample() {
3312 final char[] arrayI = new char[]{
3330 final char[] arrayI = {
33133331 //Latin Small Letter dotless I
33143332 (char) 0x0131,
33153333 //Greek Capital Letter Theta
33163334 (char) 0x03F4
33173335 };
3318 final char[] arrayJ = new char[]{
3336 final char[] arrayJ = {
33193337 //Latin Capital Letter I with dot above
33203338 (char) 0x0130,
33213339 //Greek Theta Symbol
6666 assertEquals("", StringUtils.trimToEmpty(null));
6767 }
6868
69 //-----------------------------------------------------------------------
7069 @Test
7170 public void testStrip_String() {
7271 assertNull(StringUtils.strip(null));
198197 @Test
199198 public void testStripAll() {
200199 // test stripAll method, merely an array version of the above strip
201 final String[] empty = new String[0];
202 final String[] fooSpace = new String[] { " "+FOO+" ", " "+FOO, FOO+" " };
203 final String[] fooDots = new String[] { ".."+FOO+"..", ".."+FOO, FOO+".." };
204 final String[] foo = new String[] { FOO, FOO, FOO };
200 final String[] empty = {};
201 final String[] fooSpace = { " "+FOO+" ", " "+FOO, FOO+" " };
202 final String[] fooDots = { ".."+FOO+"..", ".."+FOO, FOO+".." };
203 final String[] foo = { FOO, FOO, FOO };
205204
206205 assertNull(StringUtils.stripAll((String[]) null));
207206 // Additional varargs tests
5252 public class SystemUtilsTest {
5353
5454 @Test
55 public void testConstructor() {
56 assertNotNull(new SystemUtils());
57 final Constructor<?>[] cons = SystemUtils.class.getDeclaredConstructors();
58 assertEquals(1, cons.length);
59 assertTrue(Modifier.isPublic(cons[0].getModifiers()));
60 assertTrue(Modifier.isPublic(SystemUtils.class.getModifiers()));
61 assertFalse(Modifier.isFinal(SystemUtils.class.getModifiers()));
62 }
63
64 @Test
65 public void testGetEnvironmentVariableAbsent() {
66 final String name = "THIS_ENV_VAR_SHOULD_NOT_EXIST_FOR_THIS_TEST_TO_PASS";
67 final String expected = System.getenv(name);
68 assertNull(expected);
69 final String value = SystemUtils.getEnvironmentVariable(name, "DEFAULT");
70 assertEquals("DEFAULT", value);
71 }
72
73 @Test
74 public void testGetEnvironmentVariablePresent() {
75 final String name = "PATH";
76 final String expected = System.getenv(name);
77 final String value = SystemUtils.getEnvironmentVariable(name, null);
78 assertEquals(expected, value);
79 }
80
81 @Test
82 public void testGetHostName() {
83 final String hostName = SystemUtils.getHostName();
84 final String expected = SystemUtils.IS_OS_WINDOWS ? System.getenv("COMPUTERNAME") : System.getenv("HOSTNAME");
85 assertEquals(expected, hostName);
86 }
87
88 /**
89 * Assumes no security manager exists.
90 */
91 @Test
92 public void testGetJavaHome() {
93 final File dir = SystemUtils.getJavaHome();
94 assertNotNull(dir);
95 assertTrue(dir.exists());
96 }
97
98 /**
99 * Assumes no security manager exists.
100 */
101 @Test
102 public void testGetJavaIoTmpDir() {
103 final File dir = SystemUtils.getJavaIoTmpDir();
104 assertNotNull(dir);
105 assertTrue(dir.exists());
106 }
107
108 /**
109 * Assumes no security manager exists.
110 */
111 @Test
112 public void testGetUserDir() {
113 final File dir = SystemUtils.getUserDir();
114 assertNotNull(dir);
115 assertTrue(dir.exists());
116 }
117
118 /**
119 * Assumes no security manager exists.
120 */
121 @Test
122 public void testGetUserHome() {
123 final File dir = SystemUtils.getUserHome();
124 assertNotNull(dir);
125 assertTrue(dir.exists());
126 }
127
128 /**
129 * Assumes no security manager exists.
130 */
131 @Test
132 public void testGetUserName() {
133 assertEquals(System.getProperty("user.name"), SystemUtils.getUserName());
134 // Don't overwrite the system property in this test in case something goes awfully wrong.
135 assertEquals(System.getProperty("user.name", "foo"), SystemUtils.getUserName("foo"));
136 }
137
138 @Test
13955 @SuppressWarnings("deprecation")
140 public void testIS_JAVA() {
56 public void test_IS_JAVA() {
14157 final String javaVersion = SystemUtils.JAVA_VERSION;
14258 if (javaVersion == null) {
14359 assertFalse(SystemUtils.IS_JAVA_1_1);
296212 }
297213
298214 @Test
299 public void testIS_OS() {
215 public void test_IS_OS() {
300216 final String osName = System.getProperty("os.name");
301217 if (osName == null) {
302218 assertFalse(SystemUtils.IS_OS_WINDOWS);
337253 }
338254
339255 @Test
340 public void testIS_zOS() {
256 public void test_IS_zOS() {
341257 final String osName = System.getProperty("os.name");
342258 if (osName == null) {
343259 assertFalse(SystemUtils.IS_OS_ZOS);
347263 }
348264 }
349265
350 @Test
351 public void testJavaVersionMatches() {
352 String javaVersion = null;
353 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
354 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
355 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
356 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
357 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
358 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
359 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
360 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
361 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.8"));
362 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "9"));
363 javaVersion = "";
364 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
365 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
366 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
367 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
368 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
369 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
370 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
371 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
372 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.8"));
373 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "9"));
374 javaVersion = "1.0";
375 assertTrue(SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
376 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
377 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
378 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
379 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
380 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
381 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
382 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
383 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.8"));
384 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "9"));
385 javaVersion = "1.1";
386 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
387 assertTrue(SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
388 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
389 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
390 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
391 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
392 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
393 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
394 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.8"));
395 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "9"));
396 javaVersion = "1.2";
397 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
398 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
399 assertTrue(SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
400 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
401 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
402 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
403 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
404 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
405 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.8"));
406 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "9"));
407 javaVersion = "1.3.0";
408 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
409 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
410 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
411 assertTrue(SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
412 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
413 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
414 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
415 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
416 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.8"));
417 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "9"));
418 javaVersion = "1.3.1";
419 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
420 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
421 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
422 assertTrue(SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
423 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
424 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
425 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
426 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
427 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.8"));
428 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "9"));
429 javaVersion = "1.4.0";
430 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
431 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
432 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
433 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
434 assertTrue(SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
435 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
436 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
437 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
438 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.8"));
439 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "9"));
440 javaVersion = "1.4.1";
441 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
442 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
443 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
444 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
445 assertTrue(SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
446 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
447 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
448 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
449 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.8"));
450 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "9"));
451 javaVersion = "1.4.2";
452 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
453 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
454 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
455 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
456 assertTrue(SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
457 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
458 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
459 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
460 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.8"));
461 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "9"));
462 javaVersion = "1.5.0";
463 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
464 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
465 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
466 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
467 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
468 assertTrue(SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
469 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
470 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
471 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.8"));
472 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "9"));
473 javaVersion = "1.6.0";
474 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
475 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
476 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
477 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
478 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
479 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
480 assertTrue(SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
481 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
482 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.8"));
483 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "9"));
484 javaVersion = "1.7.0";
485 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
486 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
487 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
488 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
489 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
490 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
491 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
492 assertTrue(SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
493 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.8"));
494 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "9"));
495 javaVersion = "1.8.0";
496 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
497 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
498 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
499 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
500 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
501 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
502 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
503 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
504 assertTrue(SystemUtils.isJavaVersionMatch(javaVersion, "1.8"));
505 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "9"));
506 javaVersion = "9";
507 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
508 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
509 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
510 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
511 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
512 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
513 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
514 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
515 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.8"));
516 assertTrue(SystemUtils.isJavaVersionMatch(javaVersion, "9"));
266 /**
267 * Assumes no security manager exists.
268 */
269 @Test
270 public void test_USER_NAME() {
271 assertEquals(System.getProperty("user.name"), SystemUtils.USER_NAME);
272 }
273
274 @Test
275 public void testConstructor() {
276 assertNotNull(new SystemUtils());
277 final Constructor<?>[] cons = SystemUtils.class.getDeclaredConstructors();
278 assertEquals(1, cons.length);
279 assertTrue(Modifier.isPublic(cons[0].getModifiers()));
280 assertTrue(Modifier.isPublic(SystemUtils.class.getModifiers()));
281 assertFalse(Modifier.isFinal(SystemUtils.class.getModifiers()));
282 }
283
284 @Test
285 public void testGetEnvironmentVariableAbsent() {
286 final String name = "THIS_ENV_VAR_SHOULD_NOT_EXIST_FOR_THIS_TEST_TO_PASS";
287 final String expected = System.getenv(name);
288 assertNull(expected);
289 final String value = SystemUtils.getEnvironmentVariable(name, "DEFAULT");
290 assertEquals("DEFAULT", value);
291 }
292
293 @Test
294 public void testGetEnvironmentVariablePresent() {
295 final String name = "PATH";
296 final String expected = System.getenv(name);
297 final String value = SystemUtils.getEnvironmentVariable(name, null);
298 assertEquals(expected, value);
299 }
300
301 @Test
302 public void testGetHostName() {
303 final String hostName = SystemUtils.getHostName();
304 final String expected = SystemUtils.IS_OS_WINDOWS ? System.getenv("COMPUTERNAME") : System.getenv("HOSTNAME");
305 assertEquals(expected, hostName);
306 }
307
308 /**
309 * Assumes no security manager exists.
310 */
311 @Test
312 public void testGetJavaHome() {
313 final File dir = SystemUtils.getJavaHome();
314 assertNotNull(dir);
315 assertTrue(dir.exists());
316 }
317
318 /**
319 * Assumes no security manager exists.
320 */
321 @Test
322 public void testGetJavaIoTmpDir() {
323 final File dir = SystemUtils.getJavaIoTmpDir();
324 assertNotNull(dir);
325 assertTrue(dir.exists());
326 }
327
328 /**
329 * Assumes no security manager exists.
330 */
331 @Test
332 public void testGetUserDir() {
333 final File dir = SystemUtils.getUserDir();
334 assertNotNull(dir);
335 assertTrue(dir.exists());
336 }
337
338 /**
339 * Assumes no security manager exists.
340 */
341 @Test
342 public void testGetUserHome() {
343 final File dir = SystemUtils.getUserHome();
344 assertNotNull(dir);
345 assertTrue(dir.exists());
346 }
347
348 /**
349 * Assumes no security manager exists.
350 */
351 @Test
352 public void testGetUserName() {
353 assertEquals(System.getProperty("user.name"), SystemUtils.getUserName());
354 // Don't overwrite the system property in this test in case something goes awfully wrong.
355 assertEquals(System.getProperty("user.name", "foo"), SystemUtils.getUserName("foo"));
517356 }
518357
519358 @Test
695534 }
696535
697536 @Test
537 public void testJavaAwtHeadless() {
538 final String expectedStringValue = System.getProperty("java.awt.headless");
539 final String expectedStringValueWithDefault = System.getProperty("java.awt.headless", "false");
540 assertNotNull(expectedStringValueWithDefault);
541 final boolean expectedValue = Boolean.parseBoolean(expectedStringValue);
542 if (expectedStringValue != null) {
543 assertEquals(expectedStringValue, SystemUtils.JAVA_AWT_HEADLESS);
544 }
545 assertEquals(expectedValue, SystemUtils.isJavaAwtHeadless());
546 assertEquals(expectedStringValueWithDefault, "" + SystemUtils.isJavaAwtHeadless());
547 }
548
549 @Test
550 public void testJavaVersionMatches() {
551 String javaVersion = null;
552 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
553 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
554 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
555 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
556 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
557 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
558 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
559 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
560 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.8"));
561 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "9"));
562 javaVersion = "";
563 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
564 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
565 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
566 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
567 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
568 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
569 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
570 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
571 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.8"));
572 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "9"));
573 javaVersion = "1.0";
574 assertTrue(SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
575 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
576 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
577 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
578 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
579 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
580 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
581 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
582 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.8"));
583 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "9"));
584 javaVersion = "1.1";
585 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
586 assertTrue(SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
587 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
588 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
589 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
590 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
591 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
592 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
593 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.8"));
594 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "9"));
595 javaVersion = "1.2";
596 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
597 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
598 assertTrue(SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
599 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
600 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
601 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
602 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
603 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
604 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.8"));
605 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "9"));
606 javaVersion = "1.3.0";
607 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
608 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
609 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
610 assertTrue(SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
611 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
612 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
613 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
614 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
615 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.8"));
616 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "9"));
617 javaVersion = "1.3.1";
618 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
619 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
620 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
621 assertTrue(SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
622 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
623 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
624 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
625 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
626 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.8"));
627 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "9"));
628 javaVersion = "1.4.0";
629 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
630 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
631 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
632 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
633 assertTrue(SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
634 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
635 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
636 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
637 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.8"));
638 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "9"));
639 javaVersion = "1.4.1";
640 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
641 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
642 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
643 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
644 assertTrue(SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
645 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
646 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
647 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
648 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.8"));
649 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "9"));
650 javaVersion = "1.4.2";
651 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
652 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
653 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
654 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
655 assertTrue(SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
656 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
657 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
658 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
659 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.8"));
660 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "9"));
661 javaVersion = "1.5.0";
662 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
663 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
664 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
665 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
666 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
667 assertTrue(SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
668 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
669 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
670 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.8"));
671 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "9"));
672 javaVersion = "1.6.0";
673 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
674 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
675 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
676 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
677 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
678 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
679 assertTrue(SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
680 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
681 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.8"));
682 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "9"));
683 javaVersion = "1.7.0";
684 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
685 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
686 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
687 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
688 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
689 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
690 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
691 assertTrue(SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
692 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.8"));
693 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "9"));
694 javaVersion = "1.8.0";
695 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
696 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
697 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
698 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
699 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
700 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
701 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
702 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
703 assertTrue(SystemUtils.isJavaVersionMatch(javaVersion, "1.8"));
704 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "9"));
705 javaVersion = "9";
706 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
707 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
708 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
709 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
710 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
711 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
712 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
713 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
714 assertFalse(SystemUtils.isJavaVersionMatch(javaVersion, "1.8"));
715 assertTrue(SystemUtils.isJavaVersionMatch(javaVersion, "9"));
716 }
717
718 @Test
698719 public void testOSMatchesName() {
699720 String osName = null;
700721 assertFalse(SystemUtils.isOSNameMatch(osName, "Windows"));
771792 assertTrue(SystemUtils.isOSVersionMatch(osVersion, "10.10"));
772793 assertTrue(SystemUtils.isOSVersionMatch(osVersion, "10.10.1"));
773794 }
774
775 @Test
776 public void testJavaAwtHeadless() {
777 final String expectedStringValue = System.getProperty("java.awt.headless");
778 final String expectedStringValueWithDefault = System.getProperty("java.awt.headless", "false");
779 assertNotNull(expectedStringValueWithDefault);
780 final boolean expectedValue = Boolean.valueOf(expectedStringValue).booleanValue();
781 if (expectedStringValue != null) {
782 assertEquals(expectedStringValue, SystemUtils.JAVA_AWT_HEADLESS);
783 }
784 assertEquals(expectedValue, SystemUtils.isJavaAwtHeadless());
785 assertEquals(expectedStringValueWithDefault, "" + SystemUtils.isJavaAwtHeadless());
786 }
787795 }
2828
2929 import java.lang.reflect.Constructor;
3030 import java.lang.reflect.Modifier;
31 import java.time.Duration;
3132 import java.util.Arrays;
3233 import java.util.List;
3334 import java.util.concurrent.CountDownLatch;
3940 */
4041 public class ThreadUtilsTest {
4142
42 @Test
43 public void testNullThreadName() {
44 assertThrows(NullPointerException.class, () -> ThreadUtils.findThreadsByName(null));
45 }
46
47 @Test
48 public void testNullThreadGroupName() {
49 assertThrows(NullPointerException.class, () -> ThreadUtils.findThreadGroupsByName(null));
50 }
51
52 @Test
53 public void testNullThreadThreadGroupName1() {
54 assertThrows(NullPointerException.class, () -> ThreadUtils.findThreadsByName(null, "tgname"));
55 }
56
57 @Test
58 public void testNullThreadThreadGroupName2() {
59 assertThrows(NullPointerException.class, () -> ThreadUtils.findThreadsByName("tname", (String) null));
60 }
61
62 @Test
63 public void testNullThreadThreadGroupName3() {
64 assertThrows(NullPointerException.class, () -> ThreadUtils.findThreadsByName(null, (String) null));
65 }
66
67 @Test
68 public void testNullThreadThreadGroup1() {
69 assertThrows(NullPointerException.class, () -> ThreadUtils.findThreadsByName("tname", (ThreadGroup) null));
70 }
71
72 @Test
73 public void testNullThreadThreadGroup2() {
74 assertThrows(NullPointerException.class, () -> ThreadUtils.findThreadById(1L, (ThreadGroup) null));
75 }
76
77 @Test
78 public void testNullThreadThreadGroup3() {
79 assertThrows(NullPointerException.class, () -> ThreadUtils.findThreadsByName(null, (ThreadGroup) null));
80 }
81
82 @Test
83 public void testInvalidThreadId() {
84 assertThrows(IllegalArgumentException.class, () -> ThreadUtils.findThreadById(-5L));
85 }
86
87 @Test
88 public void testThreadGroupsByIdFail() {
89 assertThrows(NullPointerException.class,
90 () -> ThreadUtils.findThreadById(Thread.currentThread().getId(), (String) null));
91 }
92
93 @Test
94 public void testThreadgroupsNullParent() {
95 assertThrows(NullPointerException.class,
96 () -> ThreadUtils.findThreadGroups(null, true, ThreadUtils.ALWAYS_TRUE_PREDICATE));
97 }
98
99 @Test
100 public void testThreadgroupsNullPredicate() {
101 assertThrows(NullPointerException.class, () -> ThreadUtils.findThreadGroups(null));
102 }
103
104 @Test
105 public void testThreadsNullPredicate() {
106 assertThrows(NullPointerException.class, () -> ThreadUtils.findThreads(null));
107 }
108
109 @Test
110 public void testNoThread() {
111 assertEquals(0, ThreadUtils.findThreadsByName("some_thread_which_does_not_exist_18762ZucTT").size());
112 }
113
114 @Test
115 public void testNoThreadGroup() {
116 assertEquals(0, ThreadUtils.findThreadGroupsByName("some_thread_group_which_does_not_exist_18762ZucTTII").size());
117 }
118
119 @Test
120 public void testSystemThreadGroupExists() {
121 final ThreadGroup systemThreadGroup = ThreadUtils.getSystemThreadGroup();
122 assertNotNull(systemThreadGroup);
123 assertNull(systemThreadGroup.getParent());
124 assertEquals("system", systemThreadGroup.getName());
43 private static class TestThread extends Thread {
44 private final CountDownLatch latch = new CountDownLatch(1);
45
46 TestThread(final String name) {
47 super(name);
48 }
49
50 TestThread(final ThreadGroup group, final String name) {
51 super(group, name);
52 }
53
54 @Override
55 public void run() {
56 latch.countDown();
57 try {
58 synchronized(this) {
59 this.wait();
60 }
61 } catch (final InterruptedException e) {
62 Thread.currentThread().interrupt();
63 }
64 }
65
66 @Override
67 public synchronized void start() {
68 super.start();
69 try {
70 latch.await();
71 } catch (final InterruptedException e) {
72 Thread.currentThread().interrupt();
73 }
74 }
12575 }
12676
12777 @Test
12878 public void testAtLeastOneThreadExists() {
129 assertTrue(ThreadUtils.getAllThreads().size() > 0);
79 assertFalse(ThreadUtils.getAllThreads().isEmpty());
13080 }
13181
13282 @Test
13383 public void testAtLeastOneThreadGroupsExists() {
134 assertTrue(ThreadUtils.getAllThreadGroups().size() > 0);
135 }
136
137 @Test
138 public void testThreadsSameName() throws InterruptedException {
139 final Thread t1 = new TestThread("thread1_XXOOLL__");
140 final Thread alsot1 = new TestThread("thread1_XXOOLL__");
141
142 try {
143 t1.start();
144 alsot1.start();
145 assertEquals(2, ThreadUtils.findThreadsByName("thread1_XXOOLL__").size());
146 } finally {
147 t1.interrupt();
148 alsot1.interrupt();
149 t1.join();
150 alsot1.join();
151 }
152 }
153
154 @Test
155 public void testThreads() throws InterruptedException {
156 final Thread t1 = new TestThread("thread1_XXOOLL__");
157 final Thread t2 = new TestThread("thread2_XXOOLL__");
158
159 try {
160 t1.start();
161 t2.start();
162 assertEquals(1, ThreadUtils.findThreadsByName("thread2_XXOOLL__").size());
163 } finally {
164 t1.interrupt();
165 t2.interrupt();
166 t1.join();
167 t2.join();
168 }
169 }
170
171 @Test
172 public void testThreadsById() throws InterruptedException {
173 final Thread t1 = new TestThread("thread1_XXOOLL__");
174 final Thread t2 = new TestThread("thread2_XXOOLL__");
175
176 try {
177 t1.start();
178 t2.start();
179 assertSame(t1, ThreadUtils.findThreadById(t1.getId()));
180 assertSame(t2, ThreadUtils.findThreadById(t2.getId()));
181 } finally {
182 t1.interrupt();
183 t2.interrupt();
184 t1.join();
185 t2.join();
186 }
187 }
188
189 @Test
190 public void testThreadsByIdWrongGroup() throws InterruptedException {
191 final Thread t1 = new TestThread("thread1_XXOOLL__");
192 final ThreadGroup tg = new ThreadGroup("tg__HHEE22");
193
194 try {
195 t1.start();
196 assertNull(ThreadUtils.findThreadById(t1.getId(), tg));
197 } finally {
198 t1.interrupt();
199 t1.join();
200 tg.destroy();
201 }
202 }
203
204
205 @Test
206 public void testThreadGroups() throws InterruptedException {
207 final ThreadGroup threadGroup = new ThreadGroup("thread_group_DDZZ99__");
208 final Thread t1 = new TestThread(threadGroup, "thread1_XXOOPP__");
209 final Thread t2 = new TestThread(threadGroup, "thread2_XXOOPP__");
210
211 try {
212 t1.start();
213 t2.start();
214 assertEquals(1, ThreadUtils.findThreadsByName("thread1_XXOOPP__").size());
215 assertEquals(1, ThreadUtils.findThreadsByName("thread1_XXOOPP__", "thread_group_DDZZ99__").size());
216 assertEquals(1, ThreadUtils.findThreadsByName("thread2_XXOOPP__", "thread_group_DDZZ99__").size());
217 assertEquals(0, ThreadUtils.findThreadsByName("thread1_XXOOPP__", "non_existent_thread_group_JJHHZZ__").size());
218 assertEquals(0, ThreadUtils.findThreadsByName("non_existent_thread_BBDDWW__", "thread_group_DDZZ99__").size());
219 assertEquals(1, ThreadUtils.findThreadGroupsByName("thread_group_DDZZ99__").size());
220 assertEquals(0, ThreadUtils.findThreadGroupsByName("non_existent_thread_group_JJHHZZ__").size());
221 assertNotNull(ThreadUtils.findThreadById(t1.getId(), threadGroup));
222 } finally {
223 t1.interrupt();
224 t2.interrupt();
225 t1.join();
226 t2.join();
227 threadGroup.destroy();
228 }
229 }
230
231 @Test
232 public void testThreadGroupsRef() throws InterruptedException {
233 final ThreadGroup threadGroup = new ThreadGroup("thread_group_DDZZ99__");
234 final ThreadGroup deadThreadGroup = new ThreadGroup("dead_thread_group_MMQQSS__");
235 deadThreadGroup.destroy();
236 final Thread t1 = new TestThread(threadGroup, "thread1_XXOOPP__");
237 final Thread t2 = new TestThread(threadGroup, "thread2_XXOOPP__");
238
239 try {
240 t1.start();
241 t2.start();
242 assertEquals(1, ThreadUtils.findThreadsByName("thread1_XXOOPP__").size());
243 assertEquals(1, ThreadUtils.findThreadsByName("thread1_XXOOPP__", threadGroup).size());
244 assertEquals(1, ThreadUtils.findThreadsByName("thread2_XXOOPP__", threadGroup).size());
245 assertEquals(0, ThreadUtils.findThreadsByName("thread1_XXOOPP__", deadThreadGroup).size());
246 } finally {
247 t1.interrupt();
248 t2.interrupt();
249 t1.join();
250 t2.join();
251 threadGroup.destroy();
252 assertEquals(0, ThreadUtils.findThreadsByName("thread2_XXOOPP__", threadGroup).size());
253 }
254 }
255
256 @Test
257 public void testThreadGroupsById() throws InterruptedException {
258 final ThreadGroup threadGroup = new ThreadGroup("thread_group_DDZZ99__");
259 final Thread t1 = new TestThread(threadGroup, "thread1_XXOOPP__");
260 final Thread t2 = new TestThread(threadGroup, "thread2_XXOOPP__");
261 final long nonExistingId = t1.getId()+t2.getId();
262
263 try {
264 t1.start();
265 t2.start();
266 assertSame(t1, ThreadUtils.findThreadById(t1.getId(), "thread_group_DDZZ99__"));
267 assertSame(t2, ThreadUtils.findThreadById(t2.getId(), "thread_group_DDZZ99__"));
268 assertNull(ThreadUtils.findThreadById(nonExistingId, "non_existent_thread_group_JJHHZZ__"));
269 assertNull(ThreadUtils.findThreadById(nonExistingId, "thread_group_DDZZ99__"));
270 } finally {
271 t1.interrupt();
272 t2.interrupt();
273 t1.join();
274 t2.join();
275 threadGroup.destroy();
276 }
277 }
278
279 @Test
280 public void testConstructor() {
281 assertNotNull(new ThreadUtils());
282 final Constructor<?>[] cons = ThreadUtils.class.getDeclaredConstructors();
283 assertEquals(1, cons.length);
284 assertTrue(Modifier.isPublic(cons[0].getModifiers()));
285 assertTrue(Modifier.isPublic(ThreadUtils.class.getModifiers()));
286 assertFalse(Modifier.isFinal(ThreadUtils.class.getModifiers()));
84 assertFalse(ThreadUtils.getAllThreadGroups().isEmpty());
28785 }
28886
28987 @Test
335133 }
336134 }
337135
338
339 private static class TestThread extends Thread {
340 private final CountDownLatch latch = new CountDownLatch(1);
341
342 TestThread(final String name) {
343 super(name);
344 }
345
346 TestThread(final ThreadGroup group, final String name) {
347 super(group, name);
348 }
349
350 @Override
351 public synchronized void start() {
352 super.start();
353 try {
354 latch.await();
355 } catch (final InterruptedException e) {
356 Thread.currentThread().interrupt();
357 }
358 }
359
360 @Override
361 public void run() {
362 latch.countDown();
363 try {
364 synchronized(this) {
365 this.wait();
366 }
367 } catch (final InterruptedException e) {
368 Thread.currentThread().interrupt();
369 }
136 @Test
137 public void testConstructor() {
138 assertNotNull(new ThreadUtils());
139 final Constructor<?>[] cons = ThreadUtils.class.getDeclaredConstructors();
140 assertEquals(1, cons.length);
141 assertTrue(Modifier.isPublic(cons[0].getModifiers()));
142 assertTrue(Modifier.isPublic(ThreadUtils.class.getModifiers()));
143 assertFalse(Modifier.isFinal(ThreadUtils.class.getModifiers()));
144 }
145
146 @Test
147 public void testInvalidThreadId() {
148 assertThrows(IllegalArgumentException.class, () -> ThreadUtils.findThreadById(-5L));
149 }
150
151 @Test
152 public void testJoinDuration() throws InterruptedException {
153 ThreadUtils.join(new Thread(), Duration.ZERO);
154 ThreadUtils.join(new Thread(), Duration.ofMillis(1));
155 }
156
157 @Test
158 public void testNoThread() {
159 assertEquals(0, ThreadUtils.findThreadsByName("some_thread_which_does_not_exist_18762ZucTT").size());
160 }
161
162 @Test
163 public void testNoThreadGroup() {
164 assertEquals(0, ThreadUtils.findThreadGroupsByName("some_thread_group_which_does_not_exist_18762ZucTTII").size());
165 }
166
167 @Test
168 public void testNullThreadGroupName() {
169 assertThrows(NullPointerException.class, () -> ThreadUtils.findThreadGroupsByName(null));
170 }
171
172 @Test
173 public void testNullThreadName() {
174 assertThrows(NullPointerException.class, () -> ThreadUtils.findThreadsByName(null));
175 }
176
177 @Test
178 public void testNullThreadThreadGroup1() {
179 assertThrows(NullPointerException.class, () -> ThreadUtils.findThreadsByName("tname", (ThreadGroup) null));
180 }
181
182 @Test
183 public void testNullThreadThreadGroup2() {
184 assertThrows(NullPointerException.class, () -> ThreadUtils.findThreadById(1L, (ThreadGroup) null));
185 }
186
187 @Test
188 public void testNullThreadThreadGroup3() {
189 assertThrows(NullPointerException.class, () -> ThreadUtils.findThreadsByName(null, (ThreadGroup) null));
190 }
191
192 @Test
193 public void testNullThreadThreadGroupName1() {
194 assertThrows(NullPointerException.class, () -> ThreadUtils.findThreadsByName(null, "tgname"));
195 }
196
197 @Test
198 public void testNullThreadThreadGroupName2() {
199 assertThrows(NullPointerException.class, () -> ThreadUtils.findThreadsByName("tname", (String) null));
200 }
201
202 @Test
203 public void testNullThreadThreadGroupName3() {
204 assertThrows(NullPointerException.class, () -> ThreadUtils.findThreadsByName(null, (String) null));
205 }
206
207 @Test
208 public void testSleepDuration() throws InterruptedException {
209 ThreadUtils.sleep(Duration.ZERO);
210 ThreadUtils.sleep(Duration.ofMillis(1));
211 }
212
213 @Test
214 public void testSystemThreadGroupExists() {
215 final ThreadGroup systemThreadGroup = ThreadUtils.getSystemThreadGroup();
216 assertNotNull(systemThreadGroup);
217 assertNull(systemThreadGroup.getParent());
218 assertEquals("system", systemThreadGroup.getName());
219 }
220
221 @Test
222 public void testThreadGroups() throws InterruptedException {
223 final ThreadGroup threadGroup = new ThreadGroup("thread_group_DDZZ99__");
224 final Thread t1 = new TestThread(threadGroup, "thread1_XXOOPP__");
225 final Thread t2 = new TestThread(threadGroup, "thread2_XXOOPP__");
226
227 try {
228 t1.start();
229 t2.start();
230 assertEquals(1, ThreadUtils.findThreadsByName("thread1_XXOOPP__").size());
231 assertEquals(1, ThreadUtils.findThreadsByName("thread1_XXOOPP__", "thread_group_DDZZ99__").size());
232 assertEquals(1, ThreadUtils.findThreadsByName("thread2_XXOOPP__", "thread_group_DDZZ99__").size());
233 assertEquals(0, ThreadUtils.findThreadsByName("thread1_XXOOPP__", "non_existent_thread_group_JJHHZZ__").size());
234 assertEquals(0, ThreadUtils.findThreadsByName("non_existent_thread_BBDDWW__", "thread_group_DDZZ99__").size());
235 assertEquals(1, ThreadUtils.findThreadGroupsByName("thread_group_DDZZ99__").size());
236 assertEquals(0, ThreadUtils.findThreadGroupsByName("non_existent_thread_group_JJHHZZ__").size());
237 assertNotNull(ThreadUtils.findThreadById(t1.getId(), threadGroup));
238 } finally {
239 t1.interrupt();
240 t2.interrupt();
241 t1.join();
242 t2.join();
243 threadGroup.destroy();
244 }
245 }
246
247 @Test
248 public void testThreadGroupsById() throws InterruptedException {
249 final ThreadGroup threadGroup = new ThreadGroup("thread_group_DDZZ99__");
250 final Thread t1 = new TestThread(threadGroup, "thread1_XXOOPP__");
251 final Thread t2 = new TestThread(threadGroup, "thread2_XXOOPP__");
252 final long nonExistingId = t1.getId()+t2.getId();
253
254 try {
255 t1.start();
256 t2.start();
257 assertSame(t1, ThreadUtils.findThreadById(t1.getId(), "thread_group_DDZZ99__"));
258 assertSame(t2, ThreadUtils.findThreadById(t2.getId(), "thread_group_DDZZ99__"));
259 assertNull(ThreadUtils.findThreadById(nonExistingId, "non_existent_thread_group_JJHHZZ__"));
260 assertNull(ThreadUtils.findThreadById(nonExistingId, "thread_group_DDZZ99__"));
261 } finally {
262 t1.interrupt();
263 t2.interrupt();
264 t1.join();
265 t2.join();
266 threadGroup.destroy();
267 }
268 }
269
270 @Test
271 public void testThreadGroupsByIdFail() {
272 assertThrows(NullPointerException.class,
273 () -> ThreadUtils.findThreadById(Thread.currentThread().getId(), (String) null));
274 }
275
276
277 @Test
278 public void testThreadgroupsNullParent() {
279 assertThrows(NullPointerException.class,
280 () -> ThreadUtils.findThreadGroups(null, true, ThreadUtils.ALWAYS_TRUE_PREDICATE));
281 }
282
283 @Test
284 public void testThreadgroupsNullPredicate() {
285 assertThrows(NullPointerException.class, () -> ThreadUtils.findThreadGroups(null));
286 }
287
288 @Test
289 public void testThreadGroupsRef() throws InterruptedException {
290 final ThreadGroup threadGroup = new ThreadGroup("thread_group_DDZZ99__");
291 final ThreadGroup deadThreadGroup = new ThreadGroup("dead_thread_group_MMQQSS__");
292 deadThreadGroup.destroy();
293 final Thread t1 = new TestThread(threadGroup, "thread1_XXOOPP__");
294 final Thread t2 = new TestThread(threadGroup, "thread2_XXOOPP__");
295
296 try {
297 t1.start();
298 t2.start();
299 assertEquals(1, ThreadUtils.findThreadsByName("thread1_XXOOPP__").size());
300 assertEquals(1, ThreadUtils.findThreadsByName("thread1_XXOOPP__", threadGroup).size());
301 assertEquals(1, ThreadUtils.findThreadsByName("thread2_XXOOPP__", threadGroup).size());
302 assertEquals(0, ThreadUtils.findThreadsByName("thread1_XXOOPP__", deadThreadGroup).size());
303 } finally {
304 t1.interrupt();
305 t2.interrupt();
306 t1.join();
307 t2.join();
308 threadGroup.destroy();
309 assertEquals(0, ThreadUtils.findThreadsByName("thread2_XXOOPP__", threadGroup).size());
310 }
311 }
312
313 @Test
314 public void testThreads() throws InterruptedException {
315 final Thread t1 = new TestThread("thread1_XXOOLL__");
316 final Thread t2 = new TestThread("thread2_XXOOLL__");
317
318 try {
319 t1.start();
320 t2.start();
321 assertEquals(1, ThreadUtils.findThreadsByName("thread2_XXOOLL__").size());
322 } finally {
323 t1.interrupt();
324 t2.interrupt();
325 t1.join();
326 t2.join();
327 }
328 }
329
330 @Test
331 public void testThreadsById() throws InterruptedException {
332 final Thread t1 = new TestThread("thread1_XXOOLL__");
333 final Thread t2 = new TestThread("thread2_XXOOLL__");
334
335 try {
336 t1.start();
337 t2.start();
338 assertSame(t1, ThreadUtils.findThreadById(t1.getId()));
339 assertSame(t2, ThreadUtils.findThreadById(t2.getId()));
340 } finally {
341 t1.interrupt();
342 t2.interrupt();
343 t1.join();
344 t2.join();
345 }
346 }
347
348
349 @Test
350 public void testThreadsByIdWrongGroup() throws InterruptedException {
351 final Thread t1 = new TestThread("thread1_XXOOLL__");
352 final ThreadGroup tg = new ThreadGroup("tg__HHEE22");
353
354 try {
355 t1.start();
356 assertNull(ThreadUtils.findThreadById(t1.getId(), tg));
357 } finally {
358 t1.interrupt();
359 t1.join();
360 tg.destroy();
361 }
362 }
363
364 @Test
365 public void testThreadsNullPredicate() {
366 assertThrows(NullPointerException.class, () -> ThreadUtils.findThreads(null));
367 }
368
369 @Test
370 public void testThreadsSameName() throws InterruptedException {
371 final Thread t1 = new TestThread("thread1_XXOOLL__");
372 final Thread alsot1 = new TestThread("thread1_XXOOLL__");
373
374 try {
375 t1.start();
376 alsot1.start();
377 assertEquals(2, ThreadUtils.findThreadsByName("thread1_XXOOLL__").size());
378 } finally {
379 t1.interrupt();
380 alsot1.interrupt();
381 t1.join();
382 alsot1.join();
370383 }
371384 }
372385 }
207207
208208 @Test
209209 void shouldReturnTheSameInstance() {
210 final String[] array = new String[]{"hi"};
210 final String[] array = {"hi"};
211211 final String[] result = Validate.notEmpty(array);
212212
213213 assertSame(array, result);
242242
243243 @Test
244244 void shouldReturnTheSameInstance() {
245 final String[] array = new String[]{"hi"};
245 final String[] array = {"hi"};
246246 final String[] result = Validate.notEmpty(array, "MSG");
247247
248248 assertSame(array, result);
2828 */
2929 public class CompareToBuilderTest {
3030
31 //-----------------------------------------------------------------------
3231
3332 static class TestObject implements Comparable<TestObject> {
3433 private int a;
8988
9089 static class TestTransientSubObject extends TestObject {
9190 @SuppressWarnings("unused")
92 private transient int t;
91 private final transient int t;
9392 TestTransientSubObject(final int a, final int t) {
9493 super(a);
9594 this.t = t;
127126
128127 @Test
129128 public void testReflectionHierarchyCompareExcludeFields() {
130 final String[] excludeFields = new String[] { "b" };
129 final String[] excludeFields = { "b" };
131130 testReflectionHierarchyCompare(true, excludeFields);
132131
133132 TestSubObject x;
1717
1818 import static org.junit.jupiter.api.Assertions.assertEquals;
1919
20 import java.util.ArrayList;
21 import java.util.HashMap;
20 import java.util.Arrays;
21 import java.util.Collections;
2222
2323 import org.apache.commons.lang3.builder.ToStringStyleTest.Person;
2424 import org.junit.jupiter.api.AfterEach;
7070 assertEquals(baseStr + "[a=3]", new ToStringBuilder(base).append("a", i3).toString());
7171 assertEquals(baseStr + "[a=3,b=4]", new ToStringBuilder(base).append("a", i3).append("b", i4).toString());
7272 assertEquals(baseStr + "[a=<Integer>]", new ToStringBuilder(base).append("a", i3, false).toString());
73 assertEquals(baseStr + "[a=<size=0>]", new ToStringBuilder(base).append("a", new ArrayList<>(), false).toString());
74 assertEquals(baseStr + "[a=[]]", new ToStringBuilder(base).append("a", new ArrayList<>(), true).toString());
75 assertEquals(baseStr + "[a=<size=0>]", new ToStringBuilder(base).append("a", new HashMap<>(), false).toString());
76 assertEquals(baseStr + "[a={}]", new ToStringBuilder(base).append("a", new HashMap<>(), true).toString());
77 assertEquals(baseStr + "[a=<size=0>]", new ToStringBuilder(base).append("a", (Object) new String[0], false).toString());
78 assertEquals(baseStr + "[a={}]", new ToStringBuilder(base).append("a", (Object) new String[0], true).toString());
73 }
74
75 @Test
76 public void testCollection() {
77 final Integer i3 = Integer.valueOf(3);
78 final Integer i4 = Integer.valueOf(4);
79 assertEquals(baseStr + "[a=<size=0>]", new ToStringBuilder(base).append("a", Collections.emptyList(), false).toString());
80 assertEquals(baseStr + "[a=[]]", new ToStringBuilder(base).append("a", Collections.emptyList(), true).toString());
81 assertEquals(baseStr + "[a=<size=1>]", new ToStringBuilder(base).append("a", Collections.singletonList(i3), false).toString());
82 assertEquals(baseStr + "[a=[3]]", new ToStringBuilder(base).append("a", Collections.singletonList(i3), true).toString());
83 assertEquals(baseStr + "[a=<size=2>]", new ToStringBuilder(base).append("a", Arrays.asList(i3, i4), false).toString());
84 assertEquals(baseStr + "[a=[3, 4]]", new ToStringBuilder(base).append("a", Arrays.asList(i3, i4), true).toString());
85 }
86
87 @Test
88 public void testMap() {
89 assertEquals(baseStr + "[a=<size=0>]", new ToStringBuilder(base).append("a", Collections.emptyMap(), false).toString());
90 assertEquals(baseStr + "[a={}]", new ToStringBuilder(base).append("a", Collections.emptyMap(), true).toString());
91 assertEquals(baseStr + "[a=<size=1>]", new ToStringBuilder(base).append("a", Collections.singletonMap("k", "v"), false).toString());
92 assertEquals(baseStr + "[a={k=v}]", new ToStringBuilder(base).append("a", Collections.singletonMap("k", "v"), true).toString());
93 }
94
95 @Test
96 public void testArray() {
97 final Integer i3 = Integer.valueOf(3);
98 final Integer i4 = Integer.valueOf(4);
99 assertEquals(baseStr + "[a=<size=0>]", new ToStringBuilder(base).append("a", (Object) new Integer[0], false).toString());
100 assertEquals(baseStr + "[a={}]", new ToStringBuilder(base).append("a", (Object) new Integer[0], true).toString());
101 assertEquals(baseStr + "[a=<size=1>]", new ToStringBuilder(base).append("a", (Object) new Integer[] {i3}, false).toString());
102 assertEquals(baseStr + "[a={3}]", new ToStringBuilder(base).append("a", (Object) new Integer[] {i3}, true).toString());
103 assertEquals(baseStr + "[a=<size=2>]", new ToStringBuilder(base).append("a", (Object) new Integer[] {i3, i4}, false).toString());
104 assertEquals(baseStr + "[a={3,4}]", new ToStringBuilder(base).append("a", (Object) new Integer[] {i3, i4}, true).toString());
79105 }
80106
81107 @Test
97123
98124 @Test
99125 public void testObjectArray() {
100 Object[] array = new Object[] {null, base, new int[] {3, 6}};
126 Object[] array = {null, base, new int[] {3, 6}};
101127 assertEquals(baseStr + "[{<null>,5,{3,6}}]", new ToStringBuilder(base).append(array).toString());
102128 assertEquals(baseStr + "[{<null>,5,{3,6}}]", new ToStringBuilder(base).append((Object) array).toString());
103129 array = null;
107133
108134 @Test
109135 public void testLongArray() {
110 long[] array = new long[] {1, 2, -3, 4};
136 long[] array = {1, 2, -3, 4};
111137 assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append(array).toString());
112138 assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append((Object) array).toString());
113139 array = null;
117143
118144 @Test
119145 public void testLongArrayArray() {
120 long[][] array = new long[][] {{1, 2}, null, {5}};
146 long[][] array = {{1, 2}, null, {5}};
121147 assertEquals(baseStr + "[{{1,2},<null>,{5}}]", new ToStringBuilder(base).append(array).toString());
122148 assertEquals(baseStr + "[{{1,2},<null>,{5}}]", new ToStringBuilder(base).append((Object) array).toString());
123149 array = null;
3232 */
3333 public class EqualsBuilderTest {
3434
35 //-----------------------------------------------------------------------
3635
3736 static class TestObject {
3837 private int a;
124123
125124 static class TestTSubObject extends TestObject {
126125 @SuppressWarnings("unused")
127 private transient int t;
126 private final transient int t;
128127
129128 TestTSubObject(final int a, final int t) {
130129 super(a);
134133
135134 static class TestTTSubObject extends TestTSubObject {
136135 @SuppressWarnings("unused")
137 private transient int tt;
136 private final transient int tt;
138137
139138 TestTTSubObject(final int a, final int t, final int tt) {
140139 super(a, t);
915914 assertFalse(new EqualsBuilder().append(array1, array2).isEquals());
916915
917916 // compare 1 dim to 2.
918 final boolean[] array3 = new boolean[]{true, true};
917 final boolean[] array3 = {true, true};
919918 assertFalse(new EqualsBuilder().append(array1, array3).isEquals());
920919 assertFalse(new EqualsBuilder().append(array3, array1).isEquals());
921920 assertFalse(new EqualsBuilder().append(array2, array3).isEquals());
11891188 */
11901189 @Test
11911190 public void testUnrelatedClasses() {
1192 final Object[] x = new Object[]{new TestACanEqualB(1)};
1193 final Object[] y = new Object[]{new TestBCanEqualA(1)};
1191 final Object[] x = {new TestACanEqualB(1)};
1192 final Object[] y = {new TestBCanEqualA(1)};
11941193
11951194 // sanity checks:
11961195 assertArrayEquals(x, x);
12131212 */
12141213 @Test
12151214 public void testNpeForNullElement() {
1216 final Object[] x1 = new Object[]{Integer.valueOf(1), null, Integer.valueOf(3)};
1217 final Object[] x2 = new Object[]{Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(3)};
1215 final Object[] x1 = {Integer.valueOf(1), null, Integer.valueOf(3)};
1216 final Object[] x2 = {Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(3)};
12181217
12191218 // causes an NPE in 2.0 according to:
12201219 // https://issues.apache.org/bugzilla/show_bug.cgi?id=33067
13161315 final TestObject one = new TestObject(1);
13171316 final TestObject two = new TestObject(2);
13181317
1319 final Object[] o1 = new Object[]{one};
1320 final Object[] o2 = new Object[]{two};
1321 final Object[] o3 = new Object[]{one};
1318 final Object[] o1 = {one};
1319 final Object[] o2 = {two};
1320 final Object[] o3 = {one};
13221321
13231322 assertFalse(EqualsBuilder.reflectionEquals(o1, o2));
13241323 assertTrue(EqualsBuilder.reflectionEquals(o1, o1));
2626 */
2727 public class HashCodeBuilderAndEqualsBuilderTest {
2828
29 //-----------------------------------------------------------------------
3029
3130 private void testInteger(final boolean testTransients) {
3231 final Integer i1 = Integer.valueOf(12345);
2323 import java.util.Collections;
2424 import java.util.Date;
2525 import java.util.HashMap;
26 import java.util.LinkedHashMap;
2627 import java.util.List;
27
28 import java.util.LinkedHashMap;
2928 import java.util.Map;
29
3030 import org.apache.commons.lang3.builder.ToStringStyleTest.Person;
3131 import org.junit.jupiter.api.AfterEach;
3232 import org.junit.jupiter.api.BeforeEach;
304304
305305 @Test
306306 public void testObjectArray() {
307 final Object[] array = new Object[]{null, base, new int[]{3, 6}};
307 final Object[] array = {null, base, new int[]{3, 6}};
308308
309309 final ToStringBuilder toStringBuilder = new ToStringBuilder(base);
310310 assertThrows(UnsupportedOperationException.class, () -> toStringBuilder.append(array).toString());
324324
325325 @Test
326326 public void testLongArray() {
327 final long[] array = new long[]{1, 2, -3, 4};
327 final long[] array = {1, 2, -3, 4};
328328
329329 final ToStringBuilder toStringBuilder = new ToStringBuilder(base);
330330 assertThrows(UnsupportedOperationException.class, () -> toStringBuilder.append(array).toString());
344344
345345 @Test
346346 public void testIntArray() {
347 final int[] array = new int[]{1, 2, -3, 4};
347 final int[] array = {1, 2, -3, 4};
348348
349349 final ToStringBuilder toStringBuilder = new ToStringBuilder(base);
350350 assertThrows(UnsupportedOperationException.class, () -> toStringBuilder.append(array).toString());
364364
365365 @Test
366366 public void testByteArray() {
367 final byte[] array = new byte[]{1, 2, -3, 4};
367 final byte[] array = {1, 2, -3, 4};
368368
369369 final ToStringBuilder toStringBuilder = new ToStringBuilder(base);
370370 assertThrows(UnsupportedOperationException.class, () -> toStringBuilder.append(array).toString());
384384
385385 @Test
386386 public void testShortArray() {
387 final short[] array = new short[]{1, 2, -3, 4};
387 final short[] array = {1, 2, -3, 4};
388388
389389 final ToStringBuilder toStringBuilder = new ToStringBuilder(base);
390390 assertThrows(UnsupportedOperationException.class, () -> toStringBuilder.append(array).toString());
404404
405405 @Test
406406 public void testDoubleArray() {
407 final double[] array = new double[]{1, 2, -3, 4};
407 final double[] array = {1, 2, -3, 4};
408408
409409 final ToStringBuilder toStringBuilder = new ToStringBuilder(base);
410410 assertThrows(UnsupportedOperationException.class, () -> toStringBuilder.append(array).toString());
424424
425425 @Test
426426 public void testFloatArray() {
427 final float[] array = new float[]{1, 2, -3, 4};
427 final float[] array = {1, 2, -3, 4};
428428
429429 final ToStringBuilder toStringBuilder = new ToStringBuilder(base);
430430 assertThrows(UnsupportedOperationException.class, () -> toStringBuilder.append(array).toString());
444444
445445 @Test
446446 public void testCharArray() {
447 final char[] array = new char[]{'1', '2', '3', '4'};
447 final char[] array = {'1', '2', '3', '4'};
448448
449449 final ToStringBuilder toStringBuilder = new ToStringBuilder(base);
450450 assertThrows(UnsupportedOperationException.class, () -> toStringBuilder.append(array).toString());
464464
465465 @Test
466466 public void testBooleanArray() {
467 final boolean[] array = new boolean[]{true, false};
467 final boolean[] array = {true, false};
468468
469469 final ToStringBuilder toStringBuilder = new ToStringBuilder(base);
470470 assertThrows(UnsupportedOperationException.class, () -> toStringBuilder.append(array).toString());
484484
485485 @Test
486486 public void testLongArrayArray() {
487 final long[][] array = new long[][]{{1, 2}, null, {5}};
487 final long[][] array = {{1, 2}, null, {5}};
488488
489489 final ToStringBuilder toStringBuilder = new ToStringBuilder(base);
490490 assertThrows(UnsupportedOperationException.class, () -> toStringBuilder.append(array).toString());
598598 }
599599
600600 /**
601 * An object with nested object structures used to test {@link ToStringStyle.JsonToStringStyle}.
602 *
601 * An object with nested object structures used to test {@code ToStringStyle.JsonToStringStyle}.
603602 */
604603 static class NestingPerson {
605604 /**
683682 }
684683
685684 /**
686 * An object with a Map field used to test {@link ToStringStyle.JsonToStringStyle}.
687 *
685 * An object with a Map field used to test {@code ToStringStyle.JsonToStringStyle}.
688686 */
689687 static class InnerMapObject {
690688 /**
1717
1818 import static org.junit.jupiter.api.Assertions.assertEquals;
1919
20 import java.util.ArrayList;
21 import java.util.HashMap;
20 import java.util.Arrays;
21 import java.util.Collections;
2222
2323 import org.apache.commons.lang3.builder.ToStringStyleTest.Person;
2424 import org.junit.jupiter.api.AfterEach;
7070 assertEquals(baseStr + "[" + System.lineSeparator() + " a=3" + System.lineSeparator() + "]", new ToStringBuilder(base).append("a", i3).toString());
7171 assertEquals(baseStr + "[" + System.lineSeparator() + " a=3" + System.lineSeparator() + " b=4" + System.lineSeparator() + "]", new ToStringBuilder(base).append("a", i3).append("b", i4).toString());
7272 assertEquals(baseStr + "[" + System.lineSeparator() + " a=<Integer>" + System.lineSeparator() + "]", new ToStringBuilder(base).append("a", i3, false).toString());
73 assertEquals(baseStr + "[" + System.lineSeparator() + " a=<size=0>" + System.lineSeparator() + "]", new ToStringBuilder(base).append("a", new ArrayList<>(), false).toString());
74 assertEquals(baseStr + "[" + System.lineSeparator() + " a=[]" + System.lineSeparator() + "]", new ToStringBuilder(base).append("a", new ArrayList<>(), true).toString());
75 assertEquals(baseStr + "[" + System.lineSeparator() + " a=<size=0>" + System.lineSeparator() + "]", new ToStringBuilder(base).append("a", new HashMap<>(), false).toString());
76 assertEquals(baseStr + "[" + System.lineSeparator() + " a={}" + System.lineSeparator() + "]", new ToStringBuilder(base).append("a", new HashMap<>(), true).toString());
77 assertEquals(baseStr + "[" + System.lineSeparator() + " a=<size=0>" + System.lineSeparator() + "]", new ToStringBuilder(base).append("a", (Object) new String[0], false).toString());
78 assertEquals(baseStr + "[" + System.lineSeparator() + " a={}" + System.lineSeparator() + "]", new ToStringBuilder(base).append("a", (Object) new String[0], true).toString());
73 }
74
75 @Test
76 public void testCollection() {
77 final Integer i3 = Integer.valueOf(3);
78 final Integer i4 = Integer.valueOf(4);
79 assertEquals(baseStr + "[" + System.lineSeparator() + " a=<size=0>" + System.lineSeparator() + "]", new ToStringBuilder(base).append("a", Collections.emptyList(), false).toString());
80 assertEquals(baseStr + "[" + System.lineSeparator() + " a=[]" + System.lineSeparator() + "]", new ToStringBuilder(base).append("a", Collections.emptyList(), true).toString());
81 assertEquals(baseStr + "[" + System.lineSeparator() + " a=<size=1>" + System.lineSeparator() + "]", new ToStringBuilder(base).append("a", Collections.singletonList(i3), false).toString());
82 assertEquals(baseStr + "[" + System.lineSeparator() + " a=[3]" + System.lineSeparator() + "]", new ToStringBuilder(base).append("a", Collections.singletonList(i3), true).toString());
83 assertEquals(baseStr + "[" + System.lineSeparator() + " a=<size=2>" + System.lineSeparator() + "]", new ToStringBuilder(base).append("a", Arrays.asList(i3, i4), false).toString());
84 assertEquals(baseStr + "[" + System.lineSeparator() + " a=[3, 4]" + System.lineSeparator() + "]", new ToStringBuilder(base).append("a", Arrays.asList(i3, i4), true).toString());
85 }
86
87 @Test
88 public void testMap() {
89 assertEquals(baseStr + "[" + System.lineSeparator() + " a=<size=0>" + System.lineSeparator() + "]", new ToStringBuilder(base).append("a", Collections.emptyMap(), false).toString());
90 assertEquals(baseStr + "[" + System.lineSeparator() + " a={}" + System.lineSeparator() + "]", new ToStringBuilder(base).append("a", Collections.emptyMap(), true).toString());
91 assertEquals(baseStr + "[" + System.lineSeparator() + " a=<size=1>" + System.lineSeparator() + "]", new ToStringBuilder(base).append("a", Collections.singletonMap("k", "v"), false).toString());
92 assertEquals(baseStr + "[" + System.lineSeparator() + " a={k=v}" + System.lineSeparator() + "]", new ToStringBuilder(base).append("a", Collections.singletonMap("k", "v"), true).toString());
93 }
94
95 @Test
96 public void testArray() {
97 final Integer i3 = Integer.valueOf(3);
98 final Integer i4 = Integer.valueOf(4);
99 assertEquals(baseStr + "[" + System.lineSeparator() + " a=<size=0>" + System.lineSeparator() + "]", new ToStringBuilder(base).append("a", (Object) new Integer[0], false).toString());
100 assertEquals(baseStr + "[" + System.lineSeparator() + " a={}" + System.lineSeparator() + "]", new ToStringBuilder(base).append("a", (Object) new Integer[0], true).toString());
101 assertEquals(baseStr + "[" + System.lineSeparator() + " a=<size=1>" + System.lineSeparator() + "]", new ToStringBuilder(base).append("a", (Object) new Integer[] {i3}, false).toString());
102 assertEquals(baseStr + "[" + System.lineSeparator() + " a={3}" + System.lineSeparator() + "]", new ToStringBuilder(base).append("a", (Object) new Integer[] {i3}, true).toString());
103 assertEquals(baseStr + "[" + System.lineSeparator() + " a=<size=2>" + System.lineSeparator() + "]", new ToStringBuilder(base).append("a", (Object) new Integer[] {i3, i4}, false).toString());
104 assertEquals(baseStr + "[" + System.lineSeparator() + " a={3,4}" + System.lineSeparator() + "]", new ToStringBuilder(base).append("a", (Object) new Integer[] {i3, i4}, true).toString());
79105 }
80106
81107 @Test
97123
98124 @Test
99125 public void testObjectArray() {
100 Object[] array = new Object[] {null, base, new int[] {3, 6}};
126 Object[] array = {null, base, new int[] {3, 6}};
101127 assertEquals(baseStr + "[" + System.lineSeparator() + " {<null>,5,{3,6}}" + System.lineSeparator() + "]", new ToStringBuilder(base).append(array).toString());
102128 assertEquals(baseStr + "[" + System.lineSeparator() + " {<null>,5,{3,6}}" + System.lineSeparator() + "]", new ToStringBuilder(base).append((Object) array).toString());
103129 array = null;
107133
108134 @Test
109135 public void testLongArray() {
110 long[] array = new long[] {1, 2, -3, 4};
136 long[] array = {1, 2, -3, 4};
111137 assertEquals(baseStr + "[" + System.lineSeparator() + " {1,2,-3,4}" + System.lineSeparator() + "]", new ToStringBuilder(base).append(array).toString());
112138 assertEquals(baseStr + "[" + System.lineSeparator() + " {1,2,-3,4}" + System.lineSeparator() + "]", new ToStringBuilder(base).append((Object) array).toString());
113139 array = null;
117143
118144 @Test
119145 public void testLongArrayArray() {
120 long[][] array = new long[][] {{1, 2}, null, {5}};
146 long[][] array = {{1, 2}, null, {5}};
121147 assertEquals(baseStr + "[" + System.lineSeparator() + " {{1,2},<null>,{5}}" + System.lineSeparator() + "]", new ToStringBuilder(base).append(array).toString());
122148 assertEquals(baseStr + "[" + System.lineSeparator() + " {{1,2},<null>,{5}}" + System.lineSeparator() + "]", new ToStringBuilder(base).append((Object) array).toString());
123149 array = null;
1717
1818 import static org.junit.jupiter.api.Assertions.assertEquals;
1919
20 import java.util.ArrayList;
21 import java.util.HashMap;
20 import java.util.Arrays;
21 import java.util.Collections;
2222
2323 import org.apache.commons.lang3.builder.ToStringStyleTest.Person;
2424 import org.junit.jupiter.api.AfterEach;
6969 assertEquals("[a=3]", new ToStringBuilder(base).append("a", i3).toString());
7070 assertEquals("[a=3,b=4]", new ToStringBuilder(base).append("a", i3).append("b", i4).toString());
7171 assertEquals("[a=<Integer>]", new ToStringBuilder(base).append("a", i3, false).toString());
72 assertEquals("[a=<size=0>]", new ToStringBuilder(base).append("a", new ArrayList<>(), false).toString());
73 assertEquals("[a=[]]", new ToStringBuilder(base).append("a", new ArrayList<>(), true).toString());
74 assertEquals("[a=<size=0>]", new ToStringBuilder(base).append("a", new HashMap<>(), false).toString());
75 assertEquals("[a={}]", new ToStringBuilder(base).append("a", new HashMap<>(), true).toString());
76 assertEquals("[a=<size=0>]", new ToStringBuilder(base).append("a", (Object) new String[0], false).toString());
77 assertEquals("[a={}]", new ToStringBuilder(base).append("a", (Object) new String[0], true).toString());
72 }
73
74 @Test
75 public void testCollection() {
76 final Integer i3 = Integer.valueOf(3);
77 final Integer i4 = Integer.valueOf(4);
78 assertEquals("[a=<size=0>]", new ToStringBuilder(base).append("a", Collections.emptyList(), false).toString());
79 assertEquals("[a=[]]", new ToStringBuilder(base).append("a", Collections.emptyList(), true).toString());
80 assertEquals("[a=<size=1>]", new ToStringBuilder(base).append("a", Collections.singletonList(i3), false).toString());
81 assertEquals("[a=[3]]", new ToStringBuilder(base).append("a", Collections.singletonList(i3), true).toString());
82 assertEquals("[a=<size=2>]", new ToStringBuilder(base).append("a", Arrays.asList(i3, i4), false).toString());
83 assertEquals("[a=[3, 4]]", new ToStringBuilder(base).append("a", Arrays.asList(i3, i4), true).toString());
84 }
85
86 @Test
87 public void testMap() {
88 assertEquals("[a=<size=0>]", new ToStringBuilder(base).append("a", Collections.emptyMap(), false).toString());
89 assertEquals("[a={}]", new ToStringBuilder(base).append("a", Collections.emptyMap(), true).toString());
90 assertEquals("[a=<size=1>]", new ToStringBuilder(base).append("a", Collections.singletonMap("k", "v"), false).toString());
91 assertEquals("[a={k=v}]", new ToStringBuilder(base).append("a", Collections.singletonMap("k", "v"), true).toString());
92 }
93
94 @Test
95 public void testArray() {
96 final Integer i3 = Integer.valueOf(3);
97 final Integer i4 = Integer.valueOf(4);
98 assertEquals("[a=<size=0>]", new ToStringBuilder(base).append("a", (Object) new Integer[0], false).toString());
99 assertEquals("[a={}]", new ToStringBuilder(base).append("a", (Object) new Integer[0], true).toString());
100 assertEquals("[a=<size=1>]", new ToStringBuilder(base).append("a", (Object) new Integer[] {i3}, false).toString());
101 assertEquals("[a={3}]", new ToStringBuilder(base).append("a", (Object) new Integer[] {i3}, true).toString());
102 assertEquals("[a=<size=2>]", new ToStringBuilder(base).append("a", (Object) new Integer[] {i3, i4}, false).toString());
103 assertEquals("[a={3,4}]", new ToStringBuilder(base).append("a", (Object) new Integer[] {i3, i4}, true).toString());
78104 }
79105
80106 @Test
95121
96122 @Test
97123 public void testObjectArray() {
98 Object[] array = new Object[] {null, base, new int[] {3, 6}};
124 Object[] array = {null, base, new int[] {3, 6}};
99125 assertEquals("[{<null>,5,{3,6}}]", new ToStringBuilder(base).append(array).toString());
100126 assertEquals("[{<null>,5,{3,6}}]", new ToStringBuilder(base).append((Object) array).toString());
101127 array = null;
105131
106132 @Test
107133 public void testLongArray() {
108 long[] array = new long[] {1, 2, -3, 4};
134 long[] array = {1, 2, -3, 4};
109135 assertEquals("[{1,2,-3,4}]", new ToStringBuilder(base).append(array).toString());
110136 assertEquals("[{1,2,-3,4}]", new ToStringBuilder(base).append((Object) array).toString());
111137 array = null;
115141
116142 @Test
117143 public void testLongArrayArray() {
118 long[][] array = new long[][] {{1, 2}, null, {5}};
144 long[][] array = {{1, 2}, null, {5}};
119145 assertEquals("[{{1,2},<null>,{5}}]", new ToStringBuilder(base).append(array).toString());
120146 assertEquals("[{{1,2},<null>,{5}}]", new ToStringBuilder(base).append((Object) array).toString());
121147 array = null;
1717
1818 import static org.junit.jupiter.api.Assertions.assertEquals;
1919
20 import java.util.ArrayList;
21 import java.util.HashMap;
20 import java.util.Arrays;
21 import java.util.Collections;
2222
2323 import org.apache.commons.lang3.builder.ToStringStyleTest.Person;
2424 import org.junit.jupiter.api.AfterEach;
7070 assertEquals(baseStr + "[3]", new ToStringBuilder(base).append("a", i3).toString());
7171 assertEquals(baseStr + "[3,4]", new ToStringBuilder(base).append("a", i3).append("b", i4).toString());
7272 assertEquals(baseStr + "[<Integer>]", new ToStringBuilder(base).append("a", i3, false).toString());
73 assertEquals(baseStr + "[<size=0>]", new ToStringBuilder(base).append("a", new ArrayList<>(), false).toString());
74 assertEquals(baseStr + "[[]]", new ToStringBuilder(base).append("a", new ArrayList<>(), true).toString());
75 assertEquals(baseStr + "[<size=0>]", new ToStringBuilder(base).append("a", new HashMap<>(), false).toString());
76 assertEquals(baseStr + "[{}]", new ToStringBuilder(base).append("a", new HashMap<>(), true).toString());
77 assertEquals(baseStr + "[<size=0>]", new ToStringBuilder(base).append("a", (Object) new String[0], false).toString());
78 assertEquals(baseStr + "[{}]", new ToStringBuilder(base).append("a", (Object) new String[0], true).toString());
73 }
74
75 @Test
76 public void testCollection() {
77 final Integer i3 = Integer.valueOf(3);
78 final Integer i4 = Integer.valueOf(4);
79 assertEquals(baseStr + "[<size=0>]", new ToStringBuilder(base).append("a", Collections.emptyList(), false).toString());
80 assertEquals(baseStr + "[[]]", new ToStringBuilder(base).append("a", Collections.emptyList(), true).toString());
81 assertEquals(baseStr + "[<size=1>]", new ToStringBuilder(base).append("a", Collections.singletonList(i3), false).toString());
82 assertEquals(baseStr + "[[3]]", new ToStringBuilder(base).append("a", Collections.singletonList(i3), true).toString());
83 assertEquals(baseStr + "[<size=2>]", new ToStringBuilder(base).append("a", Arrays.asList(i3, i4), false).toString());
84 assertEquals(baseStr + "[[3, 4]]", new ToStringBuilder(base).append("a", Arrays.asList(i3, i4), true).toString());
85 }
86
87 @Test
88 public void testMap() {
89 assertEquals(baseStr + "[<size=0>]", new ToStringBuilder(base).append("a", Collections.emptyMap(), false).toString());
90 assertEquals(baseStr + "[{}]", new ToStringBuilder(base).append("a", Collections.emptyMap(), true).toString());
91 assertEquals(baseStr + "[<size=1>]", new ToStringBuilder(base).append("a", Collections.singletonMap("k", "v"), false).toString());
92 assertEquals(baseStr + "[{k=v}]", new ToStringBuilder(base).append("a", Collections.singletonMap("k", "v"), true).toString());
93 }
94
95 @Test
96 public void testArray() {
97 final Integer i3 = Integer.valueOf(3);
98 final Integer i4 = Integer.valueOf(4);
99 assertEquals(baseStr + "[<size=0>]", new ToStringBuilder(base).append("a", (Object) new Integer[0], false).toString());
100 assertEquals(baseStr + "[{}]", new ToStringBuilder(base).append("a", (Object) new Integer[0], true).toString());
101 assertEquals(baseStr + "[<size=1>]", new ToStringBuilder(base).append("a", (Object) new Integer[] {i3}, false).toString());
102 assertEquals(baseStr + "[{3}]", new ToStringBuilder(base).append("a", (Object) new Integer[] {i3}, true).toString());
103 assertEquals(baseStr + "[<size=2>]", new ToStringBuilder(base).append("a", (Object) new Integer[] {i3, i4}, false).toString());
104 assertEquals(baseStr + "[{3,4}]", new ToStringBuilder(base).append("a", (Object) new Integer[] {i3, i4}, true).toString());
79105 }
80106
81107 @Test
97123
98124 @Test
99125 public void testObjectArray() {
100 Object[] array = new Object[] {null, base, new int[] {3, 6}};
126 Object[] array = {null, base, new int[] {3, 6}};
101127 assertEquals(baseStr + "[{<null>,5,{3,6}}]", new ToStringBuilder(base).append(array).toString());
102128 assertEquals(baseStr + "[{<null>,5,{3,6}}]", new ToStringBuilder(base).append((Object) array).toString());
103129 array = null;
107133
108134 @Test
109135 public void testLongArray() {
110 long[] array = new long[] {1, 2, -3, 4};
136 long[] array = {1, 2, -3, 4};
111137 assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append(array).toString());
112138 assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append((Object) array).toString());
113139 array = null;
117143
118144 @Test
119145 public void testLongArrayArray() {
120 long[][] array = new long[][] {{1, 2}, null, {5}};
146 long[][] array = {{1, 2}, null, {5}};
121147 assertEquals(baseStr + "[{{1,2},<null>,{5}}]", new ToStringBuilder(base).append(array).toString());
122148 assertEquals(baseStr + "[{{1,2},<null>,{5}}]", new ToStringBuilder(base).append((Object) array).toString());
123149 array = null;
103103
104104 @Test
105105 public void testObjectArray() {
106 Object[] array = new Object[] {null, base, new int[] {3, 6}};
106 Object[] array = {null, base, new int[] {3, 6}};
107107 assertEquals(baseStr + "[{<null>,5,{3,6}}]", new ToStringBuilder(base).append(array).toString());
108108 assertEquals(baseStr + "[{<null>,5,{3,6}}]", new ToStringBuilder(base).append((Object) array).toString());
109109 array = null;
113113
114114 @Test
115115 public void testLongArray() {
116 long[] array = new long[] {1, 2, -3, 4};
116 long[] array = {1, 2, -3, 4};
117117 assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append(array).toString());
118118 assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append((Object) array).toString());
119119 array = null;
123123
124124 @Test
125125 public void testLongArrayArray() {
126 long[][] array = new long[][] {{1, 2}, null, {5}};
126 long[][] array = {{1, 2}, null, {5}};
127127 assertEquals(baseStr + "[{{1,2},<null>,{5}}]", new ToStringBuilder(base).append(array).toString());
128128 assertEquals(baseStr + "[{{1,2},<null>,{5}}]", new ToStringBuilder(base).append((Object) array).toString());
129129 array = null;
1717
1818 import static org.junit.jupiter.api.Assertions.assertEquals;
1919
20 import java.util.ArrayList;
21 import java.util.HashMap;
20 import java.util.Arrays;
21 import java.util.Collections;
2222
2323 import org.apache.commons.lang3.builder.ToStringStyleTest.Person;
2424 import org.junit.jupiter.api.AfterEach;
7070 assertEquals(baseStr + "[a=3]", new ToStringBuilder(base).append("a", i3).toString());
7171 assertEquals(baseStr + "[a=3,b=4]", new ToStringBuilder(base).append("a", i3).append("b", i4).toString());
7272 assertEquals(baseStr + "[a=<Integer>]", new ToStringBuilder(base).append("a", i3, false).toString());
73 assertEquals(baseStr + "[a=<size=0>]", new ToStringBuilder(base).append("a", new ArrayList<>(), false).toString());
74 assertEquals(baseStr + "[a=[]]", new ToStringBuilder(base).append("a", new ArrayList<>(), true).toString());
75 assertEquals(baseStr + "[a=<size=0>]", new ToStringBuilder(base).append("a", new HashMap<>(), false).toString());
76 assertEquals(baseStr + "[a={}]", new ToStringBuilder(base).append("a", new HashMap<>(), true).toString());
77 assertEquals(baseStr + "[a=<size=0>]", new ToStringBuilder(base).append("a", (Object) new String[0], false).toString());
78 assertEquals(baseStr + "[a={}]", new ToStringBuilder(base).append("a", (Object) new String[0], true).toString());
73 }
74
75 @Test
76 public void testCollection() {
77 final Integer i3 = Integer.valueOf(3);
78 final Integer i4 = Integer.valueOf(4);
79 assertEquals(baseStr + "[a=<size=0>]", new ToStringBuilder(base).append("a", Collections.emptyList(), false).toString());
80 assertEquals(baseStr + "[a=[]]", new ToStringBuilder(base).append("a", Collections.emptyList(), true).toString());
81 assertEquals(baseStr + "[a=<size=1>]", new ToStringBuilder(base).append("a", Collections.singletonList(i3), false).toString());
82 assertEquals(baseStr + "[a=[3]]", new ToStringBuilder(base).append("a", Collections.singletonList(i3), true).toString());
83 assertEquals(baseStr + "[a=<size=2>]", new ToStringBuilder(base).append("a", Arrays.asList(i3, i4), false).toString());
84 assertEquals(baseStr + "[a=[3, 4]]", new ToStringBuilder(base).append("a", Arrays.asList(i3, i4), true).toString());
85 }
86
87 @Test
88 public void testMap() {
89 assertEquals(baseStr + "[a=<size=0>]", new ToStringBuilder(base).append("a", Collections.emptyMap(), false).toString());
90 assertEquals(baseStr + "[a={}]", new ToStringBuilder(base).append("a", Collections.emptyMap(), true).toString());
91 assertEquals(baseStr + "[a=<size=1>]", new ToStringBuilder(base).append("a", Collections.singletonMap("k", "v"), false).toString());
92 assertEquals(baseStr + "[a={k=v}]", new ToStringBuilder(base).append("a", Collections.singletonMap("k", "v"), true).toString());
93 }
94
95 @Test
96 public void testArray() {
97 final Integer i3 = Integer.valueOf(3);
98 final Integer i4 = Integer.valueOf(4);
99 assertEquals(baseStr + "[a=<size=0>]", new ToStringBuilder(base).append("a", (Object) new Integer[0], false).toString());
100 assertEquals(baseStr + "[a={}]", new ToStringBuilder(base).append("a", (Object) new Integer[0], true).toString());
101 assertEquals(baseStr + "[a=<size=1>]", new ToStringBuilder(base).append("a", (Object) new Integer[] {i3}, false).toString());
102 assertEquals(baseStr + "[a={3}]", new ToStringBuilder(base).append("a", (Object) new Integer[] {i3}, true).toString());
103 assertEquals(baseStr + "[a=<size=2>]", new ToStringBuilder(base).append("a", (Object) new Integer[] {i3, i4}, false).toString());
104 assertEquals(baseStr + "[a={3,4}]", new ToStringBuilder(base).append("a", (Object) new Integer[] {i3, i4}, true).toString());
79105 }
80106
81107 @Test
97123
98124 @Test
99125 public void testObjectArray() {
100 Object[] array = new Object[] {null, base, new int[] {3, 6}};
126 Object[] array = {null, base, new int[] {3, 6}};
101127 assertEquals(baseStr + "[{<null>,5,{3,6}}]", new ToStringBuilder(base).append(array).toString());
102128 assertEquals(baseStr + "[{<null>,5,{3,6}}]", new ToStringBuilder(base).append((Object) array).toString());
103129 array = null;
107133
108134 @Test
109135 public void testLongArray() {
110 long[] array = new long[] {1, 2, -3, 4};
136 long[] array = {1, 2, -3, 4};
111137 assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append(array).toString());
112138 assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append((Object) array).toString());
113139 array = null;
117143
118144 @Test
119145 public void testLongArrayArray() {
120 long[][] array = new long[][] {{1, 2}, null, {5}};
146 long[][] array = {{1, 2}, null, {5}};
121147 assertEquals(baseStr + "[{{1,2},<null>,{5}}]", new ToStringBuilder(base).append(array).toString());
122148 assertEquals(baseStr + "[{{1,2},<null>,{5}}]", new ToStringBuilder(base).append((Object) array).toString());
123149 array = null;
1717
1818 import static org.junit.jupiter.api.Assertions.assertEquals;
1919
20 import java.util.ArrayList;
21 import java.util.HashMap;
20 import java.util.Arrays;
21 import java.util.Collections;
2222
2323 import org.apache.commons.lang3.builder.ToStringStyleTest.Person;
2424 import org.junit.jupiter.api.AfterEach;
6969 assertEquals("3", new ToStringBuilder(base).append("a", i3).toString());
7070 assertEquals("3,4", new ToStringBuilder(base).append("a", i3).append("b", i4).toString());
7171 assertEquals("<Integer>", new ToStringBuilder(base).append("a", i3, false).toString());
72 assertEquals("<size=0>", new ToStringBuilder(base).append("a", new ArrayList<>(), false).toString());
73 assertEquals("[]", new ToStringBuilder(base).append("a", new ArrayList<>(), true).toString());
74 assertEquals("<size=0>", new ToStringBuilder(base).append("a", new HashMap<>(), false).toString());
75 assertEquals("{}", new ToStringBuilder(base).append("a", new HashMap<>(), true).toString());
76 assertEquals("<size=0>", new ToStringBuilder(base).append("a", (Object) new String[0], false).toString());
77 assertEquals("{}", new ToStringBuilder(base).append("a", (Object) new String[0], true).toString());
72 }
73
74 @Test
75 public void testCollection() {
76 final Integer i3 = Integer.valueOf(3);
77 final Integer i4 = Integer.valueOf(4);
78 assertEquals("<size=0>", new ToStringBuilder(base).append("a", Collections.emptyList(), false).toString());
79 assertEquals("[]", new ToStringBuilder(base).append("a", Collections.emptyList(), true).toString());
80 assertEquals("<size=1>", new ToStringBuilder(base).append("a", Collections.singletonList(i3), false).toString());
81 assertEquals("[3]", new ToStringBuilder(base).append("a", Collections.singletonList(i3), true).toString());
82 assertEquals("<size=2>", new ToStringBuilder(base).append("a", Arrays.asList(i3, i4), false).toString());
83 assertEquals("[3, 4]", new ToStringBuilder(base).append("a", Arrays.asList(i3, i4), true).toString());
84 }
85
86 @Test
87 public void testMap() {
88 assertEquals("<size=0>", new ToStringBuilder(base).append("a", Collections.emptyMap(), false).toString());
89 assertEquals("{}", new ToStringBuilder(base).append("a", Collections.emptyMap(), true).toString());
90 assertEquals("<size=1>", new ToStringBuilder(base).append("a", Collections.singletonMap("k", "v"), false).toString());
91 assertEquals("{k=v}", new ToStringBuilder(base).append("a", Collections.singletonMap("k", "v"), true).toString());
92 }
93
94 @Test
95 public void testArray() {
96 final Integer i3 = Integer.valueOf(3);
97 final Integer i4 = Integer.valueOf(4);
98 assertEquals("<size=0>", new ToStringBuilder(base).append("a", (Object) new Integer[0], false).toString());
99 assertEquals("{}", new ToStringBuilder(base).append("a", (Object) new Integer[0], true).toString());
100 assertEquals("<size=1>", new ToStringBuilder(base).append("a", (Object) new Integer[]{i3}, false).toString());
101 assertEquals("{3}", new ToStringBuilder(base).append("a", (Object) new Integer[]{i3}, true).toString());
102 assertEquals("<size=2>", new ToStringBuilder(base).append("a", (Object) new Integer[]{i3, i4}, false).toString());
103 assertEquals("{3,4}", new ToStringBuilder(base).append("a", (Object) new Integer[]{i3, i4}, true).toString());
78104 }
79105
80106 @Test
95121
96122 @Test
97123 public void testObjectArray() {
98 Object[] array = new Object[] {null, base, new int[] {3, 6}};
124 Object[] array = {null, base, new int[] {3, 6}};
99125 assertEquals("{<null>,5,{3,6}}", new ToStringBuilder(base).append(array).toString());
100126 assertEquals("{<null>,5,{3,6}}", new ToStringBuilder(base).append((Object) array).toString());
101127 array = null;
105131
106132 @Test
107133 public void testLongArray() {
108 long[] array = new long[] {1, 2, -3, 4};
134 long[] array = {1, 2, -3, 4};
109135 assertEquals("{1,2,-3,4}", new ToStringBuilder(base).append(array).toString());
110136 assertEquals("{1,2,-3,4}", new ToStringBuilder(base).append((Object) array).toString());
111137 array = null;
115141
116142 @Test
117143 public void testLongArrayArray() {
118 long[][] array = new long[][] {{1, 2}, null, {5}};
144 long[][] array = {{1, 2}, null, {5}};
119145 assertEquals("{{1,2},<null>,{5}}", new ToStringBuilder(base).append(array).toString());
120146 assertEquals("{{1,2},<null>,{5}}", new ToStringBuilder(base).append((Object) array).toString());
121147 array = null;
1919 import static org.junit.jupiter.api.Assertions.assertFalse;
2020 import static org.junit.jupiter.api.Assertions.assertTrue;
2121
22 import java.util.ArrayList;
23 import java.util.HashMap;
22 import java.util.Arrays;
23 import java.util.Collections;
2424
2525 import org.apache.commons.lang3.builder.ToStringStyleTest.Person;
2626 import org.junit.jupiter.api.AfterEach;
8787 assertEquals(baseStr + "[a=3]", new ToStringBuilder(base).append("a", i3).toString());
8888 assertEquals(baseStr + "[a=3,b=4]", new ToStringBuilder(base).append("a", i3).append("b", i4).toString());
8989 assertEquals(baseStr + "[a=%Integer%]", new ToStringBuilder(base).append("a", i3, false).toString());
90 assertEquals(baseStr + "[a=%SIZE=0%]", new ToStringBuilder(base).append("a", new ArrayList<>(), false).toString());
91 assertEquals(baseStr + "[a=[]]", new ToStringBuilder(base).append("a", new ArrayList<>(), true).toString());
92 assertEquals(baseStr + "[a=%SIZE=0%]", new ToStringBuilder(base).append("a", new HashMap<>(), false).toString());
93 assertEquals(baseStr + "[a={}]", new ToStringBuilder(base).append("a", new HashMap<>(), true).toString());
94 assertEquals(baseStr + "[a=%SIZE=0%]", new ToStringBuilder(base).append("a", (Object) new String[0], false).toString());
95 assertEquals(baseStr + "[a=[]]", new ToStringBuilder(base).append("a", (Object) new String[0], true).toString());
90 }
91
92 @Test
93 public void testCollection() {
94 final Integer i3 = Integer.valueOf(3);
95 final Integer i4 = Integer.valueOf(4);
96 assertEquals(baseStr + "[a=%SIZE=0%]", new ToStringBuilder(base).append("a", Collections.emptyList(), false).toString());
97 assertEquals(baseStr + "[a=[]]", new ToStringBuilder(base).append("a", Collections.emptyList(), true).toString());
98 assertEquals(baseStr + "[a=%SIZE=1%]", new ToStringBuilder(base).append("a", Collections.singletonList(i3), false).toString());
99 assertEquals(baseStr + "[a=[3]]", new ToStringBuilder(base).append("a", Collections.singletonList(i3), true).toString());
100 assertEquals(baseStr + "[a=%SIZE=2%]", new ToStringBuilder(base).append("a", Arrays.asList(i3, i4), false).toString());
101 assertEquals(baseStr + "[a=[3, 4]]", new ToStringBuilder(base).append("a", Arrays.asList(i3, i4), true).toString());
102 }
103
104 @Test
105 public void testMap() {
106 assertEquals(baseStr + "[a=%SIZE=0%]", new ToStringBuilder(base).append("a", Collections.emptyMap(), false).toString());
107 assertEquals(baseStr + "[a={}]", new ToStringBuilder(base).append("a", Collections.emptyMap(), true).toString());
108 assertEquals(baseStr + "[a=%SIZE=1%]", new ToStringBuilder(base).append("a", Collections.singletonMap("k", "v"), false).toString());
109 assertEquals(baseStr + "[a={k=v}]", new ToStringBuilder(base).append("a", Collections.singletonMap("k", "v"), true).toString());
110 }
111
112 @Test
113 public void testArray() {
114 final Integer i3 = Integer.valueOf(3);
115 final Integer i4 = Integer.valueOf(4);
116 assertEquals(baseStr + "[a=%SIZE=0%]", new ToStringBuilder(base).append("a", (Object) new Integer[0], false).toString());
117 assertEquals(baseStr + "[a=[]]", new ToStringBuilder(base).append("a", (Object) new Integer[0], true).toString());
118 assertEquals(baseStr + "[a=%SIZE=1%]", new ToStringBuilder(base).append("a", (Object) new Integer[] {i3}, false).toString());
119 assertEquals(baseStr + "[a=[3]]", new ToStringBuilder(base).append("a", (Object) new Integer[] {i3}, true).toString());
120 assertEquals(baseStr + "[a=%SIZE=2%]", new ToStringBuilder(base).append("a", (Object) new Integer[] {i3, i4}, false).toString());
121 assertEquals(baseStr + "[a=[3, 4]]", new ToStringBuilder(base).append("a", (Object) new Integer[] {i3, i4}, true).toString());
96122 }
97123
98124 @Test
114140
115141 @Test
116142 public void testObjectArray() {
117 Object[] array = new Object[] {null, base, new int[] {3, 6}};
143 Object[] array = {null, base, new int[] {3, 6}};
118144 assertEquals(baseStr + "[[%NULL%, 5, [3, 6]]]", new ToStringBuilder(base).append(array).toString());
119145 assertEquals(baseStr + "[[%NULL%, 5, [3, 6]]]", new ToStringBuilder(base).append((Object) array).toString());
120146 array = null;
124150
125151 @Test
126152 public void testLongArray() {
127 long[] array = new long[] {1, 2, -3, 4};
153 long[] array = {1, 2, -3, 4};
128154 assertEquals(baseStr + "[[1, 2, -3, 4]]", new ToStringBuilder(base).append(array).toString());
129155 assertEquals(baseStr + "[[1, 2, -3, 4]]", new ToStringBuilder(base).append((Object) array).toString());
130156 array = null;
134160
135161 @Test
136162 public void testLongArrayArray() {
137 long[][] array = new long[][] {{1, 2}, null, {5}};
163 long[][] array = {{1, 2}, null, {5}};
138164 assertEquals(baseStr + "[[[1, 2], %NULL%, [5]]]", new ToStringBuilder(base).append(array).toString());
139165 assertEquals(baseStr + "[[[1, 2], %NULL%, [5]]]", new ToStringBuilder(base).append((Object) array).toString());
140166 array = null;
4747 validateNullToStringStyleRegistry();
4848 }
4949
50 //-----------------------------------------------------------------------
5150
5251 @Test
5352 public void testConstructorEx1() {
154153
155154 @Test
156155 public void testReflectionObjectArray() {
157 Object[] array = new Object[] { null, base, new int[] { 3, 6 } };
156 Object[] array = { null, base, new int[] { 3, 6 } };
158157 final String baseString = this.toBaseString(array);
159158 assertEquals(baseString + "[{<null>,5,{3,6}}]", ToStringBuilder.reflectionToString(array));
160159 array = null;
163162
164163 @Test
165164 public void testReflectionLongArray() {
166 long[] array = new long[] { 1, 2, -3, 4 };
165 long[] array = { 1, 2, -3, 4 };
167166 final String baseString = this.toBaseString(array);
168167 assertEquals(baseString + "[{1,2,-3,4}]", ToStringBuilder.reflectionToString(array));
169168 array = null;
172171
173172 @Test
174173 public void testReflectionIntArray() {
175 int[] array = new int[] { 1, 2, -3, 4 };
174 int[] array = { 1, 2, -3, 4 };
176175 final String baseString = this.toBaseString(array);
177176 assertEquals(baseString + "[{1,2,-3,4}]", ToStringBuilder.reflectionToString(array));
178177 array = null;
181180
182181 @Test
183182 public void testReflectionShortArray() {
184 short[] array = new short[] { 1, 2, -3, 4 };
183 short[] array = { 1, 2, -3, 4 };
185184 final String baseString = this.toBaseString(array);
186185 assertEquals(baseString + "[{1,2,-3,4}]", ToStringBuilder.reflectionToString(array));
187186 array = null;
190189
191190 @Test
192191 public void testReflectionyteArray() {
193 byte[] array = new byte[] { 1, 2, -3, 4 };
192 byte[] array = { 1, 2, -3, 4 };
194193 final String baseString = this.toBaseString(array);
195194 assertEquals(baseString + "[{1,2,-3,4}]", ToStringBuilder.reflectionToString(array));
196195 array = null;
199198
200199 @Test
201200 public void testReflectionCharArray() {
202 char[] array = new char[] { 'A', '2', '_', 'D' };
201 char[] array = { 'A', '2', '_', 'D' };
203202 final String baseString = this.toBaseString(array);
204203 assertEquals(baseString + "[{A,2,_,D}]", ToStringBuilder.reflectionToString(array));
205204 array = null;
208207
209208 @Test
210209 public void testReflectionDoubleArray() {
211 double[] array = new double[] { 1.0, 2.9876, -3.00001, 4.3 };
210 double[] array = { 1.0, 2.9876, -3.00001, 4.3 };
212211 final String baseString = this.toBaseString(array);
213212 assertEquals(baseString + "[{1.0,2.9876,-3.00001,4.3}]", ToStringBuilder.reflectionToString(array));
214213 array = null;
217216
218217 @Test
219218 public void testReflectionFloatArray() {
220 float[] array = new float[] { 1.0f, 2.9876f, -3.00001f, 4.3f };
219 float[] array = { 1.0f, 2.9876f, -3.00001f, 4.3f };
221220 final String baseString = this.toBaseString(array);
222221 assertEquals(baseString + "[{1.0,2.9876,-3.00001,4.3}]", ToStringBuilder.reflectionToString(array));
223222 array = null;
226225
227226 @Test
228227 public void testReflectionBooleanArray() {
229 boolean[] array = new boolean[] { true, false, false };
228 boolean[] array = { true, false, false };
230229 final String baseString = this.toBaseString(array);
231230 assertEquals(baseString + "[{true,false,false}]", ToStringBuilder.reflectionToString(array));
232231 array = null;
237236
238237 @Test
239238 public void testReflectionFloatArrayArray() {
240 float[][] array = new float[][] { { 1.0f, 2.29686f }, null, { Float.NaN } };
239 float[][] array = { { 1.0f, 2.29686f }, null, { Float.NaN } };
241240 final String baseString = this.toBaseString(array);
242241 assertEquals(baseString + "[{{1.0,2.29686},<null>,{NaN}}]", ToStringBuilder.reflectionToString(array));
243242 array = null;
247246
248247 @Test
249248 public void testReflectionLongArrayArray() {
250 long[][] array = new long[][] { { 1, 2 }, null, { 5 } };
249 long[][] array = { { 1, 2 }, null, { 5 } };
251250 final String baseString = this.toBaseString(array);
252251 assertEquals(baseString + "[{{1,2},<null>,{5}}]", ToStringBuilder.reflectionToString(array));
253252 array = null;
256255
257256 @Test
258257 public void testReflectionIntArrayArray() {
259 int[][] array = new int[][] { { 1, 2 }, null, { 5 } };
258 int[][] array = { { 1, 2 }, null, { 5 } };
260259 final String baseString = this.toBaseString(array);
261260 assertEquals(baseString + "[{{1,2},<null>,{5}}]", ToStringBuilder.reflectionToString(array));
262261 array = null;
265264
266265 @Test
267266 public void testReflectionhortArrayArray() {
268 short[][] array = new short[][] { { 1, 2 }, null, { 5 } };
267 short[][] array = { { 1, 2 }, null, { 5 } };
269268 final String baseString = this.toBaseString(array);
270269 assertEquals(baseString + "[{{1,2},<null>,{5}}]", ToStringBuilder.reflectionToString(array));
271270 array = null;
274273
275274 @Test
276275 public void testReflectionByteArrayArray() {
277 byte[][] array = new byte[][] { { 1, 2 }, null, { 5 } };
276 byte[][] array = { { 1, 2 }, null, { 5 } };
278277 final String baseString = this.toBaseString(array);
279278 assertEquals(baseString + "[{{1,2},<null>,{5}}]", ToStringBuilder.reflectionToString(array));
280279 array = null;
283282
284283 @Test
285284 public void testReflectionCharArrayArray() {
286 char[][] array = new char[][] { { 'A', 'B' }, null, { 'p' } };
285 char[][] array = { { 'A', 'B' }, null, { 'p' } };
287286 final String baseString = this.toBaseString(array);
288287 assertEquals(baseString + "[{{A,B},<null>,{p}}]", ToStringBuilder.reflectionToString(array));
289288 array = null;
292291
293292 @Test
294293 public void testReflectionDoubleArrayArray() {
295 double[][] array = new double[][] { { 1.0, 2.29686 }, null, { Double.NaN } };
294 double[][] array = { { 1.0, 2.29686 }, null, { Double.NaN } };
296295 final String baseString = this.toBaseString(array);
297296 assertEquals(baseString + "[{{1.0,2.29686},<null>,{NaN}}]", ToStringBuilder.reflectionToString(array));
298297 array = null;
301300
302301 @Test
303302 public void testReflectionBooleanArrayArray() {
304 boolean[][] array = new boolean[][] { { true, false }, null, { false } };
303 boolean[][] array = { { true, false }, null, { false } };
305304 final String baseString = this.toBaseString(array);
306305 assertEquals(baseString + "[{{true,false},<null>,{false}}]", ToStringBuilder.reflectionToString(array));
307306 assertEquals(baseString + "[{{true,false},<null>,{false}}]", ToStringBuilder.reflectionToString(array));
356355 @SuppressWarnings("unused")
357356 private final char a='a';
358357 @SuppressWarnings("unused")
359 private transient char transientA='t';
358 private final transient char transientA='t';
360359 }
361360
362361 static class ReflectionTestFixtureB extends ReflectionTestFixtureA {
363362 @SuppressWarnings("unused")
364363 private final char b='b';
365364 @SuppressWarnings("unused")
366 private transient char transientB='t';
365 private final transient char transientB='t';
367366 }
368367
369368 @Test
628627
629628 @Test
630629 public void testAppendBooleanArrayWithFieldName() {
631 final boolean[] array = new boolean[] { true, false, false };
630 final boolean[] array = { true, false, false };
632631 assertEquals(baseStr + "[flags={true,false,false}]",
633632 new ToStringBuilder(base).append("flags", array).toString());
634633 assertEquals(baseStr + "[flags=<null>]",
639638
640639 @Test
641640 public void testAppendBooleanArrayWithFieldNameAndFullDetatil() {
642 final boolean[] array = new boolean[] { true, false, false };
641 final boolean[] array = { true, false, false };
643642 assertEquals(baseStr + "[flags={true,false,false}]",
644643 new ToStringBuilder(base).append("flags", array, true).toString());
645644 assertEquals(baseStr + "[length=<size=3>]",
652651
653652 @Test
654653 public void testAppendCharArrayWithFieldName() {
655 final char[] array = new char[] { 'A', '2', '_', 'D' };
654 final char[] array = { 'A', '2', '_', 'D' };
656655 assertEquals(baseStr + "[chars={A,2,_,D}]", new ToStringBuilder(base).append("chars", array).toString());
657656 assertEquals(baseStr + "[letters={A,2,_,D}]", new ToStringBuilder(base).append("letters", array).toString());
658657 assertEquals(baseStr + "[flags=<null>]",
663662
664663 @Test
665664 public void testAppendCharArrayWithFieldNameAndFullDetatil() {
666 final char[] array = new char[] { 'A', '2', '_', 'D' };
665 final char[] array = { 'A', '2', '_', 'D' };
667666 assertEquals(baseStr + "[chars={A,2,_,D}]", new ToStringBuilder(base).append("chars", array, true).toString());
668667 assertEquals(baseStr + "[letters=<size=4>]",
669668 new ToStringBuilder(base).append("letters", array, false).toString());
675674
676675 @Test
677676 public void testAppendDoubleArrayWithFieldName() {
678 final double[] array = new double[] { 1.0, 2.9876, -3.00001, 4.3 };
677 final double[] array = { 1.0, 2.9876, -3.00001, 4.3 };
679678 assertEquals(baseStr + "[values={1.0,2.9876,-3.00001,4.3}]",
680679 new ToStringBuilder(base).append("values", array).toString());
681680 assertEquals(baseStr + "[values=<null>]",
686685
687686 @Test
688687 public void testAppendDoubleArrayWithFieldNameAndFullDetatil() {
689 final double[] array = new double[] { 1.0, 2.9876, -3.00001, 4.3 };
688 final double[] array = { 1.0, 2.9876, -3.00001, 4.3 };
690689 assertEquals(baseStr + "[values={1.0,2.9876,-3.00001,4.3}]",
691690 new ToStringBuilder(base).append("values", array, true).toString());
692691 assertEquals(baseStr + "[length=<size=4>]",
699698
700699 @Test
701700 public void testAppendObjectArrayWithFieldName() {
702 final Object[] array = new Object[] { null, base, new int[] { 3, 6 } };
701 final Object[] array = { null, base, new int[] { 3, 6 } };
703702 assertEquals(baseStr + "[values={<null>,5,{3,6}}]",
704703 new ToStringBuilder(base).append("values", array).toString());
705704 assertEquals(baseStr + "[values=<null>]",
710709
711710 @Test
712711 public void testAppendObjectArrayWithFieldNameAndFullDetatil() {
713 final Object[] array = new Object[] { null, base, new int[] { 3, 6 } };
712 final Object[] array = { null, base, new int[] { 3, 6 } };
714713 assertEquals(baseStr + "[values={<null>,5,{3,6}}]",
715714 new ToStringBuilder(base).append("values", array, true).toString());
716715 assertEquals(baseStr + "[length=<size=3>]",
723722
724723 @Test
725724 public void testAppendLongArrayWithFieldName() {
726 final long[] array = new long[] { 1, 2, -3, 4 };
725 final long[] array = { 1, 2, -3, 4 };
727726 assertEquals(baseStr + "[values={1,2,-3,4}]", new ToStringBuilder(base).append("values", array).toString());
728727 assertEquals(baseStr + "[values=<null>]",
729728 new ToStringBuilder(base).append("values", (boolean[]) null).toString());
733732
734733 @Test
735734 public void testAppendLongArrayWithFieldNameAndFullDetatil() {
736 final long[] array = new long[] { 1, 2, -3, 4 };
735 final long[] array = { 1, 2, -3, 4 };
737736 assertEquals(baseStr + "[values={1,2,-3,4}]",
738737 new ToStringBuilder(base).append("values", array, true).toString());
739738 assertEquals(baseStr + "[length=<size=4>]",
746745
747746 @Test
748747 public void testAppendIntArrayWithFieldName() {
749 final int[] array = new int[] { 1, 2, -3, 4 };
748 final int[] array = { 1, 2, -3, 4 };
750749 assertEquals(baseStr + "[values={1,2,-3,4}]", new ToStringBuilder(base).append("values", array).toString());
751750 assertEquals(baseStr + "[values=<null>]",
752751 new ToStringBuilder(base).append("values", (boolean[]) null).toString());
756755
757756 @Test
758757 public void testAppendIntArrayWithFieldNameAndFullDetatil() {
759 final int[] array = new int[] { 1, 2, -3, 4 };
758 final int[] array = { 1, 2, -3, 4 };
760759 assertEquals(baseStr + "[values={1,2,-3,4}]",
761760 new ToStringBuilder(base).append("values", array, true).toString());
762761 assertEquals(baseStr + "[length=<size=4>]",
769768
770769 @Test
771770 public void testAppendShortArrayWithFieldName() {
772 final short[] array = new short[] { 1, 2, -3, 4 };
771 final short[] array = { 1, 2, -3, 4 };
773772 assertEquals(baseStr + "[values={1,2,-3,4}]", new ToStringBuilder(base).append("values", array).toString());
774773 assertEquals(baseStr + "[values=<null>]",
775774 new ToStringBuilder(base).append("values", (boolean[]) null).toString());
779778
780779 @Test
781780 public void testAppendShortArrayWithFieldNameAndFullDetatil() {
782 final short[] array = new short[] { 1, 2, -3, 4 };
781 final short[] array = { 1, 2, -3, 4 };
783782 assertEquals(baseStr + "[values={1,2,-3,4}]",
784783 new ToStringBuilder(base).append("values", array, true).toString());
785784 assertEquals(baseStr + "[length=<size=4>]",
792791
793792 @Test
794793 public void testAppendByteArrayWithFieldName() {
795 final byte[] array = new byte[] { 1, 2, -3, 4 };
794 final byte[] array = { 1, 2, -3, 4 };
796795 assertEquals(baseStr + "[values={1,2,-3,4}]", new ToStringBuilder(base).append("values", array).toString());
797796 assertEquals(baseStr + "[values=<null>]",
798797 new ToStringBuilder(base).append("values", (boolean[]) null).toString());
802801
803802 @Test
804803 public void testAppendByteArrayWithFieldNameAndFullDetatil() {
805 final byte[] array = new byte[] { 1, 2, -3, 4 };
804 final byte[] array = { 1, 2, -3, 4 };
806805 assertEquals(baseStr + "[values={1,2,-3,4}]",
807806 new ToStringBuilder(base).append("values", array, true).toString());
808807 assertEquals(baseStr + "[length=<size=4>]",
815814
816815 @Test
817816 public void testAppendFloatArrayWithFieldName() {
818 final float[] array = new float[] { 1.0f, 2.9876f, -3.00001f, 4.3f };
817 final float[] array = { 1.0f, 2.9876f, -3.00001f, 4.3f };
819818 assertEquals(baseStr + "[values={1.0,2.9876,-3.00001,4.3}]",
820819 new ToStringBuilder(base).append("values", array).toString());
821820 assertEquals(baseStr + "[values=<null>]",
826825
827826 @Test
828827 public void testAppendFloatArrayWithFieldNameAndFullDetatil() {
829 final float[] array = new float[] { 1.0f, 2.9876f, -3.00001f, 4.3f };
828 final float[] array = { 1.0f, 2.9876f, -3.00001f, 4.3f };
830829 assertEquals(baseStr + "[values={1.0,2.9876,-3.00001,4.3}]",
831830 new ToStringBuilder(base).append("values", array, true).toString());
832831 assertEquals(baseStr + "[length=<size=4>]",
893892 assertEquals(baseStr + "[a=3,b=4]", new ToStringBuilder(base).append("a", 3L).append("b", 4L).toString());
894893 }
895894
896 @SuppressWarnings("cast") // cast is not really needed, keep for consistency
897895 @Test
898896 public void testInt() {
899897 assertEquals(baseStr + "[3]", new ToStringBuilder(base).append(3).toString());
922920 assertEquals(baseStr + "[a=3,b=4]", new ToStringBuilder(base).append("a", (byte) 3).append("b", (byte) 4).toString());
923921 }
924922
925 @SuppressWarnings("cast")
926923 @Test
927924 public void testDouble() {
928925 assertEquals(baseStr + "[3.2]", new ToStringBuilder(base).append(3.2).toString());
947944
948945 @Test
949946 public void testObjectArray() {
950 Object[] array = new Object[] {null, base, new int[] {3, 6}};
947 Object[] array = {null, base, new int[] {3, 6}};
951948 assertEquals(baseStr + "[{<null>,5,{3,6}}]", new ToStringBuilder(base).append(array).toString());
952949 assertEquals(baseStr + "[{<null>,5,{3,6}}]", new ToStringBuilder(base).append((Object) array).toString());
953950 array = null;
957954
958955 @Test
959956 public void testLongArray() {
960 long[] array = new long[] {1, 2, -3, 4};
957 long[] array = {1, 2, -3, 4};
961958 assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append(array).toString());
962959 assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append((Object) array).toString());
963960 array = null;
967964
968965 @Test
969966 public void testIntArray() {
970 int[] array = new int[] {1, 2, -3, 4};
967 int[] array = {1, 2, -3, 4};
971968 assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append(array).toString());
972969 assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append((Object) array).toString());
973970 array = null;
977974
978975 @Test
979976 public void testShortArray() {
980 short[] array = new short[] {1, 2, -3, 4};
977 short[] array = {1, 2, -3, 4};
981978 assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append(array).toString());
982979 assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append((Object) array).toString());
983980 array = null;
987984
988985 @Test
989986 public void testByteArray() {
990 byte[] array = new byte[] {1, 2, -3, 4};
987 byte[] array = {1, 2, -3, 4};
991988 assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append(array).toString());
992989 assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append((Object) array).toString());
993990 array = null;
997994
998995 @Test
999996 public void testCharArray() {
1000 char[] array = new char[] {'A', '2', '_', 'D'};
997 char[] array = {'A', '2', '_', 'D'};
1001998 assertEquals(baseStr + "[{A,2,_,D}]", new ToStringBuilder(base).append(array).toString());
1002999 assertEquals(baseStr + "[{A,2,_,D}]", new ToStringBuilder(base).append((Object) array).toString());
10031000 array = null;
10071004
10081005 @Test
10091006 public void testDoubleArray() {
1010 double[] array = new double[] {1.0, 2.9876, -3.00001, 4.3};
1007 double[] array = {1.0, 2.9876, -3.00001, 4.3};
10111008 assertEquals(baseStr + "[{1.0,2.9876,-3.00001,4.3}]", new ToStringBuilder(base).append(array).toString());
10121009 assertEquals(baseStr + "[{1.0,2.9876,-3.00001,4.3}]", new ToStringBuilder(base).append((Object) array).toString());
10131010 array = null;
10171014
10181015 @Test
10191016 public void testFloatArray() {
1020 float[] array = new float[] {1.0f, 2.9876f, -3.00001f, 4.3f};
1017 float[] array = {1.0f, 2.9876f, -3.00001f, 4.3f};
10211018 assertEquals(baseStr + "[{1.0,2.9876,-3.00001,4.3}]", new ToStringBuilder(base).append(array).toString());
10221019 assertEquals(baseStr + "[{1.0,2.9876,-3.00001,4.3}]", new ToStringBuilder(base).append((Object) array).toString());
10231020 array = null;
10271024
10281025 @Test
10291026 public void testBooleanArray() {
1030 boolean[] array = new boolean[] {true, false, false};
1027 boolean[] array = {true, false, false};
10311028 assertEquals(baseStr + "[{true,false,false}]", new ToStringBuilder(base).append(array).toString());
10321029 assertEquals(baseStr + "[{true,false,false}]", new ToStringBuilder(base).append((Object) array).toString());
10331030 array = null;
10371034
10381035 @Test
10391036 public void testLongArrayArray() {
1040 long[][] array = new long[][] {{1, 2}, null, {5}};
1037 long[][] array = {{1, 2}, null, {5}};
10411038 assertEquals(baseStr + "[{{1,2},<null>,{5}}]", new ToStringBuilder(base).append(array).toString());
10421039 assertEquals(baseStr + "[{{1,2},<null>,{5}}]", new ToStringBuilder(base).append((Object) array).toString());
10431040 array = null;
10471044
10481045 @Test
10491046 public void testIntArrayArray() {
1050 int[][] array = new int[][] {{1, 2}, null, {5}};
1047 int[][] array = {{1, 2}, null, {5}};
10511048 assertEquals(baseStr + "[{{1,2},<null>,{5}}]", new ToStringBuilder(base).append(array).toString());
10521049 assertEquals(baseStr + "[{{1,2},<null>,{5}}]", new ToStringBuilder(base).append((Object) array).toString());
10531050 array = null;
10571054
10581055 @Test
10591056 public void testShortArrayArray() {
1060 short[][] array = new short[][] {{1, 2}, null, {5}};
1057 short[][] array = {{1, 2}, null, {5}};
10611058 assertEquals(baseStr + "[{{1,2},<null>,{5}}]", new ToStringBuilder(base).append(array).toString());
10621059 assertEquals(baseStr + "[{{1,2},<null>,{5}}]", new ToStringBuilder(base).append((Object) array).toString());
10631060 array = null;
10671064
10681065 @Test
10691066 public void testByteArrayArray() {
1070 byte[][] array = new byte[][] {{1, 2}, null, {5}};
1067 byte[][] array = {{1, 2}, null, {5}};
10711068 assertEquals(baseStr + "[{{1,2},<null>,{5}}]", new ToStringBuilder(base).append(array).toString());
10721069 assertEquals(baseStr + "[{{1,2},<null>,{5}}]", new ToStringBuilder(base).append((Object) array).toString());
10731070 array = null;
10771074
10781075 @Test
10791076 public void testCharArrayArray() {
1080 char[][] array = new char[][] {{'A', 'B'}, null, {'p'}};
1077 char[][] array = {{'A', 'B'}, null, {'p'}};
10811078 assertEquals(baseStr + "[{{A,B},<null>,{p}}]", new ToStringBuilder(base).append(array).toString());
10821079 assertEquals(baseStr + "[{{A,B},<null>,{p}}]", new ToStringBuilder(base).append((Object) array).toString());
10831080 array = null;
10871084
10881085 @Test
10891086 public void testDoubleArrayArray() {
1090 double[][] array = new double[][] {{1.0, 2.29686}, null, {Double.NaN}};
1087 double[][] array = {{1.0, 2.29686}, null, {Double.NaN}};
10911088 assertEquals(baseStr + "[{{1.0,2.29686},<null>,{NaN}}]", new ToStringBuilder(base).append(array).toString());
10921089 assertEquals(baseStr + "[{{1.0,2.29686},<null>,{NaN}}]", new ToStringBuilder(base).append((Object) array).toString());
10931090 array = null;
10971094
10981095 @Test
10991096 public void testFloatArrayArray() {
1100 float[][] array = new float[][] {{1.0f, 2.29686f}, null, {Float.NaN}};
1097 float[][] array = {{1.0f, 2.29686f}, null, {Float.NaN}};
11011098 assertEquals(baseStr + "[{{1.0,2.29686},<null>,{NaN}}]", new ToStringBuilder(base).append(array).toString());
11021099 assertEquals(baseStr + "[{{1.0,2.29686},<null>,{NaN}}]", new ToStringBuilder(base).append((Object) array).toString());
11031100 array = null;
11071104
11081105 @Test
11091106 public void testBooleanArrayArray() {
1110 boolean[][] array = new boolean[][] {{true, false}, null, {false}};
1107 boolean[][] array = {{true, false}, null, {false}};
11111108 assertEquals(baseStr + "[{{true,false},<null>,{false}}]", new ToStringBuilder(base).append(array).toString());
11121109 assertEquals(baseStr + "[{{true,false},<null>,{false}}]", new ToStringBuilder(base).append((Object) array).toString());
11131110 array = null;
2929
3030 }
3131
32 //-----------------------------------------------------------------------
3332 @Test
3433 public void testSetArrayStart() {
3534 final ToStringStyle style = new ToStringStyleImpl();
2323 import static org.junit.jupiter.api.Assertions.assertThrows;
2424 import static org.junit.jupiter.api.Assertions.assertTrue;
2525
26 import java.time.Duration;
2627 import java.util.concurrent.CountDownLatch;
2728 import java.util.concurrent.ExecutorService;
2829 import java.util.concurrent.Executors;
2930 import java.util.concurrent.TimeUnit;
3031 import java.util.concurrent.atomic.AtomicReference;
3132
33 import org.apache.commons.lang3.ThreadUtils;
3234 import org.junit.jupiter.api.Test;
3335
3436 public class BackgroundInitializerTest {
279281 volatile int initializeCalls;
280282
281283 BackgroundInitializerTestImpl() {
282 super();
283284 }
284285
285286 BackgroundInitializerTestImpl(final ExecutorService exec) {
298299 throw ex;
299300 }
300301 if (shouldSleep) {
301 Thread.sleep(60000L);
302 ThreadUtils.sleep(Duration.ofMinutes(1));
302303 }
303304 return Integer.valueOf(++initializeCalls);
304305 }
268268 null));
269269 }
270270
271 //-----------------------------------------------------------------------
272271 /**
273272 * Tests initialize() for a null argument.
274273 *
351350 EasyMock.verify(init);
352351 }
353352
354 //-----------------------------------------------------------------------
355353 /**
356354 * Tests constant future.
357355 *
388386 assertFalse(test.cancel(false));
389387 }
390388
391 //-----------------------------------------------------------------------
392389 /**
393390 * Tests putIfAbsent() if the map contains the key in question.
394391 */
9595 public void testNow() {
9696 final EventCountCircuitBreaker breaker = new EventCountCircuitBreaker(OPENING_THRESHOLD, 1,
9797 TimeUnit.SECONDS);
98 final long now = breaker.now();
99 final long delta = Math.abs(System.nanoTime() - now);
100 assertTrue(delta < 100000, String.format("Delta %d ns to current time too large", delta));
98 final long nowNanos = breaker.nanoTime();
99 final long deltaNanos = Math.abs(System.nanoTime() - nowNanos);
100 assertTrue(deltaNanos < 100_000, String.format("Delta %,d ns to current time too large", deltaNanos));
101101 }
102102
103103 /**
363363 * method.
364364 */
365365 @Override
366 long now() {
366 long nanoTime() {
367367 return currentTime;
368368 }
369369 }
2727 import java.util.concurrent.ScheduledThreadPoolExecutor;
2828 import java.util.concurrent.TimeUnit;
2929
30 import org.apache.commons.lang3.ThreadUtils;
3031 import org.easymock.EasyMock;
3132 import org.junit.jupiter.api.Test;
3233
9899 UNIT, LIMIT);
99100 final ScheduledFuture<?> future = semaphore.startTimer();
100101 assertNotNull(future, "No future returned");
101 Thread.sleep(PERIOD);
102 ThreadUtils.sleepQuietly(PERIOD);
102103 final int trials = 10;
103104 int count = 0;
104105 do {
1919 import static org.junit.jupiter.api.Assertions.assertNotSame;
2020 import static org.junit.jupiter.api.Assertions.assertTrue;
2121
22 import java.time.Duration;
2223 import java.util.function.LongConsumer;
2324
25 import org.apache.commons.lang3.ArrayUtils;
26 import org.apache.commons.lang3.ThreadUtils;
2427 import org.apache.commons.lang3.concurrent.locks.LockingVisitors.LockVisitor;
2528 import org.apache.commons.lang3.concurrent.locks.LockingVisitors.StampedLockVisitor;
2629 import org.apache.commons.lang3.function.FailableConsumer;
2730 import org.junit.jupiter.api.Test;
2831
2932 public class LockingVisitorsTest {
33
34 private static final Duration SHORT_DELAY = Duration.ofMillis(100);
35 private static final Duration DELAY = Duration.ofMillis(1500);
3036 private static final int NUMBER_OF_THREADS = 10;
31 private static final long DELAY_MILLIS = 3000;
32 private static final long TOTAL_DELAY_MILLIS = NUMBER_OF_THREADS * DELAY_MILLIS;
37 private static final Duration TOTAL_DELAY = DELAY.multipliedBy(NUMBER_OF_THREADS);
38
39 protected boolean containsTrue(final boolean[] booleanArray) {
40 synchronized (booleanArray) {
41 return ArrayUtils.contains(booleanArray, true);
42 }
43 }
44
45 private void runTest(final Duration delay, final boolean exclusiveLock, final LongConsumer runTimeCheck,
46 final boolean[] booleanValues, final LockVisitor<boolean[], ?> visitor) throws InterruptedException {
47 final boolean[] runningValues = new boolean[10];
48
49 final long startTimeMillis = System.currentTimeMillis();
50 for (int i = 0; i < booleanValues.length; i++) {
51 final int index = i;
52 final FailableConsumer<boolean[], ?> consumer = b -> {
53 b[index] = false;
54 ThreadUtils.sleep(delay);
55 b[index] = true;
56 set(runningValues, index, false);
57 };
58 final Thread t = new Thread(() -> {
59 if (exclusiveLock) {
60 visitor.acceptWriteLocked(consumer);
61 } else {
62 visitor.acceptReadLocked(consumer);
63 }
64 });
65 set(runningValues, i, true);
66 t.start();
67 }
68 while (containsTrue(runningValues)) {
69 ThreadUtils.sleep(SHORT_DELAY);
70 }
71 final long endTimeMillis = System.currentTimeMillis();
72 for (final boolean booleanValue : booleanValues) {
73 assertTrue(booleanValue);
74 }
75 // WRONG assumption
76 // runTimeCheck.accept(endTimeMillis - startTimeMillis);
77 }
78
79 protected void set(final boolean[] booleanArray, final int offset, final boolean value) {
80 synchronized (booleanArray) {
81 booleanArray[offset] = value;
82 }
83 }
3384
3485 @Test
35 public void testStampedLockNotExclusive() throws Exception {
86 public void testReentrantReadWriteLockExclusive() throws Exception {
3687
3788 /*
38 * If our threads are running concurrently, then we expect to be faster than running one after the other.
89 * If our threads are running concurrently, then we expect to be no faster than running one after the other.
3990 */
40 boolean[] booleanValues = new boolean[10];
41 runTest(DELAY_MILLIS, false, l -> assertTrue(l < TOTAL_DELAY_MILLIS), booleanValues,
42 LockingVisitors.stampedLockVisitor(booleanValues));
91 final boolean[] booleanValues = new boolean[10];
92 runTest(DELAY, true, millis -> assertTrue(millis >= TOTAL_DELAY.toMillis()), booleanValues,
93 LockingVisitors.reentrantReadWriteLockVisitor(booleanValues));
4394 }
4495
4596 @Test
4899 /*
49100 * If our threads are running concurrently, then we expect to be faster than running one after the other.
50101 */
51 boolean[] booleanValues = new boolean[10];
52 runTest(DELAY_MILLIS, false, l -> assertTrue(l < TOTAL_DELAY_MILLIS), booleanValues,
102 final boolean[] booleanValues = new boolean[10];
103 runTest(DELAY, false, millis -> assertTrue(millis < TOTAL_DELAY.toMillis()), booleanValues,
53104 LockingVisitors.reentrantReadWriteLockVisitor(booleanValues));
105 }
106
107 @Test
108 public void testResultValidation() {
109 final Object hidden = new Object();
110 final StampedLockVisitor<Object> lock = LockingVisitors.stampedLockVisitor(hidden);
111 final Object o1 = lock.applyReadLocked(h -> new Object());
112 assertNotNull(o1);
113 assertNotSame(hidden, o1);
114 final Object o2 = lock.applyWriteLocked(h -> new Object());
115 assertNotNull(o2);
116 assertNotSame(hidden, o2);
54117 }
55118
56119 @Test
59122 /*
60123 * If our threads are running concurrently, then we expect to be no faster than running one after the other.
61124 */
62 boolean[] booleanValues = new boolean[10];
63 runTest(DELAY_MILLIS, true, l -> assertTrue(l >= TOTAL_DELAY_MILLIS), booleanValues,
125 final boolean[] booleanValues = new boolean[10];
126 runTest(DELAY, true, millis -> assertTrue(millis >= TOTAL_DELAY.toMillis()), booleanValues,
64127 LockingVisitors.stampedLockVisitor(booleanValues));
65128 }
66129
67130 @Test
68 public void testReentrantReadWriteLockExclusive() throws Exception {
131 public void testStampedLockNotExclusive() throws Exception {
69132
70133 /*
71 * If our threads are running concurrently, then we expect to be no faster than running one after the other.
134 * If our threads are running concurrently, then we expect to be faster than running one after the other.
72135 */
73 boolean[] booleanValues = new boolean[10];
74 runTest(DELAY_MILLIS, true, l -> assertTrue(l >= TOTAL_DELAY_MILLIS), booleanValues,
75 LockingVisitors.reentrantReadWriteLockVisitor(booleanValues));
76 }
77
78 @Test
79 public void testResultValidation() {
80 final Object hidden = new Object();
81 final StampedLockVisitor<Object> lock = LockingVisitors.stampedLockVisitor(hidden);
82 final Object o1 = lock.applyReadLocked(h -> {
83 return new Object(); });
84 assertNotNull(o1);
85 assertNotSame(hidden, o1);
86 final Object o2 = lock.applyWriteLocked(h -> {
87 return new Object(); });
88 assertNotNull(o2);
89 assertNotSame(hidden, o2);
90 }
91
92 private void runTest(final long delayMillis, final boolean exclusiveLock, final LongConsumer runTimeCheck,
93 boolean[] booleanValues, LockVisitor<boolean[], ?> visitor) throws InterruptedException {
94 final boolean[] runningValues = new boolean[10];
95
96 final long startTime = System.currentTimeMillis();
97 for (int i = 0; i < booleanValues.length; i++) {
98 final int index = i;
99 final FailableConsumer<boolean[], ?> consumer = b -> {
100 b[index] = false;
101 Thread.sleep(delayMillis);
102 b[index] = true;
103 modify(runningValues, index, false);
104 };
105 final Thread t = new Thread(() -> {
106 if (exclusiveLock) {
107 visitor.acceptWriteLocked(consumer);
108 } else {
109 visitor.acceptReadLocked(consumer);
110 }
111 });
112 modify(runningValues, i, true);
113 t.start();
114 }
115 while (someValueIsTrue(runningValues)) {
116 Thread.sleep(100);
117 }
118 final long endTime = System.currentTimeMillis();
119 for (int i = 0; i < booleanValues.length; i++) {
120 assertTrue(booleanValues[i]);
121 }
122 // WRONG assumption
123 // runTimeCheck.accept(endTime - startTime);
124 }
125
126 protected void modify(final boolean[] booleanArray, final int offset, final boolean value) {
127 synchronized (booleanArray) {
128 booleanArray[offset] = value;
129 }
130 }
131
132 protected boolean someValueIsTrue(final boolean[] booleanArray) {
133 synchronized (booleanArray) {
134 for (int i = 0; i < booleanArray.length; i++) {
135 if (booleanArray[i]) {
136 return true;
137 }
138 }
139 return false;
140 }
136 final boolean[] booleanValues = new boolean[10];
137 runTest(DELAY, false, millis -> assertTrue(millis < TOTAL_DELAY.toMillis()), booleanValues,
138 LockingVisitors.stampedLockVisitor(booleanValues));
141139 }
142140 }
6161 }
6262
6363 ExceptionWithCause(final Throwable cause) {
64 super();
6564 setCause(cause);
6665 }
6766
9493
9594 @SuppressWarnings("unused")
9695 NestableException() {
97 super();
9896 }
9997
10098 NestableException(final Throwable t) {
125123
126124 private Throwable jdkNoCause;
127125
128 //-----------------------------------------------------------------------
129126
130127 private ExceptionWithCause cyclicCause;
131128
143140 }
144141 }
145142
146 //-----------------------------------------------------------------------
147143 private Throwable createExceptionWithoutCause() {
148144 try {
149145 throw new ExceptionWithoutCause();
218214 assertFalse(Modifier.isFinal(ExceptionUtils.class.getModifiers()));
219215 }
220216
221 //-----------------------------------------------------------------------
222217 @SuppressWarnings("deprecation") // Specifically tests the deprecated methods
223218 @Test
224219 public void testGetCause_Throwable() {
263258 assertSame(cyclicCause.getCause().getCause(), ExceptionUtils.getRootCause(cyclicCause));
264259 }
265260
266 //-----------------------------------------------------------------------
267261 @Test
268262 public void testGetRootCauseStackTrace_Throwable() {
269263 assertEquals(0, ExceptionUtils.getRootCauseStackTrace(null).length);
290284 assertFalse(match);
291285 }
292286
293 //-----------------------------------------------------------------------
294287 @Test
295288 public void testGetThrowableCount_Throwable() {
296289 assertEquals(0, ExceptionUtils.getThrowableCount(null));
316309 assertSame(withoutCause, throwables.get(1));
317310 }
318311
319 //-----------------------------------------------------------------------
320312 @Test
321313 public void testGetThrowableList_Throwable_null() {
322314 final List<?> throwables = ExceptionUtils.getThrowableList(null);
363355 assertSame(withoutCause, throwables[1]);
364356 }
365357
366 //-----------------------------------------------------------------------
367358 @Test
368359 public void testGetThrowables_Throwable_null() {
369360 assertEquals(0, ExceptionUtils.getThrowables(null).length);
447438 assertEquals(-1, ExceptionUtils.indexOfThrowable(withCause, Throwable.class, 0));
448439 }
449440
450 //-----------------------------------------------------------------------
451441 @Test
452442 public void testIndexOfType_ThrowableClass() {
453443 assertEquals(-1, ExceptionUtils.indexOfType(null, null));
501491 assertEquals(0, ExceptionUtils.indexOfType(withCause, Throwable.class, 0));
502492 }
503493
504 //-----------------------------------------------------------------------
505494 @Test
506495 public void testPrintRootCauseStackTrace_Throwable() {
507496 ExceptionUtils.printRootCauseStackTrace(null);
509498 // internally this method calls stream method anyway
510499 }
511500
512 //-----------------------------------------------------------------------
513501
514502 @Test
515503 public void testPrintRootCauseStackTrace_ThrowableStream() {
0 /*
1 * Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package org.apache.commons.lang3.function;
18
19 import static org.junit.jupiter.api.Assertions.assertFalse;
20 import static org.junit.jupiter.api.Assertions.assertThrows;
21 import static org.junit.jupiter.api.Assertions.assertTrue;
22
23 import java.util.concurrent.atomic.AtomicBoolean;
24 import org.junit.jupiter.api.Assertions;
25 import org.junit.jupiter.api.Test;
26
27 /**
28 * Tests {@link BooleanConsumer}.
29 */
30 public class BooleanConsumerTest {
31
32 private BooleanConsumer accept(final BooleanConsumer consumer, final boolean expected) {
33 consumer.accept(expected);
34 return consumer;
35 }
36
37 @Test
38 public void testAccept() {
39 final AtomicBoolean aBool = new AtomicBoolean();
40 accept(aBool::lazySet, true);
41 assertTrue(aBool.get());
42 accept(aBool::lazySet, false);
43 assertFalse(aBool.get());
44 }
45
46 @Test
47 public void testAndThen() throws Throwable {
48 final BooleanConsumer nop = BooleanConsumer.nop();
49 nop.andThen(nop);
50 // Documented in Javadoc edge-case.
51 assertThrows(NullPointerException.class, () -> nop.andThen(null));
52
53 final AtomicBoolean aBool1 = new AtomicBoolean();
54 final AtomicBoolean aBool2 = new AtomicBoolean();
55
56 final BooleanConsumer bc = aBool1::lazySet;
57 final BooleanConsumer composite = bc.andThen(aBool2::lazySet);
58
59 composite.accept(true);
60 assertTrue(aBool1.get());
61 assertTrue(aBool2.get());
62
63 composite.accept(false);
64 assertFalse(aBool1.get());
65 assertFalse(aBool2.get());
66
67 // Check order
68 final BooleanConsumer bad = new BooleanConsumer() {
69 @Override
70 public void accept(boolean value) {
71 throw new IllegalStateException();
72 }
73 };
74 final BooleanConsumer badComposite = bad.andThen(aBool2::lazySet);
75
76 Assertions.assertThrows(IllegalStateException.class, () -> badComposite.accept(true));
77 assertFalse(aBool2.get(), "Second consumer should not be invoked");
78 }
79
80 }
222222 return 0;
223223 }
224224
225 public short testAsShortPrimitive() throws Throwable {
226 return testAsShortPrimitive(throwable);
227 }
228
229 public short testAsShortPrimitive(final Throwable throwable) throws Throwable {
230 if (throwable != null) {
231 throw throwable;
232 }
233 return 0;
234 }
235
225236 public void testDouble(final double i) throws Throwable {
226237 test(throwable);
227238 acceptedPrimitiveObject1 = (P) ((Double) i);
10441055 }
10451056
10461057 @Test
1058 public void testGetAsShortSupplier() {
1059 final Testable<?, ?> testable = new Testable<>(ILLEGAL_STATE_EXCEPTION);
1060 Throwable e = assertThrows(IllegalStateException.class,
1061 () -> Failable.getAsShort(testable::testAsShortPrimitive));
1062 assertSame(ILLEGAL_STATE_EXCEPTION, e);
1063
1064 testable.setThrowable(ERROR);
1065 e = assertThrows(OutOfMemoryError.class, () -> Failable.getAsShort(testable::testAsShortPrimitive));
1066 assertSame(ERROR, e);
1067
1068 final IOException ioe = new IOException("Unknown I/O error");
1069 testable.setThrowable(ioe);
1070 e = assertThrows(UncheckedIOException.class, () -> Failable.getAsShort(testable::testAsShortPrimitive));
1071 final Throwable t = e.getCause();
1072 assertNotNull(t);
1073 assertSame(ioe, t);
1074
1075 testable.setThrowable(null);
1076 final short i = Failable.getAsShort(testable::testAsShortPrimitive);
1077 assertEquals(0, i);
1078 }
1079
1080 @Test
10471081 public void testGetFromSupplier() {
10481082 FailureOnOddInvocations.invocations = 0;
10491083 final UndeclaredThrowableException e = assertThrows(UndeclaredThrowableException.class,
13391373 }
13401374
13411375 /**
1342 * Tests that our failable interface is properly defined to throw any exception. using the top level generic types
1376 * Tests that our failable interface is properly defined to throw any exception using the top level generic types
13431377 * Object and Throwable.
13441378 */
13451379 @Test
13701404 }
13711405
13721406 /**
1373 * Tests that our failable interface is properly defined to throw any exception. using the top level generic types
1407 * Tests that our failable interface is properly defined to throw any exception using the top level generic types
13741408 * Object and Throwable.
13751409 */
13761410 @Test
14001434 }
14011435
14021436 /**
1403 * Tests that our failable interface is properly defined to throw any exception. using the top level generic types
1437 * Tests that our failable interface is properly defined to throw any exception using the top level generic types
14041438 * Object and Throwable.
14051439 */
14061440 @Test
14301464 }
14311465
14321466 /**
1433 * Tests that our failable interface is properly defined to throw any exception. using the top level generic types
1434 * Object and Throwable.
1435 */
1436 @Test
1437 public void testThrows_FailableBooleanSupplier_Object_Throwable() {
1467 * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as
1468 * generic test types.
1469 */
1470 @Test
1471 public void testThrows_FailableBooleanSupplier_IOException() {
1472 new FailableBooleanSupplier<IOException>() {
1473
1474 @Override
1475 public boolean getAsBoolean() throws IOException {
1476 throw new IOException("test");
1477 }
1478 };
1479 }
1480
1481 /**
1482 * Tests that our failable interface is properly defined to throw any exception using the top level generic types
1483 * Object and Throwable.
1484 */
1485 @Test
1486 public void testThrows_FailableBooleanSupplier_Throwable() {
14381487 new FailableBooleanSupplier<Throwable>() {
14391488
14401489 @Override
14451494 }
14461495
14471496 /**
1448 * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as
1449 * generic test types.
1450 */
1451 @Test
1452 public void testThrows_FailableBooleanSupplier_String_IOException() {
1453 new FailableBooleanSupplier<IOException>() {
1454
1455 @Override
1456 public boolean getAsBoolean() throws IOException {
1457 throw new IOException("test");
1458 }
1459 };
1460 }
1461
1462 ///////////////////////////////////////////////
1463
1464 /**
1465 * Tests that our failable interface is properly defined to throw any exception. using the top level generic types
1497 * Tests that our failable interface is properly defined to throw any exception using the top level generic types
14661498 * Object and Throwable.
14671499 */
14681500 @Test
14921524 }
14931525
14941526 /**
1495 * Tests that our failable interface is properly defined to throw any exception. using the top level generic types
1527 * Tests that our failable interface is properly defined to throw any exception using the top level generic types
14961528 * Object and Throwable.
14971529 */
14981530 @Test
15241556 }
15251557
15261558 /**
1527 * Tests that our failable interface is properly defined to throw any exception. using the top level generic types
1528 * Object and Throwable.
1529 */
1530 @Test
1531 public void testThrows_FailableDoubleBinaryOperator_Object_Throwable() {
1559 * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as
1560 * generic test types.
1561 */
1562 @Test
1563 public void testThrows_FailableDoubleBinaryOperator_IOException() {
1564 new FailableDoubleBinaryOperator<IOException>() {
1565
1566 @Override
1567 public double applyAsDouble(final double left, final double right) throws IOException {
1568 throw new IOException("test");
1569 }
1570 };
1571 }
1572
1573 /**
1574 * Tests that our failable interface is properly defined to throw any exception using the top level generic types
1575 * Object and Throwable.
1576 */
1577 @Test
1578 public void testThrows_FailableDoubleBinaryOperator_Throwable() {
15321579 new FailableDoubleBinaryOperator<Throwable>() {
15331580
15341581 @Override
15431590 * generic test types.
15441591 */
15451592 @Test
1546 public void testThrows_FailableDoubleBinaryOperator_String_IOException() {
1547 new FailableDoubleBinaryOperator<IOException>() {
1548
1549 @Override
1550 public double applyAsDouble(final double left, final double right) throws IOException {
1551 throw new IOException("test");
1552 }
1553 };
1554 }
1555
1556 /**
1557 * Tests that our failable interface is properly defined to throw any exception. using the top level generic types
1558 * Object and Throwable.
1559 */
1560 @Test
1561 public void testThrows_FailableDoubleConsumer_Object_Throwable() {
1593 public void testThrows_FailableDoubleConsumer_IOException() {
1594 new FailableDoubleConsumer<IOException>() {
1595
1596 @Override
1597 public void accept(final double value) throws IOException {
1598 throw new IOException("test");
1599 }
1600 };
1601 }
1602
1603 /**
1604 * Tests that our failable interface is properly defined to throw any exception using the top level generic types
1605 * Object and Throwable.
1606 */
1607 @Test
1608 public void testThrows_FailableDoubleConsumer_Throwable() {
15621609 new FailableDoubleConsumer<Throwable>() {
15631610
15641611 @Override
15741621 * generic test types.
15751622 */
15761623 @Test
1577 public void testThrows_FailableDoubleConsumer_String_IOException() {
1578 new FailableDoubleConsumer<IOException>() {
1579
1580 @Override
1581 public void accept(final double value) throws IOException {
1582 throw new IOException("test");
1583 }
1584 };
1585 }
1586
1587 /**
1588 * Tests that our failable interface is properly defined to throw any exception. using the top level generic types
1589 * Object and Throwable.
1590 */
1591 @Test
1592 public void testThrows_FailableDoubleFunction_Object_Throwable() {
1624 public void testThrows_FailableDoubleFunction_IOException() {
1625 new FailableDoubleFunction<String, IOException>() {
1626
1627 @Override
1628 public String apply(final double input) throws IOException {
1629 throw new IOException("test");
1630 }
1631 };
1632 }
1633
1634 /**
1635 * Tests that our failable interface is properly defined to throw any exception using the top level generic types
1636 * Object and Throwable.
1637 */
1638 @Test
1639 public void testThrows_FailableDoubleFunction_Throwable() {
15931640 new FailableDoubleFunction<Object, Throwable>() {
15941641
15951642 @Override
16041651 * generic test types.
16051652 */
16061653 @Test
1607 public void testThrows_FailableDoubleFunction_String_IOException() {
1608 new FailableDoubleFunction<String, IOException>() {
1609
1610 @Override
1611 public String apply(final double input) throws IOException {
1612 throw new IOException("test");
1613 }
1614 };
1615 }
1616
1617 /**
1618 * Tests that our failable interface is properly defined to throw any exception. using the top level generic types
1619 * Object and Throwable.
1620 */
1621 @Test
1622 public void testThrows_FailableDoubleSupplier_Object_Throwable() {
1654 public void testThrows_FailableDoubleSupplier_IOException() {
1655 new FailableDoubleSupplier<IOException>() {
1656
1657 @Override
1658 public double getAsDouble() throws IOException {
1659 throw new IOException("test");
1660 }
1661 };
1662 }
1663
1664 /**
1665 * Tests that our failable interface is properly defined to throw any exception using the top level generic types
1666 * Object and Throwable.
1667 */
1668 @Test
1669 public void testThrows_FailableDoubleSupplier_Throwable() {
16231670 new FailableDoubleSupplier<Throwable>() {
16241671
16251672 @Override
16341681 * generic test types.
16351682 */
16361683 @Test
1637 public void testThrows_FailableDoubleSupplier_String_IOException() {
1638 new FailableDoubleSupplier<IOException>() {
1639
1640 @Override
1641 public double getAsDouble() throws IOException {
1642 throw new IOException("test");
1643 }
1644 };
1645 }
1646
1647 /**
1648 * Tests that our failable interface is properly defined to throw any exception. using the top level generic types
1649 * Object and Throwable.
1650 */
1651 @Test
1652 public void testThrows_FailableDoubleToIntFunction_Object_Throwable() {
1684 public void testThrows_FailableDoubleToIntFunction_IOException() {
1685 new FailableDoubleToIntFunction<IOException>() {
1686
1687 @Override
1688 public int applyAsInt(final double value) throws IOException {
1689 throw new IOException("test");
1690 }
1691 };
1692 }
1693
1694 /**
1695 * Tests that our failable interface is properly defined to throw any exception using the top level generic types
1696 * Object and Throwable.
1697 */
1698 @Test
1699 public void testThrows_FailableDoubleToIntFunction_Throwable() {
16531700 new FailableDoubleToIntFunction<Throwable>() {
16541701
16551702 @Override
16641711 * generic test types.
16651712 */
16661713 @Test
1667 public void testThrows_FailableDoubleToIntFunction_String_IOException() {
1668 new FailableDoubleToIntFunction<IOException>() {
1669
1670 @Override
1671 public int applyAsInt(final double value) throws IOException {
1672 throw new IOException("test");
1673 }
1674 };
1675 }
1676
1677 /**
1678 * Tests that our failable interface is properly defined to throw any exception. using the top level generic types
1679 * Object and Throwable.
1680 */
1681 @Test
1682 public void testThrows_FailableDoubleToLongFunction_Object_Throwable() {
1714 public void testThrows_FailableDoubleToLongFunction_IOException() {
1715 new FailableDoubleToLongFunction<IOException>() {
1716
1717 @Override
1718 public int applyAsLong(final double value) throws IOException {
1719 throw new IOException("test");
1720 }
1721 };
1722 }
1723
1724 /**
1725 * Tests that our failable interface is properly defined to throw any exception using the top level generic types
1726 * Object and Throwable.
1727 */
1728 @Test
1729 public void testThrows_FailableDoubleToLongFunction_Throwable() {
16831730 new FailableDoubleToLongFunction<Throwable>() {
16841731
16851732 @Override
16901737 }
16911738
16921739 /**
1693 * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as
1694 * generic test types.
1695 */
1696 @Test
1697 public void testThrows_FailableDoubleToLongFunction_String_IOException() {
1698 new FailableDoubleToLongFunction<IOException>() {
1699
1700 @Override
1701 public int applyAsLong(final double value) throws IOException {
1702 throw new IOException("test");
1703 }
1704 };
1705 }
1706
1707 /**
1708 * Tests that our failable interface is properly defined to throw any exception. using the top level generic types
1740 * Tests that our failable interface is properly defined to throw any exception using the top level generic types
17091741 * Object and Throwable.
17101742 */
17111743 @Test
17351767 }
17361768
17371769 /**
1738 * Tests that our failable interface is properly defined to throw any exception. using the top level generic types
1739 * Object and Throwable.
1740 */
1741 @Test
1742 public void testThrows_FailableIntBinaryOperator_Object_Throwable() {
1770 * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as
1771 * generic test types.
1772 */
1773 @Test
1774 public void testThrows_FailableIntBinaryOperator_IOException() {
1775 new FailableIntBinaryOperator<IOException>() {
1776
1777 @Override
1778 public int applyAsInt(final int left, final int right) throws IOException {
1779 throw new IOException("test");
1780 }
1781 };
1782 }
1783
1784 /**
1785 * Tests that our failable interface is properly defined to throw any exception using the top level generic types
1786 * Object and Throwable.
1787 */
1788 @Test
1789 public void testThrows_FailableIntBinaryOperator_Throwable() {
17431790 new FailableIntBinaryOperator<Throwable>() {
17441791
17451792 @Override
17541801 * generic test types.
17551802 */
17561803 @Test
1757 public void testThrows_FailableIntBinaryOperator_String_IOException() {
1758 new FailableIntBinaryOperator<IOException>() {
1759
1760 @Override
1761 public int applyAsInt(final int left, final int right) throws IOException {
1762 throw new IOException("test");
1763 }
1764 };
1765 }
1766
1767 /**
1768 * Tests that our failable interface is properly defined to throw any exception. using the top level generic types
1769 * Object and Throwable.
1770 */
1771 @Test
1772 public void testThrows_FailableIntConsumer_Object_Throwable() {
1804 public void testThrows_FailableIntConsumer_IOException() {
1805 new FailableIntConsumer<IOException>() {
1806
1807 @Override
1808 public void accept(final int value) throws IOException {
1809 throw new IOException("test");
1810 }
1811 };
1812 }
1813
1814 /**
1815 * Tests that our failable interface is properly defined to throw any exception using the top level generic types
1816 * Object and Throwable.
1817 */
1818 @Test
1819 public void testThrows_FailableIntConsumer_Throwable() {
17731820 new FailableIntConsumer<Throwable>() {
17741821
17751822 @Override
17811828 }
17821829
17831830 /**
1784 * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as
1785 * generic test types.
1786 */
1787 @Test
1788 public void testThrows_FailableIntConsumer_String_IOException() {
1789 new FailableIntConsumer<IOException>() {
1790
1791 @Override
1792 public void accept(final int value) throws IOException {
1793 throw new IOException("test");
1794 }
1795 };
1796 }
1797
1798 /**
1799 * Tests that our failable interface is properly defined to throw any exception. using the top level generic types
1831 * Tests that our failable interface is properly defined to throw any exception using the top level generic types
18001832 * Object and Throwable.
18011833 */
18021834 @Test
18261858 }
18271859
18281860 /**
1829 * Tests that our failable interface is properly defined to throw any exception. using the top level generic types
1830 * Object and Throwable.
1831 */
1832 @Test
1833 public void testThrows_FailableIntSupplier_Object_Throwable() {
1861 * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as
1862 * generic test types.
1863 */
1864 @Test
1865 public void testThrows_FailableIntSupplier_IOException() {
1866 new FailableIntSupplier<IOException>() {
1867
1868 @Override
1869 public int getAsInt() throws IOException {
1870 throw new IOException("test");
1871 }
1872 };
1873 }
1874
1875 /**
1876 * Tests that our failable interface is properly defined to throw any exception using the top level generic types
1877 * Object and Throwable.
1878 */
1879 @Test
1880 public void testThrows_FailableIntSupplier_Throwable() {
18341881 new FailableIntSupplier<Throwable>() {
18351882
18361883 @Override
18451892 * generic test types.
18461893 */
18471894 @Test
1848 public void testThrows_FailableIntSupplier_String_IOException() {
1849 new FailableIntSupplier<IOException>() {
1850
1851 @Override
1852 public int getAsInt() throws IOException {
1853 throw new IOException("test");
1854 }
1855 };
1856 }
1857
1858 /**
1859 * Tests that our failable interface is properly defined to throw any exception. using the top level generic types
1860 * Object and Throwable.
1861 */
1862 @Test
1863 public void testThrows_FailableIntToDoubleFunction_Object_Throwable() {
1895 public void testThrows_FailableIntToDoubleFunction_IOException() {
1896 new FailableIntToDoubleFunction<IOException>() {
1897
1898 @Override
1899 public double applyAsDouble(final int value) throws IOException {
1900 throw new IOException("test");
1901 }
1902 };
1903 }
1904
1905 /**
1906 * Tests that our failable interface is properly defined to throw any exception using the top level generic types
1907 * Object and Throwable.
1908 */
1909 @Test
1910 public void testThrows_FailableIntToDoubleFunction_Throwable() {
18641911 new FailableIntToDoubleFunction<Throwable>() {
18651912
18661913 @Override
18751922 * generic test types.
18761923 */
18771924 @Test
1878 public void testThrows_FailableIntToDoubleFunction_String_IOException() {
1879 new FailableIntToDoubleFunction<IOException>() {
1880
1881 @Override
1882 public double applyAsDouble(final int value) throws IOException {
1883 throw new IOException("test");
1884 }
1885 };
1886 }
1887
1888 /**
1889 * Tests that our failable interface is properly defined to throw any exception. using the top level generic types
1890 * Object and Throwable.
1891 */
1892 @Test
1893 public void testThrows_FailableIntToLongFunction_Object_Throwable() {
1925 public void testThrows_FailableIntToLongFunction_IOException() {
1926 new FailableIntToLongFunction<IOException>() {
1927
1928 @Override
1929 public long applyAsLong(final int value) throws IOException {
1930 throw new IOException("test");
1931 }
1932 };
1933 }
1934
1935 /**
1936 * Tests that our failable interface is properly defined to throw any exception using the top level generic types
1937 * Object and Throwable.
1938 */
1939 @Test
1940 public void testThrows_FailableIntToLongFunction_Throwable() {
18941941 new FailableIntToLongFunction<Throwable>() {
18951942
18961943 @Override
19051952 * generic test types.
19061953 */
19071954 @Test
1908 public void testThrows_FailableIntToLongFunction_String_IOException() {
1909 new FailableIntToLongFunction<IOException>() {
1910
1911 @Override
1912 public long applyAsLong(final int value) throws IOException {
1913 throw new IOException("test");
1914 }
1915 };
1916 }
1917
1918 /**
1919 * Tests that our failable interface is properly defined to throw any exception. using the top level generic types
1920 * Object and Throwable.
1921 */
1922 @Test
1923 public void testThrows_FailableLongBinaryOperator_Object_Throwable() {
1955 public void testThrows_FailableLongBinaryOperator_IOException() {
1956 new FailableLongBinaryOperator<IOException>() {
1957
1958 @Override
1959 public long applyAsLong(final long left, final long right) throws IOException {
1960 throw new IOException("test");
1961 }
1962 };
1963 }
1964
1965 /**
1966 * Tests that our failable interface is properly defined to throw any exception using the top level generic types
1967 * Object and Throwable.
1968 */
1969 @Test
1970 public void testThrows_FailableLongBinaryOperator_Throwable() {
19241971 new FailableLongBinaryOperator<Throwable>() {
19251972
19261973 @Override
19351982 * generic test types.
19361983 */
19371984 @Test
1938 public void testThrows_FailableLongBinaryOperator_String_IOException() {
1939 new FailableLongBinaryOperator<IOException>() {
1940
1941 @Override
1942 public long applyAsLong(final long left, final long right) throws IOException {
1943 throw new IOException("test");
1944 }
1945 };
1946 }
1947
1948 /**
1949 * Tests that our failable interface is properly defined to throw any exception. using the top level generic types
1950 * Object and Throwable.
1951 */
1952 @Test
1953 public void testThrows_FailableLongConsumer_Object_Throwable() {
1985 public void testThrows_FailableLongConsumer_IOException() {
1986 new FailableLongConsumer<IOException>() {
1987
1988 @Override
1989 public void accept(final long object) throws IOException {
1990 throw new IOException("test");
1991
1992 }
1993 };
1994 }
1995
1996 /**
1997 * Tests that our failable interface is properly defined to throw any exception using the top level generic types
1998 * Object and Throwable.
1999 */
2000 @Test
2001 public void testThrows_FailableLongConsumer_Throwable() {
19542002 new FailableLongConsumer<Throwable>() {
19552003
19562004 @Override
19662014 * generic test types.
19672015 */
19682016 @Test
1969 public void testThrows_FailableLongConsumer_String_IOException() {
1970 new FailableLongConsumer<IOException>() {
1971
1972 @Override
1973 public void accept(final long object) throws IOException {
1974 throw new IOException("test");
1975
1976 }
1977 };
1978 }
1979
1980 /**
1981 * Tests that our failable interface is properly defined to throw any exception. using the top level generic types
1982 * Object and Throwable.
1983 */
1984 @Test
1985 public void testThrows_FailableLongFunction_Object_Throwable() {
2017 public void testThrows_FailableLongFunction_IOException() {
2018 new FailableLongFunction<String, IOException>() {
2019
2020 @Override
2021 public String apply(final long input) throws IOException {
2022 throw new IOException("test");
2023 }
2024 };
2025 }
2026
2027 /**
2028 * Tests that our failable interface is properly defined to throw any exception using the top level generic types
2029 * Object and Throwable.
2030 */
2031 @Test
2032 public void testThrows_FailableLongFunction_Throwable() {
19862033 new FailableLongFunction<Object, Throwable>() {
19872034
19882035 @Override
19972044 * generic test types.
19982045 */
19992046 @Test
2000 public void testThrows_FailableLongFunction_String_IOException() {
2001 new FailableLongFunction<String, IOException>() {
2002
2003 @Override
2004 public String apply(final long input) throws IOException {
2005 throw new IOException("test");
2006 }
2007 };
2008 }
2009
2010 /**
2011 * Tests that our failable interface is properly defined to throw any exception. using the top level generic types
2012 * Object and Throwable.
2013 */
2014 @Test
2015 public void testThrows_FailableLongSupplier_Object_Throwable() {
2047 public void testThrows_FailableLongSupplier_IOException() {
2048 new FailableLongSupplier<IOException>() {
2049
2050 @Override
2051 public long getAsLong() throws IOException {
2052 throw new IOException("test");
2053 }
2054 };
2055 }
2056
2057 /**
2058 * Tests that our failable interface is properly defined to throw any exception using the top level generic types
2059 * Object and Throwable.
2060 */
2061 @Test
2062 public void testThrows_FailableLongSupplier_Throwable() {
20162063 new FailableLongSupplier<Throwable>() {
20172064
20182065 @Override
20272074 * generic test types.
20282075 */
20292076 @Test
2030 public void testThrows_FailableLongSupplier_String_IOException() {
2031 new FailableLongSupplier<IOException>() {
2032
2033 @Override
2034 public long getAsLong() throws IOException {
2035 throw new IOException("test");
2036 }
2037 };
2038 }
2039
2040 /**
2041 * Tests that our failable interface is properly defined to throw any exception. using the top level generic types
2042 * Object and Throwable.
2043 */
2044 @Test
2045 public void testThrows_FailableLongToDoubleFunction_Object_Throwable() {
2077 public void testThrows_FailableLongToDoubleFunction_IOException() {
2078 new FailableLongToDoubleFunction<IOException>() {
2079
2080 @Override
2081 public double applyAsDouble(final long value) throws IOException {
2082 throw new IOException("test");
2083 }
2084 };
2085 }
2086
2087 /**
2088 * Tests that our failable interface is properly defined to throw any exception using the top level generic types
2089 * Object and Throwable.
2090 */
2091 @Test
2092 public void testThrows_FailableLongToDoubleFunction_Throwable() {
20462093 new FailableLongToDoubleFunction<Throwable>() {
20472094
20482095 @Override
20572104 * generic test types.
20582105 */
20592106 @Test
2060 public void testThrows_FailableLongToDoubleFunction_String_IOException() {
2061 new FailableLongToDoubleFunction<IOException>() {
2062
2063 @Override
2064 public double applyAsDouble(final long value) throws IOException {
2065 throw new IOException("test");
2066 }
2067 };
2068 }
2069
2070 /**
2071 * Tests that our failable interface is properly defined to throw any exception. using the top level generic types
2072 * Object and Throwable.
2073 */
2074 @Test
2075 public void testThrows_FailableLongToIntFunction_Object_Throwable() {
2107 public void testThrows_FailableLongToIntFunction_IOException() {
2108 new FailableLongToIntFunction<IOException>() {
2109
2110 @Override
2111 public int applyAsInt(final long value) throws IOException {
2112 throw new IOException("test");
2113 }
2114 };
2115 }
2116
2117 /**
2118 * Tests that our failable interface is properly defined to throw any exception using the top level generic types
2119 * Object and Throwable.
2120 */
2121 @Test
2122 public void testThrows_FailableLongToIntFunction_Throwable() {
20762123 new FailableLongToIntFunction<Throwable>() {
20772124
20782125 @Override
20832130 }
20842131
20852132 /**
2086 * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as
2087 * generic test types.
2088 */
2089 @Test
2090 public void testThrows_FailableLongToIntFunction_String_IOException() {
2091 new FailableLongToIntFunction<IOException>() {
2092
2093 @Override
2094 public int applyAsInt(final long value) throws IOException {
2095 throw new IOException("test");
2096 }
2097 };
2098 }
2099
2100 /**
2101 * Tests that our failable interface is properly defined to throw any exception. using the top level generic types
2133 * Tests that our failable interface is properly defined to throw any exception using the top level generic types
21022134 * Object and Throwable.
21032135 */
21042136 @Test
21292161 }
21302162
21312163 /**
2132 * Tests that our failable interface is properly defined to throw any exception. using the top level generic types
2164 * Tests that our failable interface is properly defined to throw any exception using the top level generic types
21332165 * Object and Throwable.
21342166 */
21352167 @Test
21602192 }
21612193
21622194 /**
2163 * Tests that our failable interface is properly defined to throw any exception. using the top level generic types
2195 * Tests that our failable interface is properly defined to throw any exception using the top level generic types
21642196 * Object and Throwable.
21652197 */
21662198 @Test
21912223 }
21922224
21932225 /**
2194 * Tests that our failable interface is properly defined to throw any exception. using the top level generic types
2226 * Tests that our failable interface is properly defined to throw any exception using the top level generic types
21952227 * Object and Throwable.
21962228 */
21972229 @Test
22212253 }
22222254
22232255 /**
2224 * Tests that our failable interface is properly defined to throw any exception. using the top level generic types
2225 * Object and Throwable.
2226 */
2227 @Test
2228 public void testThrows_FailableRunnable_Object_Throwable() {
2256 * Tests that our failable interface is properly defined to throw any exception using String and IOExceptions as
2257 * generic test types.
2258 */
2259 @Test
2260 public void testThrows_FailableRunnable_IOException() {
2261 new FailableRunnable<IOException>() {
2262
2263 @Override
2264 public void run() throws IOException {
2265 throw new IOException("test");
2266 }
2267 };
2268 }
2269
2270 /**
2271 * Tests that our failable interface is properly defined to throw any exception using the top level generic types
2272 * Object and Throwable.
2273 */
2274 @Test
2275 public void testThrows_FailableRunnable_Throwable() {
22292276 new FailableRunnable<Throwable>() {
22302277
22312278 @Override
22412288 * generic test types.
22422289 */
22432290 @Test
2244 public void testThrows_FailableRunnable_String_IOException() {
2245 new FailableRunnable<IOException>() {
2246
2247 @Override
2248 public void run() throws IOException {
2249 throw new IOException("test");
2250 }
2251 };
2252 }
2253
2254 /**
2255 * Tests that our failable interface is properly defined to throw any exception. using the top level generic types
2291 public void testThrows_FailableShortSupplier_IOException() {
2292 new FailableShortSupplier<IOException>() {
2293
2294 @Override
2295 public short getAsShort() throws IOException {
2296 throw new IOException("test");
2297 }
2298 };
2299 }
2300
2301 /**
2302 * Tests that our failable interface is properly defined to throw any exception using the top level generic types
2303 * Object and Throwable.
2304 */
2305 @Test
2306 public void testThrows_FailableShortSupplier_Throwable() {
2307 new FailableShortSupplier<Throwable>() {
2308
2309 @Override
2310 public short getAsShort() throws Throwable {
2311 throw new IOException("test");
2312 }
2313 };
2314 }
2315
2316 /**
2317 * Tests that our failable interface is properly defined to throw any exception using the top level generic types
22562318 * Object and Throwable.
22572319 */
22582320 @Test
22822344 }
22832345
22842346 /**
2285 * Tests that our failable interface is properly defined to throw any exception. using the top level generic types
2347 * Tests that our failable interface is properly defined to throw any exception using the top level generic types
22862348 * Object and Throwable.
22872349 */
22882350 @Test
23122374 }
23132375
23142376 /**
2315 * Tests that our failable interface is properly defined to throw any exception. using the top level generic types
2377 * Tests that our failable interface is properly defined to throw any exception using the top level generic types
23162378 * Object and Throwable.
23172379 */
23182380 @Test
23422404 }
23432405
23442406 /**
2345 * Tests that our failable interface is properly defined to throw any exception. using the top level generic types
2407 * Tests that our failable interface is properly defined to throw any exception using the top level generic types
23462408 * Object and Throwable.
23472409 */
23482410 @Test
23722434 }
23732435
23742436 /**
2375 * Tests that our failable interface is properly defined to throw any exception. using the top level generic types
2437 * Tests that our failable interface is properly defined to throw any exception using the top level generic types
23762438 * Object and Throwable.
23772439 */
23782440 @Test
24022464 }
24032465
24042466 /**
2405 * Tests that our failable interface is properly defined to throw any exception. using the top level generic types
2467 * Tests that our failable interface is properly defined to throw any exception using the top level generic types
24062468 * Object and Throwable.
24072469 */
24082470 @Test
24322494 }
24332495
24342496 /**
2435 * Tests that our failable interface is properly defined to throw any exception. using the top level generic types
2497 * Tests that our failable interface is properly defined to throw any exception using the top level generic types
24362498 * Object and Throwable.
24372499 */
24382500 @Test
0 /*
1 * Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package org.apache.commons.lang3.function;
18
19 import java.util.function.Supplier;
20
21 import javax.annotation.Nonnull;
22 import javax.annotation.Nullable;
23
24 import org.apache.commons.lang3.ObjectUtils;
25
26
27 /**
28 * This class provides some replacements for the corresponding methods in
29 * {@link java.util.Objects}. The replacements have the advantage, that they are properly
30 * annotated with {@link Nullable}, and/or {@link Nonnull}, so they let the
31 * compiler know, what their respective results are.
32 *
33 * The various {@code requireNonNull} methods are particularly handy, when
34 * dealing with external code, that a) doesn't support the {@link Nonnull}
35 * annotation, or if you know for other reasons, that an object is non-null.
36 * Take for example, a {@link java.util.Map map}, that you have filled with
37 * non-null values. So, in your opinion, the following should be perfectably
38 * valid code:
39 * <pre>
40 * final Map&lt;String,Object&gt; map = getMapOfNonNullValues();
41 * final @Nonnull Object o = map.get("SomeKey");
42 * </pre>
43 * However, if your Java compiler *does* null analysis, it will reject this
44 * example as invalid, because {@link java.util.Map#get(Object)} might return
45 * a null value. As a workaround, you can use this:
46 * <pre>
47 * import static org.apache.commons.lang3.function.Objects.requireNonNull;
48 *
49 * final Map&lt;String,Object&gt; map = getMapOfNonNullValues();
50 * final @Nonnull Object o = requireNonNull(map.get("SomeKey"));
51 * </pre>
52 *
53 * This class is somewhat redundant with regards to {@link ObjectUtils}.
54 * For example, {@link #requireNonNull(Object, Object)} is almost equivalent
55 * with {@link ObjectUtils#defaultIfNull(Object, Object)}. However, it isn't
56 * quite the same, because the latter can, in fact, return null. The former
57 * can't, and the Java compiler confirms this.(An alternative to redundancy
58 * would have been to change the {@code ObjectUtils} class. However, that
59 * would mean loosing upwards compatibility, and we don't do that.)
60 *
61 * @since 3.12.0
62 */
63 public class Objects {
64 /**
65 * Checks, whether the given object is non-null. If so, returns the non-null
66 * object as a result value. Otherwise, a NullPointerException is thrown.
67 * @param <T> The type of parameter {@code value}, also the result type.
68 * @param value The value, which is being checked.
69 * @return The given input value, if it was found to be non-null.
70 * @throws NullPointerException The input value was null.
71 * @see java.util.Objects#requireNonNull(Object)
72 */
73 public static <T> @Nonnull T requireNonNull(@Nullable final T value) throws NullPointerException {
74 return requireNonNull(value, "The value must not be null.");
75 }
76
77 /**
78 * Checks, whether the given object is non-null. If so, returns the non-null
79 * object as a result value. Otherwise, a NullPointerException is thrown.
80 * @param <T> The type of parameter {@code value}, also the result type.
81 * @param value The value, which is being checked.
82 * @param defaultValue The default value, which is being returned, if the
83 * check fails, and the {@code value} is null.
84 * @throws NullPointerException The input value, and the default value are null.
85 * @return The given input value, if it was found to be non-null.
86 * @see java.util.Objects#requireNonNull(Object)
87 */
88 public static <T> @Nonnull T requireNonNull(@Nullable final T value, @Nonnull final T defaultValue) throws NullPointerException {
89 return value == null ? requireNonNull(defaultValue) : value;
90 }
91
92 /**
93 * Checks, whether the given object is non-null. If so, returns the non-null
94 * object as a result value. Otherwise, a NullPointerException is thrown.
95 * @param <T> The type of parameter {@code value}, also the result type.
96 * @param value The value, which is being checked.
97 * @param msg A string, which is being used as the exceptions message, if the
98 * check fails.
99 * @return The given input value, if it was found to be non-null.
100 * @throws NullPointerException The input value was null.
101 * @see java.util.Objects#requireNonNull(Object, String)
102 * @see #requireNonNull(Object, Supplier)
103 */
104 public static <T> @Nonnull T requireNonNull(@Nullable final T value, @Nonnull final String msg) throws NullPointerException {
105 if (value == null) {
106 throw new NullPointerException(msg);
107 }
108 return value;
109 }
110
111 /**
112 * Checks, whether the given object is non-null. If so, returns the non-null
113 * object as a result value. Otherwise, a NullPointerException is thrown.
114 * @param <T> The type of parameter {@code value}, also the result type.
115 * @param value The value, which is being checked.
116 * @param msgSupplier A supplier, which creates the exception message, if the check fails.
117 * This supplier will only be invoked, if necessary.
118 * @return The given input value, if it was found to be non-null.
119 * @throws NullPointerException The input value was null.
120 * @see java.util.Objects#requireNonNull(Object, String)
121 * @see #requireNonNull(Object, String)
122 */
123 public static <T> @Nonnull T requireNonNull(@Nullable final T value, @Nonnull final Supplier<String> msgSupplier) throws NullPointerException {
124 if (value == null) {
125 throw new NullPointerException(msgSupplier.get());
126 }
127 return value;
128 }
129
130 /** Checks, whether the given object is non-null. If so, returns the non-null
131 * object as a result value. Otherwise, invokes the given {@link Supplier},
132 * and returns the suppliers result value.
133 * @param <T> The type of parameter {@code value}, also the result type of
134 * the default value supplier, and of the method itself.
135 * @param <E> The type of exception, that the {@code default value supplier},
136 * may throw.
137 * @param value The value, which is being checked.
138 * @param defaultValueSupplier The supplier, which returns the default value. This default
139 * value <em>must</em> be non-null. The supplier will only be invoked, if
140 * necessary. (If the {@code value} parameter is null, that is.)
141 * @return The given input value, if it was found to be non-null. Otherwise,
142 * the value, that has been returned by the default value supplier.
143 * @see #requireNonNull(Object)
144 * @see #requireNonNull(Object, String)
145 * @see #requireNonNull(Object, Supplier)
146 * @throws NullPointerException The default value supplier is null, or the default
147 * value supplier has returned null.
148 */
149 public static <T, E extends Throwable> @Nonnull T requireNonNull(@Nullable final T value, @Nonnull final FailableSupplier<T, E> defaultValueSupplier) throws NullPointerException {
150 if (value == null) {
151 final FailableSupplier<T, ?> supplier = requireNonNull(defaultValueSupplier, "The supplier must not be null");
152 final T defaultValue;
153 try {
154 defaultValue = supplier.get();
155 } catch (final Throwable t) {
156 throw Failable.rethrow(t);
157 }
158 return requireNonNull(defaultValue, "The supplier must not return null.");
159 }
160 return value;
161 }
162 }
0 /*
1 * Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package org.apache.commons.lang3.function;
18
19 import static org.junit.jupiter.api.Assertions.assertEquals;
20 import static org.junit.jupiter.api.Assertions.assertFalse;
21 import static org.junit.jupiter.api.Assertions.assertSame;
22 import static org.junit.jupiter.api.Assertions.assertTrue;
23 import static org.junit.jupiter.api.Assertions.fail;
24
25 import java.util.function.Supplier;
26
27 import org.junit.jupiter.api.Test;
28
29
30 class ObjectsTest {
31 @Test
32 void testRequireNonNullObject() {
33 assertSame("foo", Objects.requireNonNull("foo"));
34 try {
35 Objects.requireNonNull(null);
36 fail("Expected Exception");
37 } catch (final NullPointerException e) {
38 assertEquals("The value must not be null.", e.getMessage());
39 }
40 }
41
42 @Test
43 void testRequireNonNullObjectString() {
44 assertSame("foo", Objects.requireNonNull("foo", "bar"));
45 try {
46 Objects.requireNonNull(null, "bar");
47 fail("Expected Exception");
48 } catch (final NullPointerException e) {
49 assertEquals("bar", e.getMessage());
50 }
51 }
52
53 public static class TestableSupplier<O> implements Supplier<O> {
54 private final Supplier<O> supplier;
55 private boolean invoked;
56
57 TestableSupplier(final Supplier<O> pSupplier) {
58 this.supplier = pSupplier;
59 }
60
61 @Override
62 public O get() {
63 invoked = true;
64 return supplier.get();
65 }
66
67 public boolean isInvoked() {
68 return invoked;
69 }
70 }
71
72 @Test
73 void testRequireNonNullObjectSupplierString() {
74 final TestableSupplier<String> supplier = new TestableSupplier<>(() -> "bar");
75 assertSame("foo", Objects.requireNonNull("foo", supplier));
76 assertFalse(supplier.isInvoked());
77 try {
78 Objects.requireNonNull(null, supplier);
79 fail("Expected Exception");
80 } catch (final NullPointerException e) {
81 assertEquals("bar", e.getMessage());
82 assertTrue(supplier.isInvoked());
83 }
84 }
85
86 public static class TestableFailableSupplier<O, E extends Exception> implements FailableSupplier<O, E> {
87 private final FailableSupplier<O, E> supplier;
88 private boolean invoked;
89
90 TestableFailableSupplier(final FailableSupplier<O, E> pSupplier) {
91 this.supplier = pSupplier;
92 }
93
94 @Override
95 public O get() throws E {
96 invoked = true;
97 return supplier.get();
98 }
99
100 public boolean isInvoked() {
101 return invoked;
102 }
103 }
104
105 @Test
106 void testRequireNonNullObjectFailableSupplierString() {
107 final TestableFailableSupplier<String, ?> supplier = new TestableFailableSupplier<>(() -> null);
108 assertSame("foo", Objects.requireNonNull("foo", supplier));
109 assertFalse(supplier.isInvoked());
110 try {
111 Objects.requireNonNull(null, supplier);
112 fail("Expected Exception");
113 } catch (final NullPointerException e) {
114 assertEquals("The supplier must not return null.", e.getMessage());
115 assertTrue(supplier.isInvoked());
116 }
117 final TestableFailableSupplier<String, ?> supplier2 = new TestableFailableSupplier<>(() -> null);
118 try {
119 Objects.requireNonNull(null, supplier2);
120 fail("Expected Exception");
121 } catch (final NullPointerException e) {
122 assertEquals("The supplier must not return null.", e.getMessage());
123 assertTrue(supplier2.isInvoked());
124 }
125 final TestableFailableSupplier<String, ?> supplier3 = new TestableFailableSupplier<>(() -> "bar");
126 assertSame("bar", Objects.requireNonNull(null, supplier3));
127 final RuntimeException rte = new RuntimeException();
128 final TestableFailableSupplier<String, ?> supplier4 = new TestableFailableSupplier<>(() -> {
129 throw rte;
130 });
131 try {
132 Objects.requireNonNull(null, supplier4);
133 fail("Expected Exception");
134 } catch (final RuntimeException e) {
135 assertSame(rte, e);
136 assertTrue(supplier4.isInvoked());
137 }
138 }
139 }
0 /*
1 * Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package org.apache.commons.lang3.function;
18
19 import static org.junit.jupiter.api.Assertions.assertEquals;
20 import static org.junit.jupiter.api.Assertions.assertNull;
21
22 import java.util.function.Supplier;
23
24 import org.junit.jupiter.api.Test;
25
26 /**
27 * Tests {@link Suppliers}.
28 */
29 public class SuppliersTest {
30
31 /**
32 * Tests {@link Suppliers#get(Supplier)}.
33 */
34 @Test
35 public void testGet() {
36 assertNull(Suppliers.get(null));
37 assertNull(Suppliers.get(() -> null));
38 assertEquals("foo", Suppliers.get(() -> "foo"));
39 }
40 }
0 /*
1 * Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package org.apache.commons.lang3.function;
18
19 import static org.junit.jupiter.api.Assertions.assertEquals;
20
21 import java.util.concurrent.atomic.AtomicReference;
22
23 import org.junit.jupiter.api.Test;
24
25 /**
26 * Tests {@linkTriConsumer}.
27 */
28 public class TriConsumerTest {
29
30 @Test
31 public void testAccept() throws Throwable {
32 final AtomicReference<Character> ref1 = new AtomicReference<>();
33 final AtomicReference<Short> ref2 = new AtomicReference<>();
34 final AtomicReference<String> ref3 = new AtomicReference<>();
35 final TriConsumer<AtomicReference<Character>, AtomicReference<Short>, AtomicReference<String>> tri = (t, u,
36 v) -> {
37 ref1.set(Character.valueOf('a'));
38 ref2.set(Short.valueOf((short) 1));
39 ref3.set("z");
40 };
41 tri.accept(ref1, ref2, ref3);
42 assertEquals(Character.valueOf('a'), ref1.get());
43 assertEquals(Short.valueOf((short) 1), ref2.get());
44 assertEquals("z", ref3.get());
45 }
46
47 @Test
48 public void testAndThen() throws Throwable {
49 final AtomicReference<Character> ref1 = new AtomicReference<>();
50 final AtomicReference<Short> ref2 = new AtomicReference<>();
51 final AtomicReference<String> ref3 = new AtomicReference<>();
52 final TriConsumer<AtomicReference<Character>, AtomicReference<Short>, AtomicReference<String>> tri = (t, u,
53 v) -> {
54 ref1.set(Character.valueOf('a'));
55 ref2.set(Short.valueOf((short) 1));
56 ref3.set("z");
57 };
58 final TriConsumer<AtomicReference<Character>, AtomicReference<Short>, AtomicReference<String>> triAfter = (t, u,
59 v) -> {
60 ref1.set(Character.valueOf('b'));
61 ref2.set(Short.valueOf((short) 2));
62 ref3.set("zz");
63 };
64 tri.andThen(triAfter).accept(ref1, ref2, ref3);
65 assertEquals(Character.valueOf('b'), ref1.get());
66 assertEquals(Short.valueOf((short) 2), ref2.get());
67 assertEquals("zz", ref3.get());
68 }
69
70 }
3232
3333 private static final int SKIP = 500; //53
3434
35 @Test
36 public void testAbs() {
37 Fraction f;
38
39 f = Fraction.getFraction(50, 75);
40 f = f.abs();
41 assertEquals(50, f.getNumerator());
42 assertEquals(75, f.getDenominator());
43
44 f = Fraction.getFraction(-50, 75);
45 f = f.abs();
46 assertEquals(50, f.getNumerator());
47 assertEquals(75, f.getDenominator());
48
49 f = Fraction.getFraction(Integer.MAX_VALUE, 1);
50 f = f.abs();
51 assertEquals(Integer.MAX_VALUE, f.getNumerator());
52 assertEquals(1, f.getDenominator());
53
54 f = Fraction.getFraction(Integer.MAX_VALUE, -1);
55 f = f.abs();
56 assertEquals(Integer.MAX_VALUE, f.getNumerator());
57 assertEquals(1, f.getDenominator());
58
59 assertThrows(ArithmeticException.class, () -> Fraction.getFraction(Integer.MIN_VALUE, 1).abs());
60 }
61
62 @Test
63 public void testAdd() {
64 Fraction f;
65 Fraction f1;
66 Fraction f2;
67
68 f1 = Fraction.getFraction(3, 5);
69 f2 = Fraction.getFraction(1, 5);
70 f = f1.add(f2);
71 assertEquals(4, f.getNumerator());
72 assertEquals(5, f.getDenominator());
73
74 f1 = Fraction.getFraction(3, 5);
75 f2 = Fraction.getFraction(2, 5);
76 f = f1.add(f2);
77 assertEquals(1, f.getNumerator());
78 assertEquals(1, f.getDenominator());
79
80 f1 = Fraction.getFraction(3, 5);
81 f2 = Fraction.getFraction(3, 5);
82 f = f1.add(f2);
83 assertEquals(6, f.getNumerator());
84 assertEquals(5, f.getDenominator());
85
86 f1 = Fraction.getFraction(3, 5);
87 f2 = Fraction.getFraction(-4, 5);
88 f = f1.add(f2);
89 assertEquals(-1, f.getNumerator());
90 assertEquals(5, f.getDenominator());
91
92 f1 = Fraction.getFraction(Integer.MAX_VALUE - 1, 1);
93 f2 = Fraction.ONE;
94 f = f1.add(f2);
95 assertEquals(Integer.MAX_VALUE, f.getNumerator());
96 assertEquals(1, f.getDenominator());
97
98 f1 = Fraction.getFraction(3, 5);
99 f2 = Fraction.getFraction(1, 2);
100 f = f1.add(f2);
101 assertEquals(11, f.getNumerator());
102 assertEquals(10, f.getDenominator());
103
104 f1 = Fraction.getFraction(3, 8);
105 f2 = Fraction.getFraction(1, 6);
106 f = f1.add(f2);
107 assertEquals(13, f.getNumerator());
108 assertEquals(24, f.getDenominator());
109
110 f1 = Fraction.getFraction(0, 5);
111 f2 = Fraction.getFraction(1, 5);
112 f = f1.add(f2);
113 assertSame(f2, f);
114 f = f2.add(f1);
115 assertSame(f2, f);
116
117 f1 = Fraction.getFraction(-1, 13*13*2*2);
118 f2 = Fraction.getFraction(-2, 13*17*2);
119 final Fraction fr = f1.add(f2);
120 assertEquals(13*13*17*2*2, fr.getDenominator());
121 assertEquals(-17 - 2*13*2, fr.getNumerator());
122
123 assertThrows(NullPointerException.class, () -> fr.add(null));
124
125 // if this fraction is added naively, it will overflow.
126 // check that it doesn't.
127 f1 = Fraction.getFraction(1, 32768*3);
128 f2 = Fraction.getFraction(1, 59049);
129 f = f1.add(f2);
130 assertEquals(52451, f.getNumerator());
131 assertEquals(1934917632, f.getDenominator());
132
133 f1 = Fraction.getFraction(Integer.MIN_VALUE, 3);
134 f2 = Fraction.ONE_THIRD;
135 f = f1.add(f2);
136 assertEquals(Integer.MIN_VALUE+1, f.getNumerator());
137 assertEquals(3, f.getDenominator());
138
139 f1 = Fraction.getFraction(Integer.MAX_VALUE - 1, 1);
140 f2 = Fraction.ONE;
141 f = f1.add(f2);
142 assertEquals(Integer.MAX_VALUE, f.getNumerator());
143 assertEquals(1, f.getDenominator());
144
145 final Fraction overflower = f;
146 assertThrows(ArithmeticException.class, () -> overflower.add(Fraction.ONE)); // should overflow
147
148 // denominator should not be a multiple of 2 or 3 to trigger overflow
149 assertThrows(
150 ArithmeticException.class,
151 () -> Fraction.getFraction(Integer.MIN_VALUE, 5).add(Fraction.getFraction(-1, 5)));
152
153 final Fraction maxValue = Fraction.getFraction(-Integer.MAX_VALUE, 1);
154 assertThrows(ArithmeticException.class, () -> maxValue.add(maxValue));
155
156 final Fraction negativeMaxValue = Fraction.getFraction(-Integer.MAX_VALUE, 1);
157 assertThrows(ArithmeticException.class, () -> negativeMaxValue.add(negativeMaxValue));
158
159 final Fraction f3 = Fraction.getFraction(3, 327680);
160 final Fraction f4 = Fraction.getFraction(2, 59049);
161 assertThrows(ArithmeticException.class, () -> f3.add(f4)); // should overflow
162 }
163
164 @Test
165 public void testCompareTo() {
166 Fraction f1;
167 Fraction f2;
168
169 f1 = Fraction.getFraction(3, 5);
170 assertEquals(0, f1.compareTo(f1));
171
172 final Fraction fr = f1;
173 assertThrows(NullPointerException.class, () -> fr.compareTo(null));
174
175 f2 = Fraction.getFraction(2, 5);
176 assertTrue(f1.compareTo(f2) > 0);
177 assertEquals(0, f2.compareTo(f2));
178
179 f2 = Fraction.getFraction(4, 5);
180 assertTrue(f1.compareTo(f2) < 0);
181 assertEquals(0, f2.compareTo(f2));
182
183 f2 = Fraction.getFraction(3, 5);
184 assertEquals(0, f1.compareTo(f2));
185 assertEquals(0, f2.compareTo(f2));
186
187 f2 = Fraction.getFraction(6, 10);
188 assertEquals(0, f1.compareTo(f2));
189 assertEquals(0, f2.compareTo(f2));
190
191 f2 = Fraction.getFraction(-1, 1, Integer.MAX_VALUE);
192 assertTrue(f1.compareTo(f2) > 0);
193 assertEquals(0, f2.compareTo(f2));
194
195 }
196
35197 //--------------------------------------------------------------------------
36198 @Test
37199 public void testConstants() {
73235 }
74236
75237 @Test
76 public void testFactory_int_int() {
77 Fraction f = null;
78
79 // zero
80 f = Fraction.getFraction(0, 1);
81 assertEquals(0, f.getNumerator());
82 assertEquals(1, f.getDenominator());
83
84 f = Fraction.getFraction(0, 2);
85 assertEquals(0, f.getNumerator());
86 assertEquals(2, f.getDenominator());
87
88 // normal
89 f = Fraction.getFraction(1, 1);
90 assertEquals(1, f.getNumerator());
91 assertEquals(1, f.getDenominator());
92
93 f = Fraction.getFraction(2, 1);
238 public void testConversions() {
239 Fraction f;
240
241 f = Fraction.getFraction(3, 7, 8);
242 assertEquals(3, f.intValue());
243 assertEquals(3L, f.longValue());
244 assertEquals(3.875f, f.floatValue(), 0.00001f);
245 assertEquals(3.875d, f.doubleValue(), 0.00001d);
246 }
247
248 @Test
249 public void testDivide() {
250 Fraction f;
251 Fraction f1;
252 Fraction f2;
253
254 f1 = Fraction.getFraction(3, 5);
255 f2 = Fraction.getFraction(2, 5);
256 f = f1.divideBy(f2);
257 assertEquals(3, f.getNumerator());
258 assertEquals(2, f.getDenominator());
259
260 assertThrows(ArithmeticException.class, () -> Fraction.getFraction(3, 5).divideBy(Fraction.ZERO));
261
262 f1 = Fraction.getFraction(0, 5);
263 f2 = Fraction.getFraction(2, 7);
264 f = f1.divideBy(f2);
265 assertSame(Fraction.ZERO, f);
266
267 f1 = Fraction.getFraction(2, 7);
268 f2 = Fraction.ONE;
269 f = f1.divideBy(f2);
94270 assertEquals(2, f.getNumerator());
95 assertEquals(1, f.getDenominator());
96
97 f = Fraction.getFraction(23, 345);
98 assertEquals(23, f.getNumerator());
99 assertEquals(345, f.getDenominator());
100
101 // improper
102 f = Fraction.getFraction(22, 7);
103 assertEquals(22, f.getNumerator());
104271 assertEquals(7, f.getDenominator());
105272
106 // negatives
107 f = Fraction.getFraction(-6, 10);
108 assertEquals(-6, f.getNumerator());
109 assertEquals(10, f.getDenominator());
110
111 f = Fraction.getFraction(6, -10);
112 assertEquals(-6, f.getNumerator());
113 assertEquals(10, f.getDenominator());
114
115 f = Fraction.getFraction(-6, -10);
116 assertEquals(6, f.getNumerator());
117 assertEquals(10, f.getDenominator());
118
119 // zero denominator
120 assertThrows(ArithmeticException.class, () -> Fraction.getFraction(1, 0));
121 assertThrows(ArithmeticException.class, () -> Fraction.getFraction(2, 0));
122 assertThrows(ArithmeticException.class, () -> Fraction.getFraction(-3, 0));
123
124 // very large: can't represent as unsimplified fraction, although
125 assertThrows(ArithmeticException.class, () -> Fraction.getFraction(4, Integer.MIN_VALUE));
126 assertThrows(ArithmeticException.class, () -> Fraction.getFraction(1, Integer.MIN_VALUE));
127 }
128
129 @Test
130 public void testFactory_int_int_int() {
131 Fraction f = null;
132
133 // zero
134 f = Fraction.getFraction(0, 0, 2);
135 assertEquals(0, f.getNumerator());
136 assertEquals(2, f.getDenominator());
137
138 f = Fraction.getFraction(2, 0, 2);
139 assertEquals(4, f.getNumerator());
140 assertEquals(2, f.getDenominator());
141
142 f = Fraction.getFraction(0, 1, 2);
143 assertEquals(1, f.getNumerator());
144 assertEquals(2, f.getDenominator());
145
146 // normal
147 f = Fraction.getFraction(1, 1, 2);
148 assertEquals(3, f.getNumerator());
149 assertEquals(2, f.getDenominator());
150
151 // negatives
152 assertThrows(ArithmeticException.class, () -> Fraction.getFraction(1, -6, -10));
153 assertThrows(ArithmeticException.class, () -> Fraction.getFraction(1, -6, -10));
154 assertThrows(ArithmeticException.class, () -> Fraction.getFraction(1, -6, -10));
155
156 // negative whole
157 f = Fraction.getFraction(-1, 6, 10);
158 assertEquals(-16, f.getNumerator());
159 assertEquals(10, f.getDenominator());
160
161 assertThrows(ArithmeticException.class, () -> Fraction.getFraction(-1, -6, 10));
162 assertThrows(ArithmeticException.class, () -> Fraction.getFraction(-1, 6, -10));
163 assertThrows(ArithmeticException.class, () -> Fraction.getFraction(-1, -6, -10));
164
165 // zero denominator
166 assertThrows(ArithmeticException.class, () -> Fraction.getFraction(0, 1, 0));
167 assertThrows(ArithmeticException.class, () -> Fraction.getFraction(1, 2, 0));
168 assertThrows(ArithmeticException.class, () -> Fraction.getFraction(-1, -3, 0));
169 assertThrows(ArithmeticException.class, () -> Fraction.getFraction(Integer.MAX_VALUE, 1, 2));
170 assertThrows(ArithmeticException.class, () -> Fraction.getFraction(-Integer.MAX_VALUE, 1, 2));
171
172 // very large
173 f = Fraction.getFraction(-1, 0, Integer.MAX_VALUE);
174 assertEquals(-Integer.MAX_VALUE, f.getNumerator());
175 assertEquals(Integer.MAX_VALUE, f.getDenominator());
176
177 // negative denominators not allowed in this constructor.
178 assertThrows(ArithmeticException.class, () -> Fraction.getFraction(0, 4, Integer.MIN_VALUE));
179 assertThrows(ArithmeticException.class, () -> Fraction.getFraction(1, 1, Integer.MAX_VALUE));
180 assertThrows(ArithmeticException.class, () -> Fraction.getFraction(-1, 2, Integer.MAX_VALUE));
181 }
182
183 @Test
184 public void testReducedFactory_int_int() {
185 Fraction f = null;
186
187 // zero
188 f = Fraction.getReducedFraction(0, 1);
189 assertEquals(0, f.getNumerator());
190 assertEquals(1, f.getDenominator());
191
192 // normal
193 f = Fraction.getReducedFraction(1, 1);
194 assertEquals(1, f.getNumerator());
195 assertEquals(1, f.getDenominator());
196
197 f = Fraction.getReducedFraction(2, 1);
198 assertEquals(2, f.getNumerator());
199 assertEquals(1, f.getDenominator());
200
201 // improper
202 f = Fraction.getReducedFraction(22, 7);
203 assertEquals(22, f.getNumerator());
204 assertEquals(7, f.getDenominator());
205
206 // negatives
207 f = Fraction.getReducedFraction(-6, 10);
208 assertEquals(-3, f.getNumerator());
209 assertEquals(5, f.getDenominator());
210
211 f = Fraction.getReducedFraction(6, -10);
212 assertEquals(-3, f.getNumerator());
213 assertEquals(5, f.getDenominator());
214
215 f = Fraction.getReducedFraction(-6, -10);
216 assertEquals(3, f.getNumerator());
217 assertEquals(5, f.getDenominator());
218
219 // zero denominator
220 assertThrows(ArithmeticException.class, () -> Fraction.getReducedFraction(1, 0));
221 assertThrows(ArithmeticException.class, () -> Fraction.getReducedFraction(2, 0));
222 assertThrows(ArithmeticException.class, () -> Fraction.getReducedFraction(-3, 0));
223
224 // reduced
225 f = Fraction.getReducedFraction(0, 2);
226 assertEquals(0, f.getNumerator());
227 assertEquals(1, f.getDenominator());
228
229 f = Fraction.getReducedFraction(2, 2);
230 assertEquals(1, f.getNumerator());
231 assertEquals(1, f.getDenominator());
232
233 f = Fraction.getReducedFraction(2, 4);
234 assertEquals(1, f.getNumerator());
235 assertEquals(2, f.getDenominator());
236
237 f = Fraction.getReducedFraction(15, 10);
238 assertEquals(3, f.getNumerator());
239 assertEquals(2, f.getDenominator());
240
241 f = Fraction.getReducedFraction(121, 22);
242 assertEquals(11, f.getNumerator());
243 assertEquals(2, f.getDenominator());
244
245 // Extreme values
246 // OK, can reduce before negating
247 f = Fraction.getReducedFraction(-2, Integer.MIN_VALUE);
248 assertEquals(1, f.getNumerator());
249 assertEquals(-(Integer.MIN_VALUE / 2), f.getDenominator());
250
251 // Can't reduce, negation will throw
252 assertThrows(ArithmeticException.class, () -> Fraction.getReducedFraction(-7, Integer.MIN_VALUE));
253
254 // LANG-662
255 f = Fraction.getReducedFraction(Integer.MIN_VALUE, 2);
256 assertEquals(Integer.MIN_VALUE / 2, f.getNumerator());
257 assertEquals(1, f.getDenominator());
273 f1 = Fraction.getFraction(1, Integer.MAX_VALUE);
274 f = f1.divideBy(f1);
275 assertEquals(1, f.getNumerator());
276 assertEquals(1, f.getDenominator());
277
278 f1 = Fraction.getFraction(Integer.MIN_VALUE, Integer.MAX_VALUE);
279 f2 = Fraction.getFraction(1, Integer.MAX_VALUE);
280 final Fraction fr = f1.divideBy(f2);
281 assertEquals(Integer.MIN_VALUE, fr.getNumerator());
282 assertEquals(1, fr.getDenominator());
283
284 assertThrows(NullPointerException.class, () -> fr.divideBy(null));
285
286 final Fraction smallest = Fraction.getFraction(1, Integer.MAX_VALUE);
287 assertThrows(ArithmeticException.class, () -> smallest.divideBy(smallest.invert())); // Should overflow
288
289 final Fraction negative = Fraction.getFraction(1, -Integer.MAX_VALUE);
290 assertThrows(ArithmeticException.class, () -> negative.divideBy(negative.invert())); // Should overflow
291 }
292
293
294 @Test
295 public void testEquals() {
296 Fraction f1;
297 Fraction f2;
298
299 f1 = Fraction.getFraction(3, 5);
300 assertNotEquals(null, f1);
301 assertNotEquals(f1, new Object());
302 assertNotEquals(f1, Integer.valueOf(6));
303
304 f1 = Fraction.getFraction(3, 5);
305 f2 = Fraction.getFraction(2, 5);
306 assertNotEquals(f1, f2);
307 assertEquals(f1, f1);
308 assertEquals(f2, f2);
309
310 f2 = Fraction.getFraction(3, 5);
311 assertEquals(f1, f2);
312
313 f2 = Fraction.getFraction(6, 10);
314 assertNotEquals(f1, f2);
258315 }
259316
260317 @Test
322379 }
323380
324381 @Test
382 public void testFactory_int_int() {
383 Fraction f;
384
385 // zero
386 f = Fraction.getFraction(0, 1);
387 assertEquals(0, f.getNumerator());
388 assertEquals(1, f.getDenominator());
389
390 f = Fraction.getFraction(0, 2);
391 assertEquals(0, f.getNumerator());
392 assertEquals(2, f.getDenominator());
393
394 // normal
395 f = Fraction.getFraction(1, 1);
396 assertEquals(1, f.getNumerator());
397 assertEquals(1, f.getDenominator());
398
399 f = Fraction.getFraction(2, 1);
400 assertEquals(2, f.getNumerator());
401 assertEquals(1, f.getDenominator());
402
403 f = Fraction.getFraction(23, 345);
404 assertEquals(23, f.getNumerator());
405 assertEquals(345, f.getDenominator());
406
407 // improper
408 f = Fraction.getFraction(22, 7);
409 assertEquals(22, f.getNumerator());
410 assertEquals(7, f.getDenominator());
411
412 // negatives
413 f = Fraction.getFraction(-6, 10);
414 assertEquals(-6, f.getNumerator());
415 assertEquals(10, f.getDenominator());
416
417 f = Fraction.getFraction(6, -10);
418 assertEquals(-6, f.getNumerator());
419 assertEquals(10, f.getDenominator());
420
421 f = Fraction.getFraction(-6, -10);
422 assertEquals(6, f.getNumerator());
423 assertEquals(10, f.getDenominator());
424
425 // zero denominator
426 assertThrows(ArithmeticException.class, () -> Fraction.getFraction(1, 0));
427 assertThrows(ArithmeticException.class, () -> Fraction.getFraction(2, 0));
428 assertThrows(ArithmeticException.class, () -> Fraction.getFraction(-3, 0));
429
430 // very large: can't represent as unsimplified fraction, although
431 assertThrows(ArithmeticException.class, () -> Fraction.getFraction(4, Integer.MIN_VALUE));
432 assertThrows(ArithmeticException.class, () -> Fraction.getFraction(1, Integer.MIN_VALUE));
433 }
434
435 @Test
436 public void testFactory_int_int_int() {
437 Fraction f;
438
439 // zero
440 f = Fraction.getFraction(0, 0, 2);
441 assertEquals(0, f.getNumerator());
442 assertEquals(2, f.getDenominator());
443
444 f = Fraction.getFraction(2, 0, 2);
445 assertEquals(4, f.getNumerator());
446 assertEquals(2, f.getDenominator());
447
448 f = Fraction.getFraction(0, 1, 2);
449 assertEquals(1, f.getNumerator());
450 assertEquals(2, f.getDenominator());
451
452 // normal
453 f = Fraction.getFraction(1, 1, 2);
454 assertEquals(3, f.getNumerator());
455 assertEquals(2, f.getDenominator());
456
457 // negatives
458 assertThrows(ArithmeticException.class, () -> Fraction.getFraction(1, -6, -10));
459 assertThrows(ArithmeticException.class, () -> Fraction.getFraction(1, -6, -10));
460 assertThrows(ArithmeticException.class, () -> Fraction.getFraction(1, -6, -10));
461
462 // negative whole
463 f = Fraction.getFraction(-1, 6, 10);
464 assertEquals(-16, f.getNumerator());
465 assertEquals(10, f.getDenominator());
466
467 assertThrows(ArithmeticException.class, () -> Fraction.getFraction(-1, -6, 10));
468 assertThrows(ArithmeticException.class, () -> Fraction.getFraction(-1, 6, -10));
469 assertThrows(ArithmeticException.class, () -> Fraction.getFraction(-1, -6, -10));
470
471 // zero denominator
472 assertThrows(ArithmeticException.class, () -> Fraction.getFraction(0, 1, 0));
473 assertThrows(ArithmeticException.class, () -> Fraction.getFraction(1, 2, 0));
474 assertThrows(ArithmeticException.class, () -> Fraction.getFraction(-1, -3, 0));
475 assertThrows(ArithmeticException.class, () -> Fraction.getFraction(Integer.MAX_VALUE, 1, 2));
476 assertThrows(ArithmeticException.class, () -> Fraction.getFraction(-Integer.MAX_VALUE, 1, 2));
477
478 // very large
479 f = Fraction.getFraction(-1, 0, Integer.MAX_VALUE);
480 assertEquals(-Integer.MAX_VALUE, f.getNumerator());
481 assertEquals(Integer.MAX_VALUE, f.getDenominator());
482
483 // negative denominators not allowed in this constructor.
484 assertThrows(ArithmeticException.class, () -> Fraction.getFraction(0, 4, Integer.MIN_VALUE));
485 assertThrows(ArithmeticException.class, () -> Fraction.getFraction(1, 1, Integer.MAX_VALUE));
486 assertThrows(ArithmeticException.class, () -> Fraction.getFraction(-1, 2, Integer.MAX_VALUE));
487 }
488
489 @Test
325490 public void testFactory_String() {
326491 assertThrows(NullPointerException.class, () -> Fraction.getFraction(null));
327492 }
328493
329
330494 @Test
331495 public void testFactory_String_double() {
332 Fraction f = null;
496 Fraction f;
333497
334498 f = Fraction.getFraction("0.0");
335499 assertEquals(0, f.getNumerator());
353517 }
354518
355519 @Test
520 public void testFactory_String_improper() {
521 Fraction f;
522
523 f = Fraction.getFraction("0/1");
524 assertEquals(0, f.getNumerator());
525 assertEquals(1, f.getDenominator());
526
527 f = Fraction.getFraction("1/5");
528 assertEquals(1, f.getNumerator());
529 assertEquals(5, f.getDenominator());
530
531 f = Fraction.getFraction("1/2");
532 assertEquals(1, f.getNumerator());
533 assertEquals(2, f.getDenominator());
534
535 f = Fraction.getFraction("2/3");
536 assertEquals(2, f.getNumerator());
537 assertEquals(3, f.getDenominator());
538
539 f = Fraction.getFraction("7/3");
540 assertEquals(7, f.getNumerator());
541 assertEquals(3, f.getDenominator());
542
543 f = Fraction.getFraction("2/4");
544 assertEquals(2, f.getNumerator());
545 assertEquals(4, f.getDenominator());
546
547 assertThrows(NumberFormatException.class, () -> Fraction.getFraction("2/d"));
548 assertThrows(NumberFormatException.class, () -> Fraction.getFraction("2e/3"));
549 assertThrows(NumberFormatException.class, () -> Fraction.getFraction("2/"));
550 assertThrows(NumberFormatException.class, () -> Fraction.getFraction("/"));
551 }
552
553 @Test
356554 public void testFactory_String_proper() {
357 Fraction f = null;
555 Fraction f;
358556
359557 f = Fraction.getFraction("0 0/1");
360558 assertEquals(0, f.getNumerator());
389587 }
390588
391589 @Test
392 public void testFactory_String_improper() {
393 Fraction f = null;
394
395 f = Fraction.getFraction("0/1");
396 assertEquals(0, f.getNumerator());
397 assertEquals(1, f.getDenominator());
398
399 f = Fraction.getFraction("1/5");
400 assertEquals(1, f.getNumerator());
401 assertEquals(5, f.getDenominator());
402
403 f = Fraction.getFraction("1/2");
404 assertEquals(1, f.getNumerator());
405 assertEquals(2, f.getDenominator());
406
407 f = Fraction.getFraction("2/3");
408 assertEquals(2, f.getNumerator());
409 assertEquals(3, f.getDenominator());
410
411 f = Fraction.getFraction("7/3");
412 assertEquals(7, f.getNumerator());
413 assertEquals(3, f.getDenominator());
414
415 f = Fraction.getFraction("2/4");
416 assertEquals(2, f.getNumerator());
417 assertEquals(4, f.getDenominator());
418
419 assertThrows(NumberFormatException.class, () -> Fraction.getFraction("2/d"));
420 assertThrows(NumberFormatException.class, () -> Fraction.getFraction("2e/3"));
421 assertThrows(NumberFormatException.class, () -> Fraction.getFraction("2/"));
422 assertThrows(NumberFormatException.class, () -> Fraction.getFraction("/"));
423 }
424
425 @Test
426590 public void testGets() {
427 Fraction f = null;
591 Fraction f;
428592
429593 f = Fraction.getFraction(3, 5, 6);
430594 assertEquals(23, f.getNumerator());
446610 }
447611
448612 @Test
449 public void testConversions() {
450 Fraction f = null;
451
452 f = Fraction.getFraction(3, 7, 8);
453 assertEquals(3, f.intValue());
454 assertEquals(3L, f.longValue());
455 assertEquals(3.875f, f.floatValue(), 0.00001f);
456 assertEquals(3.875d, f.doubleValue(), 0.00001d);
457 }
458
459 @Test
460 public void testReduce() {
461 Fraction f = null;
462
463 f = Fraction.getFraction(50, 75);
464 Fraction result = f.reduce();
465 assertEquals(2, result.getNumerator());
466 assertEquals(3, result.getDenominator());
467
468 f = Fraction.getFraction(-2, -3);
469 result = f.reduce();
470 assertEquals(2, result.getNumerator());
471 assertEquals(3, result.getDenominator());
472
473 f = Fraction.getFraction(2, -3);
474 result = f.reduce();
475 assertEquals(-2, result.getNumerator());
476 assertEquals(3, result.getDenominator());
477
478 f = Fraction.getFraction(-2, 3);
479 result = f.reduce();
480 assertEquals(-2, result.getNumerator());
481 assertEquals(3, result.getDenominator());
482 assertSame(f, result);
483
484 f = Fraction.getFraction(2, 3);
485 result = f.reduce();
486 assertEquals(2, result.getNumerator());
487 assertEquals(3, result.getDenominator());
488 assertSame(f, result);
489
490 f = Fraction.getFraction(0, 1);
491 result = f.reduce();
492 assertEquals(0, result.getNumerator());
493 assertEquals(1, result.getDenominator());
494 assertSame(f, result);
495
496 f = Fraction.getFraction(0, 100);
497 result = f.reduce();
498 assertEquals(0, result.getNumerator());
499 assertEquals(1, result.getDenominator());
500 assertSame(result, Fraction.ZERO);
501
502 f = Fraction.getFraction(Integer.MIN_VALUE, 2);
503 result = f.reduce();
504 assertEquals(Integer.MIN_VALUE / 2, result.getNumerator());
505 assertEquals(1, result.getDenominator());
613 public void testHashCode() {
614 final Fraction f1 = Fraction.getFraction(3, 5);
615 Fraction f2 = Fraction.getFraction(3, 5);
616
617 assertEquals(f1.hashCode(), f2.hashCode());
618
619 f2 = Fraction.getFraction(2, 5);
620 assertTrue(f1.hashCode() != f2.hashCode());
621
622 f2 = Fraction.getFraction(6, 10);
623 assertTrue(f1.hashCode() != f2.hashCode());
506624 }
507625
508626 @Test
509627 public void testInvert() {
510 Fraction f = null;
628 Fraction f;
511629
512630 f = Fraction.getFraction(50, 75);
513631 f = f.invert();
534652 }
535653
536654 @Test
655 public void testMultiply() {
656 Fraction f;
657 Fraction f1;
658 Fraction f2;
659
660 f1 = Fraction.getFraction(3, 5);
661 f2 = Fraction.getFraction(2, 5);
662 f = f1.multiplyBy(f2);
663 assertEquals(6, f.getNumerator());
664 assertEquals(25, f.getDenominator());
665
666 f1 = Fraction.getFraction(6, 10);
667 f2 = Fraction.getFraction(6, 10);
668 f = f1.multiplyBy(f2);
669 assertEquals(9, f.getNumerator());
670 assertEquals(25, f.getDenominator());
671 f = f.multiplyBy(f2);
672 assertEquals(27, f.getNumerator());
673 assertEquals(125, f.getDenominator());
674
675 f1 = Fraction.getFraction(3, 5);
676 f2 = Fraction.getFraction(-2, 5);
677 f = f1.multiplyBy(f2);
678 assertEquals(-6, f.getNumerator());
679 assertEquals(25, f.getDenominator());
680
681 f1 = Fraction.getFraction(-3, 5);
682 f2 = Fraction.getFraction(-2, 5);
683 f = f1.multiplyBy(f2);
684 assertEquals(6, f.getNumerator());
685 assertEquals(25, f.getDenominator());
686
687
688 f1 = Fraction.getFraction(0, 5);
689 f2 = Fraction.getFraction(2, 7);
690 f = f1.multiplyBy(f2);
691 assertSame(Fraction.ZERO, f);
692
693 f1 = Fraction.getFraction(2, 7);
694 f2 = Fraction.ONE;
695 f = f1.multiplyBy(f2);
696 assertEquals(2, f.getNumerator());
697 assertEquals(7, f.getDenominator());
698
699 f1 = Fraction.getFraction(Integer.MAX_VALUE, 1);
700 f2 = Fraction.getFraction(Integer.MIN_VALUE, Integer.MAX_VALUE);
701 f = f1.multiplyBy(f2);
702 assertEquals(Integer.MIN_VALUE, f.getNumerator());
703 assertEquals(1, f.getDenominator());
704
705 final Fraction fr = f;
706 assertThrows(NullPointerException.class, () -> fr.multiplyBy(null));
707
708 final Fraction fr1 = Fraction.getFraction(1, Integer.MAX_VALUE);
709 assertThrows(ArithmeticException.class, () -> fr1.multiplyBy(fr1));
710
711 final Fraction fr2 = Fraction.getFraction(1, -Integer.MAX_VALUE);
712 assertThrows(ArithmeticException.class, () -> fr2.multiplyBy(fr2));
713 }
714
715 @Test
537716 public void testNegate() {
538 Fraction f = null;
717 Fraction f;
539718
540719 f = Fraction.getFraction(50, 75);
541720 f = f.negate();
557736 }
558737
559738 @Test
560 public void testAbs() {
561 Fraction f = null;
562
563 f = Fraction.getFraction(50, 75);
564 f = f.abs();
565 assertEquals(50, f.getNumerator());
566 assertEquals(75, f.getDenominator());
567
568 f = Fraction.getFraction(-50, 75);
569 f = f.abs();
570 assertEquals(50, f.getNumerator());
571 assertEquals(75, f.getDenominator());
572
573 f = Fraction.getFraction(Integer.MAX_VALUE, 1);
574 f = f.abs();
575 assertEquals(Integer.MAX_VALUE, f.getNumerator());
576 assertEquals(1, f.getDenominator());
577
578 f = Fraction.getFraction(Integer.MAX_VALUE, -1);
579 f = f.abs();
580 assertEquals(Integer.MAX_VALUE, f.getNumerator());
581 assertEquals(1, f.getDenominator());
582
583 assertThrows(ArithmeticException.class, () -> Fraction.getFraction(Integer.MIN_VALUE, 1).abs());
584 }
585
586 @Test
587739 public void testPow() {
588 Fraction f = null;
740 Fraction f;
589741
590742 f = Fraction.getFraction(3, 5);
591743 assertEquals(Fraction.ONE, f.pow(0));
680832 }
681833
682834 @Test
683 public void testAdd() {
684 Fraction f = null;
685 Fraction f1 = null;
686 Fraction f2 = null;
687
688 f1 = Fraction.getFraction(3, 5);
689 f2 = Fraction.getFraction(1, 5);
690 f = f1.add(f2);
691 assertEquals(4, f.getNumerator());
692 assertEquals(5, f.getDenominator());
693
694 f1 = Fraction.getFraction(3, 5);
695 f2 = Fraction.getFraction(2, 5);
696 f = f1.add(f2);
697 assertEquals(1, f.getNumerator());
698 assertEquals(1, f.getDenominator());
699
700 f1 = Fraction.getFraction(3, 5);
701 f2 = Fraction.getFraction(3, 5);
702 f = f1.add(f2);
703 assertEquals(6, f.getNumerator());
704 assertEquals(5, f.getDenominator());
705
706 f1 = Fraction.getFraction(3, 5);
707 f2 = Fraction.getFraction(-4, 5);
708 f = f1.add(f2);
709 assertEquals(-1, f.getNumerator());
710 assertEquals(5, f.getDenominator());
711
712 f1 = Fraction.getFraction(Integer.MAX_VALUE - 1, 1);
713 f2 = Fraction.ONE;
714 f = f1.add(f2);
715 assertEquals(Integer.MAX_VALUE, f.getNumerator());
716 assertEquals(1, f.getDenominator());
717
718 f1 = Fraction.getFraction(3, 5);
719 f2 = Fraction.getFraction(1, 2);
720 f = f1.add(f2);
835 public void testReduce() {
836 Fraction f;
837
838 f = Fraction.getFraction(50, 75);
839 Fraction result = f.reduce();
840 assertEquals(2, result.getNumerator());
841 assertEquals(3, result.getDenominator());
842
843 f = Fraction.getFraction(-2, -3);
844 result = f.reduce();
845 assertEquals(2, result.getNumerator());
846 assertEquals(3, result.getDenominator());
847
848 f = Fraction.getFraction(2, -3);
849 result = f.reduce();
850 assertEquals(-2, result.getNumerator());
851 assertEquals(3, result.getDenominator());
852
853 f = Fraction.getFraction(-2, 3);
854 result = f.reduce();
855 assertEquals(-2, result.getNumerator());
856 assertEquals(3, result.getDenominator());
857 assertSame(f, result);
858
859 f = Fraction.getFraction(2, 3);
860 result = f.reduce();
861 assertEquals(2, result.getNumerator());
862 assertEquals(3, result.getDenominator());
863 assertSame(f, result);
864
865 f = Fraction.getFraction(0, 1);
866 result = f.reduce();
867 assertEquals(0, result.getNumerator());
868 assertEquals(1, result.getDenominator());
869 assertSame(f, result);
870
871 f = Fraction.getFraction(0, 100);
872 result = f.reduce();
873 assertEquals(0, result.getNumerator());
874 assertEquals(1, result.getDenominator());
875 assertSame(result, Fraction.ZERO);
876
877 f = Fraction.getFraction(Integer.MIN_VALUE, 2);
878 result = f.reduce();
879 assertEquals(Integer.MIN_VALUE / 2, result.getNumerator());
880 assertEquals(1, result.getDenominator());
881 }
882
883 @Test
884 public void testReducedFactory_int_int() {
885 Fraction f;
886
887 // zero
888 f = Fraction.getReducedFraction(0, 1);
889 assertEquals(0, f.getNumerator());
890 assertEquals(1, f.getDenominator());
891
892 // normal
893 f = Fraction.getReducedFraction(1, 1);
894 assertEquals(1, f.getNumerator());
895 assertEquals(1, f.getDenominator());
896
897 f = Fraction.getReducedFraction(2, 1);
898 assertEquals(2, f.getNumerator());
899 assertEquals(1, f.getDenominator());
900
901 // improper
902 f = Fraction.getReducedFraction(22, 7);
903 assertEquals(22, f.getNumerator());
904 assertEquals(7, f.getDenominator());
905
906 // negatives
907 f = Fraction.getReducedFraction(-6, 10);
908 assertEquals(-3, f.getNumerator());
909 assertEquals(5, f.getDenominator());
910
911 f = Fraction.getReducedFraction(6, -10);
912 assertEquals(-3, f.getNumerator());
913 assertEquals(5, f.getDenominator());
914
915 f = Fraction.getReducedFraction(-6, -10);
916 assertEquals(3, f.getNumerator());
917 assertEquals(5, f.getDenominator());
918
919 // zero denominator
920 assertThrows(ArithmeticException.class, () -> Fraction.getReducedFraction(1, 0));
921 assertThrows(ArithmeticException.class, () -> Fraction.getReducedFraction(2, 0));
922 assertThrows(ArithmeticException.class, () -> Fraction.getReducedFraction(-3, 0));
923
924 // reduced
925 f = Fraction.getReducedFraction(0, 2);
926 assertEquals(0, f.getNumerator());
927 assertEquals(1, f.getDenominator());
928
929 f = Fraction.getReducedFraction(2, 2);
930 assertEquals(1, f.getNumerator());
931 assertEquals(1, f.getDenominator());
932
933 f = Fraction.getReducedFraction(2, 4);
934 assertEquals(1, f.getNumerator());
935 assertEquals(2, f.getDenominator());
936
937 f = Fraction.getReducedFraction(15, 10);
938 assertEquals(3, f.getNumerator());
939 assertEquals(2, f.getDenominator());
940
941 f = Fraction.getReducedFraction(121, 22);
721942 assertEquals(11, f.getNumerator());
722 assertEquals(10, f.getDenominator());
723
724 f1 = Fraction.getFraction(3, 8);
725 f2 = Fraction.getFraction(1, 6);
726 f = f1.add(f2);
727 assertEquals(13, f.getNumerator());
728 assertEquals(24, f.getDenominator());
729
730 f1 = Fraction.getFraction(0, 5);
731 f2 = Fraction.getFraction(1, 5);
732 f = f1.add(f2);
733 assertSame(f2, f);
734 f = f2.add(f1);
735 assertSame(f2, f);
736
737 f1 = Fraction.getFraction(-1, 13*13*2*2);
738 f2 = Fraction.getFraction(-2, 13*17*2);
739 final Fraction fr = f1.add(f2);
740 assertEquals(13*13*17*2*2, fr.getDenominator());
741 assertEquals(-17 - 2*13*2, fr.getNumerator());
742
743 assertThrows(NullPointerException.class, () -> fr.add(null));
744
745 // if this fraction is added naively, it will overflow.
746 // check that it doesn't.
747 f1 = Fraction.getFraction(1, 32768*3);
748 f2 = Fraction.getFraction(1, 59049);
749 f = f1.add(f2);
750 assertEquals(52451, f.getNumerator());
751 assertEquals(1934917632, f.getDenominator());
752
753 f1 = Fraction.getFraction(Integer.MIN_VALUE, 3);
754 f2 = Fraction.ONE_THIRD;
755 f = f1.add(f2);
756 assertEquals(Integer.MIN_VALUE+1, f.getNumerator());
757 assertEquals(3, f.getDenominator());
758
759 f1 = Fraction.getFraction(Integer.MAX_VALUE - 1, 1);
760 f2 = Fraction.ONE;
761 f = f1.add(f2);
762 assertEquals(Integer.MAX_VALUE, f.getNumerator());
763 assertEquals(1, f.getDenominator());
764
765 final Fraction overflower = f;
766 assertThrows(ArithmeticException.class, () -> overflower.add(Fraction.ONE)); // should overflow
767
768 // denominator should not be a multiple of 2 or 3 to trigger overflow
769 assertThrows(
770 ArithmeticException.class,
771 () -> Fraction.getFraction(Integer.MIN_VALUE, 5).add(Fraction.getFraction(-1, 5)));
772
773 final Fraction maxValue = Fraction.getFraction(-Integer.MAX_VALUE, 1);
774 assertThrows(ArithmeticException.class, () -> maxValue.add(maxValue));
775
776 final Fraction negativeMaxValue = Fraction.getFraction(-Integer.MAX_VALUE, 1);
777 assertThrows(ArithmeticException.class, () -> negativeMaxValue.add(negativeMaxValue));
778
779 final Fraction f3 = Fraction.getFraction(3, 327680);
780 final Fraction f4 = Fraction.getFraction(2, 59049);
781 assertThrows(ArithmeticException.class, () -> f3.add(f4)); // should overflow
943 assertEquals(2, f.getDenominator());
944
945 // Extreme values
946 // OK, can reduce before negating
947 f = Fraction.getReducedFraction(-2, Integer.MIN_VALUE);
948 assertEquals(1, f.getNumerator());
949 assertEquals(-(Integer.MIN_VALUE / 2), f.getDenominator());
950
951 // Can't reduce, negation will throw
952 assertThrows(ArithmeticException.class, () -> Fraction.getReducedFraction(-7, Integer.MIN_VALUE));
953
954 // LANG-662
955 f = Fraction.getReducedFraction(Integer.MIN_VALUE, 2);
956 assertEquals(Integer.MIN_VALUE / 2, f.getNumerator());
957 assertEquals(1, f.getDenominator());
782958 }
783959
784960 @Test
785961 public void testSubtract() {
786 Fraction f = null;
787 Fraction f1 = null;
788 Fraction f2 = null;
962 Fraction f;
963 Fraction f1;
964 Fraction f2;
789965
790966 f1 = Fraction.getFraction(3, 5);
791967 f2 = Fraction.getFraction(1, 5);
8821058 }
8831059
8841060 @Test
885 public void testMultiply() {
886 Fraction f = null;
887 Fraction f1 = null;
888 Fraction f2 = null;
889
890 f1 = Fraction.getFraction(3, 5);
891 f2 = Fraction.getFraction(2, 5);
892 f = f1.multiplyBy(f2);
893 assertEquals(6, f.getNumerator());
894 assertEquals(25, f.getDenominator());
895
896 f1 = Fraction.getFraction(6, 10);
897 f2 = Fraction.getFraction(6, 10);
898 f = f1.multiplyBy(f2);
899 assertEquals(9, f.getNumerator());
900 assertEquals(25, f.getDenominator());
901 f = f.multiplyBy(f2);
902 assertEquals(27, f.getNumerator());
903 assertEquals(125, f.getDenominator());
904
905 f1 = Fraction.getFraction(3, 5);
906 f2 = Fraction.getFraction(-2, 5);
907 f = f1.multiplyBy(f2);
908 assertEquals(-6, f.getNumerator());
909 assertEquals(25, f.getDenominator());
910
911 f1 = Fraction.getFraction(-3, 5);
912 f2 = Fraction.getFraction(-2, 5);
913 f = f1.multiplyBy(f2);
914 assertEquals(6, f.getNumerator());
915 assertEquals(25, f.getDenominator());
916
917
918 f1 = Fraction.getFraction(0, 5);
919 f2 = Fraction.getFraction(2, 7);
920 f = f1.multiplyBy(f2);
921 assertSame(Fraction.ZERO, f);
922
923 f1 = Fraction.getFraction(2, 7);
924 f2 = Fraction.ONE;
925 f = f1.multiplyBy(f2);
926 assertEquals(2, f.getNumerator());
927 assertEquals(7, f.getDenominator());
928
929 f1 = Fraction.getFraction(Integer.MAX_VALUE, 1);
930 f2 = Fraction.getFraction(Integer.MIN_VALUE, Integer.MAX_VALUE);
931 f = f1.multiplyBy(f2);
932 assertEquals(Integer.MIN_VALUE, f.getNumerator());
933 assertEquals(1, f.getDenominator());
934
935 final Fraction fr = f;
936 assertThrows(NullPointerException.class, () -> fr.multiplyBy(null));
937
938 final Fraction fr1 = Fraction.getFraction(1, Integer.MAX_VALUE);
939 assertThrows(ArithmeticException.class, () -> fr1.multiplyBy(fr1));
940
941 final Fraction fr2 = Fraction.getFraction(1, -Integer.MAX_VALUE);
942 assertThrows(ArithmeticException.class, () -> fr2.multiplyBy(fr2));
943 }
944
945 @Test
946 public void testDivide() {
947 Fraction f = null;
948 Fraction f1 = null;
949 Fraction f2 = null;
950
951 f1 = Fraction.getFraction(3, 5);
952 f2 = Fraction.getFraction(2, 5);
953 f = f1.divideBy(f2);
954 assertEquals(3, f.getNumerator());
955 assertEquals(2, f.getDenominator());
956
957 assertThrows(ArithmeticException.class, () -> Fraction.getFraction(3, 5).divideBy(Fraction.ZERO));
958
959 f1 = Fraction.getFraction(0, 5);
960 f2 = Fraction.getFraction(2, 7);
961 f = f1.divideBy(f2);
962 assertSame(Fraction.ZERO, f);
963
964 f1 = Fraction.getFraction(2, 7);
965 f2 = Fraction.ONE;
966 f = f1.divideBy(f2);
967 assertEquals(2, f.getNumerator());
968 assertEquals(7, f.getDenominator());
969
970 f1 = Fraction.getFraction(1, Integer.MAX_VALUE);
971 f = f1.divideBy(f1);
972 assertEquals(1, f.getNumerator());
973 assertEquals(1, f.getDenominator());
974
975 f1 = Fraction.getFraction(Integer.MIN_VALUE, Integer.MAX_VALUE);
976 f2 = Fraction.getFraction(1, Integer.MAX_VALUE);
977 final Fraction fr = f1.divideBy(f2);
978 assertEquals(Integer.MIN_VALUE, fr.getNumerator());
979 assertEquals(1, fr.getDenominator());
980
981 assertThrows(NullPointerException.class, () -> fr.divideBy(null));
982
983 final Fraction smallest = Fraction.getFraction(1, Integer.MAX_VALUE);
984 assertThrows(ArithmeticException.class, () -> smallest.divideBy(smallest.invert())); // Should overflow
985
986 final Fraction negative = Fraction.getFraction(1, -Integer.MAX_VALUE);
987 assertThrows(ArithmeticException.class, () -> negative.divideBy(negative.invert())); // Should overflow
988 }
989
990 @Test
991 public void testEquals() {
992 Fraction f1 = null;
993 Fraction f2 = null;
994
995 f1 = Fraction.getFraction(3, 5);
996 assertNotEquals(null, f1);
997 assertNotEquals(f1, new Object());
998 assertNotEquals(f1, Integer.valueOf(6));
999
1000 f1 = Fraction.getFraction(3, 5);
1001 f2 = Fraction.getFraction(2, 5);
1002 assertNotEquals(f1, f2);
1003 assertEquals(f1, f1);
1004 assertEquals(f2, f2);
1005
1006 f2 = Fraction.getFraction(3, 5);
1007 assertEquals(f1, f2);
1008
1009 f2 = Fraction.getFraction(6, 10);
1010 assertNotEquals(f1, f2);
1011 }
1012
1013 @Test
1014 public void testHashCode() {
1015 final Fraction f1 = Fraction.getFraction(3, 5);
1016 Fraction f2 = Fraction.getFraction(3, 5);
1017
1018 assertEquals(f1.hashCode(), f2.hashCode());
1019
1020 f2 = Fraction.getFraction(2, 5);
1021 assertTrue(f1.hashCode() != f2.hashCode());
1022
1023 f2 = Fraction.getFraction(6, 10);
1024 assertTrue(f1.hashCode() != f2.hashCode());
1025 }
1026
1027 @Test
1028 public void testCompareTo() {
1029 Fraction f1 = null;
1030 Fraction f2 = null;
1031
1032 f1 = Fraction.getFraction(3, 5);
1033 assertEquals(0, f1.compareTo(f1));
1034
1035 final Fraction fr = f1;
1036 assertThrows(NullPointerException.class, () -> fr.compareTo(null));
1037
1038 f2 = Fraction.getFraction(2, 5);
1039 assertTrue(f1.compareTo(f2) > 0);
1040 assertEquals(0, f2.compareTo(f2));
1041
1042 f2 = Fraction.getFraction(4, 5);
1043 assertTrue(f1.compareTo(f2) < 0);
1044 assertEquals(0, f2.compareTo(f2));
1045
1046 f2 = Fraction.getFraction(3, 5);
1047 assertEquals(0, f1.compareTo(f2));
1048 assertEquals(0, f2.compareTo(f2));
1049
1050 f2 = Fraction.getFraction(6, 10);
1051 assertEquals(0, f1.compareTo(f2));
1052 assertEquals(0, f2.compareTo(f2));
1053
1054 f2 = Fraction.getFraction(-1, 1, Integer.MAX_VALUE);
1055 assertTrue(f1.compareTo(f2) > 0);
1056 assertEquals(0, f2.compareTo(f2));
1057
1061 public void testToProperString() {
1062 Fraction f;
1063
1064 f = Fraction.getFraction(3, 5);
1065 final String str = f.toProperString();
1066 assertEquals("3/5", str);
1067 assertSame(str, f.toProperString());
1068
1069 f = Fraction.getFraction(7, 5);
1070 assertEquals("1 2/5", f.toProperString());
1071
1072 f = Fraction.getFraction(14, 10);
1073 assertEquals("1 4/10", f.toProperString());
1074
1075 f = Fraction.getFraction(4, 2);
1076 assertEquals("2", f.toProperString());
1077
1078 f = Fraction.getFraction(0, 2);
1079 assertEquals("0", f.toProperString());
1080
1081 f = Fraction.getFraction(2, 2);
1082 assertEquals("1", f.toProperString());
1083
1084 f = Fraction.getFraction(-7, 5);
1085 assertEquals("-1 2/5", f.toProperString());
1086
1087 f = Fraction.getFraction(Integer.MIN_VALUE, 0, 1);
1088 assertEquals("-2147483648", f.toProperString());
1089
1090 f = Fraction.getFraction(-1, 1, Integer.MAX_VALUE);
1091 assertEquals("-1 1/2147483647", f.toProperString());
1092
1093 assertEquals("-1", Fraction.getFraction(-1).toProperString());
10581094 }
10591095
10601096 @Test
10611097 public void testToString() {
1062 Fraction f = null;
1098 Fraction f;
10631099
10641100 f = Fraction.getFraction(3, 5);
10651101 final String str = f.toString();
10841120 f = Fraction.getFraction(-1, 1, Integer.MAX_VALUE);
10851121 assertEquals("-2147483648/2147483647", f.toString());
10861122 }
1087
1088 @Test
1089 public void testToProperString() {
1090 Fraction f = null;
1091
1092 f = Fraction.getFraction(3, 5);
1093 final String str = f.toProperString();
1094 assertEquals("3/5", str);
1095 assertSame(str, f.toProperString());
1096
1097 f = Fraction.getFraction(7, 5);
1098 assertEquals("1 2/5", f.toProperString());
1099
1100 f = Fraction.getFraction(14, 10);
1101 assertEquals("1 4/10", f.toProperString());
1102
1103 f = Fraction.getFraction(4, 2);
1104 assertEquals("2", f.toProperString());
1105
1106 f = Fraction.getFraction(0, 2);
1107 assertEquals("0", f.toProperString());
1108
1109 f = Fraction.getFraction(2, 2);
1110 assertEquals("1", f.toProperString());
1111
1112 f = Fraction.getFraction(-7, 5);
1113 assertEquals("-1 2/5", f.toProperString());
1114
1115 f = Fraction.getFraction(Integer.MIN_VALUE, 0, 1);
1116 assertEquals("-2147483648", f.toProperString());
1117
1118 f = Fraction.getFraction(-1, 1, Integer.MAX_VALUE);
1119 assertEquals("-1 1/2147483647", f.toProperString());
1120
1121 assertEquals("-1", Fraction.getFraction(-1).toProperString());
1122 }
11231123 }
2727 public class IEEE754rUtilsTest {
2828
2929 @Test
30 public void testLang381() {
31 assertEquals(1.2, IEEE754rUtils.min(1.2, 2.5, Double.NaN), 0.01);
32 assertEquals(2.5, IEEE754rUtils.max(1.2, 2.5, Double.NaN), 0.01);
33 assertTrue(Double.isNaN(IEEE754rUtils.max(Double.NaN, Double.NaN, Double.NaN)));
34 assertEquals(1.2f, IEEE754rUtils.min(1.2f, 2.5f, Float.NaN), 0.01);
35 assertEquals(2.5f, IEEE754rUtils.max(1.2f, 2.5f, Float.NaN), 0.01);
36 assertTrue(Float.isNaN(IEEE754rUtils.max(Float.NaN, Float.NaN, Float.NaN)));
37
38 final double[] a = new double[] { 1.2, Double.NaN, 3.7, 27.0, 42.0, Double.NaN };
39 assertEquals(42.0, IEEE754rUtils.max(a), 0.01);
40 assertEquals(1.2, IEEE754rUtils.min(a), 0.01);
41
42 final double[] b = new double[] { Double.NaN, 1.2, Double.NaN, 3.7, 27.0, 42.0, Double.NaN };
43 assertEquals(42.0, IEEE754rUtils.max(b), 0.01);
44 assertEquals(1.2, IEEE754rUtils.min(b), 0.01);
45
46 final float[] aF = new float[] { 1.2f, Float.NaN, 3.7f, 27.0f, 42.0f, Float.NaN };
47 assertEquals(1.2f, IEEE754rUtils.min(aF), 0.01);
48 assertEquals(42.0f, IEEE754rUtils.max(aF), 0.01);
49
50 final float[] bF = new float[] { Float.NaN, 1.2f, Float.NaN, 3.7f, 27.0f, 42.0f, Float.NaN };
51 assertEquals(1.2f, IEEE754rUtils.min(bF), 0.01);
52 assertEquals(42.0f, IEEE754rUtils.max(bF), 0.01);
30 public void testConstructorExists() {
31 new IEEE754rUtils();
5332 }
5433
5534 @Test
9675 }
9776
9877 @Test
99 public void testConstructorExists() {
100 new IEEE754rUtils();
78 public void testLang381() {
79 assertEquals(1.2, IEEE754rUtils.min(1.2, 2.5, Double.NaN), 0.01);
80 assertEquals(2.5, IEEE754rUtils.max(1.2, 2.5, Double.NaN), 0.01);
81 assertTrue(Double.isNaN(IEEE754rUtils.max(Double.NaN, Double.NaN, Double.NaN)));
82 assertEquals(1.2f, IEEE754rUtils.min(1.2f, 2.5f, Float.NaN), 0.01);
83 assertEquals(2.5f, IEEE754rUtils.max(1.2f, 2.5f, Float.NaN), 0.01);
84 assertTrue(Float.isNaN(IEEE754rUtils.max(Float.NaN, Float.NaN, Float.NaN)));
85
86 final double[] a = { 1.2, Double.NaN, 3.7, 27.0, 42.0, Double.NaN };
87 assertEquals(42.0, IEEE754rUtils.max(a), 0.01);
88 assertEquals(1.2, IEEE754rUtils.min(a), 0.01);
89
90 final double[] b = { Double.NaN, 1.2, Double.NaN, 3.7, 27.0, 42.0, Double.NaN };
91 assertEquals(42.0, IEEE754rUtils.max(b), 0.01);
92 assertEquals(1.2, IEEE754rUtils.min(b), 0.01);
93
94 final float[] aF = { 1.2f, Float.NaN, 3.7f, 27.0f, 42.0f, Float.NaN };
95 assertEquals(1.2f, IEEE754rUtils.min(aF), 0.01);
96 assertEquals(42.0f, IEEE754rUtils.max(aF), 0.01);
97
98 final float[] bF = { Float.NaN, 1.2f, Float.NaN, 3.7f, 27.0f, 42.0f, Float.NaN };
99 assertEquals(1.2f, IEEE754rUtils.min(bF), 0.01);
100 assertEquals(42.0f, IEEE754rUtils.max(bF), 0.01);
101101 }
102102
103103 }
3535 */
3636 public class NumberUtilsTest {
3737
38 //-----------------------------------------------------------------------
38 private boolean checkCreateNumber(final String val) {
39 try {
40 final Object obj = NumberUtils.createNumber(val);
41 return obj != null;
42 } catch (final NumberFormatException e) {
43 return false;
44 }
45 }
46
47 // ---------------------------------------------------------------------
48
49 @Test
50 public void compareByte() {
51 assertTrue(NumberUtils.compare((byte) -3, (byte) 0) < 0);
52 assertEquals(0, NumberUtils.compare((byte) 113, (byte) 113));
53 assertTrue(NumberUtils.compare((byte) 123, (byte) 32) > 0);
54 }
55
56 @Test
57 public void compareInt() {
58 assertTrue(NumberUtils.compare(-3, 0) < 0);
59 assertEquals(0, NumberUtils.compare(113, 113));
60 assertTrue(NumberUtils.compare(213, 32) > 0);
61 }
62
63 private void compareIsCreatableWithCreateNumber(final String val, final boolean expected) {
64 final boolean isValid = NumberUtils.isCreatable(val);
65 final boolean canCreate = checkCreateNumber(val);
66 assertTrue(isValid == expected && canCreate == expected, "Expecting " + expected
67 + " for isCreatable/createNumber using \"" + val + "\" but got " + isValid + " and " + canCreate);
68 }
69
70 @SuppressWarnings("deprecation")
71 private void compareIsNumberWithCreateNumber(final String val, final boolean expected) {
72 final boolean isValid = NumberUtils.isNumber(val);
73 final boolean canCreate = checkCreateNumber(val);
74 assertTrue(isValid == expected && canCreate == expected, "Expecting " + expected
75 + " for isNumber/createNumber using \"" + val + "\" but got " + isValid + " and " + canCreate);
76 }
77
78 @Test
79 public void compareLong() {
80 assertTrue(NumberUtils.compare(-3L, 0L) < 0);
81 assertEquals(0, NumberUtils.compare(113L, 113L));
82 assertTrue(NumberUtils.compare(213L, 32L) > 0);
83 }
84
85 @Test
86 public void compareShort() {
87 assertTrue(NumberUtils.compare((short) -3, (short) 0) < 0);
88 assertEquals(0, NumberUtils.compare((short) 113, (short) 113));
89 assertTrue(NumberUtils.compare((short) 213, (short) 32) > 0);
90 }
91
92 /**
93 * Test for {@link NumberUtils#toDouble(BigDecimal)}
94 */
95 @Test
96 public void testBigIntegerToDoubleBigInteger() {
97 assertEquals(0.0d, NumberUtils.toDouble((BigDecimal) null), "toDouble(BigInteger) 1 failed");
98 assertEquals(8.5d, NumberUtils.toDouble(BigDecimal.valueOf(8.5d)), "toDouble(BigInteger) 2 failed");
99 }
100
101 /**
102 * Test for {@link NumberUtils#toDouble(BigDecimal, double)}
103 */
104 @Test
105 public void testBigIntegerToDoubleBigIntegerD() {
106 assertEquals(1.1d, NumberUtils.toDouble((BigDecimal) null, 1.1d), "toDouble(BigInteger) 1 failed");
107 assertEquals(8.5d, NumberUtils.toDouble(BigDecimal.valueOf(8.5d), 1.1d), "toDouble(BigInteger) 2 failed");
108 }
109
110 // Testing JDK against old Lang functionality
111 @Test
112 public void testCompareDouble() {
113 assertEquals(0, Double.compare(Double.NaN, Double.NaN));
114 assertEquals(Double.compare(Double.NaN, Double.POSITIVE_INFINITY), +1);
115 assertEquals(Double.compare(Double.NaN, Double.MAX_VALUE), +1);
116 assertEquals(Double.compare(Double.NaN, 1.2d), +1);
117 assertEquals(Double.compare(Double.NaN, 0.0d), +1);
118 assertEquals(Double.compare(Double.NaN, -0.0d), +1);
119 assertEquals(Double.compare(Double.NaN, -1.2d), +1);
120 assertEquals(Double.compare(Double.NaN, -Double.MAX_VALUE), +1);
121 assertEquals(Double.compare(Double.NaN, Double.NEGATIVE_INFINITY), +1);
122
123 assertEquals(Double.compare(Double.POSITIVE_INFINITY, Double.NaN), -1);
124 assertEquals(0, Double.compare(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY));
125 assertEquals(Double.compare(Double.POSITIVE_INFINITY, Double.MAX_VALUE), +1);
126 assertEquals(Double.compare(Double.POSITIVE_INFINITY, 1.2d), +1);
127 assertEquals(Double.compare(Double.POSITIVE_INFINITY, 0.0d), +1);
128 assertEquals(Double.compare(Double.POSITIVE_INFINITY, -0.0d), +1);
129 assertEquals(Double.compare(Double.POSITIVE_INFINITY, -1.2d), +1);
130 assertEquals(Double.compare(Double.POSITIVE_INFINITY, -Double.MAX_VALUE), +1);
131 assertEquals(Double.compare(Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY), +1);
132
133 assertEquals(Double.compare(Double.MAX_VALUE, Double.NaN), -1);
134 assertEquals(Double.compare(Double.MAX_VALUE, Double.POSITIVE_INFINITY), -1);
135 assertEquals(0, Double.compare(Double.MAX_VALUE, Double.MAX_VALUE));
136 assertEquals(Double.compare(Double.MAX_VALUE, 1.2d), +1);
137 assertEquals(Double.compare(Double.MAX_VALUE, 0.0d), +1);
138 assertEquals(Double.compare(Double.MAX_VALUE, -0.0d), +1);
139 assertEquals(Double.compare(Double.MAX_VALUE, -1.2d), +1);
140 assertEquals(Double.compare(Double.MAX_VALUE, -Double.MAX_VALUE), +1);
141 assertEquals(Double.compare(Double.MAX_VALUE, Double.NEGATIVE_INFINITY), +1);
142
143 assertEquals(Double.compare(1.2d, Double.NaN), -1);
144 assertEquals(Double.compare(1.2d, Double.POSITIVE_INFINITY), -1);
145 assertEquals(Double.compare(1.2d, Double.MAX_VALUE), -1);
146 assertEquals(0, Double.compare(1.2d, 1.2d));
147 assertEquals(Double.compare(1.2d, 0.0d), +1);
148 assertEquals(Double.compare(1.2d, -0.0d), +1);
149 assertEquals(Double.compare(1.2d, -1.2d), +1);
150 assertEquals(Double.compare(1.2d, -Double.MAX_VALUE), +1);
151 assertEquals(Double.compare(1.2d, Double.NEGATIVE_INFINITY), +1);
152
153 assertEquals(Double.compare(0.0d, Double.NaN), -1);
154 assertEquals(Double.compare(0.0d, Double.POSITIVE_INFINITY), -1);
155 assertEquals(Double.compare(0.0d, Double.MAX_VALUE), -1);
156 assertEquals(Double.compare(0.0d, 1.2d), -1);
157 assertEquals(0, Double.compare(0.0d, 0.0d));
158 assertEquals(Double.compare(0.0d, -0.0d), +1);
159 assertEquals(Double.compare(0.0d, -1.2d), +1);
160 assertEquals(Double.compare(0.0d, -Double.MAX_VALUE), +1);
161 assertEquals(Double.compare(0.0d, Double.NEGATIVE_INFINITY), +1);
162
163 assertEquals(Double.compare(-0.0d, Double.NaN), -1);
164 assertEquals(Double.compare(-0.0d, Double.POSITIVE_INFINITY), -1);
165 assertEquals(Double.compare(-0.0d, Double.MAX_VALUE), -1);
166 assertEquals(Double.compare(-0.0d, 1.2d), -1);
167 assertEquals(Double.compare(-0.0d, 0.0d), -1);
168 assertEquals(0, Double.compare(-0.0d, -0.0d));
169 assertEquals(Double.compare(-0.0d, -1.2d), +1);
170 assertEquals(Double.compare(-0.0d, -Double.MAX_VALUE), +1);
171 assertEquals(Double.compare(-0.0d, Double.NEGATIVE_INFINITY), +1);
172
173 assertEquals(Double.compare(-1.2d, Double.NaN), -1);
174 assertEquals(Double.compare(-1.2d, Double.POSITIVE_INFINITY), -1);
175 assertEquals(Double.compare(-1.2d, Double.MAX_VALUE), -1);
176 assertEquals(Double.compare(-1.2d, 1.2d), -1);
177 assertEquals(Double.compare(-1.2d, 0.0d), -1);
178 assertEquals(Double.compare(-1.2d, -0.0d), -1);
179 assertEquals(0, Double.compare(-1.2d, -1.2d));
180 assertEquals(Double.compare(-1.2d, -Double.MAX_VALUE), +1);
181 assertEquals(Double.compare(-1.2d, Double.NEGATIVE_INFINITY), +1);
182
183 assertEquals(Double.compare(-Double.MAX_VALUE, Double.NaN), -1);
184 assertEquals(Double.compare(-Double.MAX_VALUE, Double.POSITIVE_INFINITY), -1);
185 assertEquals(Double.compare(-Double.MAX_VALUE, Double.MAX_VALUE), -1);
186 assertEquals(Double.compare(-Double.MAX_VALUE, 1.2d), -1);
187 assertEquals(Double.compare(-Double.MAX_VALUE, 0.0d), -1);
188 assertEquals(Double.compare(-Double.MAX_VALUE, -0.0d), -1);
189 assertEquals(Double.compare(-Double.MAX_VALUE, -1.2d), -1);
190 assertEquals(0, Double.compare(-Double.MAX_VALUE, -Double.MAX_VALUE));
191 assertEquals(Double.compare(-Double.MAX_VALUE, Double.NEGATIVE_INFINITY), +1);
192
193 assertEquals(Double.compare(Double.NEGATIVE_INFINITY, Double.NaN), -1);
194 assertEquals(Double.compare(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY), -1);
195 assertEquals(Double.compare(Double.NEGATIVE_INFINITY, Double.MAX_VALUE), -1);
196 assertEquals(Double.compare(Double.NEGATIVE_INFINITY, 1.2d), -1);
197 assertEquals(Double.compare(Double.NEGATIVE_INFINITY, 0.0d), -1);
198 assertEquals(Double.compare(Double.NEGATIVE_INFINITY, -0.0d), -1);
199 assertEquals(Double.compare(Double.NEGATIVE_INFINITY, -1.2d), -1);
200 assertEquals(Double.compare(Double.NEGATIVE_INFINITY, -Double.MAX_VALUE), -1);
201 assertEquals(0, Double.compare(Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY));
202 }
203
204 @Test
205 public void testCompareFloat() {
206 assertEquals(0, Float.compare(Float.NaN, Float.NaN));
207 assertEquals(Float.compare(Float.NaN, Float.POSITIVE_INFINITY), +1);
208 assertEquals(Float.compare(Float.NaN, Float.MAX_VALUE), +1);
209 assertEquals(Float.compare(Float.NaN, 1.2f), +1);
210 assertEquals(Float.compare(Float.NaN, 0.0f), +1);
211 assertEquals(Float.compare(Float.NaN, -0.0f), +1);
212 assertEquals(Float.compare(Float.NaN, -1.2f), +1);
213 assertEquals(Float.compare(Float.NaN, -Float.MAX_VALUE), +1);
214 assertEquals(Float.compare(Float.NaN, Float.NEGATIVE_INFINITY), +1);
215
216 assertEquals(Float.compare(Float.POSITIVE_INFINITY, Float.NaN), -1);
217 assertEquals(0, Float.compare(Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY));
218 assertEquals(Float.compare(Float.POSITIVE_INFINITY, Float.MAX_VALUE), +1);
219 assertEquals(Float.compare(Float.POSITIVE_INFINITY, 1.2f), +1);
220 assertEquals(Float.compare(Float.POSITIVE_INFINITY, 0.0f), +1);
221 assertEquals(Float.compare(Float.POSITIVE_INFINITY, -0.0f), +1);
222 assertEquals(Float.compare(Float.POSITIVE_INFINITY, -1.2f), +1);
223 assertEquals(Float.compare(Float.POSITIVE_INFINITY, -Float.MAX_VALUE), +1);
224 assertEquals(Float.compare(Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY), +1);
225
226 assertEquals(Float.compare(Float.MAX_VALUE, Float.NaN), -1);
227 assertEquals(Float.compare(Float.MAX_VALUE, Float.POSITIVE_INFINITY), -1);
228 assertEquals(0, Float.compare(Float.MAX_VALUE, Float.MAX_VALUE));
229 assertEquals(Float.compare(Float.MAX_VALUE, 1.2f), +1);
230 assertEquals(Float.compare(Float.MAX_VALUE, 0.0f), +1);
231 assertEquals(Float.compare(Float.MAX_VALUE, -0.0f), +1);
232 assertEquals(Float.compare(Float.MAX_VALUE, -1.2f), +1);
233 assertEquals(Float.compare(Float.MAX_VALUE, -Float.MAX_VALUE), +1);
234 assertEquals(Float.compare(Float.MAX_VALUE, Float.NEGATIVE_INFINITY), +1);
235
236 assertEquals(Float.compare(1.2f, Float.NaN), -1);
237 assertEquals(Float.compare(1.2f, Float.POSITIVE_INFINITY), -1);
238 assertEquals(Float.compare(1.2f, Float.MAX_VALUE), -1);
239 assertEquals(0, Float.compare(1.2f, 1.2f));
240 assertEquals(Float.compare(1.2f, 0.0f), +1);
241 assertEquals(Float.compare(1.2f, -0.0f), +1);
242 assertEquals(Float.compare(1.2f, -1.2f), +1);
243 assertEquals(Float.compare(1.2f, -Float.MAX_VALUE), +1);
244 assertEquals(Float.compare(1.2f, Float.NEGATIVE_INFINITY), +1);
245
246 assertEquals(Float.compare(0.0f, Float.NaN), -1);
247 assertEquals(Float.compare(0.0f, Float.POSITIVE_INFINITY), -1);
248 assertEquals(Float.compare(0.0f, Float.MAX_VALUE), -1);
249 assertEquals(Float.compare(0.0f, 1.2f), -1);
250 assertEquals(0, Float.compare(0.0f, 0.0f));
251 assertEquals(Float.compare(0.0f, -0.0f), +1);
252 assertEquals(Float.compare(0.0f, -1.2f), +1);
253 assertEquals(Float.compare(0.0f, -Float.MAX_VALUE), +1);
254 assertEquals(Float.compare(0.0f, Float.NEGATIVE_INFINITY), +1);
255
256 assertEquals(Float.compare(-0.0f, Float.NaN), -1);
257 assertEquals(Float.compare(-0.0f, Float.POSITIVE_INFINITY), -1);
258 assertEquals(Float.compare(-0.0f, Float.MAX_VALUE), -1);
259 assertEquals(Float.compare(-0.0f, 1.2f), -1);
260 assertEquals(Float.compare(-0.0f, 0.0f), -1);
261 assertEquals(0, Float.compare(-0.0f, -0.0f));
262 assertEquals(Float.compare(-0.0f, -1.2f), +1);
263 assertEquals(Float.compare(-0.0f, -Float.MAX_VALUE), +1);
264 assertEquals(Float.compare(-0.0f, Float.NEGATIVE_INFINITY), +1);
265
266 assertEquals(Float.compare(-1.2f, Float.NaN), -1);
267 assertEquals(Float.compare(-1.2f, Float.POSITIVE_INFINITY), -1);
268 assertEquals(Float.compare(-1.2f, Float.MAX_VALUE), -1);
269 assertEquals(Float.compare(-1.2f, 1.2f), -1);
270 assertEquals(Float.compare(-1.2f, 0.0f), -1);
271 assertEquals(Float.compare(-1.2f, -0.0f), -1);
272 assertEquals(0, Float.compare(-1.2f, -1.2f));
273 assertEquals(Float.compare(-1.2f, -Float.MAX_VALUE), +1);
274 assertEquals(Float.compare(-1.2f, Float.NEGATIVE_INFINITY), +1);
275
276 assertEquals(Float.compare(-Float.MAX_VALUE, Float.NaN), -1);
277 assertEquals(Float.compare(-Float.MAX_VALUE, Float.POSITIVE_INFINITY), -1);
278 assertEquals(Float.compare(-Float.MAX_VALUE, Float.MAX_VALUE), -1);
279 assertEquals(Float.compare(-Float.MAX_VALUE, 1.2f), -1);
280 assertEquals(Float.compare(-Float.MAX_VALUE, 0.0f), -1);
281 assertEquals(Float.compare(-Float.MAX_VALUE, -0.0f), -1);
282 assertEquals(Float.compare(-Float.MAX_VALUE, -1.2f), -1);
283 assertEquals(0, Float.compare(-Float.MAX_VALUE, -Float.MAX_VALUE));
284 assertEquals(Float.compare(-Float.MAX_VALUE, Float.NEGATIVE_INFINITY), +1);
285
286 assertEquals(Float.compare(Float.NEGATIVE_INFINITY, Float.NaN), -1);
287 assertEquals(Float.compare(Float.NEGATIVE_INFINITY, Float.POSITIVE_INFINITY), -1);
288 assertEquals(Float.compare(Float.NEGATIVE_INFINITY, Float.MAX_VALUE), -1);
289 assertEquals(Float.compare(Float.NEGATIVE_INFINITY, 1.2f), -1);
290 assertEquals(Float.compare(Float.NEGATIVE_INFINITY, 0.0f), -1);
291 assertEquals(Float.compare(Float.NEGATIVE_INFINITY, -0.0f), -1);
292 assertEquals(Float.compare(Float.NEGATIVE_INFINITY, -1.2f), -1);
293 assertEquals(Float.compare(Float.NEGATIVE_INFINITY, -Float.MAX_VALUE), -1);
294 assertEquals(0, Float.compare(Float.NEGATIVE_INFINITY, Float.NEGATIVE_INFINITY));
295 }
296
297 @SuppressWarnings("cast") // suppress instanceof warning check
298 @Test
299 public void testConstants() {
300 assertTrue(NumberUtils.LONG_ZERO instanceof Long);
301 assertTrue(NumberUtils.LONG_ONE instanceof Long);
302 assertTrue(NumberUtils.LONG_MINUS_ONE instanceof Long);
303 assertTrue(NumberUtils.INTEGER_ZERO instanceof Integer);
304 assertTrue(NumberUtils.INTEGER_ONE instanceof Integer);
305 assertTrue(NumberUtils.INTEGER_MINUS_ONE instanceof Integer);
306 assertTrue(NumberUtils.SHORT_ZERO instanceof Short);
307 assertTrue(NumberUtils.SHORT_ONE instanceof Short);
308 assertTrue(NumberUtils.SHORT_MINUS_ONE instanceof Short);
309 assertTrue(NumberUtils.BYTE_ZERO instanceof Byte);
310 assertTrue(NumberUtils.BYTE_ONE instanceof Byte);
311 assertTrue(NumberUtils.BYTE_MINUS_ONE instanceof Byte);
312 assertTrue(NumberUtils.DOUBLE_ZERO instanceof Double);
313 assertTrue(NumberUtils.DOUBLE_ONE instanceof Double);
314 assertTrue(NumberUtils.DOUBLE_MINUS_ONE instanceof Double);
315 assertTrue(NumberUtils.FLOAT_ZERO instanceof Float);
316 assertTrue(NumberUtils.FLOAT_ONE instanceof Float);
317 assertTrue(NumberUtils.FLOAT_MINUS_ONE instanceof Float);
318
319 assertEquals(0, NumberUtils.LONG_ZERO.longValue());
320 assertEquals(1, NumberUtils.LONG_ONE.longValue());
321 assertEquals(NumberUtils.LONG_MINUS_ONE.longValue(), -1);
322 assertEquals(0, NumberUtils.INTEGER_ZERO.intValue());
323 assertEquals(1, NumberUtils.INTEGER_ONE.intValue());
324 assertEquals(NumberUtils.INTEGER_MINUS_ONE.intValue(), -1);
325 assertEquals(0, NumberUtils.SHORT_ZERO.shortValue());
326 assertEquals(1, NumberUtils.SHORT_ONE.shortValue());
327 assertEquals(NumberUtils.SHORT_MINUS_ONE.shortValue(), -1);
328 assertEquals(0, NumberUtils.BYTE_ZERO.byteValue());
329 assertEquals(1, NumberUtils.BYTE_ONE.byteValue());
330 assertEquals(NumberUtils.BYTE_MINUS_ONE.byteValue(), -1);
331 assertEquals(0.0d, NumberUtils.DOUBLE_ZERO.doubleValue());
332 assertEquals(1.0d, NumberUtils.DOUBLE_ONE.doubleValue());
333 assertEquals(NumberUtils.DOUBLE_MINUS_ONE.doubleValue(), -1.0d);
334 assertEquals(0.0f, NumberUtils.FLOAT_ZERO.floatValue());
335 assertEquals(1.0f, NumberUtils.FLOAT_ONE.floatValue());
336 assertEquals(NumberUtils.FLOAT_MINUS_ONE.floatValue(), -1.0f);
337 }
338
339 // -----------------------------------------------------------------------
39340 @Test
40341 public void testConstructor() {
41342 assertNotNull(new NumberUtils());
46347 assertFalse(Modifier.isFinal(NumberUtils.class.getModifiers()));
47348 }
48349
49 //---------------------------------------------------------------------
50
51 /**
52 * Test for {@link NumberUtils#toInt(String)}.
53 */
54 @Test
55 public void testToIntString() {
56 assertEquals(12345, NumberUtils.toInt("12345"), "toInt(String) 1 failed");
57 assertEquals(0, NumberUtils.toInt("abc"), "toInt(String) 2 failed");
58 assertEquals(0, NumberUtils.toInt(""), "toInt(empty) failed");
59 assertEquals(0, NumberUtils.toInt(null), "toInt(null) failed");
60 }
61
62 /**
63 * Test for {@link NumberUtils#toInt(String, int)}.
64 */
65 @Test
66 public void testToIntStringI() {
67 assertEquals(12345, NumberUtils.toInt("12345", 5), "toInt(String, int) 1 failed");
68 assertEquals(5, NumberUtils.toInt("1234.5", 5), "toInt(String, int) 2 failed");
69 }
70
71 /**
72 * Test for {@link NumberUtils#toLong(String)}.
73 */
74 @Test
75 public void testToLongString() {
76 assertEquals(12345L, NumberUtils.toLong("12345"), "toLong(String) 1 failed");
77 assertEquals(0L, NumberUtils.toLong("abc"), "toLong(String) 2 failed");
78 assertEquals(0L, NumberUtils.toLong("1L"), "toLong(String) 3 failed");
79 assertEquals(0L, NumberUtils.toLong("1l"), "toLong(String) 4 failed");
80 assertEquals(NumberUtils.toLong(Long.MAX_VALUE + ""), Long.MAX_VALUE, "toLong(Long.MAX_VALUE) failed");
81 assertEquals(NumberUtils.toLong(Long.MIN_VALUE + ""), Long.MIN_VALUE, "toLong(Long.MIN_VALUE) failed");
82 assertEquals(0L, NumberUtils.toLong(""), "toLong(empty) failed");
83 assertEquals(0L, NumberUtils.toLong(null), "toLong(null) failed");
84 }
85
86 /**
87 * Test for {@link NumberUtils#toLong(String, long)}.
88 */
89 @Test
90 public void testToLongStringL() {
91 assertEquals(12345L, NumberUtils.toLong("12345", 5L), "toLong(String, long) 1 failed");
92 assertEquals(5L, NumberUtils.toLong("1234.5", 5L), "toLong(String, long) 2 failed");
93 }
94
95 /**
96 * Test for {@link NumberUtils#toFloat(String)}.
97 */
98 @Test
99 public void testToFloatString() {
100 assertEquals(NumberUtils.toFloat("-1.2345"), -1.2345f, "toFloat(String) 1 failed");
101 assertEquals(1.2345f, NumberUtils.toFloat("1.2345"), "toFloat(String) 2 failed");
102 assertEquals(0.0f, NumberUtils.toFloat("abc"), "toFloat(String) 3 failed");
103 // LANG-1060
104 assertEquals(NumberUtils.toFloat("-001.2345"), -1.2345f, "toFloat(String) 4 failed");
105 assertEquals(1.2345f, NumberUtils.toFloat("+001.2345"), "toFloat(String) 5 failed");
106 assertEquals(1.2345f, NumberUtils.toFloat("001.2345"), "toFloat(String) 6 failed");
107 assertEquals(0f, NumberUtils.toFloat("000.00"), "toFloat(String) 7 failed");
108
109 assertEquals(NumberUtils.toFloat(Float.MAX_VALUE + ""), Float.MAX_VALUE, "toFloat(Float.MAX_VALUE) failed");
110 assertEquals(NumberUtils.toFloat(Float.MIN_VALUE + ""), Float.MIN_VALUE, "toFloat(Float.MIN_VALUE) failed");
111 assertEquals(0.0f, NumberUtils.toFloat(""), "toFloat(empty) failed");
112 assertEquals(0.0f, NumberUtils.toFloat(null), "toFloat(null) failed");
113 }
114
115 /**
116 * Test for {@link NumberUtils#toFloat(String, float)}.
117 */
118 @Test
119 public void testToFloatStringF() {
120 assertEquals(1.2345f, NumberUtils.toFloat("1.2345", 5.1f), "toFloat(String, int) 1 failed");
121 assertEquals(5.0f, NumberUtils.toFloat("a", 5.0f), "toFloat(String, int) 2 failed");
122 // LANG-1060
123 assertEquals(5.0f, NumberUtils.toFloat("-001Z.2345", 5.0f), "toFloat(String, int) 3 failed");
124 assertEquals(5.0f, NumberUtils.toFloat("+001AB.2345", 5.0f), "toFloat(String, int) 4 failed");
125 assertEquals(5.0f, NumberUtils.toFloat("001Z.2345", 5.0f), "toFloat(String, int) 5 failed");
126 }
127
128 /**
129 * Test for {(@link NumberUtils#createNumber(String)}
130 */
131 @Test
132 public void testStringCreateNumberEnsureNoPrecisionLoss() {
133 final String shouldBeFloat = "1.23";
134 final String shouldBeDouble = "3.40282354e+38";
135 final String shouldBeBigDecimal = "1.797693134862315759e+308";
136 assertTrue(NumberUtils.createNumber(shouldBeFloat) instanceof Float);
137 assertTrue(NumberUtils.createNumber(shouldBeDouble) instanceof Double);
138 assertTrue(NumberUtils.createNumber(shouldBeBigDecimal) instanceof BigDecimal);
139 // LANG-1060
140 assertTrue(NumberUtils.createNumber("001.12") instanceof Float);
141 assertTrue(NumberUtils.createNumber("-001.12") instanceof Float);
142 assertTrue(NumberUtils.createNumber("+001.12") instanceof Float);
143 assertTrue(NumberUtils.createNumber("003.40282354e+38") instanceof Double);
144 assertTrue(NumberUtils.createNumber("-003.40282354e+38") instanceof Double);
145 assertTrue(NumberUtils.createNumber("+003.40282354e+38") instanceof Double);
146 assertTrue(NumberUtils.createNumber("0001.797693134862315759e+308") instanceof BigDecimal);
147 assertTrue(NumberUtils.createNumber("-001.797693134862315759e+308") instanceof BigDecimal);
148 assertTrue(NumberUtils.createNumber("+001.797693134862315759e+308") instanceof BigDecimal);
149 }
150 /**
151 * Test for {@link NumberUtils#toDouble(String)}.
152 */
153 @Test
154 public void testStringToDoubleString() {
155 assertEquals(NumberUtils.toDouble("-1.2345"), -1.2345d, "toDouble(String) 1 failed");
156 assertEquals(1.2345d, NumberUtils.toDouble("1.2345"), "toDouble(String) 2 failed");
157 assertEquals(0.0d, NumberUtils.toDouble("abc"), "toDouble(String) 3 failed");
158 // LANG-1060
159 assertEquals(NumberUtils.toDouble("-001.2345"), -1.2345d, "toDouble(String) 4 failed");
160 assertEquals(1.2345d, NumberUtils.toDouble("+001.2345"), "toDouble(String) 5 failed");
161 assertEquals(1.2345d, NumberUtils.toDouble("001.2345"), "toDouble(String) 6 failed");
162 assertEquals(0d, NumberUtils.toDouble("000.00000"), "toDouble(String) 7 failed");
163
164 assertEquals(NumberUtils.toDouble(Double.MAX_VALUE + ""), Double.MAX_VALUE, "toDouble(Double.MAX_VALUE) failed");
165 assertEquals(NumberUtils.toDouble(Double.MIN_VALUE + ""), Double.MIN_VALUE, "toDouble(Double.MIN_VALUE) failed");
166 assertEquals(0.0d, NumberUtils.toDouble(""), "toDouble(empty) failed");
167 assertEquals(0.0d, NumberUtils.toDouble((String) null), "toDouble(null) failed");
168 }
169
170 /**
171 * Test for {@link NumberUtils#toDouble(String, double)}.
172 */
173 @Test
174 public void testStringToDoubleStringD() {
175 assertEquals(1.2345d, NumberUtils.toDouble("1.2345", 5.1d), "toDouble(String, int) 1 failed");
176 assertEquals(5.0d, NumberUtils.toDouble("a", 5.0d), "toDouble(String, int) 2 failed");
177 // LANG-1060
178 assertEquals(1.2345d, NumberUtils.toDouble("001.2345", 5.1d), "toDouble(String, int) 3 failed");
179 assertEquals(NumberUtils.toDouble("-001.2345", 5.1d), -1.2345d, "toDouble(String, int) 4 failed");
180 assertEquals(1.2345d, NumberUtils.toDouble("+001.2345", 5.1d), "toDouble(String, int) 5 failed");
181 assertEquals(0d, NumberUtils.toDouble("000.00", 5.1d), "toDouble(String, int) 7 failed");
182 }
183
184 /**
185 * Test for {@link NumberUtils#toDouble(BigDecimal)}
186 */
187 @Test
188 public void testBigIntegerToDoubleBigInteger() {
189 assertEquals(0.0d, NumberUtils.toDouble((BigDecimal) null), "toDouble(BigInteger) 1 failed");
190 assertEquals(8.5d, NumberUtils.toDouble(BigDecimal.valueOf(8.5d)), "toDouble(BigInteger) 2 failed");
191 }
192
193 /**
194 * Test for {@link NumberUtils#toDouble(BigDecimal, double)}
195 */
196 @Test
197 public void testBigIntegerToDoubleBigIntegerD() {
198 assertEquals(1.1d, NumberUtils.toDouble((BigDecimal) null, 1.1d), "toDouble(BigInteger) 1 failed");
199 assertEquals(8.5d, NumberUtils.toDouble(BigDecimal.valueOf(8.5d), 1.1d), "toDouble(BigInteger) 2 failed");
200 }
201
202 /**
203 * Test for {@link NumberUtils#toByte(String)}.
204 */
205 @Test
206 public void testToByteString() {
207 assertEquals(123, NumberUtils.toByte("123"), "toByte(String) 1 failed");
208 assertEquals(0, NumberUtils.toByte("abc"), "toByte(String) 2 failed");
209 assertEquals(0, NumberUtils.toByte(""), "toByte(empty) failed");
210 assertEquals(0, NumberUtils.toByte(null), "toByte(null) failed");
211 }
212
213 /**
214 * Test for {@link NumberUtils#toByte(String, byte)}.
215 */
216 @Test
217 public void testToByteStringI() {
218 assertEquals(123, NumberUtils.toByte("123", (byte) 5), "toByte(String, byte) 1 failed");
219 assertEquals(5, NumberUtils.toByte("12.3", (byte) 5), "toByte(String, byte) 2 failed");
220 }
221
222 /**
223 * Test for {@link NumberUtils#toShort(String)}.
224 */
225 @Test
226 public void testToShortString() {
227 assertEquals(12345, NumberUtils.toShort("12345"), "toShort(String) 1 failed");
228 assertEquals(0, NumberUtils.toShort("abc"), "toShort(String) 2 failed");
229 assertEquals(0, NumberUtils.toShort(""), "toShort(empty) failed");
230 assertEquals(0, NumberUtils.toShort(null), "toShort(null) failed");
231 }
232
233 /**
234 * Test for {@link NumberUtils#toShort(String, short)}.
235 */
236 @Test
237 public void testToShortStringI() {
238 assertEquals(12345, NumberUtils.toShort("12345", (short) 5), "toShort(String, short) 1 failed");
239 assertEquals(5, NumberUtils.toShort("1234.5", (short) 5), "toShort(String, short) 2 failed");
240 }
241
242 /**
243 * Test for {@link NumberUtils#toScaledBigDecimal(BigDecimal)}.
244 */
245 @Test
246 public void testToScaledBigDecimalBigDecimal() {
247 assertEquals(NumberUtils.toScaledBigDecimal(BigDecimal.valueOf(123.456)), BigDecimal.valueOf(123.46), "toScaledBigDecimal(BigDecimal) 1 failed");
248 // Test RoudingMode.HALF_EVEN default rounding.
249 assertEquals(NumberUtils.toScaledBigDecimal(BigDecimal.valueOf(23.515)), BigDecimal.valueOf(23.52), "toScaledBigDecimal(BigDecimal) 2 failed");
250 assertEquals(NumberUtils.toScaledBigDecimal(BigDecimal.valueOf(23.525)), BigDecimal.valueOf(23.52), "toScaledBigDecimal(BigDecimal) 3 failed");
251 assertEquals("2352.00", NumberUtils.toScaledBigDecimal(BigDecimal.valueOf(23.525))
252 .multiply(BigDecimal.valueOf(100)).toString(), "toScaledBigDecimal(BigDecimal) 4 failed");
253 assertEquals(NumberUtils.toScaledBigDecimal((BigDecimal) null), BigDecimal.ZERO, "toScaledBigDecimal(BigDecimal) 5 failed");
254 }
255
256 /**
257 * Test for {@link NumberUtils#toScaledBigDecimal(BigDecimal, int, RoundingMode)}.
258 */
259 @Test
260 public void testToScaledBigDecimalBigDecimalIRM() {
261 assertEquals(NumberUtils.toScaledBigDecimal(BigDecimal.valueOf(123.456), 1, RoundingMode.CEILING), BigDecimal.valueOf(123.5), "toScaledBigDecimal(BigDecimal, int, RoudingMode) 1 failed");
262 assertEquals(NumberUtils.toScaledBigDecimal(BigDecimal.valueOf(23.5159), 3, RoundingMode.FLOOR), BigDecimal.valueOf(23.515), "toScaledBigDecimal(BigDecimal, int, RoudingMode) 2 failed");
263 assertEquals(NumberUtils.toScaledBigDecimal(BigDecimal.valueOf(23.525), 2, RoundingMode.HALF_UP), BigDecimal.valueOf(23.53), "toScaledBigDecimal(BigDecimal, int, RoudingMode) 3 failed");
264 assertEquals("23521.0000", NumberUtils.toScaledBigDecimal(BigDecimal.valueOf(23.521), 4, RoundingMode.HALF_EVEN)
265 .multiply(BigDecimal.valueOf(1000))
266 .toString(), "toScaledBigDecimal(BigDecimal, int, RoudingMode) 4 failed");
267 assertEquals(NumberUtils.toScaledBigDecimal((BigDecimal) null, 2, RoundingMode.HALF_UP), BigDecimal.ZERO, "toScaledBigDecimal(BigDecimal, int, RoudingMode) 5 failed");
268 }
269
270 /**
271 * Test for {@link NumberUtils#toScaledBigDecimal(Float)}.
272 */
273 @Test
274 public void testToScaledBigDecimalFloat() {
275 assertEquals(NumberUtils.toScaledBigDecimal(Float.valueOf(123.456f)), BigDecimal.valueOf(123.46), "toScaledBigDecimal(Float) 1 failed");
276 // Test RoudingMode.HALF_EVEN default rounding.
277 assertEquals(NumberUtils.toScaledBigDecimal(Float.valueOf(23.515f)), BigDecimal.valueOf(23.51), "toScaledBigDecimal(Float) 2 failed");
278 // Note. NumberUtils.toScaledBigDecimal(Float.valueOf(23.515f)).equals(BigDecimal.valueOf(23.51))
279 // because of roundoff error. It is ok.
280 assertEquals(NumberUtils.toScaledBigDecimal(Float.valueOf(23.525f)), BigDecimal.valueOf(23.52), "toScaledBigDecimal(Float) 3 failed");
281 assertEquals("2352.00", NumberUtils.toScaledBigDecimal(Float.valueOf(23.525f))
282 .multiply(BigDecimal.valueOf(100)).toString(), "toScaledBigDecimal(Float) 4 failed");
283 assertEquals(NumberUtils.toScaledBigDecimal((Float) null), BigDecimal.ZERO, "toScaledBigDecimal(Float) 5 failed");
284 }
285
286 /**
287 * Test for {@link NumberUtils#toScaledBigDecimal(Float, int, RoundingMode)}.
288 */
289 @Test
290 public void testToScaledBigDecimalFloatIRM() {
291 assertEquals(NumberUtils.toScaledBigDecimal(Float.valueOf(123.456f), 1, RoundingMode.CEILING), BigDecimal.valueOf(123.5), "toScaledBigDecimal(Float, int, RoudingMode) 1 failed");
292 assertEquals(NumberUtils.toScaledBigDecimal(Float.valueOf(23.5159f), 3, RoundingMode.FLOOR), BigDecimal.valueOf(23.515), "toScaledBigDecimal(Float, int, RoudingMode) 2 failed");
293 // The following happens due to roundoff error. We're ok with this.
294 assertEquals(NumberUtils.toScaledBigDecimal(Float.valueOf(23.525f), 2, RoundingMode.HALF_UP), BigDecimal.valueOf(23.52), "toScaledBigDecimal(Float, int, RoudingMode) 3 failed");
295 assertEquals("23521.0000", NumberUtils.toScaledBigDecimal(Float.valueOf(23.521f), 4, RoundingMode.HALF_EVEN)
296 .multiply(BigDecimal.valueOf(1000))
297 .toString(), "toScaledBigDecimal(Float, int, RoudingMode) 4 failed");
298 assertEquals(NumberUtils.toScaledBigDecimal((Float) null, 2, RoundingMode.HALF_UP), BigDecimal.ZERO, "toScaledBigDecimal(Float, int, RoudingMode) 5 failed");
299 }
300
301 /**
302 * Test for {@link NumberUtils#toScaledBigDecimal(Double)}.
303 */
304 @Test
305 public void testToScaledBigDecimalDouble() {
306 assertEquals(NumberUtils.toScaledBigDecimal(Double.valueOf(123.456d)), BigDecimal.valueOf(123.46), "toScaledBigDecimal(Double) 1 failed");
307 // Test RoudingMode.HALF_EVEN default rounding.
308 assertEquals(NumberUtils.toScaledBigDecimal(Double.valueOf(23.515d)), BigDecimal.valueOf(23.52), "toScaledBigDecimal(Double) 2 failed");
309 assertEquals(NumberUtils.toScaledBigDecimal(Double.valueOf(23.525d)), BigDecimal.valueOf(23.52), "toScaledBigDecimal(Double) 3 failed");
310 assertEquals("2352.00", NumberUtils.toScaledBigDecimal(Double.valueOf(23.525d))
311 .multiply(BigDecimal.valueOf(100)).toString(), "toScaledBigDecimal(Double) 4 failed");
312 assertEquals(NumberUtils.toScaledBigDecimal((Double) null), BigDecimal.ZERO, "toScaledBigDecimal(Double) 5 failed");
313 }
314
315 /**
316 * Test for {@link NumberUtils#toScaledBigDecimal(Double, int, RoundingMode)}.
317 */
318 @Test
319 public void testToScaledBigDecimalDoubleIRM() {
320 assertEquals(NumberUtils.toScaledBigDecimal(Double.valueOf(123.456d), 1, RoundingMode.CEILING), BigDecimal.valueOf(123.5), "toScaledBigDecimal(Double, int, RoudingMode) 1 failed");
321 assertEquals(NumberUtils.toScaledBigDecimal(Double.valueOf(23.5159d), 3, RoundingMode.FLOOR), BigDecimal.valueOf(23.515), "toScaledBigDecimal(Double, int, RoudingMode) 2 failed");
322 assertEquals(NumberUtils.toScaledBigDecimal(Double.valueOf(23.525d), 2, RoundingMode.HALF_UP), BigDecimal.valueOf(23.53), "toScaledBigDecimal(Double, int, RoudingMode) 3 failed");
323 assertEquals("23521.0000", NumberUtils.toScaledBigDecimal(Double.valueOf(23.521d), 4, RoundingMode.HALF_EVEN)
324 .multiply(BigDecimal.valueOf(1000))
325 .toString(), "toScaledBigDecimal(Double, int, RoudingMode) 4 failed");
326 assertEquals(NumberUtils.toScaledBigDecimal((Double) null, 2, RoundingMode.HALF_UP), BigDecimal.ZERO, "toScaledBigDecimal(Double, int, RoudingMode) 5 failed");
327 }
328
329 /**
330 * Test for {@link NumberUtils#toScaledBigDecimal(Double)}.
331 */
332 @Test
333 public void testToScaledBigDecimalString() {
334 assertEquals(NumberUtils.toScaledBigDecimal("123.456"), BigDecimal.valueOf(123.46), "toScaledBigDecimal(String) 1 failed");
335 // Test RoudingMode.HALF_EVEN default rounding.
336 assertEquals(NumberUtils.toScaledBigDecimal("23.515"), BigDecimal.valueOf(23.52), "toScaledBigDecimal(String) 2 failed");
337 assertEquals(NumberUtils.toScaledBigDecimal("23.525"), BigDecimal.valueOf(23.52), "toScaledBigDecimal(String) 3 failed");
338 assertEquals("2352.00", NumberUtils.toScaledBigDecimal("23.525")
339 .multiply(BigDecimal.valueOf(100)).toString(), "toScaledBigDecimal(String) 4 failed");
340 assertEquals(NumberUtils.toScaledBigDecimal((String) null), BigDecimal.ZERO, "toScaledBigDecimal(String) 5 failed");
341 }
342
343 /**
344 * Test for {@link NumberUtils#toScaledBigDecimal(Double, int, RoundingMode)}.
345 */
346 @Test
347 public void testToScaledBigDecimalStringIRM() {
348 assertEquals(NumberUtils.toScaledBigDecimal("123.456", 1, RoundingMode.CEILING), BigDecimal.valueOf(123.5), "toScaledBigDecimal(String, int, RoudingMode) 1 failed");
349 assertEquals(NumberUtils.toScaledBigDecimal("23.5159", 3, RoundingMode.FLOOR), BigDecimal.valueOf(23.515), "toScaledBigDecimal(String, int, RoudingMode) 2 failed");
350 assertEquals(NumberUtils.toScaledBigDecimal("23.525", 2, RoundingMode.HALF_UP), BigDecimal.valueOf(23.53), "toScaledBigDecimal(String, int, RoudingMode) 3 failed");
351 assertEquals("23521.0000", NumberUtils.toScaledBigDecimal("23.521", 4, RoundingMode.HALF_EVEN)
352 .multiply(BigDecimal.valueOf(1000))
353 .toString(), "toScaledBigDecimal(String, int, RoudingMode) 4 failed");
354 assertEquals(NumberUtils.toScaledBigDecimal((String) null, 2, RoundingMode.HALF_UP), BigDecimal.ZERO, "toScaledBigDecimal(String, int, RoudingMode) 5 failed");
355 }
356
357 @Test
358 public void testCreateNumber() {
359 // a lot of things can go wrong
360 assertEquals(Float.valueOf("1234.5"), NumberUtils.createNumber("1234.5"), "createNumber(String) 1 failed");
361 assertEquals(Integer.valueOf("12345"), NumberUtils.createNumber("12345"), "createNumber(String) 2 failed");
362 assertEquals(Double.valueOf("1234.5"), NumberUtils.createNumber("1234.5D"), "createNumber(String) 3 failed");
363 assertEquals(Double.valueOf("1234.5"), NumberUtils.createNumber("1234.5d"), "createNumber(String) 3 failed");
364 assertEquals(Float.valueOf("1234.5"), NumberUtils.createNumber("1234.5F"), "createNumber(String) 4 failed");
365 assertEquals(Float.valueOf("1234.5"), NumberUtils.createNumber("1234.5f"), "createNumber(String) 4 failed");
366 assertEquals(Long.valueOf(Integer.MAX_VALUE + 1L), NumberUtils.createNumber(""
367 + (Integer.MAX_VALUE + 1L)), "createNumber(String) 5 failed");
368 assertEquals(Long.valueOf(12345), NumberUtils.createNumber("12345L"), "createNumber(String) 6 failed");
369 assertEquals(Long.valueOf(12345), NumberUtils.createNumber("12345l"), "createNumber(String) 6 failed");
370 assertEquals(Float.valueOf("-1234.5"), NumberUtils.createNumber("-1234.5"), "createNumber(String) 7 failed");
371 assertEquals(Integer.valueOf("-12345"), NumberUtils.createNumber("-12345"), "createNumber(String) 8 failed");
372 assertEquals(0xFADE, NumberUtils.createNumber("0xFADE").intValue(), "createNumber(String) 9a failed");
373 assertEquals(0xFADE, NumberUtils.createNumber("0Xfade").intValue(), "createNumber(String) 9b failed");
374 assertEquals(-0xFADE, NumberUtils.createNumber("-0xFADE").intValue(), "createNumber(String) 10a failed");
375 assertEquals(-0xFADE, NumberUtils.createNumber("-0Xfade").intValue(), "createNumber(String) 10b failed");
376 assertEquals(Double.valueOf("1.1E200"), NumberUtils.createNumber("1.1E200"), "createNumber(String) 11 failed");
377 assertEquals(Float.valueOf("1.1E20"), NumberUtils.createNumber("1.1E20"), "createNumber(String) 12 failed");
378 assertEquals(Double.valueOf("-1.1E200"), NumberUtils.createNumber("-1.1E200"), "createNumber(String) 13 failed");
379 assertEquals(Double.valueOf("1.1E-200"), NumberUtils.createNumber("1.1E-200"), "createNumber(String) 14 failed");
380 assertNull(NumberUtils.createNumber(null), "createNumber(null) failed");
381 assertEquals(new BigInteger("12345678901234567890"), NumberUtils.createNumber("12345678901234567890L"), "createNumber(String) failed");
382
383 assertEquals(new BigDecimal("1.1E-700"), NumberUtils.createNumber("1.1E-700F"), "createNumber(String) 15 failed");
384
385 assertEquals(Long.valueOf("10" + Integer.MAX_VALUE), NumberUtils.createNumber("10" + Integer.MAX_VALUE + "L"), "createNumber(String) 16 failed");
386 assertEquals(Long.valueOf("10" + Integer.MAX_VALUE), NumberUtils.createNumber("10" + Integer.MAX_VALUE), "createNumber(String) 17 failed");
387 assertEquals(new BigInteger("10" + Long.MAX_VALUE), NumberUtils.createNumber("10" + Long.MAX_VALUE), "createNumber(String) 18 failed");
388
389 // LANG-521
390 assertEquals(Float.valueOf("2."), NumberUtils.createNumber("2."), "createNumber(String) LANG-521 failed");
391
392 // LANG-638
393 assertFalse(checkCreateNumber("1eE"), "createNumber(String) succeeded");
394
395 // LANG-693
396 assertEquals(Double.valueOf(Double.MAX_VALUE), NumberUtils.createNumber("" + Double.MAX_VALUE), "createNumber(String) LANG-693 failed");
397
398 // LANG-822
399 // ensure that the underlying negative number would create a BigDecimal
400 final Number bigNum = NumberUtils.createNumber("-1.1E-700F");
401 assertNotNull(bigNum);
402 assertEquals(BigDecimal.class, bigNum.getClass());
403
404 // LANG-1018
405 assertEquals(Double.valueOf("-160952.54"), NumberUtils.createNumber("-160952.54"),
406 "createNumber(String) LANG-1018 failed");
407 // LANG-1187
408 assertEquals(Double.valueOf("6264583.33"), NumberUtils.createNumber("6264583.33"),
409 "createNumber(String) LANG-1187 failed");
410 // LANG-1215
411 assertEquals(Double.valueOf("193343.82"), NumberUtils.createNumber("193343.82"),
412 "createNumber(String) LANG-1215 failed");
413 // LANG-1060
414 assertEquals(Double.valueOf("001234.5678"), NumberUtils.createNumber("001234.5678"), "createNumber(String) LANG-1060a failed");
415 assertEquals(Double.valueOf("+001234.5678"), NumberUtils.createNumber("+001234.5678"), "createNumber(String) LANG-1060b failed");
416 assertEquals(Double.valueOf("-001234.5678"), NumberUtils.createNumber("-001234.5678"), "createNumber(String) LANG-1060c failed");
417 assertEquals(Double.valueOf("0000.00000"), NumberUtils.createNumber("0000.00000d"), "createNumber(String) LANG-1060d failed");
418 assertEquals(Float.valueOf("001234.56"), NumberUtils.createNumber("001234.56"), "createNumber(String) LANG-1060e failed");
419 assertEquals(Float.valueOf("+001234.56"), NumberUtils.createNumber("+001234.56"), "createNumber(String) LANG-1060f failed");
420 assertEquals(Float.valueOf("-001234.56"), NumberUtils.createNumber("-001234.56"), "createNumber(String) LANG-1060g failed");
421 assertEquals(Float.valueOf("0000.10"), NumberUtils.createNumber("0000.10"), "createNumber(String) LANG-1060h failed");
422 assertEquals(Float.valueOf("001.1E20"), NumberUtils.createNumber("001.1E20"), "createNumber(String) LANG-1060i failed");
423 assertEquals(Float.valueOf("+001.1E20"), NumberUtils.createNumber("+001.1E20"), "createNumber(String) LANG-1060j failed");
424 assertEquals(Float.valueOf("-001.1E20"), NumberUtils.createNumber("-001.1E20"), "createNumber(String) LANG-1060k failed");
425 assertEquals(Double.valueOf("001.1E200"), NumberUtils.createNumber("001.1E200"), "createNumber(String) LANG-1060l failed");
426 assertEquals(Double.valueOf("+001.1E200"), NumberUtils.createNumber("+001.1E200"), "createNumber(String) LANG-1060m failed");
427 assertEquals(Double.valueOf("-001.1E200"), NumberUtils.createNumber("-001.1E200"), "createNumber(String) LANG-1060n failed");
428 }
429
430 @Test
431 public void testLang1087() {
432 // no sign cases
433 assertEquals(Float.class, NumberUtils.createNumber("0.0").getClass());
434 assertEquals(Float.valueOf("0.0"), NumberUtils.createNumber("0.0"));
435 // explicit positive sign cases
436 assertEquals(Float.class, NumberUtils.createNumber("+0.0").getClass());
437 assertEquals(Float.valueOf("+0.0"), NumberUtils.createNumber("+0.0"));
438 // negative sign cases
439 assertEquals(Float.class, NumberUtils.createNumber("-0.0").getClass());
440 assertEquals(Float.valueOf("-0.0"), NumberUtils.createNumber("-0.0"));
441 }
442
443 @Test
444 public void TestLang747() {
445 assertEquals(Integer.valueOf(0x8000), NumberUtils.createNumber("0x8000"));
446 assertEquals(Integer.valueOf(0x80000), NumberUtils.createNumber("0x80000"));
447 assertEquals(Integer.valueOf(0x800000), NumberUtils.createNumber("0x800000"));
448 assertEquals(Integer.valueOf(0x8000000), NumberUtils.createNumber("0x8000000"));
449 assertEquals(Integer.valueOf(0x7FFFFFFF), NumberUtils.createNumber("0x7FFFFFFF"));
450 assertEquals(Long.valueOf(0x80000000L), NumberUtils.createNumber("0x80000000"));
451 assertEquals(Long.valueOf(0xFFFFFFFFL), NumberUtils.createNumber("0xFFFFFFFF"));
452
453 // Leading zero tests
454 assertEquals(Integer.valueOf(0x8000000), NumberUtils.createNumber("0x08000000"));
455 assertEquals(Integer.valueOf(0x7FFFFFFF), NumberUtils.createNumber("0x007FFFFFFF"));
456 assertEquals(Long.valueOf(0x80000000L), NumberUtils.createNumber("0x080000000"));
457 assertEquals(Long.valueOf(0xFFFFFFFFL), NumberUtils.createNumber("0x00FFFFFFFF"));
458
459 assertEquals(Long.valueOf(0x800000000L), NumberUtils.createNumber("0x800000000"));
460 assertEquals(Long.valueOf(0x8000000000L), NumberUtils.createNumber("0x8000000000"));
461 assertEquals(Long.valueOf(0x80000000000L), NumberUtils.createNumber("0x80000000000"));
462 assertEquals(Long.valueOf(0x800000000000L), NumberUtils.createNumber("0x800000000000"));
463 assertEquals(Long.valueOf(0x8000000000000L), NumberUtils.createNumber("0x8000000000000"));
464 assertEquals(Long.valueOf(0x80000000000000L), NumberUtils.createNumber("0x80000000000000"));
465 assertEquals(Long.valueOf(0x800000000000000L), NumberUtils.createNumber("0x800000000000000"));
466 assertEquals(Long.valueOf(0x7FFFFFFFFFFFFFFFL), NumberUtils.createNumber("0x7FFFFFFFFFFFFFFF"));
467 // N.B. Cannot use a hex constant such as 0x8000000000000000L here as that is interpreted as a negative long
468 assertEquals(new BigInteger("8000000000000000", 16), NumberUtils.createNumber("0x8000000000000000"));
469 assertEquals(new BigInteger("FFFFFFFFFFFFFFFF", 16), NumberUtils.createNumber("0xFFFFFFFFFFFFFFFF"));
470
471 // Leading zero tests
472 assertEquals(Long.valueOf(0x80000000000000L), NumberUtils.createNumber("0x00080000000000000"));
473 assertEquals(Long.valueOf(0x800000000000000L), NumberUtils.createNumber("0x0800000000000000"));
474 assertEquals(Long.valueOf(0x7FFFFFFFFFFFFFFFL), NumberUtils.createNumber("0x07FFFFFFFFFFFFFFF"));
475 // N.B. Cannot use a hex constant such as 0x8000000000000000L here as that is interpreted as a negative long
476 assertEquals(new BigInteger("8000000000000000", 16), NumberUtils.createNumber("0x00008000000000000000"));
477 assertEquals(new BigInteger("FFFFFFFFFFFFFFFF", 16), NumberUtils.createNumber("0x0FFFFFFFFFFFFFFFF"));
478 }
479
480 @Test
481 // Check that the code fails to create a valid number when preceded by -- rather than -
482 public void testCreateNumberFailure_1() {
483 assertThrows(NumberFormatException.class, () -> NumberUtils.createNumber("--1.1E-700F"));
484 }
485
486 @Test
487 // Check that the code fails to create a valid number when both e and E are present (with decimal)
488 public void testCreateNumberFailure_2() {
489 assertThrows(NumberFormatException.class, () -> NumberUtils.createNumber("-1.1E+0-7e00"));
490 }
491
492 @Test
493 // Check that the code fails to create a valid number when both e and E are present (no decimal)
494 public void testCreateNumberFailure_3() {
495 assertThrows(NumberFormatException.class, () -> NumberUtils.createNumber("-11E+0-7e00"));
496 }
497
498 @Test
499 // Check that the code fails to create a valid number when both e and E are present (no decimal)
500 public void testCreateNumberFailure_4() {
501 assertThrows(NumberFormatException.class, () -> NumberUtils.createNumber("1eE+00001"));
502 }
503
504 @Test
505 // Check that the code fails to create a valid number when there are multiple trailing 'f' characters (LANG-1205)
506 public void testCreateNumberFailure_5() {
507 assertThrows(NumberFormatException.class, () -> NumberUtils.createNumber("1234.5ff"));
508 }
509
510 @Test
511 // Check that the code fails to create a valid number when there are multiple trailing 'F' characters (LANG-1205)
512 public void testCreateNumberFailure_6() {
513 assertThrows(NumberFormatException.class, () -> NumberUtils.createNumber("1234.5FF"));
514 }
515
516 @Test
517 // Check that the code fails to create a valid number when there are multiple trailing 'd' characters (LANG-1205)
518 public void testCreateNumberFailure_7() {
519 assertThrows(NumberFormatException.class, () -> NumberUtils.createNumber("1234.5dd"));
520 }
521
522 @Test
523 // Check that the code fails to create a valid number when there are multiple trailing 'D' characters (LANG-1205)
524 public void testCreateNumberFailure_8() {
525 assertThrows(NumberFormatException.class, () -> NumberUtils.createNumber("1234.5DD"));
526 }
527
528 // Tests to show when magnitude causes switch to next Number type
529 // Will probably need to be adjusted if code is changed to check precision (LANG-693)
530 @Test
531 public void testCreateNumberMagnitude() {
532 // Test Float.MAX_VALUE, and same with +1 in final digit to check conversion changes to next Number type
533 assertEquals(Float.valueOf(Float.MAX_VALUE), NumberUtils.createNumber("3.4028235e+38"));
534 assertEquals(Double.valueOf(3.4028236e+38), NumberUtils.createNumber("3.4028236e+38"));
535
536 // Test Double.MAX_VALUE
537 assertEquals(Double.valueOf(Double.MAX_VALUE), NumberUtils.createNumber("1.7976931348623157e+308"));
538 // Test with +2 in final digit (+1 does not cause roll-over to BigDecimal)
539 assertEquals(new BigDecimal("1.7976931348623159e+308"), NumberUtils.createNumber("1.7976931348623159e+308"));
540
541 assertEquals(Integer.valueOf(0x12345678), NumberUtils.createNumber("0x12345678"));
542 assertEquals(Long.valueOf(0x123456789L), NumberUtils.createNumber("0x123456789"));
543
544 assertEquals(Long.valueOf(0x7fffffffffffffffL), NumberUtils.createNumber("0x7fffffffffffffff"));
545 // Does not appear to be a way to create a literal BigInteger of this magnitude
546 assertEquals(new BigInteger("7fffffffffffffff0", 16), NumberUtils.createNumber("0x7fffffffffffffff0"));
547
548 assertEquals(Long.valueOf(0x7fffffffffffffffL), NumberUtils.createNumber("#7fffffffffffffff"));
549 assertEquals(new BigInteger("7fffffffffffffff0", 16), NumberUtils.createNumber("#7fffffffffffffff0"));
550
551 assertEquals(Integer.valueOf(017777777777), NumberUtils.createNumber("017777777777")); // 31 bits
552 assertEquals(Long.valueOf(037777777777L), NumberUtils.createNumber("037777777777")); // 32 bits
553
554 assertEquals(Long.valueOf(0777777777777777777777L), NumberUtils.createNumber("0777777777777777777777")); // 63 bits
555 assertEquals(new BigInteger("1777777777777777777777", 8), NumberUtils.createNumber("01777777777777777777777")); // 64 bits
556 }
557
558 @Test
559 public void testCreateFloat() {
560 assertEquals(Float.valueOf("1234.5"), NumberUtils.createFloat("1234.5"), "createFloat(String) failed");
561 assertNull(NumberUtils.createFloat(null), "createFloat(null) failed");
562 this.testCreateFloatFailure("");
563 this.testCreateFloatFailure(" ");
564 this.testCreateFloatFailure("\b\t\n\f\r");
350 @Test
351 public void testCreateBigDecimal() {
352 assertEquals(new BigDecimal("1234.5"), NumberUtils.createBigDecimal("1234.5"),
353 "createBigDecimal(String) failed");
354 assertNull(NumberUtils.createBigDecimal(null), "createBigDecimal(null) failed");
355 this.testCreateBigDecimalFailure("");
356 this.testCreateBigDecimalFailure(" ");
357 this.testCreateBigDecimalFailure("\b\t\n\f\r");
565358 // Funky whitespaces
566 this.testCreateFloatFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F");
567 }
568
569 protected void testCreateFloatFailure(final String str) {
570 assertThrows(
571 NumberFormatException.class,
572 () -> NumberUtils.createFloat(str), "createFloat(\"" + str + "\") should have failed.");
573 }
574
575 @Test
576 public void testCreateDouble() {
577 assertEquals(Double.valueOf("1234.5"), NumberUtils.createDouble("1234.5"), "createDouble(String) failed");
578 assertNull(NumberUtils.createDouble(null), "createDouble(null) failed");
579 this.testCreateDoubleFailure("");
580 this.testCreateDoubleFailure(" ");
581 this.testCreateDoubleFailure("\b\t\n\f\r");
582 // Funky whitespaces
583 this.testCreateDoubleFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F");
584 }
585
586 protected void testCreateDoubleFailure(final String str) {
587 assertThrows(
588 NumberFormatException.class,
589 () -> NumberUtils.createDouble(str),
590 "createDouble(\"" + str + "\") should have failed.");
591 }
592
593 @Test
594 public void testCreateInteger() {
595 assertEquals(Integer.valueOf("12345"), NumberUtils.createInteger("12345"), "createInteger(String) failed");
596 assertNull(NumberUtils.createInteger(null), "createInteger(null) failed");
597 this.testCreateIntegerFailure("");
598 this.testCreateIntegerFailure(" ");
599 this.testCreateIntegerFailure("\b\t\n\f\r");
600 // Funky whitespaces
601 this.testCreateIntegerFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F");
602 }
603
604 protected void testCreateIntegerFailure(final String str) {
605 assertThrows(
606 NumberFormatException.class,
607 () -> NumberUtils.createInteger(str),
608 "createInteger(\"" + str + "\") should have failed.");
609 }
610
611 @Test
612 public void testCreateLong() {
613 assertEquals(Long.valueOf("12345"), NumberUtils.createLong("12345"), "createLong(String) failed");
614 assertNull(NumberUtils.createLong(null), "createLong(null) failed");
615 this.testCreateLongFailure("");
616 this.testCreateLongFailure(" ");
617 this.testCreateLongFailure("\b\t\n\f\r");
618 // Funky whitespaces
619 this.testCreateLongFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F");
620 }
621
622 protected void testCreateLongFailure(final String str) {
623 assertThrows(
624 NumberFormatException.class,
625 () -> NumberUtils.createLong(str),
626 "createLong(\"" + str + "\") should have failed.");
359 this.testCreateBigDecimalFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F");
360 // sign alone not valid
361 this.testCreateBigDecimalFailure("-");
362 // comment in NumberUtils suggests some implementations may incorrectly allow this
363 this.testCreateBigDecimalFailure("--");
364 this.testCreateBigDecimalFailure("--0");
365 // sign alone not valid
366 this.testCreateBigDecimalFailure("+");
367 // in case this was also allowed by some JVMs
368 this.testCreateBigDecimalFailure("++");
369 this.testCreateBigDecimalFailure("++0");
370 }
371
372 protected void testCreateBigDecimalFailure(final String str) {
373 assertThrows(NumberFormatException.class, () -> NumberUtils.createBigDecimal(str),
374 "createBigDecimal(\"" + str + "\") should have failed.");
627375 }
628376
629377 @Test
648396 testCreateBigIntegerFailure("-#");
649397 testCreateBigIntegerFailure("0x");
650398 testCreateBigIntegerFailure("-0x");
399 // LANG-1645
400 assertEquals(new BigInteger("+FFFFFFFFFFFFFFFF", 16), NumberUtils.createBigInteger("+0xFFFFFFFFFFFFFFFF"));
401 assertEquals(new BigInteger("+FFFFFFFFFFFFFFFF", 16), NumberUtils.createBigInteger("+#FFFFFFFFFFFFFFFF"));
402 assertEquals(new BigInteger("+1234567", 8), NumberUtils.createBigInteger("+01234567"));
651403 }
652404
653405 protected void testCreateBigIntegerFailure(final String str) {
654 assertThrows(
655 NumberFormatException.class,
656 () -> NumberUtils.createBigInteger(str),
657 "createBigInteger(\"" + str + "\") should have failed.");
658 }
659
660 @Test
661 public void testCreateBigDecimal() {
662 assertEquals(new BigDecimal("1234.5"), NumberUtils.createBigDecimal("1234.5"), "createBigDecimal(String) failed");
663 assertNull(NumberUtils.createBigDecimal(null), "createBigDecimal(null) failed");
664 this.testCreateBigDecimalFailure("");
665 this.testCreateBigDecimalFailure(" ");
666 this.testCreateBigDecimalFailure("\b\t\n\f\r");
406 assertThrows(NumberFormatException.class, () -> NumberUtils.createBigInteger(str),
407 "createBigInteger(\"" + str + "\") should have failed.");
408 }
409
410 @Test
411 public void testCreateDouble() {
412 assertEquals(Double.valueOf("1234.5"), NumberUtils.createDouble("1234.5"), "createDouble(String) failed");
413 assertNull(NumberUtils.createDouble(null), "createDouble(null) failed");
414 this.testCreateDoubleFailure("");
415 this.testCreateDoubleFailure(" ");
416 this.testCreateDoubleFailure("\b\t\n\f\r");
667417 // Funky whitespaces
668 this.testCreateBigDecimalFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F");
669 this.testCreateBigDecimalFailure("-"); // sign alone not valid
670 this.testCreateBigDecimalFailure("--"); // comment in NumberUtils suggests some implementations may incorrectly allow this
671 this.testCreateBigDecimalFailure("--0");
672 this.testCreateBigDecimalFailure("+"); // sign alone not valid
673 this.testCreateBigDecimalFailure("++"); // in case this was also allowed by some JVMs
674 this.testCreateBigDecimalFailure("++0");
675 }
676
677 protected void testCreateBigDecimalFailure(final String str) {
678 assertThrows(
679 NumberFormatException.class,
680 () -> NumberUtils.createBigDecimal(str),
681 "createBigDecimal(\"" + str + "\") should have failed.");
682 }
683
684 // min/max tests
685 // ----------------------------------------------------------------------
686 @Test
687 public void testMinLong_nullArray() {
688 assertThrows(NullPointerException.class, () -> NumberUtils.min((long[]) null));
689 }
690
691 @Test
692 public void testMinLong_emptyArray() {
693 assertThrows(IllegalArgumentException.class, NumberUtils::min);
694 }
695
696 @Test
697 public void testMinLong() {
698 assertEquals(5, NumberUtils.min(5), "min(long[]) failed for array length 1");
699 assertEquals(6, NumberUtils.min(6, 9), "min(long[]) failed for array length 2");
700
701 assertEquals(-10, NumberUtils.min(-10, -5, 0, 5, 10));
702 assertEquals(-10, NumberUtils.min(-5, 0, -10, 5, 10));
703 }
704
705 @Test
706 public void testMinInt_nullArray() {
707 assertThrows(NullPointerException.class, () -> NumberUtils.min((int[]) null));
708 }
709
710 @Test
711 public void testMinInt_emptyArray() {
712 assertThrows(IllegalArgumentException.class, NumberUtils::min);
713 }
714
715 @Test
716 public void testMinInt() {
717 assertEquals(5, NumberUtils.min(5), "min(int[]) failed for array length 1");
718 assertEquals(6, NumberUtils.min(6, 9), "min(int[]) failed for array length 2");
719
720 assertEquals(-10, NumberUtils.min(-10, -5, 0, 5, 10));
721 assertEquals(-10, NumberUtils.min(-5, 0, -10, 5, 10));
722 }
723
724 @Test
725 public void testMinShort_nullArray() {
726 assertThrows(NullPointerException.class, () -> NumberUtils.min((short[]) null));
727 }
728
729 @Test
730 public void testMinShort_emptyArray() {
731 assertThrows(IllegalArgumentException.class, NumberUtils::min);
732 }
733
734 @Test
735 public void testMinShort() {
736 assertEquals(5, NumberUtils.min(5), "min(short[]) failed for array length 1");
737 assertEquals(6, NumberUtils.min(6, 9), "min(short[]) failed for array length 2");
738
739 assertEquals(-10, NumberUtils.min(-10, -5, 0, 5, 10));
740 assertEquals(-10, NumberUtils.min(-5, 0, -10, 5, 10));
741 }
742
743 @Test
744 public void testMinByte_nullArray() {
745 assertThrows(NullPointerException.class, () -> NumberUtils.min((byte[]) null));
746 }
747
748 @Test
749 public void testMinByte_emptyArray() {
750 assertThrows(IllegalArgumentException.class, NumberUtils::min);
751 }
752
753 @Test
754 public void testMinByte() {
755 assertEquals(5, NumberUtils.min(5), "min(byte[]) failed for array length 1");
756 assertEquals(6, NumberUtils.min(6, 9), "min(byte[]) failed for array length 2");
757
758 assertEquals(-10, NumberUtils.min(-10, -5, 0, 5, 10));
759 assertEquals(-10, NumberUtils.min(-5, 0, -10, 5, 10));
760 }
761
762 @Test
763 public void testMinDouble_nullArray() {
764 assertThrows(NullPointerException.class, () -> NumberUtils.min((double[]) null));
765 }
766
767 @Test
768 public void testMinDouble_emptyArray() {
769 assertThrows(IllegalArgumentException.class, NumberUtils::min);
770 }
771
772 @Test
773 public void testMinDouble() {
774 assertEquals(5.12, NumberUtils.min(5.12), "min(double[]) failed for array length 1");
775 assertEquals(6.23, NumberUtils.min(6.23, 9.34), "min(double[]) failed for array length 2");
776 assertEquals(-10.45, NumberUtils.min(-10.45, -5.56, 0, 5.67, 10.78), "min(double[]) failed for array length 5");
777 assertEquals(-10, NumberUtils.min(-10, -5, 0, 5, 10), 0.0001);
778 assertEquals(-10, NumberUtils.min(-5, 0, -10, 5, 10), 0.0001);
779 }
780
781 @Test
782 public void testMinFloat_nullArray() {
783 assertThrows(NullPointerException.class, () -> NumberUtils.min((float[]) null));
784 }
785
786 @Test
787 public void testMinFloat_emptyArray() {
788 assertThrows(IllegalArgumentException.class, NumberUtils::min);
789 }
790
791 @Test
792 public void testMinFloat() {
793 assertEquals(5.9f, NumberUtils.min(5.9f), "min(float[]) failed for array length 1");
794 assertEquals(6.8f, NumberUtils.min(6.8f, 9.7f), "min(float[]) failed for array length 2");
795 assertEquals(-10.6f, NumberUtils.min(-10.6f, -5.5f, 0, 5.4f, 10.3f), "min(float[]) failed for array length 5");
796 assertEquals(-10, NumberUtils.min(-10, -5, 0, 5, 10), 0.0001f);
797 assertEquals(-10, NumberUtils.min(-5, 0, -10, 5, 10), 0.0001f);
798 }
799
800 @Test
801 public void testMaxLong_nullArray() {
802 assertThrows(NullPointerException.class, () -> NumberUtils.max((long[]) null));
803 }
804
805 @Test
806 public void testMaxLong_emptyArray() {
807 assertThrows(IllegalArgumentException.class, NumberUtils::max);
808 }
809
810 @Test
811 public void testMaxLong() {
812 assertEquals(5, NumberUtils.max(5), "max(long[]) failed for array length 1");
813 assertEquals(9, NumberUtils.max(6, 9), "max(long[]) failed for array length 2");
814 assertEquals(10, NumberUtils.max(-10, -5, 0, 5, 10), "max(long[]) failed for array length 5");
815 assertEquals(10, NumberUtils.max(-10, -5, 0, 5, 10));
816 assertEquals(10, NumberUtils.max(-5, 0, 10, 5, -10));
817 }
818
819 @Test
820 public void testMaxInt_nullArray() {
821 assertThrows(NullPointerException.class, () -> NumberUtils.max((int[]) null));
822 }
823
824 @Test
825 public void testMaxInt_emptyArray() {
826 assertThrows(IllegalArgumentException.class, NumberUtils::max);
827 }
828
829 @Test
830 public void testMaxInt() {
831 assertEquals(5, NumberUtils.max(5), "max(int[]) failed for array length 1");
832 assertEquals(9, NumberUtils.max(6, 9), "max(int[]) failed for array length 2");
833 assertEquals(10, NumberUtils.max(-10, -5, 0, 5, 10), "max(int[]) failed for array length 5");
834 assertEquals(10, NumberUtils.max(-10, -5, 0, 5, 10));
835 assertEquals(10, NumberUtils.max(-5, 0, 10, 5, -10));
836 }
837
838 @Test
839 public void testMaxShort_nullArray() {
840 assertThrows(NullPointerException.class, () -> NumberUtils.max((short[]) null));
841 }
842
843 @Test
844 public void testMaxShort_emptyArray() {
845 assertThrows(IllegalArgumentException.class, NumberUtils::max);
846 }
847
848 @Test
849 public void testMaxShort() {
850 assertEquals(5, NumberUtils.max(5), "max(short[]) failed for array length 1");
851 assertEquals(9, NumberUtils.max(6, 9), "max(short[]) failed for array length 2");
852 assertEquals(10, NumberUtils.max(-10, -5, 0, 5, 10), "max(short[]) failed for array length 5");
853 assertEquals(10, NumberUtils.max(-10, -5, 0, 5, 10));
854 assertEquals(10, NumberUtils.max(-5, 0, 10, 5, -10));
855 }
856
857 @Test
858 public void testMaxByte_nullArray() {
859 assertThrows(NullPointerException.class, () -> NumberUtils.max((byte[]) null));
860 }
861
862 @Test
863 public void testMaxByte_emptyArray() {
864 assertThrows(IllegalArgumentException.class, NumberUtils::max);
865 }
866
867 @Test
868 public void testMaxByte() {
869 assertEquals(5, NumberUtils.max(5), "max(byte[]) failed for array length 1");
870 assertEquals(9, NumberUtils.max(6, 9), "max(byte[]) failed for array length 2");
871 assertEquals(10, NumberUtils.max(-10, -5, 0, 5, 10), "max(byte[]) failed for array length 5");
872 assertEquals(10, NumberUtils.max(-10, -5, 0, 5, 10));
873 assertEquals(10, NumberUtils.max(-5, 0, 10, 5, -10));
874 }
875
876 @Test
877 public void testMaxDouble_nullArray() {
878 assertThrows(NullPointerException.class, () -> NumberUtils.max((double[]) null));
879 }
880
881 @Test
882 public void testMaxDouble_emptyArray() {
883 assertThrows(IllegalArgumentException.class, NumberUtils::max);
884 }
885
886 @Test
887 public void testMaxDouble() {
888 final double[] d = null;
889 assertThrows(
890 NullPointerException.class, () -> NumberUtils.max(d), "No exception was thrown for null input.");
891
892 assertThrows(
893 IllegalArgumentException.class,
894 NumberUtils::max,
895 "No exception was thrown for empty input.");
896
897 assertEquals(5.1f, NumberUtils.max(5.1f), "max(double[]) failed for array length 1");
898 assertEquals(9.2f, NumberUtils.max(6.3f, 9.2f), "max(double[]) failed for array length 2");
899 assertEquals(10.4f, NumberUtils.max(-10.5f, -5.6f, 0, 5.7f, 10.4f), "max(double[]) failed for float length 5");
900 assertEquals(10, NumberUtils.max(-10, -5, 0, 5, 10), 0.0001);
901 assertEquals(10, NumberUtils.max(-5, 0, 10, 5, -10), 0.0001);
902 }
903
904 @Test
905 public void testMaxFloat_nullArray() {
906 assertThrows(NullPointerException.class, () -> NumberUtils.max((float[]) null));
907 }
908
909 @Test
910 public void testMaxFloat_emptyArray() {
911 assertThrows(IllegalArgumentException.class, NumberUtils::max);
912 }
913
914 @Test
915 public void testMaxFloat() {
916 assertEquals(5.1f, NumberUtils.max(5.1f), "max(float[]) failed for array length 1");
917 assertEquals(9.2f, NumberUtils.max(6.3f, 9.2f), "max(float[]) failed for array length 2");
918 assertEquals(10.4f, NumberUtils.max(-10.5f, -5.6f, 0, 5.7f, 10.4f), "max(float[]) failed for float length 5");
919 assertEquals(10, NumberUtils.max(-10, -5, 0, 5, 10), 0.0001f);
920 assertEquals(10, NumberUtils.max(-5, 0, 10, 5, -10), 0.0001f);
921 }
922
923 @Test
924 public void testMinimumLong() {
925 assertEquals(12345L, NumberUtils.min(12345L, 12345L + 1L, 12345L + 2L), "minimum(long, long, long) 1 failed");
926 assertEquals(12345L, NumberUtils.min(12345L + 1L, 12345L, 12345 + 2L), "minimum(long, long, long) 2 failed");
927 assertEquals(12345L, NumberUtils.min(12345L + 1L, 12345L + 2L, 12345L), "minimum(long, long, long) 3 failed");
928 assertEquals(12345L, NumberUtils.min(12345L + 1L, 12345L, 12345L), "minimum(long, long, long) 4 failed");
929 assertEquals(12345L, NumberUtils.min(12345L, 12345L, 12345L), "minimum(long, long, long) 5 failed");
930 }
931
932 @Test
933 public void testMinimumInt() {
934 assertEquals(12345, NumberUtils.min(12345, 12345 + 1, 12345 + 2), "minimum(int, int, int) 1 failed");
935 assertEquals(12345, NumberUtils.min(12345 + 1, 12345, 12345 + 2), "minimum(int, int, int) 2 failed");
936 assertEquals(12345, NumberUtils.min(12345 + 1, 12345 + 2, 12345), "minimum(int, int, int) 3 failed");
937 assertEquals(12345, NumberUtils.min(12345 + 1, 12345, 12345), "minimum(int, int, int) 4 failed");
938 assertEquals(12345, NumberUtils.min(12345, 12345, 12345), "minimum(int, int, int) 5 failed");
939 }
940
941 @Test
942 public void testMinimumShort() {
943 final short low = 1234;
944 final short mid = 1234 + 1;
945 final short high = 1234 + 2;
946 assertEquals(low, NumberUtils.min(low, mid, high), "minimum(short, short, short) 1 failed");
947 assertEquals(low, NumberUtils.min(mid, low, high), "minimum(short, short, short) 2 failed");
948 assertEquals(low, NumberUtils.min(mid, high, low), "minimum(short, short, short) 3 failed");
949 assertEquals(low, NumberUtils.min(low, mid, low), "minimum(short, short, short) 4 failed");
950 }
951
952 @Test
953 public void testMinimumByte() {
954 final byte low = 123;
955 final byte mid = 123 + 1;
956 final byte high = 123 + 2;
957 assertEquals(low, NumberUtils.min(low, mid, high), "minimum(byte, byte, byte) 1 failed");
958 assertEquals(low, NumberUtils.min(mid, low, high), "minimum(byte, byte, byte) 2 failed");
959 assertEquals(low, NumberUtils.min(mid, high, low), "minimum(byte, byte, byte) 3 failed");
960 assertEquals(low, NumberUtils.min(low, mid, low), "minimum(byte, byte, byte) 4 failed");
961 }
962
963 @Test
964 public void testMinimumDouble() {
965 final double low = 12.3;
966 final double mid = 12.3 + 1;
967 final double high = 12.3 + 2;
968 assertEquals(low, NumberUtils.min(low, mid, high), 0.0001);
969 assertEquals(low, NumberUtils.min(mid, low, high), 0.0001);
970 assertEquals(low, NumberUtils.min(mid, high, low), 0.0001);
971 assertEquals(low, NumberUtils.min(low, mid, low), 0.0001);
972 assertEquals(mid, NumberUtils.min(high, mid, high), 0.0001);
973 }
974
975 @Test
976 public void testMinimumFloat() {
977 final float low = 12.3f;
978 final float mid = 12.3f + 1;
979 final float high = 12.3f + 2;
980 assertEquals(low, NumberUtils.min(low, mid, high), 0.0001f);
981 assertEquals(low, NumberUtils.min(mid, low, high), 0.0001f);
982 assertEquals(low, NumberUtils.min(mid, high, low), 0.0001f);
983 assertEquals(low, NumberUtils.min(low, mid, low), 0.0001f);
984 assertEquals(mid, NumberUtils.min(high, mid, high), 0.0001f);
985 }
986
987 @Test
988 public void testMaximumLong() {
989 assertEquals(12345L, NumberUtils.max(12345L, 12345L - 1L, 12345L - 2L), "maximum(long, long, long) 1 failed");
990 assertEquals(12345L, NumberUtils.max(12345L - 1L, 12345L, 12345L - 2L), "maximum(long, long, long) 2 failed");
991 assertEquals(12345L, NumberUtils.max(12345L - 1L, 12345L - 2L, 12345L), "maximum(long, long, long) 3 failed");
992 assertEquals(12345L, NumberUtils.max(12345L - 1L, 12345L, 12345L), "maximum(long, long, long) 4 failed");
993 assertEquals(12345L, NumberUtils.max(12345L, 12345L, 12345L), "maximum(long, long, long) 5 failed");
994 }
995
996 @Test
997 public void testMaximumInt() {
998 assertEquals(12345, NumberUtils.max(12345, 12345 - 1, 12345 - 2), "maximum(int, int, int) 1 failed");
999 assertEquals(12345, NumberUtils.max(12345 - 1, 12345, 12345 - 2), "maximum(int, int, int) 2 failed");
1000 assertEquals(12345, NumberUtils.max(12345 - 1, 12345 - 2, 12345), "maximum(int, int, int) 3 failed");
1001 assertEquals(12345, NumberUtils.max(12345 - 1, 12345, 12345), "maximum(int, int, int) 4 failed");
1002 assertEquals(12345, NumberUtils.max(12345, 12345, 12345), "maximum(int, int, int) 5 failed");
1003 }
1004
1005 @Test
1006 public void testMaximumShort() {
1007 final short low = 1234;
1008 final short mid = 1234 + 1;
1009 final short high = 1234 + 2;
1010 assertEquals(high, NumberUtils.max(low, mid, high), "maximum(short, short, short) 1 failed");
1011 assertEquals(high, NumberUtils.max(mid, low, high), "maximum(short, short, short) 2 failed");
1012 assertEquals(high, NumberUtils.max(mid, high, low), "maximum(short, short, short) 3 failed");
1013 assertEquals(high, NumberUtils.max(high, mid, high), "maximum(short, short, short) 4 failed");
1014 }
1015
1016 @Test
1017 public void testMaximumByte() {
1018 final byte low = 123;
1019 final byte mid = 123 + 1;
1020 final byte high = 123 + 2;
1021 assertEquals(high, NumberUtils.max(low, mid, high), "maximum(byte, byte, byte) 1 failed");
1022 assertEquals(high, NumberUtils.max(mid, low, high), "maximum(byte, byte, byte) 2 failed");
1023 assertEquals(high, NumberUtils.max(mid, high, low), "maximum(byte, byte, byte) 3 failed");
1024 assertEquals(high, NumberUtils.max(high, mid, high), "maximum(byte, byte, byte) 4 failed");
1025 }
1026
1027 @Test
1028 public void testMaximumDouble() {
1029 final double low = 12.3;
1030 final double mid = 12.3 + 1;
1031 final double high = 12.3 + 2;
1032 assertEquals(high, NumberUtils.max(low, mid, high), 0.0001);
1033 assertEquals(high, NumberUtils.max(mid, low, high), 0.0001);
1034 assertEquals(high, NumberUtils.max(mid, high, low), 0.0001);
1035 assertEquals(mid, NumberUtils.max(low, mid, low), 0.0001);
1036 assertEquals(high, NumberUtils.max(high, mid, high), 0.0001);
1037 }
1038
1039 @Test
1040 public void testMaximumFloat() {
1041 final float low = 12.3f;
1042 final float mid = 12.3f + 1;
1043 final float high = 12.3f + 2;
1044 assertEquals(high, NumberUtils.max(low, mid, high), 0.0001f);
1045 assertEquals(high, NumberUtils.max(mid, low, high), 0.0001f);
1046 assertEquals(high, NumberUtils.max(mid, high, low), 0.0001f);
1047 assertEquals(mid, NumberUtils.max(low, mid, low), 0.0001f);
1048 assertEquals(high, NumberUtils.max(high, mid, high), 0.0001f);
1049 }
1050
1051 // Testing JDK against old Lang functionality
1052 @Test
1053 public void testCompareDouble() {
1054 assertEquals(0, Double.compare(Double.NaN, Double.NaN));
1055 assertEquals(Double.compare(Double.NaN, Double.POSITIVE_INFINITY), +1);
1056 assertEquals(Double.compare(Double.NaN, Double.MAX_VALUE), +1);
1057 assertEquals(Double.compare(Double.NaN, 1.2d), +1);
1058 assertEquals(Double.compare(Double.NaN, 0.0d), +1);
1059 assertEquals(Double.compare(Double.NaN, -0.0d), +1);
1060 assertEquals(Double.compare(Double.NaN, -1.2d), +1);
1061 assertEquals(Double.compare(Double.NaN, -Double.MAX_VALUE), +1);
1062 assertEquals(Double.compare(Double.NaN, Double.NEGATIVE_INFINITY), +1);
1063
1064 assertEquals(Double.compare(Double.POSITIVE_INFINITY, Double.NaN), -1);
1065 assertEquals(0, Double.compare(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY));
1066 assertEquals(Double.compare(Double.POSITIVE_INFINITY, Double.MAX_VALUE), +1);
1067 assertEquals(Double.compare(Double.POSITIVE_INFINITY, 1.2d), +1);
1068 assertEquals(Double.compare(Double.POSITIVE_INFINITY, 0.0d), +1);
1069 assertEquals(Double.compare(Double.POSITIVE_INFINITY, -0.0d), +1);
1070 assertEquals(Double.compare(Double.POSITIVE_INFINITY, -1.2d), +1);
1071 assertEquals(Double.compare(Double.POSITIVE_INFINITY, -Double.MAX_VALUE), +1);
1072 assertEquals(Double.compare(Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY), +1);
1073
1074 assertEquals(Double.compare(Double.MAX_VALUE, Double.NaN), -1);
1075 assertEquals(Double.compare(Double.MAX_VALUE, Double.POSITIVE_INFINITY), -1);
1076 assertEquals(0, Double.compare(Double.MAX_VALUE, Double.MAX_VALUE));
1077 assertEquals(Double.compare(Double.MAX_VALUE, 1.2d), +1);
1078 assertEquals(Double.compare(Double.MAX_VALUE, 0.0d), +1);
1079 assertEquals(Double.compare(Double.MAX_VALUE, -0.0d), +1);
1080 assertEquals(Double.compare(Double.MAX_VALUE, -1.2d), +1);
1081 assertEquals(Double.compare(Double.MAX_VALUE, -Double.MAX_VALUE), +1);
1082 assertEquals(Double.compare(Double.MAX_VALUE, Double.NEGATIVE_INFINITY), +1);
1083
1084 assertEquals(Double.compare(1.2d, Double.NaN), -1);
1085 assertEquals(Double.compare(1.2d, Double.POSITIVE_INFINITY), -1);
1086 assertEquals(Double.compare(1.2d, Double.MAX_VALUE), -1);
1087 assertEquals(0, Double.compare(1.2d, 1.2d));
1088 assertEquals(Double.compare(1.2d, 0.0d), +1);
1089 assertEquals(Double.compare(1.2d, -0.0d), +1);
1090 assertEquals(Double.compare(1.2d, -1.2d), +1);
1091 assertEquals(Double.compare(1.2d, -Double.MAX_VALUE), +1);
1092 assertEquals(Double.compare(1.2d, Double.NEGATIVE_INFINITY), +1);
1093
1094 assertEquals(Double.compare(0.0d, Double.NaN), -1);
1095 assertEquals(Double.compare(0.0d, Double.POSITIVE_INFINITY), -1);
1096 assertEquals(Double.compare(0.0d, Double.MAX_VALUE), -1);
1097 assertEquals(Double.compare(0.0d, 1.2d), -1);
1098 assertEquals(0, Double.compare(0.0d, 0.0d));
1099 assertEquals(Double.compare(0.0d, -0.0d), +1);
1100 assertEquals(Double.compare(0.0d, -1.2d), +1);
1101 assertEquals(Double.compare(0.0d, -Double.MAX_VALUE), +1);
1102 assertEquals(Double.compare(0.0d, Double.NEGATIVE_INFINITY), +1);
1103
1104 assertEquals(Double.compare(-0.0d, Double.NaN), -1);
1105 assertEquals(Double.compare(-0.0d, Double.POSITIVE_INFINITY), -1);
1106 assertEquals(Double.compare(-0.0d, Double.MAX_VALUE), -1);
1107 assertEquals(Double.compare(-0.0d, 1.2d), -1);
1108 assertEquals(Double.compare(-0.0d, 0.0d), -1);
1109 assertEquals(0, Double.compare(-0.0d, -0.0d));
1110 assertEquals(Double.compare(-0.0d, -1.2d), +1);
1111 assertEquals(Double.compare(-0.0d, -Double.MAX_VALUE), +1);
1112 assertEquals(Double.compare(-0.0d, Double.NEGATIVE_INFINITY), +1);
1113
1114 assertEquals(Double.compare(-1.2d, Double.NaN), -1);
1115 assertEquals(Double.compare(-1.2d, Double.POSITIVE_INFINITY), -1);
1116 assertEquals(Double.compare(-1.2d, Double.MAX_VALUE), -1);
1117 assertEquals(Double.compare(-1.2d, 1.2d), -1);
1118 assertEquals(Double.compare(-1.2d, 0.0d), -1);
1119 assertEquals(Double.compare(-1.2d, -0.0d), -1);
1120 assertEquals(0, Double.compare(-1.2d, -1.2d));
1121 assertEquals(Double.compare(-1.2d, -Double.MAX_VALUE), +1);
1122 assertEquals(Double.compare(-1.2d, Double.NEGATIVE_INFINITY), +1);
1123
1124 assertEquals(Double.compare(-Double.MAX_VALUE, Double.NaN), -1);
1125 assertEquals(Double.compare(-Double.MAX_VALUE, Double.POSITIVE_INFINITY), -1);
1126 assertEquals(Double.compare(-Double.MAX_VALUE, Double.MAX_VALUE), -1);
1127 assertEquals(Double.compare(-Double.MAX_VALUE, 1.2d), -1);
1128 assertEquals(Double.compare(-Double.MAX_VALUE, 0.0d), -1);
1129 assertEquals(Double.compare(-Double.MAX_VALUE, -0.0d), -1);
1130 assertEquals(Double.compare(-Double.MAX_VALUE, -1.2d), -1);
1131 assertEquals(0, Double.compare(-Double.MAX_VALUE, -Double.MAX_VALUE));
1132 assertEquals(Double.compare(-Double.MAX_VALUE, Double.NEGATIVE_INFINITY), +1);
1133
1134 assertEquals(Double.compare(Double.NEGATIVE_INFINITY, Double.NaN), -1);
1135 assertEquals(Double.compare(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY), -1);
1136 assertEquals(Double.compare(Double.NEGATIVE_INFINITY, Double.MAX_VALUE), -1);
1137 assertEquals(Double.compare(Double.NEGATIVE_INFINITY, 1.2d), -1);
1138 assertEquals(Double.compare(Double.NEGATIVE_INFINITY, 0.0d), -1);
1139 assertEquals(Double.compare(Double.NEGATIVE_INFINITY, -0.0d), -1);
1140 assertEquals(Double.compare(Double.NEGATIVE_INFINITY, -1.2d), -1);
1141 assertEquals(Double.compare(Double.NEGATIVE_INFINITY, -Double.MAX_VALUE), -1);
1142 assertEquals(0, Double.compare(Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY));
1143 }
1144
1145 @Test
1146 public void testCompareFloat() {
1147 assertEquals(0, Float.compare(Float.NaN, Float.NaN));
1148 assertEquals(Float.compare(Float.NaN, Float.POSITIVE_INFINITY), +1);
1149 assertEquals(Float.compare(Float.NaN, Float.MAX_VALUE), +1);
1150 assertEquals(Float.compare(Float.NaN, 1.2f), +1);
1151 assertEquals(Float.compare(Float.NaN, 0.0f), +1);
1152 assertEquals(Float.compare(Float.NaN, -0.0f), +1);
1153 assertEquals(Float.compare(Float.NaN, -1.2f), +1);
1154 assertEquals(Float.compare(Float.NaN, -Float.MAX_VALUE), +1);
1155 assertEquals(Float.compare(Float.NaN, Float.NEGATIVE_INFINITY), +1);
1156
1157 assertEquals(Float.compare(Float.POSITIVE_INFINITY, Float.NaN), -1);
1158 assertEquals(0, Float.compare(Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY));
1159 assertEquals(Float.compare(Float.POSITIVE_INFINITY, Float.MAX_VALUE), +1);
1160 assertEquals(Float.compare(Float.POSITIVE_INFINITY, 1.2f), +1);
1161 assertEquals(Float.compare(Float.POSITIVE_INFINITY, 0.0f), +1);
1162 assertEquals(Float.compare(Float.POSITIVE_INFINITY, -0.0f), +1);
1163 assertEquals(Float.compare(Float.POSITIVE_INFINITY, -1.2f), +1);
1164 assertEquals(Float.compare(Float.POSITIVE_INFINITY, -Float.MAX_VALUE), +1);
1165 assertEquals(Float.compare(Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY), +1);
1166
1167 assertEquals(Float.compare(Float.MAX_VALUE, Float.NaN), -1);
1168 assertEquals(Float.compare(Float.MAX_VALUE, Float.POSITIVE_INFINITY), -1);
1169 assertEquals(0, Float.compare(Float.MAX_VALUE, Float.MAX_VALUE));
1170 assertEquals(Float.compare(Float.MAX_VALUE, 1.2f), +1);
1171 assertEquals(Float.compare(Float.MAX_VALUE, 0.0f), +1);
1172 assertEquals(Float.compare(Float.MAX_VALUE, -0.0f), +1);
1173 assertEquals(Float.compare(Float.MAX_VALUE, -1.2f), +1);
1174 assertEquals(Float.compare(Float.MAX_VALUE, -Float.MAX_VALUE), +1);
1175 assertEquals(Float.compare(Float.MAX_VALUE, Float.NEGATIVE_INFINITY), +1);
1176
1177 assertEquals(Float.compare(1.2f, Float.NaN), -1);
1178 assertEquals(Float.compare(1.2f, Float.POSITIVE_INFINITY), -1);
1179 assertEquals(Float.compare(1.2f, Float.MAX_VALUE), -1);
1180 assertEquals(0, Float.compare(1.2f, 1.2f));
1181 assertEquals(Float.compare(1.2f, 0.0f), +1);
1182 assertEquals(Float.compare(1.2f, -0.0f), +1);
1183 assertEquals(Float.compare(1.2f, -1.2f), +1);
1184 assertEquals(Float.compare(1.2f, -Float.MAX_VALUE), +1);
1185 assertEquals(Float.compare(1.2f, Float.NEGATIVE_INFINITY), +1);
1186
1187 assertEquals(Float.compare(0.0f, Float.NaN), -1);
1188 assertEquals(Float.compare(0.0f, Float.POSITIVE_INFINITY), -1);
1189 assertEquals(Float.compare(0.0f, Float.MAX_VALUE), -1);
1190 assertEquals(Float.compare(0.0f, 1.2f), -1);
1191 assertEquals(0, Float.compare(0.0f, 0.0f));
1192 assertEquals(Float.compare(0.0f, -0.0f), +1);
1193 assertEquals(Float.compare(0.0f, -1.2f), +1);
1194 assertEquals(Float.compare(0.0f, -Float.MAX_VALUE), +1);
1195 assertEquals(Float.compare(0.0f, Float.NEGATIVE_INFINITY), +1);
1196
1197 assertEquals(Float.compare(-0.0f, Float.NaN), -1);
1198 assertEquals(Float.compare(-0.0f, Float.POSITIVE_INFINITY), -1);
1199 assertEquals(Float.compare(-0.0f, Float.MAX_VALUE), -1);
1200 assertEquals(Float.compare(-0.0f, 1.2f), -1);
1201 assertEquals(Float.compare(-0.0f, 0.0f), -1);
1202 assertEquals(0, Float.compare(-0.0f, -0.0f));
1203 assertEquals(Float.compare(-0.0f, -1.2f), +1);
1204 assertEquals(Float.compare(-0.0f, -Float.MAX_VALUE), +1);
1205 assertEquals(Float.compare(-0.0f, Float.NEGATIVE_INFINITY), +1);
1206
1207 assertEquals(Float.compare(-1.2f, Float.NaN), -1);
1208 assertEquals(Float.compare(-1.2f, Float.POSITIVE_INFINITY), -1);
1209 assertEquals(Float.compare(-1.2f, Float.MAX_VALUE), -1);
1210 assertEquals(Float.compare(-1.2f, 1.2f), -1);
1211 assertEquals(Float.compare(-1.2f, 0.0f), -1);
1212 assertEquals(Float.compare(-1.2f, -0.0f), -1);
1213 assertEquals(0, Float.compare(-1.2f, -1.2f));
1214 assertEquals(Float.compare(-1.2f, -Float.MAX_VALUE), +1);
1215 assertEquals(Float.compare(-1.2f, Float.NEGATIVE_INFINITY), +1);
1216
1217 assertEquals(Float.compare(-Float.MAX_VALUE, Float.NaN), -1);
1218 assertEquals(Float.compare(-Float.MAX_VALUE, Float.POSITIVE_INFINITY), -1);
1219 assertEquals(Float.compare(-Float.MAX_VALUE, Float.MAX_VALUE), -1);
1220 assertEquals(Float.compare(-Float.MAX_VALUE, 1.2f), -1);
1221 assertEquals(Float.compare(-Float.MAX_VALUE, 0.0f), -1);
1222 assertEquals(Float.compare(-Float.MAX_VALUE, -0.0f), -1);
1223 assertEquals(Float.compare(-Float.MAX_VALUE, -1.2f), -1);
1224 assertEquals(0, Float.compare(-Float.MAX_VALUE, -Float.MAX_VALUE));
1225 assertEquals(Float.compare(-Float.MAX_VALUE, Float.NEGATIVE_INFINITY), +1);
1226
1227 assertEquals(Float.compare(Float.NEGATIVE_INFINITY, Float.NaN), -1);
1228 assertEquals(Float.compare(Float.NEGATIVE_INFINITY, Float.POSITIVE_INFINITY), -1);
1229 assertEquals(Float.compare(Float.NEGATIVE_INFINITY, Float.MAX_VALUE), -1);
1230 assertEquals(Float.compare(Float.NEGATIVE_INFINITY, 1.2f), -1);
1231 assertEquals(Float.compare(Float.NEGATIVE_INFINITY, 0.0f), -1);
1232 assertEquals(Float.compare(Float.NEGATIVE_INFINITY, -0.0f), -1);
1233 assertEquals(Float.compare(Float.NEGATIVE_INFINITY, -1.2f), -1);
1234 assertEquals(Float.compare(Float.NEGATIVE_INFINITY, -Float.MAX_VALUE), -1);
1235 assertEquals(0, Float.compare(Float.NEGATIVE_INFINITY, Float.NEGATIVE_INFINITY));
1236 }
1237
1238 @Test
1239 public void testIsDigits() {
1240 assertFalse(NumberUtils.isDigits(null), "isDigits(null) failed");
1241 assertFalse(NumberUtils.isDigits(""), "isDigits('') failed");
1242 assertTrue(NumberUtils.isDigits("12345"), "isDigits(String) failed");
1243 assertFalse(NumberUtils.isDigits("1234.5"), "isDigits(String) neg 1 failed");
1244 assertFalse(NumberUtils.isDigits("1ab"), "isDigits(String) neg 3 failed");
1245 assertFalse(NumberUtils.isDigits("abc"), "isDigits(String) neg 4 failed");
1246 }
1247
1248 /**
1249 * Tests isCreatable(String) and tests that createNumber(String) returns
1250 * a valid number iff isCreatable(String) returns false.
418 this.testCreateDoubleFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F");
419 }
420
421 protected void testCreateDoubleFailure(final String str) {
422 assertThrows(NumberFormatException.class, () -> NumberUtils.createDouble(str),
423 "createDouble(\"" + str + "\") should have failed.");
424 }
425
426 @Test
427 public void testCreateFloat() {
428 assertEquals(Float.valueOf("1234.5"), NumberUtils.createFloat("1234.5"), "createFloat(String) failed");
429 assertNull(NumberUtils.createFloat(null), "createFloat(null) failed");
430 this.testCreateFloatFailure("");
431 this.testCreateFloatFailure(" ");
432 this.testCreateFloatFailure("\b\t\n\f\r");
433 // Funky whitespaces
434 this.testCreateFloatFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F");
435 }
436
437 protected void testCreateFloatFailure(final String str) {
438 assertThrows(NumberFormatException.class, () -> NumberUtils.createFloat(str),
439 "createFloat(\"" + str + "\") should have failed.");
440 }
441
442 @Test
443 public void testCreateInteger() {
444 assertEquals(Integer.valueOf("12345"), NumberUtils.createInteger("12345"), "createInteger(String) failed");
445 assertNull(NumberUtils.createInteger(null), "createInteger(null) failed");
446 this.testCreateIntegerFailure("");
447 this.testCreateIntegerFailure(" ");
448 this.testCreateIntegerFailure("\b\t\n\f\r");
449 // Funky whitespaces
450 this.testCreateIntegerFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F");
451 // LANG-1645
452 assertEquals(Integer.decode("+0xF"), NumberUtils.createInteger("+0xF"));
453 }
454
455 protected void testCreateIntegerFailure(final String str) {
456 assertThrows(NumberFormatException.class, () -> NumberUtils.createInteger(str),
457 "createInteger(\"" + str + "\") should have failed.");
458 }
459
460 @Test
461 public void testCreateLong() {
462 assertEquals(Long.valueOf("12345"), NumberUtils.createLong("12345"), "createLong(String) failed");
463 assertNull(NumberUtils.createLong(null), "createLong(null) failed");
464 this.testCreateLongFailure("");
465 this.testCreateLongFailure(" ");
466 this.testCreateLongFailure("\b\t\n\f\r");
467 // Funky whitespaces
468 this.testCreateLongFailure("\u00A0\uFEFF\u000B\u000C\u001C\u001D\u001E\u001F");
469 // LANG-1645
470 assertEquals(Long.decode("+0xFFFFFFFF"), NumberUtils.createLong("+0xFFFFFFFF"));
471 }
472
473 protected void testCreateLongFailure(final String str) {
474 assertThrows(NumberFormatException.class, () -> NumberUtils.createLong(str),
475 "createLong(\"" + str + "\") should have failed.");
476 }
477
478 @Test
479 public void testCreateNumber() {
480 // a lot of things can go wrong
481 assertEquals(Float.valueOf("1234.5"), NumberUtils.createNumber("1234.5"), "createNumber(String) 1 failed");
482 assertEquals(Integer.valueOf("12345"), NumberUtils.createNumber("12345"), "createNumber(String) 2 failed");
483 assertEquals(Double.valueOf("1234.5"), NumberUtils.createNumber("1234.5D"), "createNumber(String) 3 failed");
484 assertEquals(Double.valueOf("1234.5"), NumberUtils.createNumber("1234.5d"), "createNumber(String) 3 failed");
485 assertEquals(Float.valueOf("1234.5"), NumberUtils.createNumber("1234.5F"), "createNumber(String) 4 failed");
486 assertEquals(Float.valueOf("1234.5"), NumberUtils.createNumber("1234.5f"), "createNumber(String) 4 failed");
487 assertEquals(Long.valueOf(Integer.MAX_VALUE + 1L), NumberUtils.createNumber("" + (Integer.MAX_VALUE + 1L)),
488 "createNumber(String) 5 failed");
489 assertEquals(Long.valueOf(12345), NumberUtils.createNumber("12345L"), "createNumber(String) 6 failed");
490 assertEquals(Long.valueOf(12345), NumberUtils.createNumber("12345l"), "createNumber(String) 6 failed");
491 assertEquals(Float.valueOf("-1234.5"), NumberUtils.createNumber("-1234.5"), "createNumber(String) 7 failed");
492 assertEquals(Integer.valueOf("-12345"), NumberUtils.createNumber("-12345"), "createNumber(String) 8 failed");
493 assertEquals(0xFADE, NumberUtils.createNumber("0xFADE").intValue(), "createNumber(String) 9a failed");
494 assertEquals(0xFADE, NumberUtils.createNumber("0Xfade").intValue(), "createNumber(String) 9b failed");
495 assertEquals(-0xFADE, NumberUtils.createNumber("-0xFADE").intValue(), "createNumber(String) 10a failed");
496 assertEquals(-0xFADE, NumberUtils.createNumber("-0Xfade").intValue(), "createNumber(String) 10b failed");
497 assertEquals(Double.valueOf("1.1E200"), NumberUtils.createNumber("1.1E200"), "createNumber(String) 11 failed");
498 assertEquals(Float.valueOf("1.1E20"), NumberUtils.createNumber("1.1E20"), "createNumber(String) 12 failed");
499 assertEquals(Double.valueOf("-1.1E200"), NumberUtils.createNumber("-1.1E200"),
500 "createNumber(String) 13 failed");
501 assertEquals(Double.valueOf("1.1E-200"), NumberUtils.createNumber("1.1E-200"),
502 "createNumber(String) 14 failed");
503 assertNull(NumberUtils.createNumber(null), "createNumber(null) failed");
504 assertEquals(new BigInteger("12345678901234567890"), NumberUtils.createNumber("12345678901234567890L"),
505 "createNumber(String) failed");
506
507 assertEquals(new BigDecimal("1.1E-700"), NumberUtils.createNumber("1.1E-700F"),
508 "createNumber(String) 15 failed");
509
510 assertEquals(Long.valueOf("10" + Integer.MAX_VALUE), NumberUtils.createNumber("10" + Integer.MAX_VALUE + "L"),
511 "createNumber(String) 16 failed");
512 assertEquals(Long.valueOf("10" + Integer.MAX_VALUE), NumberUtils.createNumber("10" + Integer.MAX_VALUE),
513 "createNumber(String) 17 failed");
514 assertEquals(new BigInteger("10" + Long.MAX_VALUE), NumberUtils.createNumber("10" + Long.MAX_VALUE),
515 "createNumber(String) 18 failed");
516
517 // LANG-521
518 assertEquals(Float.valueOf("2."), NumberUtils.createNumber("2."), "createNumber(String) LANG-521 failed");
519
520 // LANG-638
521 assertFalse(checkCreateNumber("1eE"), "createNumber(String) succeeded");
522
523 // LANG-693
524 assertEquals(Double.valueOf(Double.MAX_VALUE), NumberUtils.createNumber("" + Double.MAX_VALUE),
525 "createNumber(String) LANG-693 failed");
526
527 // LANG-822
528 // ensure that the underlying negative number would create a BigDecimal
529 final Number bigNum = NumberUtils.createNumber("-1.1E-700F");
530 assertNotNull(bigNum);
531 assertEquals(BigDecimal.class, bigNum.getClass());
532
533 // LANG-1018
534 assertEquals(Double.valueOf("-160952.54"), NumberUtils.createNumber("-160952.54"),
535 "createNumber(String) LANG-1018 failed");
536 // LANG-1187
537 assertEquals(Double.valueOf("6264583.33"), NumberUtils.createNumber("6264583.33"),
538 "createNumber(String) LANG-1187 failed");
539 // LANG-1215
540 assertEquals(Double.valueOf("193343.82"), NumberUtils.createNumber("193343.82"),
541 "createNumber(String) LANG-1215 failed");
542 // LANG-1060
543 assertEquals(Double.valueOf("001234.5678"), NumberUtils.createNumber("001234.5678"),
544 "createNumber(String) LANG-1060a failed");
545 assertEquals(Double.valueOf("+001234.5678"), NumberUtils.createNumber("+001234.5678"),
546 "createNumber(String) LANG-1060b failed");
547 assertEquals(Double.valueOf("-001234.5678"), NumberUtils.createNumber("-001234.5678"),
548 "createNumber(String) LANG-1060c failed");
549 assertEquals(Double.valueOf("0000.00000"), NumberUtils.createNumber("0000.00000d"),
550 "createNumber(String) LANG-1060d failed");
551 assertEquals(Float.valueOf("001234.56"), NumberUtils.createNumber("001234.56"),
552 "createNumber(String) LANG-1060e failed");
553 assertEquals(Float.valueOf("+001234.56"), NumberUtils.createNumber("+001234.56"),
554 "createNumber(String) LANG-1060f failed");
555 assertEquals(Float.valueOf("-001234.56"), NumberUtils.createNumber("-001234.56"),
556 "createNumber(String) LANG-1060g failed");
557 assertEquals(Float.valueOf("0000.10"), NumberUtils.createNumber("0000.10"),
558 "createNumber(String) LANG-1060h failed");
559 assertEquals(Float.valueOf("001.1E20"), NumberUtils.createNumber("001.1E20"),
560 "createNumber(String) LANG-1060i failed");
561 assertEquals(Float.valueOf("+001.1E20"), NumberUtils.createNumber("+001.1E20"),
562 "createNumber(String) LANG-1060j failed");
563 assertEquals(Float.valueOf("-001.1E20"), NumberUtils.createNumber("-001.1E20"),
564 "createNumber(String) LANG-1060k failed");
565 assertEquals(Double.valueOf("001.1E200"), NumberUtils.createNumber("001.1E200"),
566 "createNumber(String) LANG-1060l failed");
567 assertEquals(Double.valueOf("+001.1E200"), NumberUtils.createNumber("+001.1E200"),
568 "createNumber(String) LANG-1060m failed");
569 assertEquals(Double.valueOf("-001.1E200"), NumberUtils.createNumber("-001.1E200"),
570 "createNumber(String) LANG-1060n failed");
571 // LANG-1645
572 assertEquals(Integer.decode("+0xF"), NumberUtils.createNumber("+0xF"),
573 "createNumber(String) LANG-1645a failed");
574 assertEquals(Long.decode("+0xFFFFFFFF"), NumberUtils.createNumber("+0xFFFFFFFF"),
575 "createNumber(String) LANG-1645b failed");
576 assertEquals(new BigInteger("+FFFFFFFFFFFFFFFF", 16), NumberUtils.createNumber("+0xFFFFFFFFFFFFFFFF"),
577 "createNumber(String) LANG-1645c failed");
578 }
579
580 @Test
581 // Check that the code fails to create a valid number when preceded by -- rather than -
582 public void testCreateNumberFailure_1() {
583 assertThrows(NumberFormatException.class, () -> NumberUtils.createNumber("--1.1E-700F"));
584 }
585
586 @Test
587 // Check that the code fails to create a valid number when both e and E are present (with decimal)
588 public void testCreateNumberFailure_2() {
589 assertThrows(NumberFormatException.class, () -> NumberUtils.createNumber("-1.1E+0-7e00"));
590 }
591
592 @Test
593 // Check that the code fails to create a valid number when both e and E are present (no decimal)
594 public void testCreateNumberFailure_3() {
595 assertThrows(NumberFormatException.class, () -> NumberUtils.createNumber("-11E+0-7e00"));
596 }
597
598 @Test
599 // Check that the code fails to create a valid number when both e and E are present (no decimal)
600 public void testCreateNumberFailure_4() {
601 assertThrows(NumberFormatException.class, () -> NumberUtils.createNumber("1eE+00001"));
602 }
603
604 @Test
605 // Check that the code fails to create a valid number when there are multiple trailing 'f' characters (LANG-1205)
606 public void testCreateNumberFailure_5() {
607 assertThrows(NumberFormatException.class, () -> NumberUtils.createNumber("1234.5ff"));
608 }
609
610 @Test
611 // Check that the code fails to create a valid number when there are multiple trailing 'F' characters (LANG-1205)
612 public void testCreateNumberFailure_6() {
613 assertThrows(NumberFormatException.class, () -> NumberUtils.createNumber("1234.5FF"));
614 }
615
616 @Test
617 // Check that the code fails to create a valid number when there are multiple trailing 'd' characters (LANG-1205)
618 public void testCreateNumberFailure_7() {
619 assertThrows(NumberFormatException.class, () -> NumberUtils.createNumber("1234.5dd"));
620 }
621
622 @Test
623 // Check that the code fails to create a valid number when there are multiple trailing 'D' characters (LANG-1205)
624 public void testCreateNumberFailure_8() {
625 assertThrows(NumberFormatException.class, () -> NumberUtils.createNumber("1234.5DD"));
626 }
627
628 // Tests to show when magnitude causes switch to next Number type
629 // Will probably need to be adjusted if code is changed to check precision (LANG-693)
630 @Test
631 public void testCreateNumberMagnitude() {
632 // Test Float.MAX_VALUE, and same with +1 in final digit to check conversion changes to next Number type
633 assertEquals(Float.valueOf(Float.MAX_VALUE), NumberUtils.createNumber("3.4028235e+38"));
634 assertEquals(Double.valueOf(3.4028236e+38), NumberUtils.createNumber("3.4028236e+38"));
635
636 // Test Double.MAX_VALUE
637 assertEquals(Double.valueOf(Double.MAX_VALUE), NumberUtils.createNumber("1.7976931348623157e+308"));
638 // Test with +2 in final digit (+1 does not cause roll-over to BigDecimal)
639 assertEquals(new BigDecimal("1.7976931348623159e+308"), NumberUtils.createNumber("1.7976931348623159e+308"));
640
641 // Requested type is parsed as zero but the value is not zero
642 final Double nonZero1 = Double.valueOf(((double) Float.MIN_VALUE) / 2);
643 assertEquals(nonZero1, NumberUtils.createNumber(nonZero1.toString()));
644 assertEquals(nonZero1, NumberUtils.createNumber(nonZero1.toString() + "F"));
645 // Smallest double is 4.9e-324.
646 // Test a number with zero before and/or after the decimal place to hit edge cases.
647 final BigDecimal nonZero2 = new BigDecimal("4.9e-325");
648 assertEquals(nonZero2, NumberUtils.createNumber("4.9e-325"));
649 assertEquals(nonZero2, NumberUtils.createNumber("4.9e-325D"));
650 final BigDecimal nonZero3 = new BigDecimal("1e-325");
651 assertEquals(nonZero3, NumberUtils.createNumber("1e-325"));
652 assertEquals(nonZero3, NumberUtils.createNumber("1e-325D"));
653 final BigDecimal nonZero4 = new BigDecimal("0.1e-325");
654 assertEquals(nonZero4, NumberUtils.createNumber("0.1e-325"));
655 assertEquals(nonZero4, NumberUtils.createNumber("0.1e-325D"));
656
657 assertEquals(Integer.valueOf(0x12345678), NumberUtils.createNumber("0x12345678"));
658 assertEquals(Long.valueOf(0x123456789L), NumberUtils.createNumber("0x123456789"));
659
660 assertEquals(Long.valueOf(0x7fffffffffffffffL), NumberUtils.createNumber("0x7fffffffffffffff"));
661 // Does not appear to be a way to create a literal BigInteger of this magnitude
662 assertEquals(new BigInteger("7fffffffffffffff0", 16), NumberUtils.createNumber("0x7fffffffffffffff0"));
663
664 assertEquals(Long.valueOf(0x7fffffffffffffffL), NumberUtils.createNumber("#7fffffffffffffff"));
665 assertEquals(new BigInteger("7fffffffffffffff0", 16), NumberUtils.createNumber("#7fffffffffffffff0"));
666
667 assertEquals(Integer.valueOf(017777777777), NumberUtils.createNumber("017777777777")); // 31 bits
668 assertEquals(Long.valueOf(037777777777L), NumberUtils.createNumber("037777777777")); // 32 bits
669
670 // 63 bits
671 assertEquals(Long.valueOf(0777777777777777777777L), NumberUtils.createNumber("0777777777777777777777"));
672 // 64 bits
673 assertEquals(new BigInteger("1777777777777777777777", 8), NumberUtils.createNumber("01777777777777777777777"));
674 }
675
676 /**
677 * LANG-1646: Support the requested Number type (Long, Float, Double) of valid zero input.
678 */
679 @Test
680 public void testCreateNumberZero() {
681 // Handle integers
682 assertEquals(Integer.valueOf(0), NumberUtils.createNumber("0"));
683 assertEquals(Integer.valueOf(0), NumberUtils.createNumber("-0"));
684 assertEquals(Long.valueOf(0), NumberUtils.createNumber("0L"));
685 assertEquals(Long.valueOf(0), NumberUtils.createNumber("-0L"));
686
687 // Handle floating-point with optional leading sign, trailing exponent (eX)
688 // and format specifier (F or D).
689 // This should allow: 0. ; .0 ; 0.0 ; 0 (if exponent or format specifier is present)
690
691 // Exponent does not matter for zero
692 final int[] exponents = {-2345, 0, 13};
693 final String[] zeros = {"0.", ".0", "0.0", "0"};
694 final Float f0 = Float.valueOf(0);
695 final Float fn0 = Float.valueOf(-0F);
696 final Double d0 = Double.valueOf(0);
697 final Double dn0 = Double.valueOf(-0D);
698
699 for (final String zero : zeros) {
700 // Assume float if no preference.
701 // This requires a decimal point if there is no exponent.
702 if (zero.indexOf('.') != -1) {
703 assertCreateNumberZero(zero, f0, fn0);
704 }
705 for (final int exp : exponents) {
706 assertCreateNumberZero(zero + "e" + exp, f0, fn0);
707 }
708 // Type preference
709 assertCreateNumberZero(zero + "F", f0, fn0);
710 assertCreateNumberZero(zero + "D", d0, dn0);
711 for (final int exp : exponents) {
712 final String number = zero + "e" + exp;
713 assertCreateNumberZero(number + "F", f0, fn0);
714 assertCreateNumberZero(number + "D", d0, dn0);
715 }
716 }
717 }
718
719 private static void assertCreateNumberZero(final String number, final Object zero, final Object negativeZero) {
720 assertEquals(zero, NumberUtils.createNumber(number), () -> "Input: " + number);
721 assertEquals(zero, NumberUtils.createNumber("+" + number), () -> "Input: +" + number);
722 assertEquals(negativeZero, NumberUtils.createNumber("-" + number), () -> "Input: -" + number);
723 }
724
725 /**
726 * Tests isCreatable(String) and tests that createNumber(String) returns a valid number iff isCreatable(String)
727 * returns false.
1251728 */
1252729 @Test
1253730 public void testIsCreatable() {
1302779
1303780 compareIsCreatableWithCreateNumber("2.", true); // LANG-521
1304781 compareIsCreatableWithCreateNumber("1.1L", false); // LANG-664
1305 }
1306
1307 @Test
1308 public void testLANG971() {
1309 compareIsCreatableWithCreateNumber("0085", false);
1310 compareIsCreatableWithCreateNumber("085", false);
1311 compareIsCreatableWithCreateNumber("08", false);
1312 compareIsCreatableWithCreateNumber("07", true);
1313 compareIsCreatableWithCreateNumber("00", true);
1314 }
1315
1316 @Test
1317 public void testLANG992() {
1318 compareIsCreatableWithCreateNumber("0.0", true);
1319 compareIsCreatableWithCreateNumber("0.4790", true);
1320 }
1321
1322 @Test
1323 public void testLANG972() {
1324 compareIsCreatableWithCreateNumber("0xABCD", true);
1325 compareIsCreatableWithCreateNumber("0XABCD", true);
1326 }
1327
1328 @Test
1329 public void testLANG1252() {
1330 compareIsCreatableWithCreateNumber("+2", true);
1331 compareIsCreatableWithCreateNumber("+2.0", true);
1332 }
1333
1334 private void compareIsCreatableWithCreateNumber(final String val, final boolean expected) {
1335 final boolean isValid = NumberUtils.isCreatable(val);
1336 final boolean canCreate = checkCreateNumber(val);
1337 assertTrue(
1338 isValid == expected && canCreate == expected,
1339 "Expecting " + expected + " for isCreatable/createNumber using \"" + val + "\" but got " + isValid + " and " + canCreate);
1340 }
1341
1342 /**
1343 * Tests isCreatable(String) and tests that createNumber(String) returns
1344 * a valid number iff isCreatable(String) returns false.
782 compareIsCreatableWithCreateNumber("+0xF", true); // LANG-1645
783 compareIsCreatableWithCreateNumber("+0xFFFFFFFF", true); // LANG-1645
784 compareIsCreatableWithCreateNumber("+0xFFFFFFFFFFFFFFFF", true); // LANG-1645
785 compareIsCreatableWithCreateNumber(".0", true); // LANG-1646
786 compareIsCreatableWithCreateNumber("0.", true); // LANG-1646
787 compareIsCreatableWithCreateNumber("0.D", true); // LANG-1646
788 compareIsCreatableWithCreateNumber("0e1", true); // LANG-1646
789 compareIsCreatableWithCreateNumber("0e1D", true); // LANG-1646
790 compareIsCreatableWithCreateNumber(".D", false); // LANG-1646
791 compareIsCreatableWithCreateNumber(".e10", false); // LANG-1646
792 compareIsCreatableWithCreateNumber(".e10D", false); // LANG-1646
793 }
794
795 @Test
796 public void testIsDigits() {
797 assertFalse(NumberUtils.isDigits(null), "isDigits(null) failed");
798 assertFalse(NumberUtils.isDigits(""), "isDigits('') failed");
799 assertTrue(NumberUtils.isDigits("12345"), "isDigits(String) failed");
800 assertFalse(NumberUtils.isDigits("1234.5"), "isDigits(String) neg 1 failed");
801 assertFalse(NumberUtils.isDigits("1ab"), "isDigits(String) neg 3 failed");
802 assertFalse(NumberUtils.isDigits("abc"), "isDigits(String) neg 4 failed");
803 }
804
805 /**
806 * Tests isCreatable(String) and tests that createNumber(String) returns a valid number iff isCreatable(String)
807 * returns false.
1345808 */
1346809 @Test
1347810 public void testIsNumber() {
1402865
1403866 compareIsNumberWithCreateNumber("2.", true); // LANG-521
1404867 compareIsNumberWithCreateNumber("1.1L", false); // LANG-664
868 compareIsNumberWithCreateNumber("+0xF", true); // LANG-1645
869 compareIsNumberWithCreateNumber("+0xFFFFFFFF", true); // LANG-1645
870 compareIsNumberWithCreateNumber("+0xFFFFFFFFFFFFFFFF", true); // LANG-1645
871 compareIsNumberWithCreateNumber(".0", true); // LANG-1646
872 compareIsNumberWithCreateNumber("0.", true); // LANG-1646
873 compareIsNumberWithCreateNumber("0.D", true); // LANG-1646
874 compareIsNumberWithCreateNumber("0e1", true); // LANG-1646
875 compareIsNumberWithCreateNumber("0e1D", true); // LANG-1646
876 compareIsNumberWithCreateNumber(".D", false); // LANG-1646
877 compareIsNumberWithCreateNumber(".e10", false); // LANG-1646
878 compareIsNumberWithCreateNumber(".e10D", false); // LANG-1646
879 }
880
881 @Test
882 public void testIsNumberLANG1252() {
883 compareIsNumberWithCreateNumber("+2", true);
884 compareIsNumberWithCreateNumber("+2.0", true);
885 }
886
887 @Test
888 public void testIsNumberLANG1385() {
889 compareIsNumberWithCreateNumber("L", false);
1405890 }
1406891
1407892 @Test
1414899 }
1415900
1416901 @Test
902 public void testIsNumberLANG972() {
903 compareIsNumberWithCreateNumber("0xABCD", true);
904 compareIsNumberWithCreateNumber("0XABCD", true);
905 }
906
907 @Test
1417908 public void testIsNumberLANG992() {
1418909 compareIsNumberWithCreateNumber("0.0", true);
1419910 compareIsNumberWithCreateNumber("0.4790", true);
1420 }
1421
1422 @Test
1423 public void testIsNumberLANG972() {
1424 compareIsNumberWithCreateNumber("0xABCD", true);
1425 compareIsNumberWithCreateNumber("0XABCD", true);
1426 }
1427
1428 @Test
1429 public void testIsNumberLANG1252() {
1430 compareIsNumberWithCreateNumber("+2", true);
1431 compareIsNumberWithCreateNumber("+2.0", true);
1432 }
1433
1434 @Test
1435 public void testIsNumberLANG1385() {
1436 compareIsNumberWithCreateNumber("L", false);
1437 }
1438
1439 private void compareIsNumberWithCreateNumber(final String val, final boolean expected) {
1440 final boolean isValid = NumberUtils.isCreatable(val);
1441 final boolean canCreate = checkCreateNumber(val);
1442 assertTrue(
1443 isValid == expected && canCreate == expected,
1444 "Expecting "+ expected + " for isCreatable/createNumber using \"" + val + "\" but got " + isValid + " and " + canCreate);
1445911 }
1446912
1447913 @Test
1467933 assertTrue(NumberUtils.isParsable("-.236"));
1468934 }
1469935
1470 private boolean checkCreateNumber(final String val) {
1471 try {
1472 final Object obj = NumberUtils.createNumber(val);
1473 return obj != null;
1474 } catch (final NumberFormatException e) {
1475 return false;
1476 }
1477 }
1478
1479 @SuppressWarnings("cast") // suppress instanceof warning check
1480 @Test
1481 public void testConstants() {
1482 assertTrue(NumberUtils.LONG_ZERO instanceof Long);
1483 assertTrue(NumberUtils.LONG_ONE instanceof Long);
1484 assertTrue(NumberUtils.LONG_MINUS_ONE instanceof Long);
1485 assertTrue(NumberUtils.INTEGER_ZERO instanceof Integer);
1486 assertTrue(NumberUtils.INTEGER_ONE instanceof Integer);
1487 assertTrue(NumberUtils.INTEGER_MINUS_ONE instanceof Integer);
1488 assertTrue(NumberUtils.SHORT_ZERO instanceof Short);
1489 assertTrue(NumberUtils.SHORT_ONE instanceof Short);
1490 assertTrue(NumberUtils.SHORT_MINUS_ONE instanceof Short);
1491 assertTrue(NumberUtils.BYTE_ZERO instanceof Byte);
1492 assertTrue(NumberUtils.BYTE_ONE instanceof Byte);
1493 assertTrue(NumberUtils.BYTE_MINUS_ONE instanceof Byte);
1494 assertTrue(NumberUtils.DOUBLE_ZERO instanceof Double);
1495 assertTrue(NumberUtils.DOUBLE_ONE instanceof Double);
1496 assertTrue(NumberUtils.DOUBLE_MINUS_ONE instanceof Double);
1497 assertTrue(NumberUtils.FLOAT_ZERO instanceof Float);
1498 assertTrue(NumberUtils.FLOAT_ONE instanceof Float);
1499 assertTrue(NumberUtils.FLOAT_MINUS_ONE instanceof Float);
1500
1501 assertEquals(0, NumberUtils.LONG_ZERO.longValue());
1502 assertEquals(1, NumberUtils.LONG_ONE.longValue());
1503 assertEquals(NumberUtils.LONG_MINUS_ONE.longValue(), -1);
1504 assertEquals(0, NumberUtils.INTEGER_ZERO.intValue());
1505 assertEquals(1, NumberUtils.INTEGER_ONE.intValue());
1506 assertEquals(NumberUtils.INTEGER_MINUS_ONE.intValue(), -1);
1507 assertEquals(0, NumberUtils.SHORT_ZERO.shortValue());
1508 assertEquals(1, NumberUtils.SHORT_ONE.shortValue());
1509 assertEquals(NumberUtils.SHORT_MINUS_ONE.shortValue(), -1);
1510 assertEquals(0, NumberUtils.BYTE_ZERO.byteValue());
1511 assertEquals(1, NumberUtils.BYTE_ONE.byteValue());
1512 assertEquals(NumberUtils.BYTE_MINUS_ONE.byteValue(), -1);
1513 assertEquals(0.0d, NumberUtils.DOUBLE_ZERO.doubleValue());
1514 assertEquals(1.0d, NumberUtils.DOUBLE_ONE.doubleValue());
1515 assertEquals(NumberUtils.DOUBLE_MINUS_ONE.doubleValue(), -1.0d);
1516 assertEquals(0.0f, NumberUtils.FLOAT_ZERO.floatValue());
1517 assertEquals(1.0f, NumberUtils.FLOAT_ONE.floatValue());
1518 assertEquals(NumberUtils.FLOAT_MINUS_ONE.floatValue(), -1.0f);
936 @Test
937 public void testLang1087() {
938 // no sign cases
939 assertEquals(Float.class, NumberUtils.createNumber("0.0").getClass());
940 assertEquals(Float.valueOf("0.0"), NumberUtils.createNumber("0.0"));
941 // explicit positive sign cases
942 assertEquals(Float.class, NumberUtils.createNumber("+0.0").getClass());
943 assertEquals(Float.valueOf("+0.0"), NumberUtils.createNumber("+0.0"));
944 // negative sign cases
945 assertEquals(Float.class, NumberUtils.createNumber("-0.0").getClass());
946 assertEquals(Float.valueOf("-0.0"), NumberUtils.createNumber("-0.0"));
947 }
948
949 @Test
950 public void testLANG1252() {
951 compareIsCreatableWithCreateNumber("+2", true);
952 compareIsCreatableWithCreateNumber("+2.0", true);
1519953 }
1520954
1521955 @Test
1532966 assertTrue(Float.isNaN(NumberUtils.min(1.2f, 2.5f, Float.NaN)));
1533967 assertTrue(Float.isNaN(NumberUtils.max(1.2f, 2.5f, Float.NaN)));
1534968
1535 final double[] a = new double[] { 1.2, Double.NaN, 3.7, 27.0, 42.0, Double.NaN };
969 final double[] a = {1.2, Double.NaN, 3.7, 27.0, 42.0, Double.NaN};
1536970 assertTrue(Double.isNaN(NumberUtils.max(a)));
1537971 assertTrue(Double.isNaN(NumberUtils.min(a)));
1538972
1539 final double[] b = new double[] { Double.NaN, 1.2, Double.NaN, 3.7, 27.0, 42.0, Double.NaN };
973 final double[] b = {Double.NaN, 1.2, Double.NaN, 3.7, 27.0, 42.0, Double.NaN};
1540974 assertTrue(Double.isNaN(NumberUtils.max(b)));
1541975 assertTrue(Double.isNaN(NumberUtils.min(b)));
1542976
1543 final float[] aF = new float[] { 1.2f, Float.NaN, 3.7f, 27.0f, 42.0f, Float.NaN };
977 final float[] aF = {1.2f, Float.NaN, 3.7f, 27.0f, 42.0f, Float.NaN};
1544978 assertTrue(Float.isNaN(NumberUtils.max(aF)));
1545979
1546 final float[] bF = new float[] { Float.NaN, 1.2f, Float.NaN, 3.7f, 27.0f, 42.0f, Float.NaN };
980 final float[] bF = {Float.NaN, 1.2f, Float.NaN, 3.7f, 27.0f, 42.0f, Float.NaN};
1547981 assertTrue(Float.isNaN(NumberUtils.max(bF)));
1548982 }
1549983
1550984 @Test
1551 public void compareInt() {
1552 assertTrue(NumberUtils.compare(-3, 0) < 0);
1553 assertEquals(0, NumberUtils.compare(113, 113));
1554 assertTrue(NumberUtils.compare(213, 32) > 0);
1555 }
1556
1557 @Test
1558 public void compareLong() {
1559 assertTrue(NumberUtils.compare(-3L, 0L) < 0);
1560 assertEquals(0, NumberUtils.compare(113L, 113L));
1561 assertTrue(NumberUtils.compare(213L, 32L) > 0);
1562 }
1563
1564 @Test
1565 public void compareShort() {
1566 assertTrue(NumberUtils.compare((short) -3, (short) 0) < 0);
1567 assertEquals(0, NumberUtils.compare((short) 113, (short) 113));
1568 assertTrue(NumberUtils.compare((short) 213, (short) 32) > 0);
1569 }
1570
1571 @Test
1572 public void compareByte() {
1573 assertTrue(NumberUtils.compare((byte) -3, (byte) 0) < 0);
1574 assertEquals(0, NumberUtils.compare((byte) 113, (byte) 113));
1575 assertTrue(NumberUtils.compare((byte) 123, (byte) 32) > 0);
985 public void TestLang747() {
986 assertEquals(Integer.valueOf(0x8000), NumberUtils.createNumber("0x8000"));
987 assertEquals(Integer.valueOf(0x80000), NumberUtils.createNumber("0x80000"));
988 assertEquals(Integer.valueOf(0x800000), NumberUtils.createNumber("0x800000"));
989 assertEquals(Integer.valueOf(0x8000000), NumberUtils.createNumber("0x8000000"));
990 assertEquals(Integer.valueOf(0x7FFFFFFF), NumberUtils.createNumber("0x7FFFFFFF"));
991 assertEquals(Long.valueOf(0x80000000L), NumberUtils.createNumber("0x80000000"));
992 assertEquals(Long.valueOf(0xFFFFFFFFL), NumberUtils.createNumber("0xFFFFFFFF"));
993
994 // Leading zero tests
995 assertEquals(Integer.valueOf(0x8000000), NumberUtils.createNumber("0x08000000"));
996 assertEquals(Integer.valueOf(0x7FFFFFFF), NumberUtils.createNumber("0x007FFFFFFF"));
997 assertEquals(Long.valueOf(0x80000000L), NumberUtils.createNumber("0x080000000"));
998 assertEquals(Long.valueOf(0xFFFFFFFFL), NumberUtils.createNumber("0x00FFFFFFFF"));
999
1000 assertEquals(Long.valueOf(0x800000000L), NumberUtils.createNumber("0x800000000"));
1001 assertEquals(Long.valueOf(0x8000000000L), NumberUtils.createNumber("0x8000000000"));
1002 assertEquals(Long.valueOf(0x80000000000L), NumberUtils.createNumber("0x80000000000"));
1003 assertEquals(Long.valueOf(0x800000000000L), NumberUtils.createNumber("0x800000000000"));
1004 assertEquals(Long.valueOf(0x8000000000000L), NumberUtils.createNumber("0x8000000000000"));
1005 assertEquals(Long.valueOf(0x80000000000000L), NumberUtils.createNumber("0x80000000000000"));
1006 assertEquals(Long.valueOf(0x800000000000000L), NumberUtils.createNumber("0x800000000000000"));
1007 assertEquals(Long.valueOf(0x7FFFFFFFFFFFFFFFL), NumberUtils.createNumber("0x7FFFFFFFFFFFFFFF"));
1008 // N.B. Cannot use a hex constant such as 0x8000000000000000L here as that is interpreted as a negative long
1009 assertEquals(new BigInteger("8000000000000000", 16), NumberUtils.createNumber("0x8000000000000000"));
1010 assertEquals(new BigInteger("FFFFFFFFFFFFFFFF", 16), NumberUtils.createNumber("0xFFFFFFFFFFFFFFFF"));
1011
1012 // Leading zero tests
1013 assertEquals(Long.valueOf(0x80000000000000L), NumberUtils.createNumber("0x00080000000000000"));
1014 assertEquals(Long.valueOf(0x800000000000000L), NumberUtils.createNumber("0x0800000000000000"));
1015 assertEquals(Long.valueOf(0x7FFFFFFFFFFFFFFFL), NumberUtils.createNumber("0x07FFFFFFFFFFFFFFF"));
1016 // N.B. Cannot use a hex constant such as 0x8000000000000000L here as that is interpreted as a negative long
1017 assertEquals(new BigInteger("8000000000000000", 16), NumberUtils.createNumber("0x00008000000000000000"));
1018 assertEquals(new BigInteger("FFFFFFFFFFFFFFFF", 16), NumberUtils.createNumber("0x0FFFFFFFFFFFFFFFF"));
1019 }
1020
1021 @Test
1022 public void testLANG971() {
1023 compareIsCreatableWithCreateNumber("0085", false);
1024 compareIsCreatableWithCreateNumber("085", false);
1025 compareIsCreatableWithCreateNumber("08", false);
1026 compareIsCreatableWithCreateNumber("07", true);
1027 compareIsCreatableWithCreateNumber("00", true);
1028 }
1029
1030 @Test
1031 public void testLANG972() {
1032 compareIsCreatableWithCreateNumber("0xABCD", true);
1033 compareIsCreatableWithCreateNumber("0XABCD", true);
1034 }
1035
1036 @Test
1037 public void testLANG992() {
1038 compareIsCreatableWithCreateNumber("0.0", true);
1039 compareIsCreatableWithCreateNumber("0.4790", true);
1040 }
1041
1042 @Test
1043 public void testMaxByte() {
1044 assertEquals((byte) 5, NumberUtils.max((byte) 5), "max(byte[]) failed for array length 1");
1045 assertEquals((byte) 9, NumberUtils.max((byte) 6, (byte) 9), "max(byte[]) failed for array length 2");
1046 assertEquals((byte) 10, NumberUtils.max((byte) -10, (byte) -5, (byte) 0, (byte) 5, (byte) 10),
1047 "max(byte[]) failed for array length 5");
1048 assertEquals((byte) 10, NumberUtils.max((byte) -10, (byte) -5, (byte) 0, (byte) 5, (byte) 10));
1049 assertEquals((byte) 10, NumberUtils.max((byte) -5, (byte) 0, (byte) 10, (byte) 5, (byte) -10));
1050 }
1051
1052 @Test
1053 public void testMaxByte_emptyArray() {
1054 assertThrows(IllegalArgumentException.class, NumberUtils::max);
1055 }
1056
1057 @Test
1058 public void testMaxByte_nullArray() {
1059 assertThrows(NullPointerException.class, () -> NumberUtils.max((byte[]) null));
1060 }
1061
1062 @Test
1063 public void testMaxDouble() {
1064 final double[] d = null;
1065 assertThrows(NullPointerException.class, () -> NumberUtils.max(d), "No exception was thrown for null input.");
1066
1067 assertThrows(IllegalArgumentException.class, NumberUtils::max, "No exception was thrown for empty input.");
1068
1069 assertEquals(5.1f, NumberUtils.max(5.1f), "max(double[]) failed for array length 1");
1070 assertEquals(9.2f, NumberUtils.max(6.3f, 9.2f), "max(double[]) failed for array length 2");
1071 assertEquals(10.4f, NumberUtils.max(-10.5f, -5.6f, 0, 5.7f, 10.4f), "max(double[]) failed for float length 5");
1072 assertEquals(10, NumberUtils.max(-10, -5, 0, 5, 10), 0.0001);
1073 assertEquals(10, NumberUtils.max(-5, 0, 10, 5, -10), 0.0001);
1074 }
1075
1076 @Test
1077 public void testMaxDouble_emptyArray() {
1078 assertThrows(IllegalArgumentException.class, NumberUtils::max);
1079 }
1080
1081 @Test
1082 public void testMaxDouble_nullArray() {
1083 assertThrows(NullPointerException.class, () -> NumberUtils.max((double[]) null));
1084 }
1085
1086 @Test
1087 public void testMaxFloat() {
1088 assertEquals(5.1f, NumberUtils.max(5.1f), "max(float[]) failed for array length 1");
1089 assertEquals(9.2f, NumberUtils.max(6.3f, 9.2f), "max(float[]) failed for array length 2");
1090 assertEquals(10.4f, NumberUtils.max(-10.5f, -5.6f, 0, 5.7f, 10.4f), "max(float[]) failed for float length 5");
1091 assertEquals(10, NumberUtils.max(-10, -5, 0, 5, 10), 0.0001f);
1092 assertEquals(10, NumberUtils.max(-5, 0, 10, 5, -10), 0.0001f);
1093 }
1094
1095 @Test
1096 public void testMaxFloat_emptyArray() {
1097 assertThrows(IllegalArgumentException.class, NumberUtils::max);
1098 }
1099
1100 @Test
1101 public void testMaxFloat_nullArray() {
1102 assertThrows(NullPointerException.class, () -> NumberUtils.max((float[]) null));
1103 }
1104
1105 @Test
1106 public void testMaximumByte() {
1107 final byte low = 123;
1108 final byte mid = 123 + 1;
1109 final byte high = 123 + 2;
1110 assertEquals(high, NumberUtils.max(low, mid, high), "maximum(byte, byte, byte) 1 failed");
1111 assertEquals(high, NumberUtils.max(mid, low, high), "maximum(byte, byte, byte) 2 failed");
1112 assertEquals(high, NumberUtils.max(mid, high, low), "maximum(byte, byte, byte) 3 failed");
1113 assertEquals(high, NumberUtils.max(high, mid, high), "maximum(byte, byte, byte) 4 failed");
1114 }
1115
1116 @Test
1117 public void testMaximumDouble() {
1118 final double low = 12.3;
1119 final double mid = 12.3 + 1;
1120 final double high = 12.3 + 2;
1121 assertEquals(high, NumberUtils.max(low, mid, high), 0.0001);
1122 assertEquals(high, NumberUtils.max(mid, low, high), 0.0001);
1123 assertEquals(high, NumberUtils.max(mid, high, low), 0.0001);
1124 assertEquals(mid, NumberUtils.max(low, mid, low), 0.0001);
1125 assertEquals(high, NumberUtils.max(high, mid, high), 0.0001);
1126 }
1127
1128 @Test
1129 public void testMaximumFloat() {
1130 final float low = 12.3f;
1131 final float mid = 12.3f + 1;
1132 final float high = 12.3f + 2;
1133 assertEquals(high, NumberUtils.max(low, mid, high), 0.0001f);
1134 assertEquals(high, NumberUtils.max(mid, low, high), 0.0001f);
1135 assertEquals(high, NumberUtils.max(mid, high, low), 0.0001f);
1136 assertEquals(mid, NumberUtils.max(low, mid, low), 0.0001f);
1137 assertEquals(high, NumberUtils.max(high, mid, high), 0.0001f);
1138 }
1139
1140 @Test
1141 public void testMaximumInt() {
1142 assertEquals(12345, NumberUtils.max(12345, 12345 - 1, 12345 - 2), "maximum(int, int, int) 1 failed");
1143 assertEquals(12345, NumberUtils.max(12345 - 1, 12345, 12345 - 2), "maximum(int, int, int) 2 failed");
1144 assertEquals(12345, NumberUtils.max(12345 - 1, 12345 - 2, 12345), "maximum(int, int, int) 3 failed");
1145 assertEquals(12345, NumberUtils.max(12345 - 1, 12345, 12345), "maximum(int, int, int) 4 failed");
1146 assertEquals(12345, NumberUtils.max(12345, 12345, 12345), "maximum(int, int, int) 5 failed");
1147 }
1148
1149 @Test
1150 public void testMaximumLong() {
1151 assertEquals(12345L, NumberUtils.max(12345L, 12345L - 1L, 12345L - 2L), "maximum(long, long, long) 1 failed");
1152 assertEquals(12345L, NumberUtils.max(12345L - 1L, 12345L, 12345L - 2L), "maximum(long, long, long) 2 failed");
1153 assertEquals(12345L, NumberUtils.max(12345L - 1L, 12345L - 2L, 12345L), "maximum(long, long, long) 3 failed");
1154 assertEquals(12345L, NumberUtils.max(12345L - 1L, 12345L, 12345L), "maximum(long, long, long) 4 failed");
1155 assertEquals(12345L, NumberUtils.max(12345L, 12345L, 12345L), "maximum(long, long, long) 5 failed");
1156 }
1157
1158 @Test
1159 public void testMaximumShort() {
1160 final short low = 1234;
1161 final short mid = 1234 + 1;
1162 final short high = 1234 + 2;
1163 assertEquals(high, NumberUtils.max(low, mid, high), "maximum(short, short, short) 1 failed");
1164 assertEquals(high, NumberUtils.max(mid, low, high), "maximum(short, short, short) 2 failed");
1165 assertEquals(high, NumberUtils.max(mid, high, low), "maximum(short, short, short) 3 failed");
1166 assertEquals(high, NumberUtils.max(high, mid, high), "maximum(short, short, short) 4 failed");
1167 }
1168
1169 @Test
1170 public void testMaxInt() {
1171 assertEquals(5, NumberUtils.max(5), "max(int[]) failed for array length 1");
1172 assertEquals(9, NumberUtils.max(6, 9), "max(int[]) failed for array length 2");
1173 assertEquals(10, NumberUtils.max(-10, -5, 0, 5, 10), "max(int[]) failed for array length 5");
1174 assertEquals(10, NumberUtils.max(-10, -5, 0, 5, 10));
1175 assertEquals(10, NumberUtils.max(-5, 0, 10, 5, -10));
1176 }
1177
1178 @Test
1179 public void testMaxInt_emptyArray() {
1180 assertThrows(IllegalArgumentException.class, NumberUtils::max);
1181 }
1182
1183 @Test
1184 public void testMaxInt_nullArray() {
1185 assertThrows(NullPointerException.class, () -> NumberUtils.max((int[]) null));
1186 }
1187
1188 @Test
1189 public void testMaxLong() {
1190 assertEquals(5L, NumberUtils.max(5L), "max(long[]) failed for array length 1");
1191 assertEquals(9L, NumberUtils.max(6L, 9L), "max(long[]) failed for array length 2");
1192 assertEquals(10L, NumberUtils.max(-10L, -5L, 0L, 5L, 10L), "max(long[]) failed for array length 5");
1193 assertEquals(10L, NumberUtils.max(-10L, -5L, 0L, 5L, 10L));
1194 assertEquals(10L, NumberUtils.max(-5L, 0L, 10L, 5L, -10L));
1195 }
1196
1197 @Test
1198 public void testMaxLong_emptyArray() {
1199 assertThrows(IllegalArgumentException.class, NumberUtils::max);
1200 }
1201
1202 @Test
1203 public void testMaxLong_nullArray() {
1204 assertThrows(NullPointerException.class, () -> NumberUtils.max((long[]) null));
1205 }
1206
1207 @Test
1208 public void testMaxShort() {
1209 assertEquals((short) 5, NumberUtils.max((short) 5), "max(short[]) failed for array length 1");
1210 assertEquals((short) 9, NumberUtils.max((short) 6, (short) 9), "max(short[]) failed for array length 2");
1211 assertEquals((short) 10, NumberUtils.max((short) -10, (short) -5, (short) 0, (short) 5, (short) 10),
1212 "max(short[]) failed for array length 5");
1213 assertEquals((short) 10, NumberUtils.max((short) -10, (short) -5, (short) 0, (short) 5, (short) 10));
1214 assertEquals((short) 10, NumberUtils.max((short) -5, (short) 0, (short) 10, (short) 5, (short) -10));
1215 }
1216
1217 @Test
1218 public void testMaxShort_emptyArray() {
1219 assertThrows(IllegalArgumentException.class, NumberUtils::max);
1220 }
1221
1222 @Test
1223 public void testMaxShort_nullArray() {
1224 assertThrows(NullPointerException.class, () -> NumberUtils.max((short[]) null));
1225 }
1226
1227 @Test
1228 public void testMinByte() {
1229 assertEquals((byte) 5, NumberUtils.min((byte) 5), "min(byte[]) failed for array length 1");
1230 assertEquals((byte) 6, NumberUtils.min((byte) 6, (byte) 9), "min(byte[]) failed for array length 2");
1231
1232 assertEquals((byte) -10, NumberUtils.min((byte) -10, (byte) -5, (byte) 0, (byte) 5, (byte) 10));
1233 assertEquals((byte) -10, NumberUtils.min((byte) -5, (byte) 0, (byte) -10, (byte) 5, (byte) 10));
1234 }
1235
1236 @Test
1237 public void testMinByte_emptyArray() {
1238 assertThrows(IllegalArgumentException.class, NumberUtils::min);
1239 }
1240
1241 @Test
1242 public void testMinByte_nullArray() {
1243 assertThrows(NullPointerException.class, () -> NumberUtils.min((byte[]) null));
1244 }
1245
1246 @Test
1247 public void testMinDouble() {
1248 assertEquals(5.12, NumberUtils.min(5.12), "min(double[]) failed for array length 1");
1249 assertEquals(6.23, NumberUtils.min(6.23, 9.34), "min(double[]) failed for array length 2");
1250 assertEquals(-10.45, NumberUtils.min(-10.45, -5.56, 0, 5.67, 10.78), "min(double[]) failed for array length 5");
1251 assertEquals(-10, NumberUtils.min(-10, -5, 0, 5, 10), 0.0001);
1252 assertEquals(-10, NumberUtils.min(-5, 0, -10, 5, 10), 0.0001);
1253 }
1254
1255 @Test
1256 public void testMinDouble_emptyArray() {
1257 assertThrows(IllegalArgumentException.class, NumberUtils::min);
1258 }
1259
1260 @Test
1261 public void testMinDouble_nullArray() {
1262 assertThrows(NullPointerException.class, () -> NumberUtils.min((double[]) null));
1263 }
1264
1265 @Test
1266 public void testMinFloat() {
1267 assertEquals(5.9f, NumberUtils.min(5.9f), "min(float[]) failed for array length 1");
1268 assertEquals(6.8f, NumberUtils.min(6.8f, 9.7f), "min(float[]) failed for array length 2");
1269 assertEquals(-10.6f, NumberUtils.min(-10.6f, -5.5f, 0, 5.4f, 10.3f), "min(float[]) failed for array length 5");
1270 assertEquals(-10, NumberUtils.min(-10, -5, 0, 5, 10), 0.0001f);
1271 assertEquals(-10, NumberUtils.min(-5, 0, -10, 5, 10), 0.0001f);
1272 }
1273
1274 @Test
1275 public void testMinFloat_emptyArray() {
1276 assertThrows(IllegalArgumentException.class, NumberUtils::min);
1277 }
1278
1279 @Test
1280 public void testMinFloat_nullArray() {
1281 assertThrows(NullPointerException.class, () -> NumberUtils.min((float[]) null));
1282 }
1283
1284 @Test
1285 public void testMinimumByte() {
1286 final byte low = 123;
1287 final byte mid = 123 + 1;
1288 final byte high = 123 + 2;
1289 assertEquals(low, NumberUtils.min(low, mid, high), "minimum(byte, byte, byte) 1 failed");
1290 assertEquals(low, NumberUtils.min(mid, low, high), "minimum(byte, byte, byte) 2 failed");
1291 assertEquals(low, NumberUtils.min(mid, high, low), "minimum(byte, byte, byte) 3 failed");
1292 assertEquals(low, NumberUtils.min(low, mid, low), "minimum(byte, byte, byte) 4 failed");
1293 }
1294
1295 @Test
1296 public void testMinimumDouble() {
1297 final double low = 12.3;
1298 final double mid = 12.3 + 1;
1299 final double high = 12.3 + 2;
1300 assertEquals(low, NumberUtils.min(low, mid, high), 0.0001);
1301 assertEquals(low, NumberUtils.min(mid, low, high), 0.0001);
1302 assertEquals(low, NumberUtils.min(mid, high, low), 0.0001);
1303 assertEquals(low, NumberUtils.min(low, mid, low), 0.0001);
1304 assertEquals(mid, NumberUtils.min(high, mid, high), 0.0001);
1305 }
1306
1307 @Test
1308 public void testMinimumFloat() {
1309 final float low = 12.3f;
1310 final float mid = 12.3f + 1;
1311 final float high = 12.3f + 2;
1312 assertEquals(low, NumberUtils.min(low, mid, high), 0.0001f);
1313 assertEquals(low, NumberUtils.min(mid, low, high), 0.0001f);
1314 assertEquals(low, NumberUtils.min(mid, high, low), 0.0001f);
1315 assertEquals(low, NumberUtils.min(low, mid, low), 0.0001f);
1316 assertEquals(mid, NumberUtils.min(high, mid, high), 0.0001f);
1317 }
1318
1319 @Test
1320 public void testMinimumInt() {
1321 assertEquals(12345, NumberUtils.min(12345, 12345 + 1, 12345 + 2), "minimum(int, int, int) 1 failed");
1322 assertEquals(12345, NumberUtils.min(12345 + 1, 12345, 12345 + 2), "minimum(int, int, int) 2 failed");
1323 assertEquals(12345, NumberUtils.min(12345 + 1, 12345 + 2, 12345), "minimum(int, int, int) 3 failed");
1324 assertEquals(12345, NumberUtils.min(12345 + 1, 12345, 12345), "minimum(int, int, int) 4 failed");
1325 assertEquals(12345, NumberUtils.min(12345, 12345, 12345), "minimum(int, int, int) 5 failed");
1326 }
1327
1328 @Test
1329 public void testMinimumLong() {
1330 assertEquals(12345L, NumberUtils.min(12345L, 12345L + 1L, 12345L + 2L), "minimum(long, long, long) 1 failed");
1331 assertEquals(12345L, NumberUtils.min(12345L + 1L, 12345L, 12345 + 2L), "minimum(long, long, long) 2 failed");
1332 assertEquals(12345L, NumberUtils.min(12345L + 1L, 12345L + 2L, 12345L), "minimum(long, long, long) 3 failed");
1333 assertEquals(12345L, NumberUtils.min(12345L + 1L, 12345L, 12345L), "minimum(long, long, long) 4 failed");
1334 assertEquals(12345L, NumberUtils.min(12345L, 12345L, 12345L), "minimum(long, long, long) 5 failed");
1335 }
1336
1337 @Test
1338 public void testMinimumShort() {
1339 final short low = 1234;
1340 final short mid = 1234 + 1;
1341 final short high = 1234 + 2;
1342 assertEquals(low, NumberUtils.min(low, mid, high), "minimum(short, short, short) 1 failed");
1343 assertEquals(low, NumberUtils.min(mid, low, high), "minimum(short, short, short) 2 failed");
1344 assertEquals(low, NumberUtils.min(mid, high, low), "minimum(short, short, short) 3 failed");
1345 assertEquals(low, NumberUtils.min(low, mid, low), "minimum(short, short, short) 4 failed");
1346 }
1347
1348 @Test
1349 public void testMinInt() {
1350 assertEquals(5, NumberUtils.min(5), "min(int[]) failed for array length 1");
1351 assertEquals(6, NumberUtils.min(6, 9), "min(int[]) failed for array length 2");
1352
1353 assertEquals(-10, NumberUtils.min(-10, -5, 0, 5, 10));
1354 assertEquals(-10, NumberUtils.min(-5, 0, -10, 5, 10));
1355 }
1356
1357 @Test
1358 public void testMinInt_emptyArray() {
1359 assertThrows(IllegalArgumentException.class, NumberUtils::min);
1360 }
1361
1362 @Test
1363 public void testMinInt_nullArray() {
1364 assertThrows(NullPointerException.class, () -> NumberUtils.min((int[]) null));
1365 }
1366
1367 @Test
1368 public void testMinLong() {
1369 assertEquals(5L, NumberUtils.min(5L), "min(long[]) failed for array length 1");
1370 assertEquals(6L, NumberUtils.min(6L, 9L), "min(long[]) failed for array length 2");
1371
1372 assertEquals(-10L, NumberUtils.min(-10L, -5L, 0L, 5L, 10L));
1373 assertEquals(-10L, NumberUtils.min(-5L, 0L, -10L, 5L, 10L));
1374 }
1375
1376 @Test
1377 public void testMinLong_emptyArray() {
1378 assertThrows(IllegalArgumentException.class, NumberUtils::min);
1379 }
1380
1381 // min/max tests
1382 // ----------------------------------------------------------------------
1383 @Test
1384 public void testMinLong_nullArray() {
1385 assertThrows(NullPointerException.class, () -> NumberUtils.min((long[]) null));
1386 }
1387
1388 @Test
1389 public void testMinShort() {
1390 assertEquals((short) 5, NumberUtils.min((short) 5), "min(short[]) failed for array length 1");
1391 assertEquals((short) 6, NumberUtils.min((short) 6, (short) 9), "min(short[]) failed for array length 2");
1392
1393 assertEquals((short) -10, NumberUtils.min((short) -10, (short) -5, (short) 0, (short) 5, (short) 10));
1394 assertEquals((short) -10, NumberUtils.min((short) -5, (short) 0, (short) -10, (short) 5, (short) 10));
1395 }
1396
1397 @Test
1398 public void testMinShort_emptyArray() {
1399 assertThrows(IllegalArgumentException.class, NumberUtils::min);
1400 }
1401
1402 @Test
1403 public void testMinShort_nullArray() {
1404 assertThrows(NullPointerException.class, () -> NumberUtils.min((short[]) null));
1405 }
1406
1407 /**
1408 * Test for {(@link NumberUtils#createNumber(String)}
1409 */
1410 @Test
1411 public void testStringCreateNumberEnsureNoPrecisionLoss() {
1412 final String shouldBeFloat = "1.23";
1413 final String shouldBeDouble = "3.40282354e+38";
1414 final String shouldBeBigDecimal = "1.797693134862315759e+308";
1415 assertTrue(NumberUtils.createNumber(shouldBeFloat) instanceof Float);
1416 assertTrue(NumberUtils.createNumber(shouldBeDouble) instanceof Double);
1417 assertTrue(NumberUtils.createNumber(shouldBeBigDecimal) instanceof BigDecimal);
1418 // LANG-1060
1419 assertTrue(NumberUtils.createNumber("001.12") instanceof Float);
1420 assertTrue(NumberUtils.createNumber("-001.12") instanceof Float);
1421 assertTrue(NumberUtils.createNumber("+001.12") instanceof Float);
1422 assertTrue(NumberUtils.createNumber("003.40282354e+38") instanceof Double);
1423 assertTrue(NumberUtils.createNumber("-003.40282354e+38") instanceof Double);
1424 assertTrue(NumberUtils.createNumber("+003.40282354e+38") instanceof Double);
1425 assertTrue(NumberUtils.createNumber("0001.797693134862315759e+308") instanceof BigDecimal);
1426 assertTrue(NumberUtils.createNumber("-001.797693134862315759e+308") instanceof BigDecimal);
1427 assertTrue(NumberUtils.createNumber("+001.797693134862315759e+308") instanceof BigDecimal);
1428 //LANG-1613
1429 assertTrue(NumberUtils.createNumber(Double.toString(Double.MIN_NORMAL)) instanceof Double);
1430 assertTrue(NumberUtils.createNumber(Double.toString(Double.MIN_NORMAL) + "D") instanceof Double);
1431 assertTrue(NumberUtils.createNumber(Double.toString(Double.MIN_NORMAL) + "F") instanceof Double);
1432 assertTrue(NumberUtils.createNumber(Double.toString(Double.MIN_VALUE)) instanceof Double);
1433 assertTrue(NumberUtils.createNumber(Double.toString(Double.MIN_VALUE) + "D") instanceof Double);
1434 assertTrue(NumberUtils.createNumber(Double.toString(Double.MIN_VALUE) + "F") instanceof Double);
1435 assertTrue(NumberUtils.createNumber(Double.toString(Double.MAX_VALUE)) instanceof Double);
1436 assertTrue(NumberUtils.createNumber(Double.toString(Double.MAX_VALUE) + "D") instanceof Double);
1437 assertTrue(NumberUtils.createNumber(Double.toString(Double.MAX_VALUE) + "F") instanceof Double);
1438 assertTrue(NumberUtils.createNumber("4.9e-324D") instanceof Double);
1439 assertTrue(NumberUtils.createNumber("4.9e-324F") instanceof Double);
1440 }
1441
1442 /**
1443 * Test for {@link NumberUtils#toDouble(String)}.
1444 */
1445 @Test
1446 public void testStringToDoubleString() {
1447 assertEquals(NumberUtils.toDouble("-1.2345"), -1.2345d, "toDouble(String) 1 failed");
1448 assertEquals(1.2345d, NumberUtils.toDouble("1.2345"), "toDouble(String) 2 failed");
1449 assertEquals(0.0d, NumberUtils.toDouble("abc"), "toDouble(String) 3 failed");
1450 // LANG-1060
1451 assertEquals(NumberUtils.toDouble("-001.2345"), -1.2345d, "toDouble(String) 4 failed");
1452 assertEquals(1.2345d, NumberUtils.toDouble("+001.2345"), "toDouble(String) 5 failed");
1453 assertEquals(1.2345d, NumberUtils.toDouble("001.2345"), "toDouble(String) 6 failed");
1454 assertEquals(0d, NumberUtils.toDouble("000.00000"), "toDouble(String) 7 failed");
1455
1456 assertEquals(NumberUtils.toDouble(Double.MAX_VALUE + ""), Double.MAX_VALUE,
1457 "toDouble(Double.MAX_VALUE) failed");
1458 assertEquals(NumberUtils.toDouble(Double.MIN_VALUE + ""), Double.MIN_VALUE,
1459 "toDouble(Double.MIN_VALUE) failed");
1460 assertEquals(0.0d, NumberUtils.toDouble(""), "toDouble(empty) failed");
1461 assertEquals(0.0d, NumberUtils.toDouble((String) null), "toDouble(null) failed");
1462 }
1463
1464 /**
1465 * Test for {@link NumberUtils#toDouble(String, double)}.
1466 */
1467 @Test
1468 public void testStringToDoubleStringD() {
1469 assertEquals(1.2345d, NumberUtils.toDouble("1.2345", 5.1d), "toDouble(String, int) 1 failed");
1470 assertEquals(5.0d, NumberUtils.toDouble("a", 5.0d), "toDouble(String, int) 2 failed");
1471 // LANG-1060
1472 assertEquals(1.2345d, NumberUtils.toDouble("001.2345", 5.1d), "toDouble(String, int) 3 failed");
1473 assertEquals(NumberUtils.toDouble("-001.2345", 5.1d), -1.2345d, "toDouble(String, int) 4 failed");
1474 assertEquals(1.2345d, NumberUtils.toDouble("+001.2345", 5.1d), "toDouble(String, int) 5 failed");
1475 assertEquals(0d, NumberUtils.toDouble("000.00", 5.1d), "toDouble(String, int) 7 failed");
1476 }
1477
1478 /**
1479 * Test for {@link NumberUtils#toByte(String)}.
1480 */
1481 @Test
1482 public void testToByteString() {
1483 assertEquals(123, NumberUtils.toByte("123"), "toByte(String) 1 failed");
1484 assertEquals(0, NumberUtils.toByte("abc"), "toByte(String) 2 failed");
1485 assertEquals(0, NumberUtils.toByte(""), "toByte(empty) failed");
1486 assertEquals(0, NumberUtils.toByte(null), "toByte(null) failed");
1487 }
1488
1489 /**
1490 * Test for {@link NumberUtils#toByte(String, byte)}.
1491 */
1492 @Test
1493 public void testToByteStringI() {
1494 assertEquals(123, NumberUtils.toByte("123", (byte) 5), "toByte(String, byte) 1 failed");
1495 assertEquals(5, NumberUtils.toByte("12.3", (byte) 5), "toByte(String, byte) 2 failed");
1496 }
1497
1498 /**
1499 * Test for {@link NumberUtils#toFloat(String)}.
1500 */
1501 @Test
1502 public void testToFloatString() {
1503 assertEquals(NumberUtils.toFloat("-1.2345"), -1.2345f, "toFloat(String) 1 failed");
1504 assertEquals(1.2345f, NumberUtils.toFloat("1.2345"), "toFloat(String) 2 failed");
1505 assertEquals(0.0f, NumberUtils.toFloat("abc"), "toFloat(String) 3 failed");
1506 // LANG-1060
1507 assertEquals(NumberUtils.toFloat("-001.2345"), -1.2345f, "toFloat(String) 4 failed");
1508 assertEquals(1.2345f, NumberUtils.toFloat("+001.2345"), "toFloat(String) 5 failed");
1509 assertEquals(1.2345f, NumberUtils.toFloat("001.2345"), "toFloat(String) 6 failed");
1510 assertEquals(0f, NumberUtils.toFloat("000.00"), "toFloat(String) 7 failed");
1511
1512 assertEquals(NumberUtils.toFloat(Float.MAX_VALUE + ""), Float.MAX_VALUE, "toFloat(Float.MAX_VALUE) failed");
1513 assertEquals(NumberUtils.toFloat(Float.MIN_VALUE + ""), Float.MIN_VALUE, "toFloat(Float.MIN_VALUE) failed");
1514 assertEquals(0.0f, NumberUtils.toFloat(""), "toFloat(empty) failed");
1515 assertEquals(0.0f, NumberUtils.toFloat(null), "toFloat(null) failed");
1516 }
1517
1518 /**
1519 * Test for {@link NumberUtils#toFloat(String, float)}.
1520 */
1521 @Test
1522 public void testToFloatStringF() {
1523 assertEquals(1.2345f, NumberUtils.toFloat("1.2345", 5.1f), "toFloat(String, int) 1 failed");
1524 assertEquals(5.0f, NumberUtils.toFloat("a", 5.0f), "toFloat(String, int) 2 failed");
1525 // LANG-1060
1526 assertEquals(5.0f, NumberUtils.toFloat("-001Z.2345", 5.0f), "toFloat(String, int) 3 failed");
1527 assertEquals(5.0f, NumberUtils.toFloat("+001AB.2345", 5.0f), "toFloat(String, int) 4 failed");
1528 assertEquals(5.0f, NumberUtils.toFloat("001Z.2345", 5.0f), "toFloat(String, int) 5 failed");
1529 }
1530
1531 /**
1532 * Test for {@link NumberUtils#toInt(String)}.
1533 */
1534 @Test
1535 public void testToIntString() {
1536 assertEquals(12345, NumberUtils.toInt("12345"), "toInt(String) 1 failed");
1537 assertEquals(0, NumberUtils.toInt("abc"), "toInt(String) 2 failed");
1538 assertEquals(0, NumberUtils.toInt(""), "toInt(empty) failed");
1539 assertEquals(0, NumberUtils.toInt(null), "toInt(null) failed");
1540 }
1541
1542 /**
1543 * Test for {@link NumberUtils#toInt(String, int)}.
1544 */
1545 @Test
1546 public void testToIntStringI() {
1547 assertEquals(12345, NumberUtils.toInt("12345", 5), "toInt(String, int) 1 failed");
1548 assertEquals(5, NumberUtils.toInt("1234.5", 5), "toInt(String, int) 2 failed");
1549 }
1550
1551 /**
1552 * Test for {@link NumberUtils#toLong(String)}.
1553 */
1554 @Test
1555 public void testToLongString() {
1556 assertEquals(12345L, NumberUtils.toLong("12345"), "toLong(String) 1 failed");
1557 assertEquals(0L, NumberUtils.toLong("abc"), "toLong(String) 2 failed");
1558 assertEquals(0L, NumberUtils.toLong("1L"), "toLong(String) 3 failed");
1559 assertEquals(0L, NumberUtils.toLong("1l"), "toLong(String) 4 failed");
1560 assertEquals(NumberUtils.toLong(Long.MAX_VALUE + ""), Long.MAX_VALUE, "toLong(Long.MAX_VALUE) failed");
1561 assertEquals(NumberUtils.toLong(Long.MIN_VALUE + ""), Long.MIN_VALUE, "toLong(Long.MIN_VALUE) failed");
1562 assertEquals(0L, NumberUtils.toLong(""), "toLong(empty) failed");
1563 assertEquals(0L, NumberUtils.toLong(null), "toLong(null) failed");
1564 }
1565
1566 /**
1567 * Test for {@link NumberUtils#toLong(String, long)}.
1568 */
1569 @Test
1570 public void testToLongStringL() {
1571 assertEquals(12345L, NumberUtils.toLong("12345", 5L), "toLong(String, long) 1 failed");
1572 assertEquals(5L, NumberUtils.toLong("1234.5", 5L), "toLong(String, long) 2 failed");
1573 }
1574
1575 /**
1576 * Test for {@link NumberUtils#toScaledBigDecimal(BigDecimal)}.
1577 */
1578 @Test
1579 public void testToScaledBigDecimalBigDecimal() {
1580 assertEquals(NumberUtils.toScaledBigDecimal(BigDecimal.valueOf(123.456)), BigDecimal.valueOf(123.46),
1581 "toScaledBigDecimal(BigDecimal) 1 failed");
1582 // Test RoudingMode.HALF_EVEN default rounding.
1583 assertEquals(NumberUtils.toScaledBigDecimal(BigDecimal.valueOf(23.515)), BigDecimal.valueOf(23.52),
1584 "toScaledBigDecimal(BigDecimal) 2 failed");
1585 assertEquals(NumberUtils.toScaledBigDecimal(BigDecimal.valueOf(23.525)), BigDecimal.valueOf(23.52),
1586 "toScaledBigDecimal(BigDecimal) 3 failed");
1587 assertEquals("2352.00",
1588 NumberUtils.toScaledBigDecimal(BigDecimal.valueOf(23.525)).multiply(BigDecimal.valueOf(100)).toString(),
1589 "toScaledBigDecimal(BigDecimal) 4 failed");
1590 assertEquals(NumberUtils.toScaledBigDecimal((BigDecimal) null), BigDecimal.ZERO,
1591 "toScaledBigDecimal(BigDecimal) 5 failed");
1592 }
1593
1594 /**
1595 * Test for {@link NumberUtils#toScaledBigDecimal(BigDecimal, int, RoundingMode)}.
1596 */
1597 @Test
1598 public void testToScaledBigDecimalBigDecimalIRM() {
1599 assertEquals(NumberUtils.toScaledBigDecimal(BigDecimal.valueOf(123.456), 1, RoundingMode.CEILING),
1600 BigDecimal.valueOf(123.5), "toScaledBigDecimal(BigDecimal, int, RoudingMode) 1 failed");
1601 assertEquals(NumberUtils.toScaledBigDecimal(BigDecimal.valueOf(23.5159), 3, RoundingMode.FLOOR),
1602 BigDecimal.valueOf(23.515), "toScaledBigDecimal(BigDecimal, int, RoudingMode) 2 failed");
1603 assertEquals(NumberUtils.toScaledBigDecimal(BigDecimal.valueOf(23.525), 2, RoundingMode.HALF_UP),
1604 BigDecimal.valueOf(23.53), "toScaledBigDecimal(BigDecimal, int, RoudingMode) 3 failed");
1605 assertEquals("23521.0000",
1606 NumberUtils.toScaledBigDecimal(BigDecimal.valueOf(23.521), 4, RoundingMode.HALF_EVEN)
1607 .multiply(BigDecimal.valueOf(1000)).toString(),
1608 "toScaledBigDecimal(BigDecimal, int, RoudingMode) 4 failed");
1609 assertEquals(NumberUtils.toScaledBigDecimal((BigDecimal) null, 2, RoundingMode.HALF_UP), BigDecimal.ZERO,
1610 "toScaledBigDecimal(BigDecimal, int, RoudingMode) 5 failed");
1611 }
1612
1613 /**
1614 * Test for {@link NumberUtils#toScaledBigDecimal(Double)}.
1615 */
1616 @Test
1617 public void testToScaledBigDecimalDouble() {
1618 assertEquals(NumberUtils.toScaledBigDecimal(Double.valueOf(123.456d)), BigDecimal.valueOf(123.46),
1619 "toScaledBigDecimal(Double) 1 failed");
1620 // Test RoudingMode.HALF_EVEN default rounding.
1621 assertEquals(NumberUtils.toScaledBigDecimal(Double.valueOf(23.515d)), BigDecimal.valueOf(23.52),
1622 "toScaledBigDecimal(Double) 2 failed");
1623 assertEquals(NumberUtils.toScaledBigDecimal(Double.valueOf(23.525d)), BigDecimal.valueOf(23.52),
1624 "toScaledBigDecimal(Double) 3 failed");
1625 assertEquals("2352.00",
1626 NumberUtils.toScaledBigDecimal(Double.valueOf(23.525d)).multiply(BigDecimal.valueOf(100)).toString(),
1627 "toScaledBigDecimal(Double) 4 failed");
1628 assertEquals(NumberUtils.toScaledBigDecimal((Double) null), BigDecimal.ZERO,
1629 "toScaledBigDecimal(Double) 5 failed");
1630 }
1631
1632 /**
1633 * Test for {@link NumberUtils#toScaledBigDecimal(Double, int, RoundingMode)}.
1634 */
1635 @Test
1636 public void testToScaledBigDecimalDoubleIRM() {
1637 assertEquals(NumberUtils.toScaledBigDecimal(Double.valueOf(123.456d), 1, RoundingMode.CEILING),
1638 BigDecimal.valueOf(123.5), "toScaledBigDecimal(Double, int, RoudingMode) 1 failed");
1639 assertEquals(NumberUtils.toScaledBigDecimal(Double.valueOf(23.5159d), 3, RoundingMode.FLOOR),
1640 BigDecimal.valueOf(23.515), "toScaledBigDecimal(Double, int, RoudingMode) 2 failed");
1641 assertEquals(NumberUtils.toScaledBigDecimal(Double.valueOf(23.525d), 2, RoundingMode.HALF_UP),
1642 BigDecimal.valueOf(23.53), "toScaledBigDecimal(Double, int, RoudingMode) 3 failed");
1643 assertEquals("23521.0000",
1644 NumberUtils.toScaledBigDecimal(Double.valueOf(23.521d), 4, RoundingMode.HALF_EVEN)
1645 .multiply(BigDecimal.valueOf(1000)).toString(),
1646 "toScaledBigDecimal(Double, int, RoudingMode) 4 failed");
1647 assertEquals(NumberUtils.toScaledBigDecimal((Double) null, 2, RoundingMode.HALF_UP), BigDecimal.ZERO,
1648 "toScaledBigDecimal(Double, int, RoudingMode) 5 failed");
1649 }
1650
1651 /**
1652 * Test for {@link NumberUtils#toScaledBigDecimal(Float)}.
1653 */
1654 @Test
1655 public void testToScaledBigDecimalFloat() {
1656 assertEquals(NumberUtils.toScaledBigDecimal(Float.valueOf(123.456f)), BigDecimal.valueOf(123.46),
1657 "toScaledBigDecimal(Float) 1 failed");
1658 // Test RoudingMode.HALF_EVEN default rounding.
1659 assertEquals(NumberUtils.toScaledBigDecimal(Float.valueOf(23.515f)), BigDecimal.valueOf(23.51),
1660 "toScaledBigDecimal(Float) 2 failed");
1661 // Note. NumberUtils.toScaledBigDecimal(Float.valueOf(23.515f)).equals(BigDecimal.valueOf(23.51))
1662 // because of roundoff error. It is ok.
1663 assertEquals(NumberUtils.toScaledBigDecimal(Float.valueOf(23.525f)), BigDecimal.valueOf(23.52),
1664 "toScaledBigDecimal(Float) 3 failed");
1665 assertEquals("2352.00",
1666 NumberUtils.toScaledBigDecimal(Float.valueOf(23.525f)).multiply(BigDecimal.valueOf(100)).toString(),
1667 "toScaledBigDecimal(Float) 4 failed");
1668 assertEquals(NumberUtils.toScaledBigDecimal((Float) null), BigDecimal.ZERO,
1669 "toScaledBigDecimal(Float) 5 failed");
1670 }
1671
1672 /**
1673 * Test for {@link NumberUtils#toScaledBigDecimal(Float, int, RoundingMode)}.
1674 */
1675 @Test
1676 public void testToScaledBigDecimalFloatIRM() {
1677 assertEquals(NumberUtils.toScaledBigDecimal(Float.valueOf(123.456f), 1, RoundingMode.CEILING),
1678 BigDecimal.valueOf(123.5), "toScaledBigDecimal(Float, int, RoudingMode) 1 failed");
1679 assertEquals(NumberUtils.toScaledBigDecimal(Float.valueOf(23.5159f), 3, RoundingMode.FLOOR),
1680 BigDecimal.valueOf(23.515), "toScaledBigDecimal(Float, int, RoudingMode) 2 failed");
1681 // The following happens due to roundoff error. We're ok with this.
1682 assertEquals(NumberUtils.toScaledBigDecimal(Float.valueOf(23.525f), 2, RoundingMode.HALF_UP),
1683 BigDecimal.valueOf(23.52), "toScaledBigDecimal(Float, int, RoudingMode) 3 failed");
1684 assertEquals("23521.0000", NumberUtils.toScaledBigDecimal(Float.valueOf(23.521f), 4, RoundingMode.HALF_EVEN)
1685 .multiply(BigDecimal.valueOf(1000)).toString(), "toScaledBigDecimal(Float, int, RoudingMode) 4 failed");
1686 assertEquals(NumberUtils.toScaledBigDecimal((Float) null, 2, RoundingMode.HALF_UP), BigDecimal.ZERO,
1687 "toScaledBigDecimal(Float, int, RoudingMode) 5 failed");
1688 }
1689
1690 /**
1691 * Test for {@link NumberUtils#toScaledBigDecimal(Double)}.
1692 */
1693 @Test
1694 public void testToScaledBigDecimalString() {
1695 assertEquals(NumberUtils.toScaledBigDecimal("123.456"), BigDecimal.valueOf(123.46),
1696 "toScaledBigDecimal(String) 1 failed");
1697 // Test RoudingMode.HALF_EVEN default rounding.
1698 assertEquals(NumberUtils.toScaledBigDecimal("23.515"), BigDecimal.valueOf(23.52),
1699 "toScaledBigDecimal(String) 2 failed");
1700 assertEquals(NumberUtils.toScaledBigDecimal("23.525"), BigDecimal.valueOf(23.52),
1701 "toScaledBigDecimal(String) 3 failed");
1702 assertEquals("2352.00", NumberUtils.toScaledBigDecimal("23.525").multiply(BigDecimal.valueOf(100)).toString(),
1703 "toScaledBigDecimal(String) 4 failed");
1704 assertEquals(NumberUtils.toScaledBigDecimal((String) null), BigDecimal.ZERO,
1705 "toScaledBigDecimal(String) 5 failed");
1706 }
1707
1708 /**
1709 * Test for {@link NumberUtils#toScaledBigDecimal(Double, int, RoundingMode)}.
1710 */
1711 @Test
1712 public void testToScaledBigDecimalStringIRM() {
1713 assertEquals(NumberUtils.toScaledBigDecimal("123.456", 1, RoundingMode.CEILING), BigDecimal.valueOf(123.5),
1714 "toScaledBigDecimal(String, int, RoudingMode) 1 failed");
1715 assertEquals(NumberUtils.toScaledBigDecimal("23.5159", 3, RoundingMode.FLOOR), BigDecimal.valueOf(23.515),
1716 "toScaledBigDecimal(String, int, RoudingMode) 2 failed");
1717 assertEquals(NumberUtils.toScaledBigDecimal("23.525", 2, RoundingMode.HALF_UP), BigDecimal.valueOf(23.53),
1718 "toScaledBigDecimal(String, int, RoudingMode) 3 failed");
1719 assertEquals(
1720 "23521.0000", NumberUtils.toScaledBigDecimal("23.521", 4, RoundingMode.HALF_EVEN)
1721 .multiply(BigDecimal.valueOf(1000)).toString(),
1722 "toScaledBigDecimal(String, int, RoudingMode) 4 failed");
1723 assertEquals(NumberUtils.toScaledBigDecimal((String) null, 2, RoundingMode.HALF_UP), BigDecimal.ZERO,
1724 "toScaledBigDecimal(String, int, RoudingMode) 5 failed");
1725 }
1726
1727 /**
1728 * Test for {@link NumberUtils#toShort(String)}.
1729 */
1730 @Test
1731 public void testToShortString() {
1732 assertEquals(12345, NumberUtils.toShort("12345"), "toShort(String) 1 failed");
1733 assertEquals(0, NumberUtils.toShort("abc"), "toShort(String) 2 failed");
1734 assertEquals(0, NumberUtils.toShort(""), "toShort(empty) failed");
1735 assertEquals(0, NumberUtils.toShort(null), "toShort(null) failed");
1736 }
1737
1738 /**
1739 * Test for {@link NumberUtils#toShort(String, short)}.
1740 */
1741 @Test
1742 public void testToShortStringI() {
1743 assertEquals(12345, NumberUtils.toShort("12345", (short) 5), "toShort(String, short) 1 failed");
1744 assertEquals(5, NumberUtils.toShort("1234.5", (short) 5), "toShort(String, short) 2 failed");
15761745 }
15771746 }
4949 assertThrows(NullPointerException.class, () -> mutBool.compareTo(null));
5050 }
5151
52 @Test
53 public void testConstructorNull() {
54 assertThrows(NullPointerException.class, () -> new MutableBoolean(null));
55 }
56
5257 // ----------------------------------------------------------------
5358 @Test
5459 public void testConstructors() {
6065 assertTrue(new MutableBoolean(Boolean.TRUE).booleanValue());
6166 assertFalse(new MutableBoolean(Boolean.FALSE).booleanValue());
6267
63 }
64
65 @Test
66 public void testConstructorNull() {
67 assertThrows(NullPointerException.class, () -> new MutableBoolean(null));
6868 }
6969
7070 @Test
117117 }
118118
119119 @Test
120 public void testSetNull() {
121 final MutableBoolean mutBool = new MutableBoolean(false);
122 assertThrows(NullPointerException.class, () -> mutBool.setValue(null));
123 }
124
125 @Test
126120 public void testHashCode() {
127121 final MutableBoolean mutBoolA = new MutableBoolean(false);
128122 final MutableBoolean mutBoolB = new MutableBoolean(false);
136130 }
137131
138132 @Test
133 public void testSetNull() {
134 final MutableBoolean mutBool = new MutableBoolean(false);
135 assertThrows(NullPointerException.class, () -> mutBool.setValue(null));
136 }
137
138 @Test
139139 public void testToString() {
140140 assertEquals(Boolean.FALSE.toString(), new MutableBoolean(false).toString());
141141 assertEquals(Boolean.TRUE.toString(), new MutableBoolean(true).toString());
2828 */
2929 public class MutableByteTest {
3030
31 @Test
32 public void testAddAndGetValueObject() {
33 final MutableByte mutableByte = new MutableByte((byte) 0);
34 final byte result = mutableByte.addAndGet(Byte.valueOf((byte) 1));
35
36 assertEquals((byte) 1, result);
37 assertEquals((byte) 1, mutableByte.byteValue());
38 }
39
40 @Test
41 public void testAddAndGetValuePrimitive() {
42 final MutableByte mutableByte = new MutableByte((byte) 0);
43 final byte result = mutableByte.addAndGet((byte) 1);
44
45 assertEquals((byte) 1, result);
46 assertEquals((byte) 1, mutableByte.byteValue());
47 }
48
49 @Test
50 public void testAddValueObject() {
51 final MutableByte mutNum = new MutableByte((byte) 1);
52 mutNum.add(Integer.valueOf(1));
53
54 assertEquals((byte) 2, mutNum.byteValue());
55 }
56
57 @Test
58 public void testAddValuePrimitive() {
59 final MutableByte mutNum = new MutableByte((byte) 1);
60 mutNum.add((byte) 1);
61
62 assertEquals((byte) 2, mutNum.byteValue());
63 }
64
65 @Test
66 public void testCompareTo() {
67 final MutableByte mutNum = new MutableByte((byte) 0);
68
69 assertEquals((byte) 0, mutNum.compareTo(new MutableByte((byte) 0)));
70 assertEquals((byte) +1, mutNum.compareTo(new MutableByte((byte) -1)));
71 assertEquals((byte) -1, mutNum.compareTo(new MutableByte((byte) 1)));
72 }
73
74 @Test
75 public void testCompareToNull() {
76 final MutableByte mutNum = new MutableByte((byte) 0);
77 assertThrows(NullPointerException.class, () -> mutNum.compareTo(null));
78 }
79
80 @Test
81 public void testConstructorNull() {
82 assertThrows(NullPointerException.class, () -> new MutableByte((Number) null));
83 }
84
3185 // ----------------------------------------------------------------
3286 @Test
3387 public void testConstructors() {
4397 }
4498
4599 @Test
46 public void testConstructorNull() {
47 assertThrows(NullPointerException.class, () -> new MutableByte((Number) null));
48 }
49
50 @Test
51 public void testGetSet() {
52 final MutableByte mutNum = new MutableByte((byte) 0);
53 assertEquals((byte) 0, new MutableByte().byteValue());
54 assertEquals(Byte.valueOf((byte) 0), new MutableByte().getValue());
55
56 mutNum.setValue((byte) 1);
57 assertEquals((byte) 1, mutNum.byteValue());
58 assertEquals(Byte.valueOf((byte) 1), mutNum.getValue());
59
60 mutNum.setValue(Byte.valueOf((byte) 2));
61 assertEquals((byte) 2, mutNum.byteValue());
62 assertEquals(Byte.valueOf((byte) 2), mutNum.getValue());
63
64 mutNum.setValue(new MutableByte((byte) 3));
65 assertEquals((byte) 3, mutNum.byteValue());
66 assertEquals(Byte.valueOf((byte) 3), mutNum.getValue());
67 }
68
69 @Test
70 public void testSetNull() {
71 final MutableByte mutNum = new MutableByte((byte) 0);
72 assertThrows(NullPointerException.class, () -> mutNum.setValue(null));
100 public void testDecrement() {
101 final MutableByte mutNum = new MutableByte((byte) 1);
102 mutNum.decrement();
103
104 assertEquals(0, mutNum.intValue());
105 assertEquals(0L, mutNum.longValue());
106 }
107
108 @Test
109 public void testDecrementAndGet() {
110 final MutableByte mutNum = new MutableByte((byte) 1);
111 final byte result = mutNum.decrementAndGet();
112
113 assertEquals(0, result);
114 assertEquals(0, mutNum.intValue());
115 assertEquals(0L, mutNum.longValue());
73116 }
74117
75118 @Test
91134 }
92135
93136 @Test
137 public void testGetAndAddValueObject() {
138 final MutableByte mutableByte = new MutableByte((byte) 0);
139 final byte result = mutableByte.getAndAdd(Byte.valueOf((byte) 1));
140
141 assertEquals((byte) 0, result);
142 assertEquals((byte) 1, mutableByte.byteValue());
143 }
144
145 @Test
146 public void testGetAndAddValuePrimitive() {
147 final MutableByte mutableByte = new MutableByte((byte) 0);
148 final byte result = mutableByte.getAndAdd((byte) 1);
149
150 assertEquals((byte) 0, result);
151 assertEquals((byte) 1, mutableByte.byteValue());
152 }
153
154 @Test
155 public void testGetAndDecrement() {
156 final MutableByte mutNum = new MutableByte((byte) 1);
157 final byte result = mutNum.getAndDecrement();
158
159 assertEquals(1, result);
160 assertEquals(0, mutNum.intValue());
161 assertEquals(0L, mutNum.longValue());
162 }
163
164 @Test
165 public void testGetAndIncrement() {
166 final MutableByte mutNum = new MutableByte((byte) 1);
167 final byte result = mutNum.getAndIncrement();
168
169 assertEquals(1, result);
170 assertEquals(2, mutNum.intValue());
171 assertEquals(2L, mutNum.longValue());
172 }
173
174 @Test
175 public void testGetSet() {
176 final MutableByte mutNum = new MutableByte((byte) 0);
177 assertEquals((byte) 0, new MutableByte().byteValue());
178 assertEquals(Byte.valueOf((byte) 0), new MutableByte().getValue());
179
180 mutNum.setValue((byte) 1);
181 assertEquals((byte) 1, mutNum.byteValue());
182 assertEquals(Byte.valueOf((byte) 1), mutNum.getValue());
183
184 mutNum.setValue(Byte.valueOf((byte) 2));
185 assertEquals((byte) 2, mutNum.byteValue());
186 assertEquals(Byte.valueOf((byte) 2), mutNum.getValue());
187
188 mutNum.setValue(new MutableByte((byte) 3));
189 assertEquals((byte) 3, mutNum.byteValue());
190 assertEquals(Byte.valueOf((byte) 3), mutNum.getValue());
191 }
192
193 @Test
94194 public void testHashCode() {
95195 final MutableByte mutNumA = new MutableByte((byte) 0);
96196 final MutableByte mutNumB = new MutableByte((byte) 0);
103203 }
104204
105205 @Test
106 public void testCompareTo() {
107 final MutableByte mutNum = new MutableByte((byte) 0);
108
109 assertEquals((byte) 0, mutNum.compareTo(new MutableByte((byte) 0)));
110 assertEquals((byte) +1, mutNum.compareTo(new MutableByte((byte) -1)));
111 assertEquals((byte) -1, mutNum.compareTo(new MutableByte((byte) 1)));
112 }
113
114 @Test
115 public void testCompareToNull() {
116 final MutableByte mutNum = new MutableByte((byte) 0);
117 assertThrows(NullPointerException.class, () -> mutNum.compareTo(null));
206 public void testIncrement() {
207 final MutableByte mutNum = new MutableByte((byte) 1);
208 mutNum.increment();
209
210 assertEquals(2, mutNum.intValue());
211 assertEquals(2L, mutNum.longValue());
212 }
213
214 @Test
215 public void testIncrementAndGet() {
216 final MutableByte mutNum = new MutableByte((byte) 1);
217 final byte result = mutNum.incrementAndGet();
218
219 assertEquals(2, result);
220 assertEquals(2, mutNum.intValue());
221 assertEquals(2L, mutNum.longValue());
118222 }
119223
120224 @Test
129233 }
130234
131235 @Test
236 public void testSetNull() {
237 final MutableByte mutNum = new MutableByte((byte) 0);
238 assertThrows(NullPointerException.class, () -> mutNum.setValue(null));
239 }
240
241 @Test
242 public void testSubtractValueObject() {
243 final MutableByte mutNum = new MutableByte((byte) 1);
244 mutNum.subtract(Integer.valueOf(1));
245
246 assertEquals((byte) 0, mutNum.byteValue());
247 }
248
249 @Test
250 public void testSubtractValuePrimitive() {
251 final MutableByte mutNum = new MutableByte((byte) 1);
252 mutNum.subtract((byte) 1);
253
254 assertEquals((byte) 0, mutNum.byteValue());
255 }
256
257 @Test
132258 public void testToByte() {
133259 assertEquals(Byte.valueOf((byte) 0), new MutableByte((byte) 0).toByte());
134260 assertEquals(Byte.valueOf((byte) 123), new MutableByte((byte) 123).toByte());
135 }
136
137 @Test
138 public void testIncrement() {
139 final MutableByte mutNum = new MutableByte((byte) 1);
140 mutNum.increment();
141
142 assertEquals(2, mutNum.intValue());
143 assertEquals(2L, mutNum.longValue());
144 }
145
146 @Test
147 public void testIncrementAndGet() {
148 final MutableByte mutNum = new MutableByte((byte) 1);
149 final byte result = mutNum.incrementAndGet();
150
151 assertEquals(2, result);
152 assertEquals(2, mutNum.intValue());
153 assertEquals(2L, mutNum.longValue());
154 }
155
156 @Test
157 public void testGetAndIncrement() {
158 final MutableByte mutNum = new MutableByte((byte) 1);
159 final byte result = mutNum.getAndIncrement();
160
161 assertEquals(1, result);
162 assertEquals(2, mutNum.intValue());
163 assertEquals(2L, mutNum.longValue());
164 }
165
166 @Test
167 public void testDecrement() {
168 final MutableByte mutNum = new MutableByte((byte) 1);
169 mutNum.decrement();
170
171 assertEquals(0, mutNum.intValue());
172 assertEquals(0L, mutNum.longValue());
173 }
174
175 @Test
176 public void testDecrementAndGet() {
177 final MutableByte mutNum = new MutableByte((byte) 1);
178 final byte result = mutNum.decrementAndGet();
179
180 assertEquals(0, result);
181 assertEquals(0, mutNum.intValue());
182 assertEquals(0L, mutNum.longValue());
183 }
184
185 @Test
186 public void testGetAndDecrement() {
187 final MutableByte mutNum = new MutableByte((byte) 1);
188 final byte result = mutNum.getAndDecrement();
189
190 assertEquals(1, result);
191 assertEquals(0, mutNum.intValue());
192 assertEquals(0L, mutNum.longValue());
193 }
194
195 @Test
196 public void testAddValuePrimitive() {
197 final MutableByte mutNum = new MutableByte((byte) 1);
198 mutNum.add((byte) 1);
199
200 assertEquals((byte) 2, mutNum.byteValue());
201 }
202
203 @Test
204 public void testAddValueObject() {
205 final MutableByte mutNum = new MutableByte((byte) 1);
206 mutNum.add(Integer.valueOf(1));
207
208 assertEquals((byte) 2, mutNum.byteValue());
209 }
210
211 @Test
212 public void testGetAndAddValuePrimitive() {
213 final MutableByte mutableByte = new MutableByte((byte) 0);
214 final byte result = mutableByte.getAndAdd((byte) 1);
215
216 assertEquals((byte) 0, result);
217 assertEquals((byte) 1, mutableByte.byteValue());
218 }
219
220 @Test
221 public void testGetAndAddValueObject() {
222 final MutableByte mutableByte = new MutableByte((byte) 0);
223 final byte result = mutableByte.getAndAdd(Byte.valueOf((byte) 1));
224
225 assertEquals((byte) 0, result);
226 assertEquals((byte) 1, mutableByte.byteValue());
227 }
228
229 @Test
230 public void testAddAndGetValuePrimitive() {
231 final MutableByte mutableByte = new MutableByte((byte) 0);
232 final byte result = mutableByte.addAndGet((byte) 1);
233
234 assertEquals((byte) 1, result);
235 assertEquals((byte) 1, mutableByte.byteValue());
236 }
237
238 @Test
239 public void testAddAndGetValueObject() {
240 final MutableByte mutableByte = new MutableByte((byte) 0);
241 final byte result = mutableByte.addAndGet(Byte.valueOf((byte) 1));
242
243 assertEquals((byte) 1, result);
244 assertEquals((byte) 1, mutableByte.byteValue());
245 }
246
247 @Test
248 public void testSubtractValuePrimitive() {
249 final MutableByte mutNum = new MutableByte((byte) 1);
250 mutNum.subtract((byte) 1);
251
252 assertEquals((byte) 0, mutNum.byteValue());
253 }
254
255 @Test
256 public void testSubtractValueObject() {
257 final MutableByte mutNum = new MutableByte((byte) 1);
258 mutNum.subtract(Integer.valueOf(1));
259
260 assertEquals((byte) 0, mutNum.byteValue());
261261 }
262262
263263 @Test
2929 */
3030 public class MutableDoubleTest {
3131
32 @Test
33 public void testAddAndGetValueObject() {
34 final MutableDouble mutableDouble = new MutableDouble(7.5d);
35 final double result = mutableDouble.addAndGet(Double.valueOf(-2.5d));
36
37 assertEquals(5d, result, 0.01d);
38 assertEquals(5d, mutableDouble.doubleValue(), 0.01d);
39 }
40
41 @Test
42 public void testAddAndGetValuePrimitive() {
43 final MutableDouble mutableDouble = new MutableDouble(10.5d);
44 final double result = mutableDouble.addAndGet(-0.5d);
45
46 assertEquals(10d, result, 0.01d);
47 assertEquals(10d, mutableDouble.doubleValue(), 0.01d);
48 }
49
50 @Test
51 public void testAddValueObject() {
52 final MutableDouble mutNum = new MutableDouble(1);
53 mutNum.add(Double.valueOf(1.1d));
54
55 assertEquals(2.1d, mutNum.doubleValue(), 0.01d);
56 }
57
58 @Test
59 public void testAddValuePrimitive() {
60 final MutableDouble mutNum = new MutableDouble(1);
61 mutNum.add(1.1d);
62
63 assertEquals(2.1d, mutNum.doubleValue(), 0.01d);
64 }
65
66 @Test
67 public void testCompareTo() {
68 final MutableDouble mutNum = new MutableDouble(0d);
69
70 assertEquals(0, mutNum.compareTo(new MutableDouble(0d)));
71 assertEquals(+1, mutNum.compareTo(new MutableDouble(-1d)));
72 assertEquals(-1, mutNum.compareTo(new MutableDouble(1d)));
73 }
74
75 @Test
76 public void testCompareToNull() {
77 final MutableDouble mutNum = new MutableDouble(0d);
78 assertThrows(NullPointerException.class, () -> mutNum.compareTo(null));
79 }
80
81 @Test
82 public void testConstructorNull() {
83 assertThrows(NullPointerException.class, () -> new MutableDouble((Number) null));
84 }
85
3286 // ----------------------------------------------------------------
3387 @Test
3488 public void testConstructors() {
4498 }
4599
46100 @Test
47 public void testConstructorNull() {
48 assertThrows(NullPointerException.class, () -> new MutableDouble((Number) null));
49 }
50
51 @Test
52 public void testGetSet() {
53 final MutableDouble mutNum = new MutableDouble(0d);
54 assertEquals(0d, new MutableDouble().doubleValue(), 0.0001d);
55 assertEquals(Double.valueOf(0), new MutableDouble().getValue());
56
57 mutNum.setValue(1);
58 assertEquals(1d, mutNum.doubleValue(), 0.0001d);
59 assertEquals(Double.valueOf(1d), mutNum.getValue());
60
61 mutNum.setValue(Double.valueOf(2d));
62 assertEquals(2d, mutNum.doubleValue(), 0.0001d);
63 assertEquals(Double.valueOf(2d), mutNum.getValue());
64
65 mutNum.setValue(new MutableDouble(3d));
66 assertEquals(3d, mutNum.doubleValue(), 0.0001d);
67 assertEquals(Double.valueOf(3d), mutNum.getValue());
68 }
69
70 @Test
71 public void testSetNull() {
72 final MutableDouble mutNum = new MutableDouble(0d);
73 assertThrows(NullPointerException.class, () -> mutNum.setValue(null));
74 }
75
76 @Test
77 public void testNanInfinite() {
78 MutableDouble mutNum = new MutableDouble(Double.NaN);
79 assertTrue(mutNum.isNaN());
80
81 mutNum = new MutableDouble(Double.POSITIVE_INFINITY);
82 assertTrue(mutNum.isInfinite());
83
84 mutNum = new MutableDouble(Double.NEGATIVE_INFINITY);
85 assertTrue(mutNum.isInfinite());
101 public void testDecrement() {
102 final MutableDouble mutNum = new MutableDouble(1);
103 mutNum.decrement();
104
105 assertEquals(0, mutNum.intValue());
106 assertEquals(0L, mutNum.longValue());
107 }
108
109 @Test
110 public void testDecrementAndGet() {
111 final MutableDouble mutNum = new MutableDouble(1d);
112 final double result = mutNum.decrementAndGet();
113
114 assertEquals(0d, result, 0.01d);
115 assertEquals(0, mutNum.intValue());
116 assertEquals(0L, mutNum.longValue());
86117 }
87118
88119 @Test
104135 }
105136
106137 @Test
138 public void testGetAndAddValueObject() {
139 final MutableDouble mutableDouble = new MutableDouble(0.5d);
140 final double result = mutableDouble.getAndAdd(Double.valueOf(2d));
141
142 assertEquals(0.5d, result, 0.01d);
143 assertEquals(2.5d, mutableDouble.doubleValue(), 0.01d);
144 }
145
146 @Test
147 public void testGetAndAddValuePrimitive() {
148 final MutableDouble mutableDouble = new MutableDouble(0.5d);
149 final double result = mutableDouble.getAndAdd(1d);
150
151 assertEquals(0.5d, result, 0.01d);
152 assertEquals(1.5d, mutableDouble.doubleValue(), 0.01d);
153 }
154
155 @Test
156 public void testGetAndDecrement() {
157 final MutableDouble mutNum = new MutableDouble(1d);
158 final double result = mutNum.getAndDecrement();
159
160 assertEquals(1d, result, 0.01d);
161 assertEquals(0, mutNum.intValue());
162 assertEquals(0L, mutNum.longValue());
163 }
164
165 @Test
166 public void testGetAndIncrement() {
167 final MutableDouble mutNum = new MutableDouble(1d);
168 final double result = mutNum.getAndIncrement();
169
170 assertEquals(1d, result, 0.01d);
171 assertEquals(2, mutNum.intValue());
172 assertEquals(2L, mutNum.longValue());
173 }
174
175 @Test
176 public void testGetSet() {
177 final MutableDouble mutNum = new MutableDouble(0d);
178 assertEquals(0d, new MutableDouble().doubleValue(), 0.0001d);
179 assertEquals(Double.valueOf(0), new MutableDouble().getValue());
180
181 mutNum.setValue(1);
182 assertEquals(1d, mutNum.doubleValue(), 0.0001d);
183 assertEquals(Double.valueOf(1d), mutNum.getValue());
184
185 mutNum.setValue(Double.valueOf(2d));
186 assertEquals(2d, mutNum.doubleValue(), 0.0001d);
187 assertEquals(Double.valueOf(2d), mutNum.getValue());
188
189 mutNum.setValue(new MutableDouble(3d));
190 assertEquals(3d, mutNum.doubleValue(), 0.0001d);
191 assertEquals(Double.valueOf(3d), mutNum.getValue());
192 }
193
194 @Test
107195 public void testHashCode() {
108196 final MutableDouble mutNumA = new MutableDouble(0d);
109197 final MutableDouble mutNumB = new MutableDouble(0d);
116204 }
117205
118206 @Test
119 public void testCompareTo() {
120 final MutableDouble mutNum = new MutableDouble(0d);
121
122 assertEquals(0, mutNum.compareTo(new MutableDouble(0d)));
123 assertEquals(+1, mutNum.compareTo(new MutableDouble(-1d)));
124 assertEquals(-1, mutNum.compareTo(new MutableDouble(1d)));
125 }
126
127 @Test
128 public void testCompareToNull() {
129 final MutableDouble mutNum = new MutableDouble(0d);
130 assertThrows(NullPointerException.class, () -> mutNum.compareTo(null));
207 public void testIncrement() {
208 final MutableDouble mutNum = new MutableDouble(1);
209 mutNum.increment();
210
211 assertEquals(2, mutNum.intValue());
212 assertEquals(2L, mutNum.longValue());
213 }
214
215 @Test
216 public void testIncrementAndGet() {
217 final MutableDouble mutNum = new MutableDouble(1d);
218 final double result = mutNum.incrementAndGet();
219
220 assertEquals(2d, result, 0.01d);
221 assertEquals(2, mutNum.intValue());
222 assertEquals(2L, mutNum.longValue());
223 }
224
225 @Test
226 public void testNanInfinite() {
227 MutableDouble mutNum = new MutableDouble(Double.NaN);
228 assertTrue(mutNum.isNaN());
229
230 mutNum = new MutableDouble(Double.POSITIVE_INFINITY);
231 assertTrue(mutNum.isInfinite());
232
233 mutNum = new MutableDouble(Double.NEGATIVE_INFINITY);
234 assertTrue(mutNum.isInfinite());
131235 }
132236
133237 @Test
142246 }
143247
144248 @Test
249 public void testSetNull() {
250 final MutableDouble mutNum = new MutableDouble(0d);
251 assertThrows(NullPointerException.class, () -> mutNum.setValue(null));
252 }
253
254 @Test
255 public void testSubtractValueObject() {
256 final MutableDouble mutNum = new MutableDouble(1);
257 mutNum.subtract(Double.valueOf(0.9d));
258
259 assertEquals(0.1d, mutNum.doubleValue(), 0.01d);
260 }
261
262 @Test
263 public void testSubtractValuePrimitive() {
264 final MutableDouble mutNum = new MutableDouble(1);
265 mutNum.subtract(0.9d);
266
267 assertEquals(0.1d, mutNum.doubleValue(), 0.01d);
268 }
269
270 @Test
145271 public void testToDouble() {
146272 assertEquals(Double.valueOf(0d), new MutableDouble(0d).toDouble());
147273 assertEquals(Double.valueOf(12.3d), new MutableDouble(12.3d).toDouble());
148 }
149
150 @Test
151 public void testIncrement() {
152 final MutableDouble mutNum = new MutableDouble(1);
153 mutNum.increment();
154
155 assertEquals(2, mutNum.intValue());
156 assertEquals(2L, mutNum.longValue());
157 }
158
159 @Test
160 public void testIncrementAndGet() {
161 final MutableDouble mutNum = new MutableDouble(1d);
162 final double result = mutNum.incrementAndGet();
163
164 assertEquals(2d, result, 0.01d);
165 assertEquals(2, mutNum.intValue());
166 assertEquals(2L, mutNum.longValue());
167 }
168
169 @Test
170 public void testGetAndIncrement() {
171 final MutableDouble mutNum = new MutableDouble(1d);
172 final double result = mutNum.getAndIncrement();
173
174 assertEquals(1d, result, 0.01d);
175 assertEquals(2, mutNum.intValue());
176 assertEquals(2L, mutNum.longValue());
177 }
178
179 @Test
180 public void testDecrement() {
181 final MutableDouble mutNum = new MutableDouble(1);
182 mutNum.decrement();
183
184 assertEquals(0, mutNum.intValue());
185 assertEquals(0L, mutNum.longValue());
186 }
187
188 @Test
189 public void testDecrementAndGet() {
190 final MutableDouble mutNum = new MutableDouble(1d);
191 final double result = mutNum.decrementAndGet();
192
193 assertEquals(0d, result, 0.01d);
194 assertEquals(0, mutNum.intValue());
195 assertEquals(0L, mutNum.longValue());
196 }
197
198 @Test
199 public void testGetAndDecrement() {
200 final MutableDouble mutNum = new MutableDouble(1d);
201 final double result = mutNum.getAndDecrement();
202
203 assertEquals(1d, result, 0.01d);
204 assertEquals(0, mutNum.intValue());
205 assertEquals(0L, mutNum.longValue());
206 }
207
208 @Test
209 public void testAddValuePrimitive() {
210 final MutableDouble mutNum = new MutableDouble(1);
211 mutNum.add(1.1d);
212
213 assertEquals(2.1d, mutNum.doubleValue(), 0.01d);
214 }
215
216 @Test
217 public void testAddValueObject() {
218 final MutableDouble mutNum = new MutableDouble(1);
219 mutNum.add(Double.valueOf(1.1d));
220
221 assertEquals(2.1d, mutNum.doubleValue(), 0.01d);
222 }
223
224 @Test
225 public void testGetAndAddValuePrimitive() {
226 final MutableDouble mutableDouble = new MutableDouble(0.5d);
227 final double result = mutableDouble.getAndAdd(1d);
228
229 assertEquals(0.5d, result, 0.01d);
230 assertEquals(1.5d, mutableDouble.doubleValue(), 0.01d);
231 }
232
233 @Test
234 public void testGetAndAddValueObject() {
235 final MutableDouble mutableDouble = new MutableDouble(0.5d);
236 final double result = mutableDouble.getAndAdd(Double.valueOf(2d));
237
238 assertEquals(0.5d, result, 0.01d);
239 assertEquals(2.5d, mutableDouble.doubleValue(), 0.01d);
240 }
241
242 @Test
243 public void testAddAndGetValuePrimitive() {
244 final MutableDouble mutableDouble = new MutableDouble(10.5d);
245 final double result = mutableDouble.addAndGet(-0.5d);
246
247 assertEquals(10d, result, 0.01d);
248 assertEquals(10d, mutableDouble.doubleValue(), 0.01d);
249 }
250
251 @Test
252 public void testAddAndGetValueObject() {
253 final MutableDouble mutableDouble = new MutableDouble(7.5d);
254 final double result = mutableDouble.addAndGet(Double.valueOf(-2.5d));
255
256 assertEquals(5d, result, 0.01d);
257 assertEquals(5d, mutableDouble.doubleValue(), 0.01d);
258 }
259
260 @Test
261 public void testSubtractValuePrimitive() {
262 final MutableDouble mutNum = new MutableDouble(1);
263 mutNum.subtract(0.9d);
264
265 assertEquals(0.1d, mutNum.doubleValue(), 0.01d);
266 }
267
268 @Test
269 public void testSubtractValueObject() {
270 final MutableDouble mutNum = new MutableDouble(1);
271 mutNum.subtract(Double.valueOf(0.9d));
272
273 assertEquals(0.1d, mutNum.doubleValue(), 0.01d);
274274 }
275275
276276 @Test
2929 */
3030 public class MutableFloatTest {
3131
32 @Test
33 public void testAddAndGetValueObject() {
34 final MutableFloat mutableFloat = new MutableFloat(5f);
35 final float result = mutableFloat.addAndGet(Float.valueOf(2.5f));
36
37 assertEquals(7.5f, result, 0.01f);
38 assertEquals(7.5f, mutableFloat.floatValue(), 0.01f);
39 }
40
41 @Test
42 public void testAddAndGetValuePrimitive() {
43 final MutableFloat mutableFloat = new MutableFloat(0.5f);
44 final float result = mutableFloat.addAndGet(1f);
45
46 assertEquals(1.5f, result, 0.01f);
47 assertEquals(1.5f, mutableFloat.floatValue(), 0.01f);
48 }
49
50 @Test
51 public void testAddValueObject() {
52 final MutableFloat mutNum = new MutableFloat(1);
53 mutNum.add(Float.valueOf(1.1f));
54
55 assertEquals(2.1f, mutNum.floatValue(), 0.01f);
56 }
57
58 @Test
59 public void testAddValuePrimitive() {
60 final MutableFloat mutNum = new MutableFloat(1);
61 mutNum.add(1.1f);
62
63 assertEquals(2.1f, mutNum.floatValue(), 0.01f);
64 }
65
66 @Test
67 public void testCompareTo() {
68 final MutableFloat mutNum = new MutableFloat(0f);
69
70 assertEquals(0, mutNum.compareTo(new MutableFloat(0f)));
71 assertEquals(+1, mutNum.compareTo(new MutableFloat(-1f)));
72 assertEquals(-1, mutNum.compareTo(new MutableFloat(1f)));
73 }
74
75 @Test
76 public void testCompareToNull() {
77 final MutableFloat mutNum = new MutableFloat(0f);
78 assertThrows(NullPointerException.class, () -> mutNum.compareTo(null));
79 }
80
81 @Test
82 public void testConstructorNull() {
83 assertThrows(NullPointerException.class, () -> new MutableFloat((Number) null));
84 }
85
3286 // ----------------------------------------------------------------
3387 @Test
3488 public void testConstructors() {
4498 }
4599
46100 @Test
47 public void testConstructorNull() {
48 assertThrows(NullPointerException.class, () -> new MutableFloat((Number) null));
49 }
50
51 @Test
52 public void testGetSet() {
53 final MutableFloat mutNum = new MutableFloat(0f);
54 assertEquals(0f, new MutableFloat().floatValue(), 0.0001f);
55 assertEquals(Float.valueOf(0), new MutableFloat().getValue());
56
57 mutNum.setValue(1);
58 assertEquals(1f, mutNum.floatValue(), 0.0001f);
59 assertEquals(Float.valueOf(1f), mutNum.getValue());
60
61 mutNum.setValue(Float.valueOf(2f));
62 assertEquals(2f, mutNum.floatValue(), 0.0001f);
63 assertEquals(Float.valueOf(2f), mutNum.getValue());
64
65 mutNum.setValue(new MutableFloat(3f));
66 assertEquals(3f, mutNum.floatValue(), 0.0001f);
67 assertEquals(Float.valueOf(3f), mutNum.getValue());
68 }
69
70 @Test
71 public void testSetNull() {
72 final MutableFloat mutNum = new MutableFloat(0f);
73 assertThrows(NullPointerException.class, () -> mutNum.setValue(null));
74 }
75
76 @Test
77 public void testNanInfinite() {
78 MutableFloat mutNum = new MutableFloat(Float.NaN);
79 assertTrue(mutNum.isNaN());
80
81 mutNum = new MutableFloat(Float.POSITIVE_INFINITY);
82 assertTrue(mutNum.isInfinite());
83
84 mutNum = new MutableFloat(Float.NEGATIVE_INFINITY);
85 assertTrue(mutNum.isInfinite());
101 public void testDecrement() {
102 final MutableFloat mutNum = new MutableFloat(1);
103 mutNum.decrement();
104
105 assertEquals(0, mutNum.intValue());
106 assertEquals(0L, mutNum.longValue());
107 }
108
109 @Test
110 public void testDecrementAndGet() {
111 final MutableFloat mutNum = new MutableFloat(1f);
112 final float result = mutNum.decrementAndGet();
113
114 assertEquals(0f, result, 0.01f);
115 assertEquals(0, mutNum.intValue());
116 assertEquals(0L, mutNum.longValue());
86117 }
87118
88119 @Test
104135 }
105136
106137 @Test
138 public void testGetAndAddValueObject() {
139 final MutableFloat mutableFloat = new MutableFloat(7.75f);
140 final float result = mutableFloat.getAndAdd(Float.valueOf(2.25f));
141
142 assertEquals(7.75f, result, 0.01f);
143 assertEquals(10f, mutableFloat.floatValue(), 0.01f);
144 }
145
146 @Test
147 public void testGetAndAddValuePrimitive() {
148 final MutableFloat mutableFloat = new MutableFloat(1.25f);
149 final float result = mutableFloat.getAndAdd(0.75f);
150
151 assertEquals(1.25f, result, 0.01f);
152 assertEquals(2f, mutableFloat.floatValue(), 0.01f);
153 }
154
155 @Test
156 public void testGetAndDecrement() {
157 final MutableFloat mutNum = new MutableFloat(1f);
158 final float result = mutNum.getAndDecrement();
159
160 assertEquals(1f, result, 0.01f);
161 assertEquals(0, mutNum.intValue());
162 assertEquals(0L, mutNum.longValue());
163 }
164
165 @Test
166 public void testGetAndIncrement() {
167 final MutableFloat mutNum = new MutableFloat(1f);
168 final float result = mutNum.getAndIncrement();
169
170 assertEquals(1f, result, 0.01f);
171 assertEquals(2, mutNum.intValue());
172 assertEquals(2L, mutNum.longValue());
173 }
174
175 @Test
176 public void testGetSet() {
177 final MutableFloat mutNum = new MutableFloat(0f);
178 assertEquals(0f, new MutableFloat().floatValue(), 0.0001f);
179 assertEquals(Float.valueOf(0), new MutableFloat().getValue());
180
181 mutNum.setValue(1);
182 assertEquals(1f, mutNum.floatValue(), 0.0001f);
183 assertEquals(Float.valueOf(1f), mutNum.getValue());
184
185 mutNum.setValue(Float.valueOf(2f));
186 assertEquals(2f, mutNum.floatValue(), 0.0001f);
187 assertEquals(Float.valueOf(2f), mutNum.getValue());
188
189 mutNum.setValue(new MutableFloat(3f));
190 assertEquals(3f, mutNum.floatValue(), 0.0001f);
191 assertEquals(Float.valueOf(3f), mutNum.getValue());
192 }
193
194 @Test
107195 public void testHashCode() {
108196 final MutableFloat mutNumA = new MutableFloat(0f);
109197 final MutableFloat mutNumB = new MutableFloat(0f);
116204 }
117205
118206 @Test
119 public void testCompareTo() {
120 final MutableFloat mutNum = new MutableFloat(0f);
121
122 assertEquals(0, mutNum.compareTo(new MutableFloat(0f)));
123 assertEquals(+1, mutNum.compareTo(new MutableFloat(-1f)));
124 assertEquals(-1, mutNum.compareTo(new MutableFloat(1f)));
125 }
126
127 @Test
128 public void testCompareToNull() {
129 final MutableFloat mutNum = new MutableFloat(0f);
130 assertThrows(NullPointerException.class, () -> mutNum.compareTo(null));
207 public void testIncrement() {
208 final MutableFloat mutNum = new MutableFloat(1);
209 mutNum.increment();
210
211 assertEquals(2, mutNum.intValue());
212 assertEquals(2L, mutNum.longValue());
213 }
214
215 @Test
216 public void testIncrementAndGet() {
217 final MutableFloat mutNum = new MutableFloat(1f);
218 final float result = mutNum.incrementAndGet();
219
220 assertEquals(2f, result, 0.01f);
221 assertEquals(2, mutNum.intValue());
222 assertEquals(2L, mutNum.longValue());
223 }
224
225 @Test
226 public void testNanInfinite() {
227 MutableFloat mutNum = new MutableFloat(Float.NaN);
228 assertTrue(mutNum.isNaN());
229
230 mutNum = new MutableFloat(Float.POSITIVE_INFINITY);
231 assertTrue(mutNum.isInfinite());
232
233 mutNum = new MutableFloat(Float.NEGATIVE_INFINITY);
234 assertTrue(mutNum.isInfinite());
131235 }
132236
133237 @Test
143247 }
144248
145249 @Test
250 public void testSetNull() {
251 final MutableFloat mutNum = new MutableFloat(0f);
252 assertThrows(NullPointerException.class, () -> mutNum.setValue(null));
253 }
254
255 @Test
256 public void testSubtractValueObject() {
257 final MutableFloat mutNum = new MutableFloat(1);
258 mutNum.subtract(Float.valueOf(0.9f));
259
260 assertEquals(0.1f, mutNum.floatValue(), 0.01f);
261 }
262
263 @Test
264 public void testSubtractValuePrimitive() {
265 final MutableFloat mutNum = new MutableFloat(1);
266 mutNum.subtract(0.9f);
267
268 assertEquals(0.1f, mutNum.floatValue(), 0.01f);
269 }
270
271 @Test
146272 public void testToFloat() {
147273 assertEquals(Float.valueOf(0f), new MutableFloat(0f).toFloat());
148274 assertEquals(Float.valueOf(12.3f), new MutableFloat(12.3f).toFloat());
149 }
150
151 @Test
152 public void testIncrement() {
153 final MutableFloat mutNum = new MutableFloat(1);
154 mutNum.increment();
155
156 assertEquals(2, mutNum.intValue());
157 assertEquals(2L, mutNum.longValue());
158 }
159
160 @Test
161 public void testIncrementAndGet() {
162 final MutableFloat mutNum = new MutableFloat(1f);
163 final float result = mutNum.incrementAndGet();
164
165 assertEquals(2f, result, 0.01f);
166 assertEquals(2, mutNum.intValue());
167 assertEquals(2L, mutNum.longValue());
168 }
169
170 @Test
171 public void testGetAndIncrement() {
172 final MutableFloat mutNum = new MutableFloat(1f);
173 final float result = mutNum.getAndIncrement();
174
175 assertEquals(1f, result, 0.01f);
176 assertEquals(2, mutNum.intValue());
177 assertEquals(2L, mutNum.longValue());
178 }
179
180 @Test
181 public void testDecrement() {
182 final MutableFloat mutNum = new MutableFloat(1);
183 mutNum.decrement();
184
185 assertEquals(0, mutNum.intValue());
186 assertEquals(0L, mutNum.longValue());
187 }
188
189 @Test
190 public void testDecrementAndGet() {
191 final MutableFloat mutNum = new MutableFloat(1f);
192 final float result = mutNum.decrementAndGet();
193
194 assertEquals(0f, result, 0.01f);
195 assertEquals(0, mutNum.intValue());
196 assertEquals(0L, mutNum.longValue());
197 }
198
199 @Test
200 public void testGetAndDecrement() {
201 final MutableFloat mutNum = new MutableFloat(1f);
202 final float result = mutNum.getAndDecrement();
203
204 assertEquals(1f, result, 0.01f);
205 assertEquals(0, mutNum.intValue());
206 assertEquals(0L, mutNum.longValue());
207 }
208
209 @Test
210 public void testAddValuePrimitive() {
211 final MutableFloat mutNum = new MutableFloat(1);
212 mutNum.add(1.1f);
213
214 assertEquals(2.1f, mutNum.floatValue(), 0.01f);
215 }
216
217 @Test
218 public void testAddValueObject() {
219 final MutableFloat mutNum = new MutableFloat(1);
220 mutNum.add(Float.valueOf(1.1f));
221
222 assertEquals(2.1f, mutNum.floatValue(), 0.01f);
223 }
224
225 @Test
226 public void testGetAndAddValuePrimitive() {
227 final MutableFloat mutableFloat = new MutableFloat(1.25f);
228 final float result = mutableFloat.getAndAdd(0.75f);
229
230 assertEquals(1.25f, result, 0.01f);
231 assertEquals(2f, mutableFloat.floatValue(), 0.01f);
232 }
233
234 @Test
235 public void testGetAndAddValueObject() {
236 final MutableFloat mutableFloat = new MutableFloat(7.75f);
237 final float result = mutableFloat.getAndAdd(Float.valueOf(2.25f));
238
239 assertEquals(7.75f, result, 0.01f);
240 assertEquals(10f, mutableFloat.floatValue(), 0.01f);
241 }
242
243 @Test
244 public void testAddAndGetValuePrimitive() {
245 final MutableFloat mutableFloat = new MutableFloat(0.5f);
246 final float result = mutableFloat.addAndGet(1f);
247
248 assertEquals(1.5f, result, 0.01f);
249 assertEquals(1.5f, mutableFloat.floatValue(), 0.01f);
250 }
251
252 @Test
253 public void testAddAndGetValueObject() {
254 final MutableFloat mutableFloat = new MutableFloat(5f);
255 final float result = mutableFloat.addAndGet(Float.valueOf(2.5f));
256
257 assertEquals(7.5f, result, 0.01f);
258 assertEquals(7.5f, mutableFloat.floatValue(), 0.01f);
259 }
260
261 @Test
262 public void testSubtractValuePrimitive() {
263 final MutableFloat mutNum = new MutableFloat(1);
264 mutNum.subtract(0.9f);
265
266 assertEquals(0.1f, mutNum.floatValue(), 0.01f);
267 }
268
269 @Test
270 public void testSubtractValueObject() {
271 final MutableFloat mutNum = new MutableFloat(1);
272 mutNum.subtract(Float.valueOf(0.9f));
273
274 assertEquals(0.1f, mutNum.floatValue(), 0.01f);
275275 }
276276
277277 @Test
2828 */
2929 public class MutableIntTest {
3030
31 @Test
32 public void testAddAndGetValueObject() {
33 final MutableInt mutableInteger = new MutableInt(0);
34 final int result = mutableInteger.addAndGet(Integer.valueOf(1));
35
36 assertEquals(1, result);
37 assertEquals(1, mutableInteger.intValue());
38 }
39
40 @Test
41 public void testAddAndGetValuePrimitive() {
42 final MutableInt mutableInteger = new MutableInt(0);
43 final int result = mutableInteger.addAndGet(1);
44
45 assertEquals(1, result);
46 assertEquals(1, mutableInteger.intValue());
47 }
48
49 @Test
50 public void testAddValueObject() {
51 final MutableInt mutNum = new MutableInt(1);
52 mutNum.add(Integer.valueOf(1));
53
54 assertEquals(2, mutNum.intValue());
55 assertEquals(2L, mutNum.longValue());
56 }
57
58 @Test
59 public void testAddValuePrimitive() {
60 final MutableInt mutNum = new MutableInt(1);
61 mutNum.add(1);
62
63 assertEquals(2, mutNum.intValue());
64 assertEquals(2L, mutNum.longValue());
65 }
66
67 @Test
68 public void testCompareTo() {
69 final MutableInt mutNum = new MutableInt(0);
70
71 assertEquals(0, mutNum.compareTo(new MutableInt(0)));
72 assertEquals(+1, mutNum.compareTo(new MutableInt(-1)));
73 assertEquals(-1, mutNum.compareTo(new MutableInt(1)));
74 }
75
76 @Test
77 public void testCompareToNull() {
78 final MutableInt mutNum = new MutableInt(0);
79 assertThrows(NullPointerException.class, () -> mutNum.compareTo(null));
80 }
81
82 @Test
83 public void testConstructorNull() {
84 assertThrows(NullPointerException.class, () -> new MutableInt((Number) null));
85 }
86
3187 // ----------------------------------------------------------------
3288 @Test
3389 public void testConstructors() {
4399 }
44100
45101 @Test
46 public void testConstructorNull() {
47 assertThrows(NullPointerException.class, () -> new MutableInt((Number) null));
48 }
49
50 @Test
51 public void testGetSet() {
52 final MutableInt mutNum = new MutableInt(0);
53 assertEquals(0, new MutableInt().intValue());
54 assertEquals(Integer.valueOf(0), new MutableInt().getValue());
55
56 mutNum.setValue(1);
57 assertEquals(1, mutNum.intValue());
58 assertEquals(Integer.valueOf(1), mutNum.getValue());
59
60 mutNum.setValue(Integer.valueOf(2));
61 assertEquals(2, mutNum.intValue());
62 assertEquals(Integer.valueOf(2), mutNum.getValue());
63
64 mutNum.setValue(new MutableLong(3));
65 assertEquals(3, mutNum.intValue());
66 assertEquals(Integer.valueOf(3), mutNum.getValue());
67 }
68
69 @Test
70 public void testSetNull() {
71 final MutableInt mutNum = new MutableInt(0);
72 assertThrows(NullPointerException.class, () -> mutNum.setValue(null));
102 public void testDecrement() {
103 final MutableInt mutNum = new MutableInt(1);
104 mutNum.decrement();
105
106 assertEquals(0, mutNum.intValue());
107 assertEquals(0L, mutNum.longValue());
108 }
109
110 @Test
111 public void testDecrementAndGet() {
112 final MutableInt mutNum = new MutableInt(1);
113 final int result = mutNum.decrementAndGet();
114
115 assertEquals(0, result);
116 assertEquals(0, mutNum.intValue());
117 assertEquals(0L, mutNum.longValue());
73118 }
74119
75120 @Test
98143 }
99144
100145 @Test
146 public void testGetAndAddValueObject() {
147 final MutableInt mutableInteger = new MutableInt(0);
148 final int result = mutableInteger.getAndAdd(Integer.valueOf(1));
149
150 assertEquals(0, result);
151 assertEquals(1, mutableInteger.intValue());
152 }
153
154 @Test
155 public void testGetAndAddValuePrimitive() {
156 final MutableInt mutableInteger = new MutableInt(0);
157 final int result = mutableInteger.getAndAdd(1);
158
159 assertEquals(0, result);
160 assertEquals(1, mutableInteger.intValue());
161 }
162
163 @Test
164 public void testGetAndDecrement() {
165 final MutableInt mutNum = new MutableInt(1);
166 final int result = mutNum.getAndDecrement();
167
168 assertEquals(1, result);
169 assertEquals(0, mutNum.intValue());
170 assertEquals(0L, mutNum.longValue());
171 }
172
173 @Test
174 public void testGetAndIncrement() {
175 final MutableInt mutNum = new MutableInt(1);
176 final int result = mutNum.getAndIncrement();
177
178 assertEquals(1, result);
179 assertEquals(2, mutNum.intValue());
180 assertEquals(2L, mutNum.longValue());
181 }
182
183 @Test
184 public void testGetSet() {
185 final MutableInt mutNum = new MutableInt(0);
186 assertEquals(0, new MutableInt().intValue());
187 assertEquals(Integer.valueOf(0), new MutableInt().getValue());
188
189 mutNum.setValue(1);
190 assertEquals(1, mutNum.intValue());
191 assertEquals(Integer.valueOf(1), mutNum.getValue());
192
193 mutNum.setValue(Integer.valueOf(2));
194 assertEquals(2, mutNum.intValue());
195 assertEquals(Integer.valueOf(2), mutNum.getValue());
196
197 mutNum.setValue(new MutableLong(3));
198 assertEquals(3, mutNum.intValue());
199 assertEquals(Integer.valueOf(3), mutNum.getValue());
200 }
201
202 @Test
101203 public void testHashCode() {
102204 final MutableInt mutNumA = new MutableInt(0);
103205 final MutableInt mutNumB = new MutableInt(0);
110212 }
111213
112214 @Test
113 public void testCompareTo() {
114 final MutableInt mutNum = new MutableInt(0);
115
116 assertEquals(0, mutNum.compareTo(new MutableInt(0)));
117 assertEquals(+1, mutNum.compareTo(new MutableInt(-1)));
118 assertEquals(-1, mutNum.compareTo(new MutableInt(1)));
119 }
120
121 @Test
122 public void testCompareToNull() {
123 final MutableInt mutNum = new MutableInt(0);
124 assertThrows(NullPointerException.class, () -> mutNum.compareTo(null));
215 public void testIncrement() {
216 final MutableInt mutNum = new MutableInt(1);
217 mutNum.increment();
218
219 assertEquals(2, mutNum.intValue());
220 assertEquals(2L, mutNum.longValue());
221 }
222
223 @Test
224 public void testIncrementAndGet() {
225 final MutableInt mutNum = new MutableInt(1);
226 final int result = mutNum.incrementAndGet();
227
228 assertEquals(2, result);
229 assertEquals(2, mutNum.intValue());
230 assertEquals(2L, mutNum.longValue());
125231 }
126232
127233 @Test
135241 }
136242
137243 @Test
244 public void testSetNull() {
245 final MutableInt mutNum = new MutableInt(0);
246 assertThrows(NullPointerException.class, () -> mutNum.setValue(null));
247 }
248
249 @Test
250 public void testSubtractValueObject() {
251 final MutableInt mutNum = new MutableInt(1);
252 mutNum.subtract(Integer.valueOf(1));
253
254 assertEquals(0, mutNum.intValue());
255 assertEquals(0L, mutNum.longValue());
256 }
257
258 @Test
259 public void testSubtractValuePrimitive() {
260 final MutableInt mutNum = new MutableInt(1);
261 mutNum.subtract(1);
262
263 assertEquals(0, mutNum.intValue());
264 assertEquals(0L, mutNum.longValue());
265 }
266
267 @Test
138268 public void testToInteger() {
139269 assertEquals(Integer.valueOf(0), new MutableInt(0).toInteger());
140270 assertEquals(Integer.valueOf(123), new MutableInt(123).toInteger());
141 }
142
143 @Test
144 public void testIncrement() {
145 final MutableInt mutNum = new MutableInt(1);
146 mutNum.increment();
147
148 assertEquals(2, mutNum.intValue());
149 assertEquals(2L, mutNum.longValue());
150 }
151
152 @Test
153 public void testIncrementAndGet() {
154 final MutableInt mutNum = new MutableInt(1);
155 final int result = mutNum.incrementAndGet();
156
157 assertEquals(2, result);
158 assertEquals(2, mutNum.intValue());
159 assertEquals(2L, mutNum.longValue());
160 }
161
162 @Test
163 public void testGetAndIncrement() {
164 final MutableInt mutNum = new MutableInt(1);
165 final int result = mutNum.getAndIncrement();
166
167 assertEquals(1, result);
168 assertEquals(2, mutNum.intValue());
169 assertEquals(2L, mutNum.longValue());
170 }
171
172 @Test
173 public void testDecrement() {
174 final MutableInt mutNum = new MutableInt(1);
175 mutNum.decrement();
176
177 assertEquals(0, mutNum.intValue());
178 assertEquals(0L, mutNum.longValue());
179 }
180
181 @Test
182 public void testDecrementAndGet() {
183 final MutableInt mutNum = new MutableInt(1);
184 final int result = mutNum.decrementAndGet();
185
186 assertEquals(0, result);
187 assertEquals(0, mutNum.intValue());
188 assertEquals(0L, mutNum.longValue());
189 }
190
191 @Test
192 public void testGetAndDecrement() {
193 final MutableInt mutNum = new MutableInt(1);
194 final int result = mutNum.getAndDecrement();
195
196 assertEquals(1, result);
197 assertEquals(0, mutNum.intValue());
198 assertEquals(0L, mutNum.longValue());
199 }
200
201 @Test
202 public void testAddValuePrimitive() {
203 final MutableInt mutNum = new MutableInt(1);
204 mutNum.add(1);
205
206 assertEquals(2, mutNum.intValue());
207 assertEquals(2L, mutNum.longValue());
208 }
209
210 @Test
211 public void testAddValueObject() {
212 final MutableInt mutNum = new MutableInt(1);
213 mutNum.add(Integer.valueOf(1));
214
215 assertEquals(2, mutNum.intValue());
216 assertEquals(2L, mutNum.longValue());
217 }
218
219 @Test
220 public void testGetAndAddValuePrimitive() {
221 final MutableInt mutableInteger = new MutableInt(0);
222 final int result = mutableInteger.getAndAdd(1);
223
224 assertEquals(0, result);
225 assertEquals(1, mutableInteger.intValue());
226 }
227
228 @Test
229 public void testGetAndAddValueObject() {
230 final MutableInt mutableInteger = new MutableInt(0);
231 final int result = mutableInteger.getAndAdd(Integer.valueOf(1));
232
233 assertEquals(0, result);
234 assertEquals(1, mutableInteger.intValue());
235 }
236
237 @Test
238 public void testAddAndGetValuePrimitive() {
239 final MutableInt mutableInteger = new MutableInt(0);
240 final int result = mutableInteger.addAndGet(1);
241
242 assertEquals(1, result);
243 assertEquals(1, mutableInteger.intValue());
244 }
245
246 @Test
247 public void testAddAndGetValueObject() {
248 final MutableInt mutableInteger = new MutableInt(0);
249 final int result = mutableInteger.addAndGet(Integer.valueOf(1));
250
251 assertEquals(1, result);
252 assertEquals(1, mutableInteger.intValue());
253 }
254
255 @Test
256 public void testSubtractValuePrimitive() {
257 final MutableInt mutNum = new MutableInt(1);
258 mutNum.subtract(1);
259
260 assertEquals(0, mutNum.intValue());
261 assertEquals(0L, mutNum.longValue());
262 }
263
264 @Test
265 public void testSubtractValueObject() {
266 final MutableInt mutNum = new MutableInt(1);
267 mutNum.subtract(Integer.valueOf(1));
268
269 assertEquals(0, mutNum.intValue());
270 assertEquals(0L, mutNum.longValue());
271271 }
272272
273273 @Test
2828 */
2929 public class MutableLongTest {
3030
31 @Test
32 public void testAddAndGetValueObject() {
33 final MutableLong mutableLong = new MutableLong(0L);
34 final long result = mutableLong.addAndGet(Long.valueOf(1L));
35
36 assertEquals(1L, result);
37 assertEquals(1L, mutableLong.longValue());
38 }
39
40 @Test
41 public void testAddAndGetValuePrimitive() {
42 final MutableLong mutableLong = new MutableLong(0L);
43 final long result = mutableLong.addAndGet(1L);
44
45 assertEquals(1L, result);
46 assertEquals(1L, mutableLong.longValue());
47 }
48
49 @Test
50 public void testAddValueObject() {
51 final MutableLong mutNum = new MutableLong(1);
52 mutNum.add(Long.valueOf(1));
53
54 assertEquals(2, mutNum.intValue());
55 assertEquals(2L, mutNum.longValue());
56 }
57
58 @Test
59 public void testAddValuePrimitive() {
60 final MutableLong mutNum = new MutableLong(1);
61 mutNum.add(1);
62
63 assertEquals(2, mutNum.intValue());
64 assertEquals(2L, mutNum.longValue());
65 }
66
67 @Test
68 public void testCompareTo() {
69 final MutableLong mutNum = new MutableLong(0);
70
71 assertEquals(0, mutNum.compareTo(new MutableLong(0)));
72 assertEquals(+1, mutNum.compareTo(new MutableLong(-1)));
73 assertEquals(-1, mutNum.compareTo(new MutableLong(1)));
74 }
75
76 @Test
77 public void testCompareToNull() {
78 final MutableLong mutNum = new MutableLong(0);
79 assertThrows(NullPointerException.class, () -> mutNum.compareTo(null));
80 }
81
82 @Test
83 public void testConstructorNull() {
84 assertThrows(NullPointerException.class, () -> new MutableLong((Number) null));
85 }
86
3187 // ----------------------------------------------------------------
3288 @Test
3389 public void testConstructors() {
4399 }
44100
45101 @Test
46 public void testConstructorNull() {
47 assertThrows(NullPointerException.class, () -> new MutableLong((Number) null));
48 }
49
50 @Test
51 public void testGetSet() {
52 final MutableLong mutNum = new MutableLong(0);
53 assertEquals(0, new MutableLong().longValue());
54 assertEquals(Long.valueOf(0), new MutableLong().getValue());
55
56 mutNum.setValue(1);
57 assertEquals(1, mutNum.longValue());
58 assertEquals(Long.valueOf(1), mutNum.getValue());
59
60 mutNum.setValue(Long.valueOf(2));
61 assertEquals(2, mutNum.longValue());
62 assertEquals(Long.valueOf(2), mutNum.getValue());
63
64 mutNum.setValue(new MutableLong(3));
65 assertEquals(3, mutNum.longValue());
66 assertEquals(Long.valueOf(3), mutNum.getValue());
67 }
68
69 @Test
70 public void testSetNull() {
71 final MutableLong mutNum = new MutableLong(0);
72 assertThrows(NullPointerException.class, () -> mutNum.setValue(null));
102 public void testDecrement() {
103 final MutableLong mutNum = new MutableLong(1);
104 mutNum.decrement();
105
106 assertEquals(0, mutNum.intValue());
107 assertEquals(0L, mutNum.longValue());
108 }
109
110 @Test
111 public void testDecrementAndGet() {
112 final MutableLong mutNum = new MutableLong(1L);
113 final long result = mutNum.decrementAndGet();
114
115 assertEquals(0, result);
116 assertEquals(0, mutNum.intValue());
117 assertEquals(0L, mutNum.longValue());
73118 }
74119
75120 @Test
91136 }
92137
93138 @Test
139 public void testGetAndAddValueObject() {
140 final MutableLong mutableLong = new MutableLong(0L);
141 final long result = mutableLong.getAndAdd(Long.valueOf(1L));
142
143 assertEquals(0L, result);
144 assertEquals(1L, mutableLong.longValue());
145 }
146
147 @Test
148 public void testGetAndAddValuePrimitive() {
149 final MutableLong mutableLong = new MutableLong(0L);
150 final long result = mutableLong.getAndAdd(1L);
151
152 assertEquals(0L, result);
153 assertEquals(1L, mutableLong.longValue());
154 }
155
156 @Test
157 public void testGetAndDecrement() {
158 final MutableLong mutNum = new MutableLong(1L);
159 final long result = mutNum.getAndDecrement();
160
161 assertEquals(1, result);
162 assertEquals(0, mutNum.intValue());
163 assertEquals(0L, mutNum.longValue());
164 }
165
166 @Test
167 public void testGetAndIncrement() {
168 final MutableLong mutNum = new MutableLong(1L);
169 final long result = mutNum.getAndIncrement();
170
171 assertEquals(1, result);
172 assertEquals(2, mutNum.intValue());
173 assertEquals(2L, mutNum.longValue());
174 }
175
176 @Test
177 public void testGetSet() {
178 final MutableLong mutNum = new MutableLong(0);
179 assertEquals(0, new MutableLong().longValue());
180 assertEquals(Long.valueOf(0), new MutableLong().getValue());
181
182 mutNum.setValue(1);
183 assertEquals(1, mutNum.longValue());
184 assertEquals(Long.valueOf(1), mutNum.getValue());
185
186 mutNum.setValue(Long.valueOf(2));
187 assertEquals(2, mutNum.longValue());
188 assertEquals(Long.valueOf(2), mutNum.getValue());
189
190 mutNum.setValue(new MutableLong(3));
191 assertEquals(3, mutNum.longValue());
192 assertEquals(Long.valueOf(3), mutNum.getValue());
193 }
194
195 @Test
94196 public void testHashCode() {
95197 final MutableLong mutNumA = new MutableLong(0);
96198 final MutableLong mutNumB = new MutableLong(0);
103205 }
104206
105207 @Test
106 public void testCompareTo() {
107 final MutableLong mutNum = new MutableLong(0);
108
109 assertEquals(0, mutNum.compareTo(new MutableLong(0)));
110 assertEquals(+1, mutNum.compareTo(new MutableLong(-1)));
111 assertEquals(-1, mutNum.compareTo(new MutableLong(1)));
112 }
113
114 @Test
115 public void testCompareToNull() {
116 final MutableLong mutNum = new MutableLong(0);
117 assertThrows(NullPointerException.class, () -> mutNum.compareTo(null));
208 public void testIncrement() {
209 final MutableLong mutNum = new MutableLong(1);
210 mutNum.increment();
211
212 assertEquals(2, mutNum.intValue());
213 assertEquals(2L, mutNum.longValue());
214 }
215
216 @Test
217 public void testIncrementAndGet() {
218 final MutableLong mutNum = new MutableLong(1L);
219 final long result = mutNum.incrementAndGet();
220
221 assertEquals(2, result);
222 assertEquals(2, mutNum.intValue());
223 assertEquals(2L, mutNum.longValue());
118224 }
119225
120226 @Test
129235 }
130236
131237 @Test
238 public void testSetNull() {
239 final MutableLong mutNum = new MutableLong(0);
240 assertThrows(NullPointerException.class, () -> mutNum.setValue(null));
241 }
242
243 @Test
244 public void testSubtractValueObject() {
245 final MutableLong mutNum = new MutableLong(1);
246 mutNum.subtract(Long.valueOf(1));
247
248 assertEquals(0, mutNum.intValue());
249 assertEquals(0L, mutNum.longValue());
250 }
251
252 @Test
253 public void testSubtractValuePrimitive() {
254 final MutableLong mutNum = new MutableLong(1);
255 mutNum.subtract(1);
256
257 assertEquals(0, mutNum.intValue());
258 assertEquals(0L, mutNum.longValue());
259 }
260
261 @Test
132262 public void testToLong() {
133263 assertEquals(Long.valueOf(0L), new MutableLong(0L).toLong());
134264 assertEquals(Long.valueOf(123L), new MutableLong(123L).toLong());
135 }
136
137 @Test
138 public void testIncrement() {
139 final MutableLong mutNum = new MutableLong(1);
140 mutNum.increment();
141
142 assertEquals(2, mutNum.intValue());
143 assertEquals(2L, mutNum.longValue());
144 }
145
146 @Test
147 public void testIncrementAndGet() {
148 final MutableLong mutNum = new MutableLong(1L);
149 final long result = mutNum.incrementAndGet();
150
151 assertEquals(2, result);
152 assertEquals(2, mutNum.intValue());
153 assertEquals(2L, mutNum.longValue());
154 }
155
156 @Test
157 public void testGetAndIncrement() {
158 final MutableLong mutNum = new MutableLong(1L);
159 final long result = mutNum.getAndIncrement();
160
161 assertEquals(1, result);
162 assertEquals(2, mutNum.intValue());
163 assertEquals(2L, mutNum.longValue());
164 }
165
166 @Test
167 public void testDecrement() {
168 final MutableLong mutNum = new MutableLong(1);
169 mutNum.decrement();
170
171 assertEquals(0, mutNum.intValue());
172 assertEquals(0L, mutNum.longValue());
173 }
174
175 @Test
176 public void testDecrementAndGet() {
177 final MutableLong mutNum = new MutableLong(1L);
178 final long result = mutNum.decrementAndGet();
179
180 assertEquals(0, result);
181 assertEquals(0, mutNum.intValue());
182 assertEquals(0L, mutNum.longValue());
183 }
184
185 @Test
186 public void testGetAndDecrement() {
187 final MutableLong mutNum = new MutableLong(1L);
188 final long result = mutNum.getAndDecrement();
189
190 assertEquals(1, result);
191 assertEquals(0, mutNum.intValue());
192 assertEquals(0L, mutNum.longValue());
193 }
194
195 @Test
196 public void testAddValuePrimitive() {
197 final MutableLong mutNum = new MutableLong(1);
198 mutNum.add(1);
199
200 assertEquals(2, mutNum.intValue());
201 assertEquals(2L, mutNum.longValue());
202 }
203
204 @Test
205 public void testAddValueObject() {
206 final MutableLong mutNum = new MutableLong(1);
207 mutNum.add(Long.valueOf(1));
208
209 assertEquals(2, mutNum.intValue());
210 assertEquals(2L, mutNum.longValue());
211 }
212
213 @Test
214 public void testGetAndAddValuePrimitive() {
215 final MutableLong mutableLong = new MutableLong(0L);
216 final long result = mutableLong.getAndAdd(1L);
217
218 assertEquals(0L, result);
219 assertEquals(1L, mutableLong.longValue());
220 }
221
222 @Test
223 public void testGetAndAddValueObject() {
224 final MutableLong mutableLong = new MutableLong(0L);
225 final long result = mutableLong.getAndAdd(Long.valueOf(1L));
226
227 assertEquals(0L, result);
228 assertEquals(1L, mutableLong.longValue());
229 }
230
231 @Test
232 public void testAddAndGetValuePrimitive() {
233 final MutableLong mutableLong = new MutableLong(0L);
234 final long result = mutableLong.addAndGet(1L);
235
236 assertEquals(1L, result);
237 assertEquals(1L, mutableLong.longValue());
238 }
239
240 @Test
241 public void testAddAndGetValueObject() {
242 final MutableLong mutableLong = new MutableLong(0L);
243 final long result = mutableLong.addAndGet(Long.valueOf(1L));
244
245 assertEquals(1L, result);
246 assertEquals(1L, mutableLong.longValue());
247 }
248
249 @Test
250 public void testSubtractValuePrimitive() {
251 final MutableLong mutNum = new MutableLong(1);
252 mutNum.subtract(1);
253
254 assertEquals(0, mutNum.intValue());
255 assertEquals(0L, mutNum.longValue());
256 }
257
258 @Test
259 public void testSubtractValueObject() {
260 final MutableLong mutNum = new MutableLong(1);
261 mutNum.subtract(Long.valueOf(1));
262
263 assertEquals(0, mutNum.intValue());
264 assertEquals(0L, mutNum.longValue());
265265 }
266266
267267 @Test
4242 }
4343
4444 @Test
45 public void testGetSet() {
46 final MutableObject<String> mutNum = new MutableObject<>();
47 assertNull(new MutableObject<>().getValue());
48
49 mutNum.setValue("HELLO");
50 assertSame("HELLO", mutNum.getValue());
51
52 mutNum.setValue(null);
53 assertSame(null, mutNum.getValue());
54 }
55
56 @Test
5745 public void testEquals() {
5846 final MutableObject<String> mutNumA = new MutableObject<>("ALPHA");
5947 final MutableObject<String> mutNumB = new MutableObject<>("ALPHA");
7361 assertNotEquals(null, mutNumA);
7462 assertNotEquals(mutNumA, new Object());
7563 assertNotEquals("0", mutNumA);
64 }
65
66 @Test
67 public void testGetSet() {
68 final MutableObject<String> mutNum = new MutableObject<>();
69 assertNull(new MutableObject<>().getValue());
70
71 mutNum.setValue("HELLO");
72 assertSame("HELLO", mutNum.getValue());
73
74 mutNum.setValue(null);
75 assertSame(null, mutNum.getValue());
7676 }
7777
7878 @Test
2828 */
2929 public class MutableShortTest {
3030
31 @Test
32 public void testAddAndGetValueObject() {
33 final MutableShort mutableShort = new MutableShort((short) 0);
34 final short result = mutableShort.addAndGet(Short.valueOf((short) 1));
35
36 assertEquals((short) 1, result);
37 assertEquals((short) 1, mutableShort.shortValue());
38 }
39
40 @Test
41 public void testAddAndGetValuePrimitive() {
42 final MutableShort mutableShort = new MutableShort((short) 0);
43 final short result = mutableShort.addAndGet((short) 1);
44
45 assertEquals((short) 1, result);
46 assertEquals((short) 1, mutableShort.shortValue());
47 }
48
49 @Test
50 public void testAddValueObject() {
51 final MutableShort mutNum = new MutableShort((short) 1);
52 mutNum.add(Short.valueOf((short) 1));
53
54 assertEquals((short) 2, mutNum.shortValue());
55 }
56
57 @Test
58 public void testAddValuePrimitive() {
59 final MutableShort mutNum = new MutableShort((short) 1);
60 mutNum.add((short) 1);
61
62 assertEquals((short) 2, mutNum.shortValue());
63 }
64
65 @Test
66 public void testCompareTo() {
67 final MutableShort mutNum = new MutableShort((short) 0);
68
69 assertEquals((short) 0, mutNum.compareTo(new MutableShort((short) 0)));
70 assertEquals((short) +1, mutNum.compareTo(new MutableShort((short) -1)));
71 assertEquals((short) -1, mutNum.compareTo(new MutableShort((short) 1)));
72 assertThrows(NullPointerException.class, () -> mutNum.compareTo(null));
73 }
74
3175 // ----------------------------------------------------------------
3276 @Test
3377 public void testConstructors() {
4488 }
4589
4690 @Test
47 public void testGetSet() {
48 final MutableShort mutNum = new MutableShort((short) 0);
49 assertEquals((short) 0, new MutableShort().shortValue());
50 assertEquals(Short.valueOf((short) 0), new MutableShort().getValue());
51
52 mutNum.setValue((short) 1);
53 assertEquals((short) 1, mutNum.shortValue());
54 assertEquals(Short.valueOf((short) 1), mutNum.getValue());
55
56 mutNum.setValue(Short.valueOf((short) 2));
57 assertEquals((short) 2, mutNum.shortValue());
58 assertEquals(Short.valueOf((short) 2), mutNum.getValue());
59
60 mutNum.setValue(new MutableShort((short) 3));
61 assertEquals((short) 3, mutNum.shortValue());
62 assertEquals(Short.valueOf((short) 3), mutNum.getValue());
63 assertThrows(NullPointerException.class, () -> mutNum.setValue(null));
91 public void testDecrement() {
92 final MutableShort mutNum = new MutableShort((short) 1);
93 mutNum.decrement();
94
95 assertEquals(0, mutNum.intValue());
96 assertEquals(0L, mutNum.longValue());
97 }
98
99 @Test
100 public void testDecrementAndGet() {
101 final MutableShort mutNum = new MutableShort((short) 1);
102 final short result = mutNum.decrementAndGet();
103
104 assertEquals(0, result);
105 assertEquals(0, mutNum.intValue());
106 assertEquals(0L, mutNum.longValue());
64107 }
65108
66109 @Test
82125 }
83126
84127 @Test
128 public void testGetAndAddValueObject() {
129 final MutableShort mutableShort = new MutableShort((short) 0);
130 final short result = mutableShort.getAndAdd(Short.valueOf((short) 1));
131
132 assertEquals((short) 0, result);
133 assertEquals((short) 1, mutableShort.shortValue());
134 }
135
136 @Test
137 public void testGetAndAddValuePrimitive() {
138 final MutableShort mutableShort = new MutableShort((short) 0);
139 final short result = mutableShort.getAndAdd((short) 1);
140
141 assertEquals((short) 0, result);
142 assertEquals((short) 1, mutableShort.shortValue());
143 }
144
145 @Test
146 public void testGetAndDecrement() {
147 final MutableShort mutNum = new MutableShort((short) 1);
148 final short result = mutNum.getAndDecrement();
149
150 assertEquals(1, result);
151 assertEquals(0, mutNum.intValue());
152 assertEquals(0L, mutNum.longValue());
153 }
154
155 @Test
156 public void testGetAndIncrement() {
157 final MutableShort mutNum = new MutableShort((short) 1);
158 final short result = mutNum.getAndIncrement();
159
160 assertEquals(1, result);
161 assertEquals(2, mutNum.intValue());
162 assertEquals(2L, mutNum.longValue());
163 }
164
165 @Test
166 public void testGetSet() {
167 final MutableShort mutNum = new MutableShort((short) 0);
168 assertEquals((short) 0, new MutableShort().shortValue());
169 assertEquals(Short.valueOf((short) 0), new MutableShort().getValue());
170
171 mutNum.setValue((short) 1);
172 assertEquals((short) 1, mutNum.shortValue());
173 assertEquals(Short.valueOf((short) 1), mutNum.getValue());
174
175 mutNum.setValue(Short.valueOf((short) 2));
176 assertEquals((short) 2, mutNum.shortValue());
177 assertEquals(Short.valueOf((short) 2), mutNum.getValue());
178
179 mutNum.setValue(new MutableShort((short) 3));
180 assertEquals((short) 3, mutNum.shortValue());
181 assertEquals(Short.valueOf((short) 3), mutNum.getValue());
182 assertThrows(NullPointerException.class, () -> mutNum.setValue(null));
183 }
184
185 @Test
85186 public void testHashCode() {
86187 final MutableShort mutNumA = new MutableShort((short) 0);
87188 final MutableShort mutNumB = new MutableShort((short) 0);
94195 }
95196
96197 @Test
97 public void testCompareTo() {
98 final MutableShort mutNum = new MutableShort((short) 0);
99
100 assertEquals((short) 0, mutNum.compareTo(new MutableShort((short) 0)));
101 assertEquals((short) +1, mutNum.compareTo(new MutableShort((short) -1)));
102 assertEquals((short) -1, mutNum.compareTo(new MutableShort((short) 1)));
103 assertThrows(NullPointerException.class, () -> mutNum.compareTo(null));
198 public void testIncrement() {
199 final MutableShort mutNum = new MutableShort((short) 1);
200 mutNum.increment();
201
202 assertEquals(2, mutNum.intValue());
203 assertEquals(2L, mutNum.longValue());
204 }
205
206 @Test
207 public void testIncrementAndGet() {
208 final MutableShort mutNum = new MutableShort((short) 1);
209 final short result = mutNum.incrementAndGet();
210
211 assertEquals(2, result);
212 assertEquals(2, mutNum.intValue());
213 assertEquals(2L, mutNum.longValue());
104214 }
105215
106216 @Test
115225 }
116226
117227 @Test
228 public void testSubtractValueObject() {
229 final MutableShort mutNum = new MutableShort((short) 1);
230 mutNum.subtract(Short.valueOf((short) 1));
231
232 assertEquals((short) 0, mutNum.shortValue());
233 }
234
235 @Test
236 public void testSubtractValuePrimitive() {
237 final MutableShort mutNum = new MutableShort((short) 1);
238 mutNum.subtract((short) 1);
239
240 assertEquals((short) 0, mutNum.shortValue());
241 }
242
243 @Test
118244 public void testToShort() {
119245 assertEquals(Short.valueOf((short) 0), new MutableShort((short) 0).toShort());
120246 assertEquals(Short.valueOf((short) 123), new MutableShort((short) 123).toShort());
121 }
122
123 @Test
124 public void testIncrement() {
125 final MutableShort mutNum = new MutableShort((short) 1);
126 mutNum.increment();
127
128 assertEquals(2, mutNum.intValue());
129 assertEquals(2L, mutNum.longValue());
130 }
131
132 @Test
133 public void testIncrementAndGet() {
134 final MutableShort mutNum = new MutableShort((short) 1);
135 final short result = mutNum.incrementAndGet();
136
137 assertEquals(2, result);
138 assertEquals(2, mutNum.intValue());
139 assertEquals(2L, mutNum.longValue());
140 }
141
142 @Test
143 public void testGetAndIncrement() {
144 final MutableShort mutNum = new MutableShort((short) 1);
145 final short result = mutNum.getAndIncrement();
146
147 assertEquals(1, result);
148 assertEquals(2, mutNum.intValue());
149 assertEquals(2L, mutNum.longValue());
150 }
151
152 @Test
153 public void testDecrement() {
154 final MutableShort mutNum = new MutableShort((short) 1);
155 mutNum.decrement();
156
157 assertEquals(0, mutNum.intValue());
158 assertEquals(0L, mutNum.longValue());
159 }
160
161 @Test
162 public void testDecrementAndGet() {
163 final MutableShort mutNum = new MutableShort((short) 1);
164 final short result = mutNum.decrementAndGet();
165
166 assertEquals(0, result);
167 assertEquals(0, mutNum.intValue());
168 assertEquals(0L, mutNum.longValue());
169 }
170
171 @Test
172 public void testGetAndDecrement() {
173 final MutableShort mutNum = new MutableShort((short) 1);
174 final short result = mutNum.getAndDecrement();
175
176 assertEquals(1, result);
177 assertEquals(0, mutNum.intValue());
178 assertEquals(0L, mutNum.longValue());
179 }
180
181 @Test
182 public void testAddValuePrimitive() {
183 final MutableShort mutNum = new MutableShort((short) 1);
184 mutNum.add((short) 1);
185
186 assertEquals((short) 2, mutNum.shortValue());
187 }
188
189 @Test
190 public void testAddValueObject() {
191 final MutableShort mutNum = new MutableShort((short) 1);
192 mutNum.add(Short.valueOf((short) 1));
193
194 assertEquals((short) 2, mutNum.shortValue());
195 }
196
197 @Test
198 public void testGetAndAddValuePrimitive() {
199 final MutableShort mutableShort = new MutableShort((short) 0);
200 final short result = mutableShort.getAndAdd((short) 1);
201
202 assertEquals((short) 0, result);
203 assertEquals((short) 1, mutableShort.shortValue());
204 }
205
206 @Test
207 public void testGetAndAddValueObject() {
208 final MutableShort mutableShort = new MutableShort((short) 0);
209 final short result = mutableShort.getAndAdd(Short.valueOf((short) 1));
210
211 assertEquals((short) 0, result);
212 assertEquals((short) 1, mutableShort.shortValue());
213 }
214
215 @Test
216 public void testAddAndGetValuePrimitive() {
217 final MutableShort mutableShort = new MutableShort((short) 0);
218 final short result = mutableShort.addAndGet((short) 1);
219
220 assertEquals((short) 1, result);
221 assertEquals((short) 1, mutableShort.shortValue());
222 }
223
224 @Test
225 public void testAddAndGetValueObject() {
226 final MutableShort mutableShort = new MutableShort((short) 0);
227 final short result = mutableShort.addAndGet(Short.valueOf((short) 1));
228
229 assertEquals((short) 1, result);
230 assertEquals((short) 1, mutableShort.shortValue());
231 }
232
233 @Test
234 public void testSubtractValuePrimitive() {
235 final MutableShort mutNum = new MutableShort((short) 1);
236 mutNum.subtract((short) 1);
237
238 assertEquals((short) 0, mutNum.shortValue());
239 }
240
241 @Test
242 public void testSubtractValueObject() {
243 final MutableShort mutNum = new MutableShort((short) 1);
244 mutNum.subtract(Short.valueOf((short) 1));
245
246 assertEquals((short) 0, mutNum.shortValue());
247247 }
248248
249249 @Test
8888 public TestBean(final Integer first, final int... args) {
8989 toString = "(Integer, String...)";
9090 varArgs = new String[args.length];
91 for (int i = 0; i< args.length; ++i) {
91 for (int i = 0; i < args.length; ++i) {
9292 varArgs[i] = Integer.toString(args[i]);
9393 }
9494 }
3333 import java.util.HashSet;
3434 import java.util.List;
3535
36 import org.apache.commons.lang3.ArraySorter;
3637 import org.apache.commons.lang3.ArrayUtils;
3738 import org.apache.commons.lang3.JavaVersion;
3839 import org.apache.commons.lang3.SystemUtils;
40 import org.apache.commons.lang3.compare.ObjectToStringComparator;
3941 import org.apache.commons.lang3.reflect.testbed.Ambig;
4042 import org.apache.commons.lang3.reflect.testbed.Annotated;
4143 import org.apache.commons.lang3.reflect.testbed.Foo;
164166 @Test
165167 public void testGetAllFields() {
166168 assertArrayEquals(new Field[0], FieldUtils.getAllFields(Object.class));
167 final Field[] fieldsNumber = Number.class.getDeclaredFields();
168 assertArrayEquals(fieldsNumber, FieldUtils.getAllFields(Number.class));
169 final Field[] fieldsNumber = sort(Number.class.getDeclaredFields());
170 assertArrayEquals(fieldsNumber, sort(FieldUtils.getAllFields(Number.class)));
169171 final Field[] fieldsInteger = Integer.class.getDeclaredFields();
170 assertArrayEquals(ArrayUtils.addAll(fieldsInteger, fieldsNumber), FieldUtils.getAllFields(Integer.class));
172 assertArrayEquals(sort(ArrayUtils.addAll(fieldsInteger, fieldsNumber)), sort(FieldUtils.getAllFields(Integer.class)));
171173 final Field[] allFields = FieldUtils.getAllFields(PublicChild.class);
172174 // Under Jacoco,0.8.1 and Java 10, the field count is 7.
173175 int expected = 5;
177179 }
178180 }
179181 assertEquals(expected, allFields.length, Arrays.toString(allFields));
182 }
183
184 private Field[] sort(final Field[] fields) {
185 // Field does not implement Comparable, so we use a KISS solution here.
186 return ArraySorter.sort(fields, ObjectToStringComparator.INSTANCE);
180187 }
181188
182189 @Test
203210 @Test
204211 public void testGetFieldsWithAnnotation() throws NoSuchFieldException {
205212 assertArrayEquals(new Field[0], FieldUtils.getFieldsWithAnnotation(Object.class, Annotated.class));
206 final Field[] annotatedFields = new Field[]{
213 final Field[] annotatedFields = sort(new Field[] {
207214 FieldUtilsTest.class.getDeclaredField("publicChild"),
208 FieldUtilsTest.class.getDeclaredField("privatelyShadowedChild")
209 };
210 assertArrayEquals(annotatedFields, FieldUtils.getFieldsWithAnnotation(FieldUtilsTest.class, Annotated.class));
215 FieldUtilsTest.class.getDeclaredField("privatelyShadowedChild") });
216 assertArrayEquals(annotatedFields,
217 sort(FieldUtils.getFieldsWithAnnotation(FieldUtilsTest.class, Annotated.class)));
211218 }
212219
213220 @Test
2828 import static org.junit.jupiter.api.Assertions.assertThrows;
2929 import static org.junit.jupiter.api.Assertions.assertTrue;
3030
31 import java.awt.Color;
3132 import java.lang.reflect.Method;
3233 import java.lang.reflect.Type;
3334 import java.util.Arrays;
10171018
10181019 distanceMethod.setAccessible(false);
10191020 }
1021
1022 @Test
1023 public void testGetMatchingMethod() throws NoSuchMethodException {
1024 assertEquals(MethodUtils.getMatchingMethod(GetMatchingMethodClass.class, "testMethod"),
1025 GetMatchingMethodClass.class.getMethod("testMethod"));
1026
1027 assertEquals(MethodUtils.getMatchingMethod(GetMatchingMethodClass.class, "testMethod", Long.TYPE),
1028 GetMatchingMethodClass.class.getMethod("testMethod", Long.TYPE));
1029
1030 assertEquals(MethodUtils.getMatchingMethod(GetMatchingMethodClass.class, "testMethod", Long.class),
1031 GetMatchingMethodClass.class.getMethod("testMethod", Long.class));
1032
1033 assertEquals(MethodUtils.getMatchingMethod(GetMatchingMethodClass.class, "testMethod", (Class<?>) null),
1034 GetMatchingMethodClass.class.getMethod("testMethod", Long.class));
1035
1036 assertThrows(IllegalStateException.class,
1037 () -> MethodUtils.getMatchingMethod(GetMatchingMethodClass.class, "testMethod2", (Class<?>) null));
1038
1039 assertEquals(MethodUtils.getMatchingMethod(GetMatchingMethodClass.class, "testMethod3", Long.TYPE, Long.class),
1040 GetMatchingMethodClass.class.getMethod("testMethod3", Long.TYPE, Long.class));
1041
1042 assertEquals(MethodUtils.getMatchingMethod(GetMatchingMethodClass.class, "testMethod3", Long.class, Long.TYPE),
1043 GetMatchingMethodClass.class.getMethod("testMethod3", Long.class, Long.TYPE));
1044
1045 assertEquals(MethodUtils.getMatchingMethod(GetMatchingMethodClass.class, "testMethod3", null, Long.TYPE),
1046 GetMatchingMethodClass.class.getMethod("testMethod3", Long.class, Long.TYPE));
1047
1048 assertEquals(MethodUtils.getMatchingMethod(GetMatchingMethodClass.class, "testMethod3", Long.TYPE, null),
1049 GetMatchingMethodClass.class.getMethod("testMethod3", Long.TYPE, Long.class));
1050
1051 assertThrows(IllegalStateException.class,
1052 () -> MethodUtils.getMatchingMethod(GetMatchingMethodClass.class, "testMethod4", null, null));
1053 }
1054
1055 private static final class GetMatchingMethodClass {
1056 public void testMethod() {
1057 }
1058
1059 public void testMethod(final Long aLong) {
1060 }
1061
1062 public void testMethod(final long aLong) {
1063 }
1064
1065 public void testMethod2(final Long aLong) {
1066 }
1067
1068 public void testMethod2(final Color aColor) {
1069 }
1070
1071 public void testMethod2(final long aLong) {
1072 }
1073
1074 public void testMethod3(final long aLong, final Long anotherLong) {
1075 }
1076
1077 public void testMethod3(final Long aLong, final long anotherLong) {
1078 }
1079
1080 public void testMethod3(final Long aLong, final Long anotherLong) {
1081 }
1082
1083 public void testMethod4(final Long aLong, final Long anotherLong) {
1084 }
1085
1086 public void testMethod4(final Color aColor1, final Color aColor2) {
1087 }
1088 }
10201089 }
2121 import static org.junit.jupiter.api.Assertions.assertNull;
2222 import static org.junit.jupiter.api.Assertions.assertTrue;
2323
24 import java.awt.Insets;
2425 import java.io.Serializable;
26 import java.lang.reflect.Constructor;
2527 import java.lang.reflect.Field;
2628 import java.lang.reflect.GenericArrayType;
2729 import java.lang.reflect.Method;
3638 import java.util.HashMap;
3739 import java.util.List;
3840 import java.util.Map;
41 import java.util.Properties;
3942 import java.util.TreeSet;
4043
4144 import org.apache.commons.lang3.reflect.testbed.Foo;
4245 import org.apache.commons.lang3.reflect.testbed.GenericParent;
4346 import org.apache.commons.lang3.reflect.testbed.GenericTypeHolder;
4447 import org.apache.commons.lang3.reflect.testbed.StringParameterizedChild;
48 import org.junit.jupiter.api.Disabled;
4549 import org.junit.jupiter.api.Test;
50
51 class AAAClass extends AAClass<String> {
52 public class BBBClass extends BBClass<String> {
53 }
54 }
55
56 class AAClass<T> {
57
58 public class BBClass<S> {
59 }
60 }
61
62 @SuppressWarnings("rawtypes")
63 //raw types, where used, are used purposely
64 class AClass extends AAClass<String>.BBClass<Number> {
65
66 public interface AInterface<T> {
67 }
68
69 public class BClass<T> {
70 }
71
72 public class CClass<T> extends BClass {
73 }
74
75 public class DClass<T> extends CClass<T> {
76 }
77
78 public class EClass<T> extends DClass {
79 }
80
81 public class FClass extends EClass<String> {
82 }
83
84 public class GClass<T extends BClass<? extends T> & AInterface<AInterface<? super T>>> {
85 }
86
87 public BClass<Number> bClass;
88
89 public CClass<? extends String> cClass;
90
91 public DClass<String> dClass;
92
93 public EClass<String> eClass;
94
95 public FClass fClass;
96
97 public GClass gClass;
98
99 AClass(final AAClass<String> enclosingInstance) {
100 enclosingInstance.super();
101 }
102 }
103 @SuppressWarnings("rawtypes")
104 abstract class Test1<G> {
105 public abstract Object m0();
106 public abstract String[] m1();
107 public abstract <E> E[] m2();
108 public abstract <E> List<? extends E> m3();
109 public abstract <E extends Enum<E>> List<? extends Enum<E>> m4();
110 public abstract List<? extends Enum<?>> m5();
111 public abstract List<? super Enum<?>> m6();
112 public abstract List<?> m7();
113 public abstract Map<? extends Enum<?>, ? super Enum<?>> m8();
114 public abstract <K, V> Map<? extends K, ? super V[]> m9();
115 public abstract <K, V> Map<? extends K, V[]> m10();
116 public abstract <K, V> Map<? extends K, List<V[]>> m11();
117 public abstract List m12();
118 public abstract Map m13();
119 public abstract Properties m14();
120 public abstract G m15();
121 public abstract List<G> m16();
122 public abstract Enum m17();
123 }
46124
47125 /**
48126 * Test TypeUtils
51129 //raw types, where used, are used purposely
52130 public class TypeUtilsTest<B> {
53131
132 public interface And<K, V> extends This<Number, Number> {
133 }
134
135 public static class ClassWithSuperClassWithGenericType extends ArrayList<Object> {
136 private static final long serialVersionUID = 1L;
137
138 public static <U> Iterable<U> methodWithGenericReturnType() {
139 return null;
140 }
141 }
142
143 public class Other<T> implements This<String, T> {
144 }
145
146 public class Tester implements This<String, B> {
147 }
148
149 public class That<K, V> implements This<K, V> {
150 }
151
152 public class The<K, V> extends That<Number, Number> implements And<String, String> {
153 }
154
155 public class Thing<Q> extends Other<B> {
156 }
157
54158 public interface This<K, V> {
55159 }
56160
57 public class That<K, V> implements This<K, V> {
58 }
59
60 public interface And<K, V> extends This<Number, Number> {
61 }
62
63 public class The<K, V> extends That<Number, Number> implements And<String, String> {
64 }
65
66 public class Other<T> implements This<String, T> {
67 }
68
69 public class Thing<Q> extends Other<B> {
70 }
71
72 public class Tester implements This<String, B> {
161 public static Comparable<String> stringComparable;
162
163 public static Comparable<URI> uriComparable;
164
165 public static Comparable<Integer> intComparable;
166
167 public static Comparable<Long> longComparable;
168
169 public static Comparable<?> wildcardComparable;
170
171 public static URI uri;
172
173 public static List<String>[] stringListArray;
174
175 public static <G extends Comparable<G>> G stub() {
176 return null;
177 }
178
179 public static <G extends Comparable<? super G>> G stub2() {
180 return null;
181 }
182
183 public static <T extends Comparable<? extends T>> T stub3() {
184 return null;
73185 }
74186
75187 public This<String, String> dis;
92204
93205 public Comparable<? extends Integer>[] intWildcardComparable;
94206
95 public static Comparable<String> stringComparable;
96
97 public static Comparable<URI> uriComparable;
98
99 public static Comparable<Integer> intComparable;
100
101 public static Comparable<Long> longComparable;
102
103 public static Comparable<?> wildcardComparable;
104
105 public static URI uri;
106
107 public static List<String>[] stringListArray;
207 public Iterable<? extends Map<Integer, ? extends Collection<?>>> iterable;
208
209 public void delegateBooleanAssertion(final Type[] types, final int i2, final int i1, final boolean expected) {
210 final Type type1 = types[i1];
211 final Type type2 = types[i2];
212 final boolean isAssignable = TypeUtils.isAssignable(type2, type1);
213
214 if (expected) {
215 assertTrue(isAssignable,
216 "[" + i1 + ", " + i2 + "]: From "
217 + String.valueOf(type2) + " to "
218 + String.valueOf(type1));
219 } else {
220 assertFalse(isAssignable,
221 "[" + i1 + ", " + i2 + "]: From "
222 + String.valueOf(type2) + " to "
223 + String.valueOf(type1));
224 }
225 }
108226
109227 public void dummyMethod(final List list0, final List<Object> list1, final List<?> list2,
110228 final List<? super Object> list3, final List<String> list4, final List<? extends String> list5,
113231 final List<? super String>[] list13) {
114232 }
115233
234 @Test
235 public void testContainsTypeVariables() throws Exception {
236 assertFalse(TypeUtils.containsTypeVariables(Test1.class.getMethod("m0").getGenericReturnType()));
237 assertFalse(TypeUtils.containsTypeVariables(Test1.class.getMethod("m1").getGenericReturnType()));
238 assertTrue(TypeUtils.containsTypeVariables(Test1.class.getMethod("m2").getGenericReturnType()));
239 assertTrue(TypeUtils.containsTypeVariables(Test1.class.getMethod("m3").getGenericReturnType()));
240 assertTrue(TypeUtils.containsTypeVariables(Test1.class.getMethod("m4").getGenericReturnType()));
241 assertFalse(TypeUtils.containsTypeVariables(Test1.class.getMethod("m5").getGenericReturnType()));
242 assertFalse(TypeUtils.containsTypeVariables(Test1.class.getMethod("m6").getGenericReturnType()));
243 assertFalse(TypeUtils.containsTypeVariables(Test1.class.getMethod("m7").getGenericReturnType()));
244 assertFalse(TypeUtils.containsTypeVariables(Test1.class.getMethod("m8").getGenericReturnType()));
245 assertTrue(TypeUtils.containsTypeVariables(Test1.class.getMethod("m9").getGenericReturnType()));
246 assertTrue(TypeUtils.containsTypeVariables(Test1.class.getMethod("m10").getGenericReturnType()));
247 assertTrue(TypeUtils.containsTypeVariables(Test1.class.getMethod("m11").getGenericReturnType()));
248 assertTrue(TypeUtils.containsTypeVariables(Test1.class.getMethod("m12").getGenericReturnType()));
249 assertTrue(TypeUtils.containsTypeVariables(Test1.class.getMethod("m13").getGenericReturnType()));
250 assertFalse(TypeUtils.containsTypeVariables(Test1.class.getMethod("m14").getGenericReturnType()));
251 assertTrue(TypeUtils.containsTypeVariables(Test1.class.getMethod("m15").getGenericReturnType()));
252 assertTrue(TypeUtils.containsTypeVariables(Test1.class.getMethod("m16").getGenericReturnType()));
253 assertTrue(TypeUtils.containsTypeVariables(Test1.class.getMethod("m17").getGenericReturnType()));
254 }
255
256 @Test
257 public void testDetermineTypeVariableAssignments() throws SecurityException,
258 NoSuchFieldException {
259 final ParameterizedType iterableType = (ParameterizedType) getClass().getField("iterable")
260 .getGenericType();
261 final Map<TypeVariable<?>, Type> typeVarAssigns = TypeUtils.determineTypeArguments(TreeSet.class,
262 iterableType);
263 final TypeVariable<?> treeSetTypeVar = TreeSet.class.getTypeParameters()[0];
264 assertTrue(typeVarAssigns.containsKey(treeSetTypeVar));
265 assertEquals(iterableType.getActualTypeArguments()[0], typeVarAssigns
266 .get(treeSetTypeVar));
267 }
268
269 @Test
270 public void testGenericArrayType() throws Exception {
271 final Type expected = getClass().getField("intWildcardComparable").getGenericType();
272 final GenericArrayType actual =
273 TypeUtils.genericArrayType(TypeUtils.parameterize(Comparable.class, TypeUtils.wildcardType()
274 .withUpperBounds(Integer.class).build()));
275 assertTrue(TypeUtils.equals(expected, actual));
276 assertEquals("java.lang.Comparable<? extends java.lang.Integer>[]", actual.toString());
277 }
278
279 @Test
280 public void testGetArrayComponentType() throws Exception {
281 final Method method = getClass().getMethod("dummyMethod", List.class, List.class, List.class,
282 List.class, List.class, List.class, List.class, List[].class, List[].class,
283 List[].class, List[].class, List[].class, List[].class, List[].class);
284
285 final Type[] types = method.getGenericParameterTypes();
286
287 assertNull(TypeUtils.getArrayComponentType(types[0]));
288 assertNull(TypeUtils.getArrayComponentType(types[1]));
289 assertNull(TypeUtils.getArrayComponentType(types[2]));
290 assertNull(TypeUtils.getArrayComponentType(types[3]));
291 assertNull(TypeUtils.getArrayComponentType(types[4]));
292 assertNull(TypeUtils.getArrayComponentType(types[5]));
293 assertNull(TypeUtils.getArrayComponentType(types[6]));
294 assertEquals(types[0], TypeUtils.getArrayComponentType(types[7]));
295 assertEquals(types[1], TypeUtils.getArrayComponentType(types[8]));
296 assertEquals(types[2], TypeUtils.getArrayComponentType(types[9]));
297 assertEquals(types[3], TypeUtils.getArrayComponentType(types[10]));
298 assertEquals(types[4], TypeUtils.getArrayComponentType(types[11]));
299 assertEquals(types[5], TypeUtils.getArrayComponentType(types[12]));
300 assertEquals(types[6], TypeUtils.getArrayComponentType(types[13]));
301 }
302
303 @Test
304 public void testGetPrimitiveArrayComponentType() {
305 assertEquals(boolean.class, TypeUtils.getArrayComponentType(boolean[].class));
306 assertEquals(byte.class, TypeUtils.getArrayComponentType(byte[].class));
307 assertEquals(short.class, TypeUtils.getArrayComponentType(short[].class));
308 assertEquals(int.class, TypeUtils.getArrayComponentType(int[].class));
309 assertEquals(char.class, TypeUtils.getArrayComponentType(char[].class));
310 assertEquals(long.class, TypeUtils.getArrayComponentType(long[].class));
311 assertEquals(float.class, TypeUtils.getArrayComponentType(float[].class));
312 assertEquals(double.class, TypeUtils.getArrayComponentType(double[].class));
313
314 assertNull(TypeUtils.getArrayComponentType(boolean.class));
315 assertNull(TypeUtils.getArrayComponentType(byte.class));
316 assertNull(TypeUtils.getArrayComponentType(short.class));
317 assertNull(TypeUtils.getArrayComponentType(int.class));
318 assertNull(TypeUtils.getArrayComponentType(char.class));
319 assertNull(TypeUtils.getArrayComponentType(long.class));
320 assertNull(TypeUtils.getArrayComponentType(float.class));
321 assertNull(TypeUtils.getArrayComponentType(double.class));
322 }
323
324 @Test
325 public void testGetRawType() throws SecurityException, NoSuchFieldException {
326 final Type stringParentFieldType = GenericTypeHolder.class.getDeclaredField("stringParent")
327 .getGenericType();
328 final Type integerParentFieldType = GenericTypeHolder.class.getDeclaredField("integerParent")
329 .getGenericType();
330 final Type foosFieldType = GenericTypeHolder.class.getDeclaredField("foos").getGenericType();
331 final Type genericParentT = GenericParent.class.getTypeParameters()[0];
332 assertEquals(GenericParent.class, TypeUtils.getRawType(stringParentFieldType, null));
333 assertEquals(GenericParent.class, TypeUtils.getRawType(integerParentFieldType,
334 null));
335 assertEquals(List.class, TypeUtils.getRawType(foosFieldType, null));
336 assertEquals(String.class, TypeUtils.getRawType(genericParentT,
337 StringParameterizedChild.class));
338 assertEquals(String.class, TypeUtils.getRawType(genericParentT,
339 stringParentFieldType));
340 assertEquals(Foo.class, TypeUtils.getRawType(Iterable.class.getTypeParameters()[0],
341 foosFieldType));
342 assertEquals(Foo.class, TypeUtils.getRawType(List.class.getTypeParameters()[0],
343 foosFieldType));
344 assertNull(TypeUtils.getRawType(genericParentT, GenericParent.class));
345 assertEquals(GenericParent[].class, TypeUtils.getRawType(GenericTypeHolder.class
346 .getDeclaredField("barParents").getGenericType(), null));
347 }
348
349 @Test
350 public void testGetTypeArguments() {
351 Map<TypeVariable<?>, Type> typeVarAssigns;
352 TypeVariable<?> treeSetTypeVar;
353 Type typeArg;
354
355 typeVarAssigns = TypeUtils.getTypeArguments(Integer.class, Comparable.class);
356 treeSetTypeVar = Comparable.class.getTypeParameters()[0];
357 assertTrue(typeVarAssigns.containsKey(treeSetTypeVar),
358 "Type var assigns for Comparable from Integer: " + typeVarAssigns);
359 typeArg = typeVarAssigns.get(treeSetTypeVar);
360 assertEquals(Integer.class, typeVarAssigns.get(treeSetTypeVar),
361 "Type argument of Comparable from Integer: " + typeArg);
362
363 typeVarAssigns = TypeUtils.getTypeArguments(int.class, Comparable.class);
364 treeSetTypeVar = Comparable.class.getTypeParameters()[0];
365 assertTrue(typeVarAssigns.containsKey(treeSetTypeVar),
366 "Type var assigns for Comparable from int: " + typeVarAssigns);
367 typeArg = typeVarAssigns.get(treeSetTypeVar);
368 assertEquals(Integer.class, typeVarAssigns.get(treeSetTypeVar),
369 "Type argument of Comparable from int: " + typeArg);
370
371 final Collection<Integer> col = Collections.emptyList();
372 typeVarAssigns = TypeUtils.getTypeArguments(List.class, Collection.class);
373 treeSetTypeVar = Comparable.class.getTypeParameters()[0];
374 assertFalse(typeVarAssigns.containsKey(treeSetTypeVar),
375 "Type var assigns for Collection from List: " + typeVarAssigns);
376
377 typeVarAssigns = TypeUtils.getTypeArguments(AAAClass.BBBClass.class, AAClass.BBClass.class);
378 assertEquals(2, typeVarAssigns.size());
379 assertEquals(String.class, typeVarAssigns.get(AAClass.class.getTypeParameters()[0]));
380 assertEquals(String.class, typeVarAssigns.get(AAClass.BBClass.class.getTypeParameters()[0]));
381
382 typeVarAssigns = TypeUtils.getTypeArguments(Other.class, This.class);
383 assertEquals(2, typeVarAssigns.size());
384 assertEquals(String.class, typeVarAssigns.get(This.class.getTypeParameters()[0]));
385 assertEquals(Other.class.getTypeParameters()[0], typeVarAssigns.get(This.class.getTypeParameters()[1]));
386
387 typeVarAssigns = TypeUtils.getTypeArguments(And.class, This.class);
388 assertEquals(2, typeVarAssigns.size());
389 assertEquals(Number.class, typeVarAssigns.get(This.class.getTypeParameters()[0]));
390 assertEquals(Number.class, typeVarAssigns.get(This.class.getTypeParameters()[1]));
391
392 typeVarAssigns = TypeUtils.getTypeArguments(Thing.class, Other.class);
393 assertEquals(2, typeVarAssigns.size());
394 assertEquals(getClass().getTypeParameters()[0], typeVarAssigns.get(getClass().getTypeParameters()[0]));
395 assertEquals(getClass().getTypeParameters()[0], typeVarAssigns.get(Other.class.getTypeParameters()[0]));
396 }
397
398 @Test
399 public void testIsArrayGenericTypes() throws Exception {
400 final Method method = getClass().getMethod("dummyMethod", List.class, List.class, List.class,
401 List.class, List.class, List.class, List.class, List[].class, List[].class,
402 List[].class, List[].class, List[].class, List[].class, List[].class);
403
404 final Type[] types = method.getGenericParameterTypes();
405
406 assertFalse(TypeUtils.isArrayType(types[0]));
407 assertFalse(TypeUtils.isArrayType(types[1]));
408 assertFalse(TypeUtils.isArrayType(types[2]));
409 assertFalse(TypeUtils.isArrayType(types[3]));
410 assertFalse(TypeUtils.isArrayType(types[4]));
411 assertFalse(TypeUtils.isArrayType(types[5]));
412 assertFalse(TypeUtils.isArrayType(types[6]));
413 assertTrue(TypeUtils.isArrayType(types[7]));
414 assertTrue(TypeUtils.isArrayType(types[8]));
415 assertTrue(TypeUtils.isArrayType(types[9]));
416 assertTrue(TypeUtils.isArrayType(types[10]));
417 assertTrue(TypeUtils.isArrayType(types[11]));
418 assertTrue(TypeUtils.isArrayType(types[12]));
419 assertTrue(TypeUtils.isArrayType(types[13]));
420 }
421
422 @Test
423 public void testIsArrayTypeClasses() {
424 assertTrue(TypeUtils.isArrayType(boolean[].class));
425 assertTrue(TypeUtils.isArrayType(byte[].class));
426 assertTrue(TypeUtils.isArrayType(short[].class));
427 assertTrue(TypeUtils.isArrayType(int[].class));
428 assertTrue(TypeUtils.isArrayType(char[].class));
429 assertTrue(TypeUtils.isArrayType(long[].class));
430 assertTrue(TypeUtils.isArrayType(float[].class));
431 assertTrue(TypeUtils.isArrayType(double[].class));
432 assertTrue(TypeUtils.isArrayType(Object[].class));
433 assertTrue(TypeUtils.isArrayType(String[].class));
434
435 assertFalse(TypeUtils.isArrayType(boolean.class));
436 assertFalse(TypeUtils.isArrayType(byte.class));
437 assertFalse(TypeUtils.isArrayType(short.class));
438 assertFalse(TypeUtils.isArrayType(int.class));
439 assertFalse(TypeUtils.isArrayType(char.class));
440 assertFalse(TypeUtils.isArrayType(long.class));
441 assertFalse(TypeUtils.isArrayType(float.class));
442 assertFalse(TypeUtils.isArrayType(double.class));
443 assertFalse(TypeUtils.isArrayType(Object.class));
444 assertFalse(TypeUtils.isArrayType(String.class));
445 }
446
116447 @SuppressWarnings("boxing") // deliberately used here
117448 @Test
118449 public void testIsAssignable() throws SecurityException, NoSuchMethodException,
119450 NoSuchFieldException {
120451 List list0 = null;
121 List<Object> list1 = null;
122 List<?> list2 = null;
123 List<? super Object> list3 = null;
124 List<String> list4 = null;
125 List<? extends String> list5 = null;
126 List<? super String> list6 = null;
452 List<Object> list1;
453 List<?> list2;
454 List<? super Object> list3;
455 List<String> list4;
456 List<? extends String> list5;
457 List<? super String> list6;
127458 List[] list7 = null;
128 List<Object>[] list8 = null;
129 List<?>[] list9 = null;
130 List<? super Object>[] list10 = null;
131 List<String>[] list11 = null;
132 List<? extends String>[] list12 = null;
459 List<Object>[] list8;
460 List<?>[] list9;
461 List<? super Object>[] list10;
462 List<String>[] list11;
463 List<? extends String>[] list12;
133464 List<? super String>[] list13;
134465 final Class<?> clazz = getClass();
135466 final Method method = clazz.getMethod("dummyMethod", List.class, List.class, List.class,
370701 int in = 0;
371702 long lo = 0;
372703 final float fl = 0;
373 double du = 0;
704 double du;
374705 du = ch;
375706 assertTrue(TypeUtils.isAssignable(char.class, double.class));
376707 du = by;
451782 assertTrue(TypeUtils.isAssignable(fClassType, eClassType));
452783 }
453784
454 public void delegateBooleanAssertion(final Type[] types, final int i2, final int i1, final boolean expected) {
455 final Type type1 = types[i1];
456 final Type type2 = types[i2];
457 final boolean isAssignable = TypeUtils.isAssignable(type2, type1);
458
459 if (expected) {
460 assertTrue(isAssignable,
461 "[" + i1 + ", " + i2 + "]: From "
462 + String.valueOf(type2) + " to "
463 + String.valueOf(type1));
464 } else {
465 assertFalse(isAssignable,
466 "[" + i1 + ", " + i2 + "]: From "
467 + String.valueOf(type2) + " to "
468 + String.valueOf(type1));
469 }
785 private void testIsAssignable(final Class testUnassignableClass) {
786 final Class<Constructor> rawClass = Constructor.class;
787 final Class<Insets> typeArgClass = Insets.class;
788 // Builds a ParameterizedType for Constructor<Insets>
789 final ParameterizedType paramType = TypeUtils.parameterize(rawClass, typeArgClass);
790 assertEquals(rawClass, paramType.getRawType());
791 assertEquals(typeArgClass, paramType.getActualTypeArguments()[0]);
792
793 assertFalse(testUnassignableClass.isAssignableFrom(paramType.getClass()));
794 assertFalse(paramType.getClass().isAssignableFrom(testUnassignableClass));
795
796 final GenericArrayType arrayType = TypeUtils.genericArrayType(paramType);
797 assertFalse(TypeUtils.isAssignable(arrayType, paramType),
798 () -> String.format("TypeUtils.isAssignable(%s, %s)", arrayType, paramType));
799 assertFalse(TypeUtils.isAssignable(paramType, arrayType),
800 () -> String.format("TypeUtils.isAssignable(%s, %s)", paramType, arrayType));
801 }
802
803 @Test
804 public void testIsAssignableGenericArrayTypeToParameterizedType() {
805 final Class<Constructor> rawClass = Constructor.class;
806 final Class<Insets> typeArgClass = Insets.class;
807 // Builds a ParameterizedType for Constructor<Insets>
808 final ParameterizedType paramType = TypeUtils.parameterize(rawClass, typeArgClass);
809 assertEquals(rawClass, paramType.getRawType());
810 assertEquals(typeArgClass, paramType.getActualTypeArguments()[0]);
811
812 assertFalse(GenericArrayType.class.isAssignableFrom(paramType.getClass()));
813 assertFalse(paramType.getClass().isAssignableFrom(GenericArrayType.class));
814
815 final GenericArrayType testType = TypeUtils.genericArrayType(paramType);
816 assertFalse(TypeUtils.isAssignable(paramType, testType),
817 () -> String.format("TypeUtils.isAssignable(%s, %s)", paramType, testType));
818 assertFalse(TypeUtils.isAssignable(testType, paramType),
819 () -> String.format("TypeUtils.isAssignable(%s, %s)", testType, paramType));
820 }
821
822 @Test
823 @Disabled("TODO")
824 public void testIsAssignableGenericArrayTypeToWildercardType() {
825 final Class<Constructor> rawClass = Constructor.class;
826 final Class<Insets> typeArgClass = Insets.class;
827 // Builds a ParameterizedType for Constructor<Insets>
828 final ParameterizedType paramType = TypeUtils.parameterize(rawClass, typeArgClass);
829 assertEquals(rawClass, paramType.getRawType());
830 assertEquals(typeArgClass, paramType.getActualTypeArguments()[0]);
831
832 assertFalse(WildcardType.class.isAssignableFrom(paramType.getClass()));
833 assertFalse(paramType.getClass().isAssignableFrom(WildcardType.class));
834
835 final WildcardType testType = TypeUtils.WILDCARD_ALL;
836 // TODO This test returns true unlike the test above.
837 // Is this a bug in this test or in the main code?
838 assertFalse(TypeUtils.isAssignable(paramType, testType),
839 () -> String.format("TypeUtils.isAssignable(%s, %s)", paramType, testType));
840 assertFalse(TypeUtils.isAssignable(testType, paramType),
841 () -> String.format("TypeUtils.isAssignable(%s, %s)", testType, paramType));
842 }
843
844 @Test
845 public void testIsAssignableGenericArrayTypeToObject() {
846 final Class<Constructor> rawClass = Constructor.class;
847 final Class<Insets> typeArgClass = Insets.class;
848 // Builds a ParameterizedType for Constructor<Insets>
849 final ParameterizedType paramType = TypeUtils.parameterize(rawClass, typeArgClass);
850 assertEquals(rawClass, paramType.getRawType());
851 assertEquals(typeArgClass, paramType.getActualTypeArguments()[0]);
852
853 assertTrue(Object.class.isAssignableFrom(paramType.getClass()));
854 assertFalse(paramType.getClass().isAssignableFrom(Object.class));
855
856 final Type testType = Object.class;
857 assertTrue(TypeUtils.isAssignable(paramType, testType),
858 () -> String.format("TypeUtils.isAssignable(%s, %s)", paramType, testType));
859 assertFalse(TypeUtils.isAssignable(testType, paramType),
860 () -> String.format("TypeUtils.isAssignable(%s, %s)", testType, paramType));
470861 }
471862
472863 @SuppressWarnings("boxing") // boxing is deliberate here
481872 }
482873
483874 @Test
484 public void testGetTypeArguments() {
485 Map<TypeVariable<?>, Type> typeVarAssigns;
486 TypeVariable<?> treeSetTypeVar;
487 Type typeArg;
488
489 typeVarAssigns = TypeUtils.getTypeArguments(Integer.class, Comparable.class);
490 treeSetTypeVar = Comparable.class.getTypeParameters()[0];
491 assertTrue(typeVarAssigns.containsKey(treeSetTypeVar),
492 "Type var assigns for Comparable from Integer: " + typeVarAssigns);
493 typeArg = typeVarAssigns.get(treeSetTypeVar);
494 assertEquals(Integer.class, typeVarAssigns.get(treeSetTypeVar),
495 "Type argument of Comparable from Integer: " + typeArg);
496
497 typeVarAssigns = TypeUtils.getTypeArguments(int.class, Comparable.class);
498 treeSetTypeVar = Comparable.class.getTypeParameters()[0];
499 assertTrue(typeVarAssigns.containsKey(treeSetTypeVar),
500 "Type var assigns for Comparable from int: " + typeVarAssigns);
501 typeArg = typeVarAssigns.get(treeSetTypeVar);
502 assertEquals(Integer.class, typeVarAssigns.get(treeSetTypeVar),
503 "Type argument of Comparable from int: " + typeArg);
504
505 final Collection<Integer> col = Collections.emptyList();
506 typeVarAssigns = TypeUtils.getTypeArguments(List.class, Collection.class);
507 treeSetTypeVar = Comparable.class.getTypeParameters()[0];
508 assertFalse(typeVarAssigns.containsKey(treeSetTypeVar),
509 "Type var assigns for Collection from List: " + typeVarAssigns);
510
511 typeVarAssigns = TypeUtils.getTypeArguments(AAAClass.BBBClass.class, AAClass.BBClass.class);
512 assertEquals(2, typeVarAssigns.size());
513 assertEquals(String.class, typeVarAssigns.get(AAClass.class.getTypeParameters()[0]));
514 assertEquals(String.class, typeVarAssigns.get(AAClass.BBClass.class.getTypeParameters()[0]));
515
516 typeVarAssigns = TypeUtils.getTypeArguments(Other.class, This.class);
517 assertEquals(2, typeVarAssigns.size());
518 assertEquals(String.class, typeVarAssigns.get(This.class.getTypeParameters()[0]));
519 assertEquals(Other.class.getTypeParameters()[0], typeVarAssigns.get(This.class.getTypeParameters()[1]));
520
521 typeVarAssigns = TypeUtils.getTypeArguments(And.class, This.class);
522 assertEquals(2, typeVarAssigns.size());
523 assertEquals(Number.class, typeVarAssigns.get(This.class.getTypeParameters()[0]));
524 assertEquals(Number.class, typeVarAssigns.get(This.class.getTypeParameters()[1]));
525
526 typeVarAssigns = TypeUtils.getTypeArguments(Thing.class, Other.class);
527 assertEquals(2, typeVarAssigns.size());
528 assertEquals(getClass().getTypeParameters()[0], typeVarAssigns.get(getClass().getTypeParameters()[0]));
529 assertEquals(getClass().getTypeParameters()[0], typeVarAssigns.get(Other.class.getTypeParameters()[0]));
875 public void testLang1114() throws Exception {
876 final Type nonWildcardType = getClass().getDeclaredField("wildcardComparable").getGenericType();
877 final Type wildcardType = ((ParameterizedType) nonWildcardType).getActualTypeArguments()[0];
878
879 assertFalse(TypeUtils.equals(wildcardType, nonWildcardType));
880 assertFalse(TypeUtils.equals(nonWildcardType, wildcardType));
881 }
882
883 @Test
884 public void testLANG1190() throws Exception {
885 final Type fromType = ClassWithSuperClassWithGenericType.class.getDeclaredMethod("methodWithGenericReturnType").getGenericReturnType();
886 final Type failingToType = TypeUtils.wildcardType().withLowerBounds(ClassWithSuperClassWithGenericType.class).build();
887
888 assertTrue(TypeUtils.isAssignable(fromType, failingToType));
889 }
890
891 @Test
892 public void testLANG1348() throws Exception {
893 final Method method = Enum.class.getMethod("valueOf", Class.class, String.class);
894 assertEquals("T extends java.lang.Enum<T>", TypeUtils.toString(method.getGenericReturnType()));
895 }
896
897 @Test
898 public void testLang820() {
899 final Type[] typeArray = {String.class, String.class};
900 final Type[] expectedArray = {String.class};
901 assertArrayEquals(expectedArray, TypeUtils.normalizeUpperBounds(typeArray));
902 }
903
904 @Test
905 public void testLowerBoundedWildcardType() {
906 final WildcardType lowerBounded = TypeUtils.wildcardType().withLowerBounds(java.sql.Date.class).build();
907 assertEquals(String.format("? super %s", java.sql.Date.class.getName()), TypeUtils.toString(lowerBounded));
908 assertEquals(String.format("? super %s", java.sql.Date.class.getName()), lowerBounded.toString());
909
910 final TypeVariable<Class<Iterable>> iterableT0 = Iterable.class.getTypeParameters()[0];
911 final WildcardType lowerTypeVariable = TypeUtils.wildcardType().withLowerBounds(iterableT0).build();
912 assertEquals(String.format("? super %s", iterableT0.getName()), TypeUtils.toString(lowerTypeVariable));
913 assertEquals(String.format("? super %s", iterableT0.getName()), lowerTypeVariable.toString());
914 }
915
916 @Test
917 public void testParameterize() throws Exception {
918 final ParameterizedType stringComparableType = TypeUtils.parameterize(Comparable.class, String.class);
919 assertTrue(TypeUtils.equals(getClass().getField("stringComparable").getGenericType(),
920 stringComparableType));
921 assertEquals("java.lang.Comparable<java.lang.String>", stringComparableType.toString());
922 }
923
924 @Test
925 public void testParameterizeNarrowerTypeArray() {
926 final TypeVariable<?>[] variables = ArrayList.class.getTypeParameters();
927 final ParameterizedType parameterizedType = TypeUtils.parameterize(ArrayList.class, variables);
928 final Map<TypeVariable<?>, Type> mapping = Collections.<TypeVariable<?>, Type>singletonMap(variables[0], String.class);
929 final Type unrolled = TypeUtils.unrollVariables(mapping, parameterizedType);
930 assertEquals(TypeUtils.parameterize(ArrayList.class, String.class), unrolled);
931 }
932
933 @Test
934 public void testParameterizeWithOwner() throws Exception {
935 final Type owner = TypeUtils.parameterize(TypeUtilsTest.class, String.class);
936 final ParameterizedType dat2Type = TypeUtils.parameterizeWithOwner(owner, That.class, String.class, String.class);
937 assertTrue(TypeUtils.equals(getClass().getField("dat2").getGenericType(), dat2Type));
938 }
939
940 @Test
941 public void testToLongString() {
942 assertEquals(getClass().getName() + ":B", TypeUtils.toLongString(getClass().getTypeParameters()[0]));
943 }
944
945 @Test
946 public void testToStringLang1311() {
947 assertEquals("int[]", TypeUtils.toString(int[].class));
948 assertEquals("java.lang.Integer[]", TypeUtils.toString(Integer[].class));
949 final Field stringListField = FieldUtils.getDeclaredField(getClass(), "stringListArray");
950 assertEquals("java.util.List<java.lang.String>[]", TypeUtils.toString(stringListField.getGenericType()));
530951 }
531952
532953 @Test
545966 }
546967
547968 @Test
548 public void testDetermineTypeVariableAssignments() throws SecurityException,
549 NoSuchFieldException {
550 final ParameterizedType iterableType = (ParameterizedType) getClass().getField("iterable")
551 .getGenericType();
552 final Map<TypeVariable<?>, Type> typeVarAssigns = TypeUtils.determineTypeArguments(TreeSet.class,
553 iterableType);
554 final TypeVariable<?> treeSetTypeVar = TreeSet.class.getTypeParameters()[0];
555 assertTrue(typeVarAssigns.containsKey(treeSetTypeVar));
556 assertEquals(iterableType.getActualTypeArguments()[0], typeVarAssigns
557 .get(treeSetTypeVar));
558 }
559
560 @Test
561 public void testGetRawType() throws SecurityException, NoSuchFieldException {
562 final Type stringParentFieldType = GenericTypeHolder.class.getDeclaredField("stringParent")
563 .getGenericType();
564 final Type integerParentFieldType = GenericTypeHolder.class.getDeclaredField("integerParent")
565 .getGenericType();
566 final Type foosFieldType = GenericTypeHolder.class.getDeclaredField("foos").getGenericType();
567 final Type genericParentT = GenericParent.class.getTypeParameters()[0];
568 assertEquals(GenericParent.class, TypeUtils.getRawType(stringParentFieldType, null));
569 assertEquals(GenericParent.class, TypeUtils.getRawType(integerParentFieldType,
570 null));
571 assertEquals(List.class, TypeUtils.getRawType(foosFieldType, null));
572 assertEquals(String.class, TypeUtils.getRawType(genericParentT,
573 StringParameterizedChild.class));
574 assertEquals(String.class, TypeUtils.getRawType(genericParentT,
575 stringParentFieldType));
576 assertEquals(Foo.class, TypeUtils.getRawType(Iterable.class.getTypeParameters()[0],
577 foosFieldType));
578 assertEquals(Foo.class, TypeUtils.getRawType(List.class.getTypeParameters()[0],
579 foosFieldType));
580 assertNull(TypeUtils.getRawType(genericParentT, GenericParent.class));
581 assertEquals(GenericParent[].class, TypeUtils.getRawType(GenericTypeHolder.class
582 .getDeclaredField("barParents").getGenericType(), null));
583 }
584
585 @Test
586 public void testIsArrayTypeClasses() {
587 assertTrue(TypeUtils.isArrayType(boolean[].class));
588 assertTrue(TypeUtils.isArrayType(byte[].class));
589 assertTrue(TypeUtils.isArrayType(short[].class));
590 assertTrue(TypeUtils.isArrayType(int[].class));
591 assertTrue(TypeUtils.isArrayType(char[].class));
592 assertTrue(TypeUtils.isArrayType(long[].class));
593 assertTrue(TypeUtils.isArrayType(float[].class));
594 assertTrue(TypeUtils.isArrayType(double[].class));
595 assertTrue(TypeUtils.isArrayType(Object[].class));
596 assertTrue(TypeUtils.isArrayType(String[].class));
597
598 assertFalse(TypeUtils.isArrayType(boolean.class));
599 assertFalse(TypeUtils.isArrayType(byte.class));
600 assertFalse(TypeUtils.isArrayType(short.class));
601 assertFalse(TypeUtils.isArrayType(int.class));
602 assertFalse(TypeUtils.isArrayType(char.class));
603 assertFalse(TypeUtils.isArrayType(long.class));
604 assertFalse(TypeUtils.isArrayType(float.class));
605 assertFalse(TypeUtils.isArrayType(double.class));
606 assertFalse(TypeUtils.isArrayType(Object.class));
607 assertFalse(TypeUtils.isArrayType(String.class));
608 }
609
610 @Test
611 public void testIsArrayGenericTypes() throws Exception {
612 final Method method = getClass().getMethod("dummyMethod", List.class, List.class, List.class,
613 List.class, List.class, List.class, List.class, List[].class, List[].class,
614 List[].class, List[].class, List[].class, List[].class, List[].class);
615
616 final Type[] types = method.getGenericParameterTypes();
617
618 assertFalse(TypeUtils.isArrayType(types[0]));
619 assertFalse(TypeUtils.isArrayType(types[1]));
620 assertFalse(TypeUtils.isArrayType(types[2]));
621 assertFalse(TypeUtils.isArrayType(types[3]));
622 assertFalse(TypeUtils.isArrayType(types[4]));
623 assertFalse(TypeUtils.isArrayType(types[5]));
624 assertFalse(TypeUtils.isArrayType(types[6]));
625 assertTrue(TypeUtils.isArrayType(types[7]));
626 assertTrue(TypeUtils.isArrayType(types[8]));
627 assertTrue(TypeUtils.isArrayType(types[9]));
628 assertTrue(TypeUtils.isArrayType(types[10]));
629 assertTrue(TypeUtils.isArrayType(types[11]));
630 assertTrue(TypeUtils.isArrayType(types[12]));
631 assertTrue(TypeUtils.isArrayType(types[13]));
632 }
633
634 @Test
635 public void testGetPrimitiveArrayComponentType() {
636 assertEquals(boolean.class, TypeUtils.getArrayComponentType(boolean[].class));
637 assertEquals(byte.class, TypeUtils.getArrayComponentType(byte[].class));
638 assertEquals(short.class, TypeUtils.getArrayComponentType(short[].class));
639 assertEquals(int.class, TypeUtils.getArrayComponentType(int[].class));
640 assertEquals(char.class, TypeUtils.getArrayComponentType(char[].class));
641 assertEquals(long.class, TypeUtils.getArrayComponentType(long[].class));
642 assertEquals(float.class, TypeUtils.getArrayComponentType(float[].class));
643 assertEquals(double.class, TypeUtils.getArrayComponentType(double[].class));
644
645 assertNull(TypeUtils.getArrayComponentType(boolean.class));
646 assertNull(TypeUtils.getArrayComponentType(byte.class));
647 assertNull(TypeUtils.getArrayComponentType(short.class));
648 assertNull(TypeUtils.getArrayComponentType(int.class));
649 assertNull(TypeUtils.getArrayComponentType(char.class));
650 assertNull(TypeUtils.getArrayComponentType(long.class));
651 assertNull(TypeUtils.getArrayComponentType(float.class));
652 assertNull(TypeUtils.getArrayComponentType(double.class));
653 }
654
655 @Test
656 public void testGetArrayComponentType() throws Exception {
657 final Method method = getClass().getMethod("dummyMethod", List.class, List.class, List.class,
658 List.class, List.class, List.class, List.class, List[].class, List[].class,
659 List[].class, List[].class, List[].class, List[].class, List[].class);
660
661 final Type[] types = method.getGenericParameterTypes();
662
663 assertNull(TypeUtils.getArrayComponentType(types[0]));
664 assertNull(TypeUtils.getArrayComponentType(types[1]));
665 assertNull(TypeUtils.getArrayComponentType(types[2]));
666 assertNull(TypeUtils.getArrayComponentType(types[3]));
667 assertNull(TypeUtils.getArrayComponentType(types[4]));
668 assertNull(TypeUtils.getArrayComponentType(types[5]));
669 assertNull(TypeUtils.getArrayComponentType(types[6]));
670 assertEquals(types[0], TypeUtils.getArrayComponentType(types[7]));
671 assertEquals(types[1], TypeUtils.getArrayComponentType(types[8]));
672 assertEquals(types[2], TypeUtils.getArrayComponentType(types[9]));
673 assertEquals(types[3], TypeUtils.getArrayComponentType(types[10]));
674 assertEquals(types[4], TypeUtils.getArrayComponentType(types[11]));
675 assertEquals(types[5], TypeUtils.getArrayComponentType(types[12]));
676 assertEquals(types[6], TypeUtils.getArrayComponentType(types[13]));
677 }
678
679 @Test
680 public void testLang820() {
681 final Type[] typeArray = {String.class, String.class};
682 final Type[] expectedArray = {String.class};
683 assertArrayEquals(expectedArray, TypeUtils.normalizeUpperBounds(typeArray));
684 }
685
686 @Test
687 public void testParameterize() throws Exception {
688 final ParameterizedType stringComparableType = TypeUtils.parameterize(Comparable.class, String.class);
689 assertTrue(TypeUtils.equals(getClass().getField("stringComparable").getGenericType(),
690 stringComparableType));
691 assertEquals("java.lang.Comparable<java.lang.String>", stringComparableType.toString());
692 }
693
694 @Test
695 public void testParameterizeNarrowerTypeArray() {
696 final TypeVariable<?>[] variables = ArrayList.class.getTypeParameters();
697 final ParameterizedType parameterizedType = TypeUtils.parameterize(ArrayList.class, variables);
698 final Map<TypeVariable<?>, Type> mapping = Collections.<TypeVariable<?>, Type>singletonMap(variables[0], String.class);
699 final Type unrolled = TypeUtils.unrollVariables(mapping, parameterizedType);
700 assertEquals(TypeUtils.parameterize(ArrayList.class, String.class), unrolled);
701 }
702
703 @Test
704 public void testParameterizeWithOwner() throws Exception {
705 final Type owner = TypeUtils.parameterize(TypeUtilsTest.class, String.class);
706 final ParameterizedType dat2Type = TypeUtils.parameterizeWithOwner(owner, That.class, String.class, String.class);
707 assertTrue(TypeUtils.equals(getClass().getField("dat2").getGenericType(), dat2Type));
969 public void testUnboundedWildcardType() {
970 final WildcardType unbounded = TypeUtils.wildcardType().withLowerBounds((Type) null).withUpperBounds().build();
971 assertTrue(TypeUtils.equals(TypeUtils.WILDCARD_ALL, unbounded));
972 assertArrayEquals(new Type[] { Object.class }, TypeUtils.getImplicitUpperBounds(unbounded));
973 assertArrayEquals(new Type[] { null }, TypeUtils.getImplicitLowerBounds(unbounded));
974 assertEquals("?", TypeUtils.toString(unbounded));
975 assertEquals("?", unbounded.toString());
708976 }
709977
710978 @Test
718986 }
719987
720988 @Test
721 public void testUnboundedWildcardType() {
722 final WildcardType unbounded = TypeUtils.wildcardType().withLowerBounds((Type) null).withUpperBounds().build();
723 assertTrue(TypeUtils.equals(TypeUtils.WILDCARD_ALL, unbounded));
724 assertArrayEquals(new Type[] { Object.class }, TypeUtils.getImplicitUpperBounds(unbounded));
725 assertArrayEquals(new Type[] { null }, TypeUtils.getImplicitLowerBounds(unbounded));
726 assertEquals("?", TypeUtils.toString(unbounded));
727 assertEquals("?", unbounded.toString());
728 }
729
730 @Test
731 public void testLowerBoundedWildcardType() {
732 final WildcardType lowerBounded = TypeUtils.wildcardType().withLowerBounds(java.sql.Date.class).build();
733 assertEquals(String.format("? super %s", java.sql.Date.class.getName()), TypeUtils.toString(lowerBounded));
734 assertEquals(String.format("? super %s", java.sql.Date.class.getName()), lowerBounded.toString());
735
736 final TypeVariable<Class<Iterable>> iterableT0 = Iterable.class.getTypeParameters()[0];
737 final WildcardType lowerTypeVariable = TypeUtils.wildcardType().withLowerBounds(iterableT0).build();
738 assertEquals(String.format("? super %s", iterableT0.getName()), TypeUtils.toString(lowerTypeVariable));
739 assertEquals(String.format("? super %s", iterableT0.getName()), lowerTypeVariable.toString());
740 }
741
742 @Test
743 public void testLang1114() throws Exception {
744 final Type nonWildcardType = getClass().getDeclaredField("wildcardComparable").getGenericType();
745 final Type wildcardType = ((ParameterizedType) nonWildcardType).getActualTypeArguments()[0];
746
747 assertFalse(TypeUtils.equals(wildcardType, nonWildcardType));
748 assertFalse(TypeUtils.equals(nonWildcardType, wildcardType));
749 }
750
751 @Test
752 public void testGenericArrayType() throws Exception {
753 final Type expected = getClass().getField("intWildcardComparable").getGenericType();
754 final GenericArrayType actual =
755 TypeUtils.genericArrayType(TypeUtils.parameterize(Comparable.class, TypeUtils.wildcardType()
756 .withUpperBounds(Integer.class).build()));
757 assertTrue(TypeUtils.equals(expected, actual));
758 assertEquals("java.lang.Comparable<? extends java.lang.Integer>[]", actual.toString());
759 }
760
761 @Test
762 public void testToStringLang1311() {
763 assertEquals("int[]", TypeUtils.toString(int[].class));
764 assertEquals("java.lang.Integer[]", TypeUtils.toString(Integer[].class));
765 final Field stringListField = FieldUtils.getDeclaredField(getClass(), "stringListArray");
766 assertEquals("java.util.List<java.lang.String>[]", TypeUtils.toString(stringListField.getGenericType()));
767 }
768
769 @Test
770 public void testToLongString() {
771 assertEquals(getClass().getName() + ":B", TypeUtils.toLongString(getClass().getTypeParameters()[0]));
772 }
773
774 @Test
775989 public void testWrap() {
776990 final Type t = getClass().getTypeParameters()[0];
777991 assertTrue(TypeUtils.equals(t, TypeUtils.wrap(t).getType()));
778992
779993 assertEquals(String.class, TypeUtils.wrap(String.class).getType());
780994 }
781
782 public static class ClassWithSuperClassWithGenericType extends ArrayList<Object> {
783 private static final long serialVersionUID = 1L;
784
785 public static <U> Iterable<U> methodWithGenericReturnType() {
786 return null;
787 }
788 }
789
790 @Test
791 public void testLANG1190() throws Exception {
792 final Type fromType = ClassWithSuperClassWithGenericType.class.getDeclaredMethod("methodWithGenericReturnType").getGenericReturnType();
793 final Type failingToType = TypeUtils.wildcardType().withLowerBounds(ClassWithSuperClassWithGenericType.class).build();
794
795 assertTrue(TypeUtils.isAssignable(fromType, failingToType));
796 }
797
798 @Test
799 public void testLANG1348() throws Exception {
800 final Method method = Enum.class.getMethod("valueOf", Class.class, String.class);
801 assertEquals("T extends java.lang.Enum<T>", TypeUtils.toString(method.getGenericReturnType()));
802 }
803
804 public Iterable<? extends Map<Integer, ? extends Collection<?>>> iterable;
805
806 public static <G extends Comparable<G>> G stub() {
807 return null;
808 }
809
810 public static <G extends Comparable<? super G>> G stub2() {
811 return null;
812 }
813
814 public static <T extends Comparable<? extends T>> T stub3() {
815 return null;
816 }
817995 }
818
819 class AAClass<T> {
820
821 public class BBClass<S> {
822 }
823 }
824
825 class AAAClass extends AAClass<String> {
826 public class BBBClass extends BBClass<String> {
827 }
828 }
829
830 @SuppressWarnings("rawtypes")
831 //raw types, where used, are used purposely
832 class AClass extends AAClass<String>.BBClass<Number> {
833
834 AClass(final AAClass<String> enclosingInstance) {
835 enclosingInstance.super();
836 }
837
838 public class BClass<T> {
839 }
840
841 public class CClass<T> extends BClass {
842 }
843
844 public class DClass<T> extends CClass<T> {
845 }
846
847 public class EClass<T> extends DClass {
848 }
849
850 public class FClass extends EClass<String> {
851 }
852
853 public class GClass<T extends BClass<? extends T> & AInterface<AInterface<? super T>>> {
854 }
855
856 public BClass<Number> bClass;
857
858 public CClass<? extends String> cClass;
859
860 public DClass<String> dClass;
861
862 public EClass<String> eClass;
863
864 public FClass fClass;
865
866 public GClass gClass;
867
868 public interface AInterface<T> {
869 }
870 }
4545
4646 protected <T extends Throwable> FailableConsumer<String, T> asIntConsumer(final T pThrowable) {
4747 return s -> {
48 final Integer i = Integer.valueOf(s);
49 if (i.intValue() == 4) {
48 final int i = Integer.parseInt(s);
49 if (i == 4) {
5050 throw pThrowable;
5151 }
5252 };
5454
5555 protected <T extends Throwable> FailablePredicate<Integer, T> asIntPredicate(final T pThrowable) {
5656 return i -> {
57 if (i.intValue() == 5) {
58 if (pThrowable != null) {
59 throw pThrowable;
60 }
57 if (i.intValue() == 5 && pThrowable != null) {
58 throw pThrowable;
6159 }
6260 return i % 2 == 0;
6361 };
137135 }
138136
139137 @Test
138 public void testOfArray() {
139 assertEquals(0, Streams.of((Object[]) null).count());
140 assertEquals(1, Streams.of("foo").count());
141 assertEquals(2, Streams.of("foo", "bar").count());
142 }
143
144 @Test
145 public void testStreamCollection() {
146 final List<String> input = Arrays.asList("1", "2", "3", "4", "5", "6");
147 assertEquals(6, Streams.stream(input).collect(Collectors.toList()).size());
148 }
149
150 @Test
151 public void testStreamCollectionNull() {
152 final List<String> input = null;
153 assertEquals(0, Streams.stream(input).collect(Collectors.toList()).size());
154 }
155
156 @Test
140157 public void testSimpleStreamFilter() {
141158 final List<String> input = Arrays.asList("1", "2", "3", "4", "5", "6");
142159 final List<Integer> output = Failable.stream(input).map(Integer::valueOf).filter(i -> (i.intValue() % 2 == 0))
109109 public void testExtendedAndBuiltInFormats() {
110110 final Calendar cal = Calendar.getInstance();
111111 cal.set(2007, Calendar.JANUARY, 23, 18, 33, 5);
112 final Object[] args = new Object[] {"John Doe", cal.getTime(), Double.valueOf("12345.67")};
112 final Object[] args = {"John Doe", cal.getTime(), Double.valueOf("12345.67")};
113113 final String builtinsPattern = "DOB: {1,date,short} Salary: {2,number,currency}";
114114 final String extendedPattern = "Name: {0,upper} ";
115115 final String pattern = extendedPattern + builtinsPattern;
206206 @Test
207207 public void testBuiltInChoiceFormat() {
208208 final Object[] values = new Number[] {Integer.valueOf(1), Double.valueOf("2.2"), Double.valueOf("1234.5")};
209 String choicePattern = null;
209 String choicePattern;
210210 final Locale[] availableLocales = NumberFormat.getAvailableLocales();
211211
212212 choicePattern = "{0,choice,1#One|2#Two|3#Many {0,number}}";
227227 public void testBuiltInDateTimeFormat() {
228228 final Calendar cal = Calendar.getInstance();
229229 cal.set(2007, Calendar.JANUARY, 23, 18, 33, 5);
230 final Object[] args = new Object[] {cal.getTime()};
230 final Object[] args = {cal.getTime()};
231231 final Locale[] availableLocales = DateFormat.getAvailableLocales();
232232
233233 checkBuiltInFormat("1: {0,date,short}", args, availableLocales);
248248 public void testOverriddenBuiltinFormat() {
249249 final Calendar cal = Calendar.getInstance();
250250 cal.set(2007, Calendar.JANUARY, 23);
251 final Object[] args = new Object[] {cal.getTime()};
251 final Object[] args = {cal.getTime()};
252252 final Locale[] availableLocales = DateFormat.getAvailableLocales();
253253 final Map<String, ? extends FormatFactory> dateRegistry = Collections.singletonMap("date", new OverrideShortDateFormatFactory());
254254
275275 */
276276 @Test
277277 public void testBuiltInNumberFormat() {
278 final Object[] args = new Object[] {Double.valueOf("6543.21")};
278 final Object[] args = {Double.valueOf("6543.21")};
279279 final Locale[] availableLocales = NumberFormat.getAvailableLocales();
280280 checkBuiltInFormat("1: {0,number}", args, availableLocales);
281281 checkBuiltInFormat("2: {0,number,integer}", args, availableLocales);
295295 final String pattern = "Pattern: {0,testfmt}";
296296 final ExtendedMessageFormat emf = new ExtendedMessageFormat(pattern, Locale.US, fmtRegistry);
297297
298 ExtendedMessageFormat other = null;
298 ExtendedMessageFormat other;
299299
300300 // Same object
301301 assertEquals(emf, emf, "same, equals()");
4444 }
4545 };
4646
47 //-----------------------------------------------------------------------
4847 @Test
4948 public void testAppendNewLine() {
5049 StrBuilder sb = new StrBuilder("---");
5655 assertEquals("---#" + SEP, sb.toString());
5756 }
5857
59 //-----------------------------------------------------------------------
6058 @Test
6159 public void testAppendWithNullText() {
6260 final StrBuilder sb = new StrBuilder();
8886 assertEquals("NULLNULLfooNULLbarNULLbaz", sb.toString());
8987 }
9088
91 //-----------------------------------------------------------------------
9289 @Test
9390 public void testAppend_Object() {
9491 final StrBuilder sb = new StrBuilder();
117114 assertEquals("foobazyesSeqbld", sb.toString());
118115 }
119116
120 //-----------------------------------------------------------------------
121117 @Test
122118 public void testAppend_StringBuilder() {
123119 StrBuilder sb = new StrBuilder();
135131 assertEquals("foobar", sb.toString());
136132 }
137133
138 //-----------------------------------------------------------------------
139134 @Test
140135 public void testAppend_String() {
141136 StrBuilder sb = new StrBuilder();
153148 assertEquals("foobar", sb.toString());
154149 }
155150
156 //-----------------------------------------------------------------------
157151 @Test
158152 public void testAppend_String_int_int() {
159153 StrBuilder sb = new StrBuilder();
205199 assertEquals("foobarard", sb.toString());
206200 }
207201
208 //-----------------------------------------------------------------------
209202 @Test
210203 public void testAppend_StringBuilder_int_int() {
211204 StrBuilder sb = new StrBuilder();
257250 assertEquals("foobarard", sb.toString());
258251 }
259252
260 //-----------------------------------------------------------------------
261253 @Test
262254 public void testAppend_StringBuffer() {
263255 StrBuilder sb = new StrBuilder();
275267 assertEquals("foobar", sb.toString());
276268 }
277269
278 //-----------------------------------------------------------------------
279270 @Test
280271 public void testAppend_StringBuffer_int_int() {
281272 StrBuilder sb = new StrBuilder();
324315 assertEquals("foobar", sb.toString());
325316 }
326317
327 //-----------------------------------------------------------------------
328318 @Test
329319 public void testAppend_StrBuilder() {
330320 StrBuilder sb = new StrBuilder();
342332 assertEquals("foobar", sb.toString());
343333 }
344334
345 //-----------------------------------------------------------------------
346335 @Test
347336 public void testAppend_StrBuilder_int_int() {
348337 StrBuilder sb = new StrBuilder();
391380 assertEquals("foobar", sb.toString());
392381 }
393382
394 //-----------------------------------------------------------------------
395383 @Test
396384 public void testAppend_CharArray() {
397385 StrBuilder sb = new StrBuilder();
406394 assertEquals("foo", sb.toString());
407395 }
408396
409 //-----------------------------------------------------------------------
410397 @Test
411398 public void testAppend_CharArray_int_int() {
412399 StrBuilder sb = new StrBuilder();
455442 assertEquals("foobar", sb.toString());
456443 }
457444
458 //-----------------------------------------------------------------------
459445 @Test
460446 public void testAppend_Boolean() {
461447 final StrBuilder sb = new StrBuilder();
469455 assertEquals("truefalse!", sb.toString());
470456 }
471457
472 //-----------------------------------------------------------------------
473458 @Test
474459 public void testAppend_PrimitiveNumber() {
475460 final StrBuilder sb = new StrBuilder();
486471 assertEquals("012.34.5", sb.toString());
487472 }
488473
489 //-----------------------------------------------------------------------
490474 @Test
491475 public void testAppendln_FormattedString() {
492476 final int[] count = new int[2];
510494 assertEquals(1, count[1]);
511495 }
512496
513 //-----------------------------------------------------------------------
514497 @Test
515498 public void testAppendln_Object() {
516499 final StrBuilder sb = new StrBuilder();
524507 assertEquals(SEP + "foo" + SEP + "6" + SEP, sb.toString());
525508 }
526509
527 //-----------------------------------------------------------------------
528510 @Test
529511 public void testAppendln_String() {
530512 final int[] count = new int[2];
548530 assertEquals(1, count[1]);
549531 }
550532
551 //-----------------------------------------------------------------------
552533 @Test
553534 public void testAppendln_String_int_int() {
554535 final int[] count = new int[2];
572553 assertEquals(1, count[1]);
573554 }
574555
575 //-----------------------------------------------------------------------
576556 @Test
577557 public void testAppendln_StringBuffer() {
578558 final int[] count = new int[2];
596576 assertEquals(1, count[1]);
597577 }
598578
599 //-----------------------------------------------------------------------
600579 @Test
601580 public void testAppendln_StringBuilder() {
602581 final int[] count = new int[2];
620599 assertEquals(1, count[1]);
621600 }
622601
623 //-----------------------------------------------------------------------
624602 @Test
625603 public void testAppendln_StringBuffer_int_int() {
626604 final int[] count = new int[2];
644622 assertEquals(1, count[1]);
645623 }
646624
647 //-----------------------------------------------------------------------
648625 @Test
649626 public void testAppendln_StringBuilder_int_int() {
650627 final int[] count = new int[2];
668645 assertEquals(1, count[1]);
669646 }
670647
671 //-----------------------------------------------------------------------
672648 @Test
673649 public void testAppendln_StrBuilder() {
674650 final int[] count = new int[2];
692668 assertEquals(1, count[1]);
693669 }
694670
695 //-----------------------------------------------------------------------
696671 @Test
697672 public void testAppendln_StrBuilder_int_int() {
698673 final int[] count = new int[2];
716691 assertEquals(1, count[1]);
717692 }
718693
719 //-----------------------------------------------------------------------
720694 @Test
721695 public void testAppendln_CharArray() {
722696 final int[] count = new int[2];
740714 assertEquals(1, count[1]);
741715 }
742716
743 //-----------------------------------------------------------------------
744717 @Test
745718 public void testAppendln_CharArray_int_int() {
746719 final int[] count = new int[2];
764737 assertEquals(1, count[1]);
765738 }
766739
767 //-----------------------------------------------------------------------
768740 @Test
769741 public void testAppendln_Boolean() {
770742 final StrBuilder sb = new StrBuilder();
776748 assertEquals("false" + SEP, sb.toString());
777749 }
778750
779 //-----------------------------------------------------------------------
780751 @Test
781752 public void testAppendln_PrimitiveNumber() {
782753 final StrBuilder sb = new StrBuilder();
796767 assertEquals("4.5" + SEP, sb.toString());
797768 }
798769
799 //-----------------------------------------------------------------------
800770 @Test
801771 public void testAppendPadding() {
802772 final StrBuilder sb = new StrBuilder();
818788 assertEquals("foo-----------------", sb.toString());
819789 }
820790
821 //-----------------------------------------------------------------------
822791 @Test
823792 public void testAppendFixedWidthPadLeft() {
824793 final StrBuilder sb = new StrBuilder();
857826 assertEquals("-null", sb.toString());
858827 }
859828
860 //-----------------------------------------------------------------------
861829 @Test
862830 public void testAppendFixedWidthPadLeft_int() {
863831 final StrBuilder sb = new StrBuilder();
891859 assertEquals("-------123", sb.toString());
892860 }
893861
894 //-----------------------------------------------------------------------
895862 @Test
896863 public void testAppendFixedWidthPadRight() {
897864 final StrBuilder sb = new StrBuilder();
938905 assertEquals("f", sb.toString());
939906 }
940907
941 //-----------------------------------------------------------------------
942908 @Test
943909 public void testAppendFixedWidthPadRight_int() {
944910 final StrBuilder sb = new StrBuilder();
972938 assertEquals("123-------", sb.toString());
973939 }
974940
975 //-----------------------------------------------------------------------
976941 @Test
977942 public void testAppend_FormattedString() {
978943 StrBuilder sb;
997962 assertEquals(expected, sb.toString());
998963 }
999964
1000 //-----------------------------------------------------------------------
1001965 @Test
1002966 public void testAppendAll_Array() {
1003967 final StrBuilder sb = new StrBuilder();
1017981 assertEquals("foobarbaz", sb.toString());
1018982 }
1019983
1020 //-----------------------------------------------------------------------
1021984 @Test
1022985 public void testAppendAll_Collection() {
1023986 final StrBuilder sb = new StrBuilder();
1033996 assertEquals("foobarbaz", sb.toString());
1034997 }
1035998
1036 //-----------------------------------------------------------------------
1037999 @Test
10381000 public void testAppendAll_Iterator() {
10391001 final StrBuilder sb = new StrBuilder();
10491011 assertEquals("foobarbaz", sb.toString());
10501012 }
10511013
1052 //-----------------------------------------------------------------------
10531014 @Test
10541015 public void testAppendWithSeparators_Array() {
10551016 final StrBuilder sb = new StrBuilder();
10731034 assertEquals("foo,,baz", sb.toString());
10741035 }
10751036
1076 //-----------------------------------------------------------------------
10771037 @Test
10781038 public void testAppendWithSeparators_Collection() {
10791039 final StrBuilder sb = new StrBuilder();
10971057 assertEquals("foo,,baz", sb.toString());
10981058 }
10991059
1100 //-----------------------------------------------------------------------
11011060 @Test
11021061 public void testAppendWithSeparators_Iterator() {
11031062 final StrBuilder sb = new StrBuilder();
11211080 assertEquals("foo,,baz", sb.toString());
11221081 }
11231082
1124 //-----------------------------------------------------------------------
11251083 @Test
11261084 public void testAppendWithSeparatorsWithNullText() {
11271085 final StrBuilder sb = new StrBuilder();
11341092 assertEquals("foo,null,baz", sb.toString());
11351093 }
11361094
1137 //-----------------------------------------------------------------------
11381095 @Test
11391096 public void testAppendSeparator_String() {
11401097 final StrBuilder sb = new StrBuilder();
11461103 assertEquals("foo,", sb.toString());
11471104 }
11481105
1149 //-----------------------------------------------------------------------
11501106 @Test
11511107 public void testAppendSeparator_String_String() {
11521108 final StrBuilder sb = new StrBuilder();
11691125 assertEquals(startSeparator + foo + standardSeparator, sb.toString());
11701126 }
11711127
1172 //-----------------------------------------------------------------------
11731128 @Test
11741129 public void testAppendSeparator_char() {
11751130 final StrBuilder sb = new StrBuilder();
11941149 assertEquals(String.valueOf(startSeparator) + foo + standardSeparator, sb.toString());
11951150 }
11961151
1197 //-----------------------------------------------------------------------
11981152 @Test
11991153 public void testAppendSeparator_String_int() {
12001154 final StrBuilder sb = new StrBuilder();
12091163 assertEquals("foo,", sb.toString());
12101164 }
12111165
1212 //-----------------------------------------------------------------------
12131166 @Test
12141167 public void testAppendSeparator_char_int() {
12151168 final StrBuilder sb = new StrBuilder();
12241177 assertEquals("foo,", sb.toString());
12251178 }
12261179
1227 //-----------------------------------------------------------------------
12281180 @Test
12291181 public void testInsert() {
12301182
14431395 assertEquals("4.5barbaz", sb.toString());
14441396 }
14451397
1446 //-----------------------------------------------------------------------
14471398 @Test
14481399 public void testInsertWithNullText() {
14491400 final StrBuilder sb = new StrBuilder();
4343 @Deprecated
4444 public class StrBuilderTest {
4545
46 //-----------------------------------------------------------------------
4746 @Test
4847 public void testConstructors() {
4948 final StrBuilder sb0 = new StrBuilder();
8786 assertEquals(3, sb7.size());
8887 }
8988
90 //-----------------------------------------------------------------------
9189 @Test
9290 public void testChaining() {
9391 final StrBuilder sb = new StrBuilder();
102100 assertSame(sb, sb.trim());
103101 }
104102
105 //-----------------------------------------------------------------------
106103 @Test
107104 public void testReadFromReader() throws Exception {
108105 String s = "";
180177 }
181178 }
182179
183 //-----------------------------------------------------------------------
184180 @Test
185181 public void testGetSetNewLineText() {
186182 final StrBuilder sb = new StrBuilder();
196192 assertNull(sb.getNewLineText());
197193 }
198194
199 //-----------------------------------------------------------------------
200195 @Test
201196 public void testGetSetNullText() {
202197 final StrBuilder sb = new StrBuilder();
215210 assertNull(sb.getNullText());
216211 }
217212
218 //-----------------------------------------------------------------------
219213 @Test
220214 public void testCapacityAndLength() {
221215 final StrBuilder sb = new StrBuilder();
298292 assertTrue(sb.isEmpty());
299293 }
300294
301 //-----------------------------------------------------------------------
302295 @Test
303296 public void testLength() {
304297 final StrBuilder sb = new StrBuilder();
325318 "setLength(-1) expected StringIndexOutOfBoundsException");
326319 }
327320
328 //-----------------------------------------------------------------------
329321 @Test
330322 public void testCapacity() {
331323 final StrBuilder sb = new StrBuilder();
360352 assertEquals(10, sb.capacity());
361353 }
362354
363 //-----------------------------------------------------------------------
364355 @Test
365356 public void testSize() {
366357 final StrBuilder sb = new StrBuilder();
391382 assertTrue(sb.buffer.length >= 5);
392383 }
393384
394 //-----------------------------------------------------------------------
395385 @Test
396386 public void testCharAt() {
397387 final StrBuilder sb = new StrBuilder();
409399 IndexOutOfBoundsException.class, () -> sb.charAt(3), "charAt(3) expected IndexOutOfBoundsException");
410400 }
411401
412 //-----------------------------------------------------------------------
413402 @Test
414403 public void testSetCharAt() {
415404 final StrBuilder sb = new StrBuilder();
432421 assertEquals("bar", sb.toString());
433422 }
434423
435 //-----------------------------------------------------------------------
436424 @Test
437425 public void testDeleteCharAt() {
438426 final StrBuilder sb = new StrBuilder("abc");
442430 assertThrows(IndexOutOfBoundsException.class, () -> sb.deleteCharAt(1000));
443431 }
444432
445 //-----------------------------------------------------------------------
446433 @Test
447434 public void testToCharArray() {
448435 final StrBuilder sb = new StrBuilder();
533520 assertThrows(IndexOutOfBoundsException.class, () -> sb.getChars(4, 2, b, 0));
534521 }
535522
536 //-----------------------------------------------------------------------
537523 @Test
538524 public void testDeleteIntInt() {
539525 final StrBuilder sb = new StrBuilder("abc");
551537 assertThrows(IndexOutOfBoundsException.class, () -> new StrBuilder("anything").delete(2, 1));
552538 }
553539
554 //-----------------------------------------------------------------------
555540 @Test
556541 public void testDeleteAll_char() {
557542 StrBuilder sb = new StrBuilder("abcbccba");
701686 assertThrows(IndexOutOfBoundsException.class, () -> sb2.replace(-1, 1, "anything"));
702687 }
703688
704 //-----------------------------------------------------------------------
705689 @Test
706690 public void testReplaceAll_char_char() {
707691 final StrBuilder sb = new StrBuilder("abcbccba");
717701 assertEquals("defeffed", sb.toString());
718702 }
719703
720 //-----------------------------------------------------------------------
721704 @Test
722705 public void testReplaceFirst_char_char() {
723706 final StrBuilder sb = new StrBuilder("abcbccba");
733716 assertEquals("defbccba", sb.toString());
734717 }
735718
736 //-----------------------------------------------------------------------
737719 @Test
738720 public void testReplaceAll_String_String() {
739721 StrBuilder sb = new StrBuilder("abcbccba");
794776 assertEquals("xbxb", sb.toString());
795777 }
796778
797 //-----------------------------------------------------------------------
798779 @Test
799780 public void testReplaceAll_StrMatcher_String() {
800781 StrBuilder sb = new StrBuilder("abcbccba");
867848 assertEquals("***-A2A3-A4", sb.toString());
868849 }
869850
870 //-----------------------------------------------------------------------
871851 @Test
872852 public void testReplace_StrMatcher_String_int_int_int_VaryMatcher() {
873853 StrBuilder sb = new StrBuilder("abcbccba");
10551035 assertEquals("-x--y-", sb.toString());
10561036 }
10571037
1058 //-----------------------------------------------------------------------
10591038 @Test
10601039 public void testReverse() {
10611040 final StrBuilder sb = new StrBuilder();
10661045 assertEquals("true", sb.reverse().toString());
10671046 }
10681047
1069 //-----------------------------------------------------------------------
10701048 @Test
10711049 public void testTrim() {
10721050 final StrBuilder sb = new StrBuilder();
10881066 assertEquals("a b c", sb.trim().toString());
10891067 }
10901068
1091 //-----------------------------------------------------------------------
10921069 @Test
10931070 public void testStartsWith() {
10941071 final StrBuilder sb = new StrBuilder();
11191096 assertFalse(sb.endsWith("abc "));
11201097 }
11211098
1122 //-----------------------------------------------------------------------
11231099 @Test
11241100 public void testSubSequenceIntInt() {
11251101 final StrBuilder sb = new StrBuilder ("hello goodbye");
15571533 }
15581534 };
15591535
1560 //-----------------------------------------------------------------------
15611536 @Test
15621537 public void testAsTokenizer() {
15631538 // from Javadoc
16531628 assertEquals(9, r.read(array, 0, 30));
16541629 }
16551630
1656 //-----------------------------------------------------------------------
16571631 @Test
16581632 public void testAsWriter() throws Exception {
16591633 final StrBuilder sb = new StrBuilder("base");
16881662 assertEquals("based", sb.toString());
16891663 }
16901664
1691 //-----------------------------------------------------------------------
16921665 @Test
16931666 public void testEqualsIgnoreCase() {
16941667 final StrBuilder sb1 = new StrBuilder();
17121685 assertTrue(sb1.equalsIgnoreCase(sb2));
17131686 }
17141687
1715 //-----------------------------------------------------------------------
17161688 @Test
17171689 public void testEquals() {
17181690 final StrBuilder sb1 = new StrBuilder();
17451717 assertFalse(sb.equals(other));
17461718 }
17471719
1748 //-----------------------------------------------------------------------
17491720 @Test
17501721 public void testHashCode() {
17511722 final StrBuilder sb = new StrBuilder();
17611732 assertEquals(hc2a, hc2b);
17621733 }
17631734
1764 //-----------------------------------------------------------------------
17651735 @Test
17661736 public void testToString() {
17671737 final StrBuilder sb = new StrBuilder("abc");
17681738 assertEquals("abc", sb.toString());
17691739 }
17701740
1771 //-----------------------------------------------------------------------
17721741 @Test
17731742 public void testToStringBuffer() {
17741743 final StrBuilder sb = new StrBuilder();
17781747 assertEquals(new StringBuffer("junit").toString(), sb.toStringBuffer().toString());
17791748 }
17801749
1781 //-----------------------------------------------------------------------
17821750 @Test
17831751 public void testToStringBuilder() {
17841752 final StrBuilder sb = new StrBuilder();
17881756 assertEquals(new StringBuilder("junit").toString(), sb.toStringBuilder().toString());
17891757 }
17901758
1791 //-----------------------------------------------------------------------
17921759 @Test
17931760 public void testLang294() {
17941761 final StrBuilder sb = new StrBuilder("\n%BLAH%\nDo more stuff\neven more stuff\n%BLAH%\n");
18031770 assertEquals(-1, sb.indexOf("three"));
18041771 }
18051772
1806 //-----------------------------------------------------------------------
18071773 @Test
18081774 public void testLang295() {
18091775 final StrBuilder sb = new StrBuilder("onetwothree");
18121778 assertEquals(-1, sb.indexOf('h'), "The indexOf(char) method is looking beyond the end of the string");
18131779 }
18141780
1815 //-----------------------------------------------------------------------
18161781 @Test
18171782 public void testLang412Right() {
18181783 final StrBuilder sb = new StrBuilder();
18331798 assertEquals(sb.toString(), sb.build());
18341799 }
18351800
1836 //-----------------------------------------------------------------------
18371801 @Test
18381802 public void testAppendCharBuffer() {
18391803 final StrBuilder sb1 = new StrBuilder();
18481812 assertEquals("12345678", sb2.toString());
18491813 }
18501814
1851 //-----------------------------------------------------------------------
18521815 @Test
18531816 public void testAppendToWriter() throws Exception {
18541817 final StrBuilder sb = new StrBuilder("1234567890");
3232 @Deprecated
3333 public class StrLookupTest {
3434
35 //-----------------------------------------------------------------------
3635 @Test
3736 public void testNoneLookup() {
3837 assertNull(StrLookup.noneLookup().lookup(null));
3333 private static final char[] BUFFER2 = "abcdef".toCharArray();
3434
3535
36 //-----------------------------------------------------------------------
3736 @Test
3837 public void testCommaMatcher() {
3938 final StrMatcher matcher = StrMatcher.commaMatcher();
4342 assertEquals(0, matcher.isMatch(BUFFER1, 2));
4443 }
4544
46 //-----------------------------------------------------------------------
4745 @Test
4846 public void testTabMatcher() {
4947 final StrMatcher matcher = StrMatcher.tabMatcher();
5351 assertEquals(0, matcher.isMatch(BUFFER1, 4));
5452 }
5553
56 //-----------------------------------------------------------------------
5754 @Test
5855 public void testSpaceMatcher() {
5956 final StrMatcher matcher = StrMatcher.spaceMatcher();
6360 assertEquals(0, matcher.isMatch(BUFFER1, 6));
6461 }
6562
66 //-----------------------------------------------------------------------
6763 @Test
6864 public void testSplitMatcher() {
6965 final StrMatcher matcher = StrMatcher.splitMatcher();
7975 assertEquals(0, matcher.isMatch(BUFFER1, 10));
8076 }
8177
82 //-----------------------------------------------------------------------
8378 @Test
8479 public void testTrimMatcher() {
8580 final StrMatcher matcher = StrMatcher.trimMatcher();
9590 assertEquals(1, matcher.isMatch(BUFFER1, 10));
9691 }
9792
98 //-----------------------------------------------------------------------
9993 @Test
10094 public void testSingleQuoteMatcher() {
10195 final StrMatcher matcher = StrMatcher.singleQuoteMatcher();
10599 assertEquals(0, matcher.isMatch(BUFFER1, 12));
106100 }
107101
108 //-----------------------------------------------------------------------
109102 @Test
110103 public void testDoubleQuoteMatcher() {
111104 final StrMatcher matcher = StrMatcher.doubleQuoteMatcher();
114107 assertEquals(1, matcher.isMatch(BUFFER1, 12));
115108 }
116109
117 //-----------------------------------------------------------------------
118110 @Test
119111 public void testQuoteMatcher() {
120112 final StrMatcher matcher = StrMatcher.quoteMatcher();
124116 assertEquals(1, matcher.isMatch(BUFFER1, 12));
125117 }
126118
127 //-----------------------------------------------------------------------
128119 @Test
129120 public void testNoneMatcher() {
130121 final StrMatcher matcher = StrMatcher.noneMatcher();
144135 assertEquals(0, matcher.isMatch(BUFFER1, 12));
145136 }
146137
147 //-----------------------------------------------------------------------
148138 @Test
149139 public void testCharMatcher_char() {
150140 final StrMatcher matcher = StrMatcher.charMatcher('c');
156146 assertEquals(0, matcher.isMatch(BUFFER2, 5));
157147 }
158148
159 //-----------------------------------------------------------------------
160149 @Test
161150 public void testCharSetMatcher_String() {
162151 final StrMatcher matcher = StrMatcher.charSetMatcher("ace");
171160 assertTrue(StrMatcher.charSetMatcher("a") instanceof StrMatcher.CharMatcher);
172161 }
173162
174 //-----------------------------------------------------------------------
175163 @Test
176164 public void testCharSetMatcher_charArray() {
177165 final StrMatcher matcher = StrMatcher.charSetMatcher("ace".toCharArray());
186174 assertTrue(StrMatcher.charSetMatcher("a".toCharArray()) instanceof StrMatcher.CharMatcher);
187175 }
188176
189 //-----------------------------------------------------------------------
190177 @Test
191178 public void testStringMatcher_String() {
192179 final StrMatcher matcher = StrMatcher.stringMatcher("bc");
200187 assertSame(StrMatcher.noneMatcher(), StrMatcher.stringMatcher(null));
201188 }
202189
203 //-----------------------------------------------------------------------
204190 @Test
205191 public void testMatcherIndices() {
206192 // remember that the API contract is tight for the isMatch() method
5252 values = null;
5353 }
5454
55 //-----------------------------------------------------------------------
5655 /**
5756 * Tests simple key replace.
5857 */
391390 sub.replace("The ${animal} jumps over the lazy ${target}. ${undefined.number!1234567890}."));
392391 }
393392
394 //-----------------------------------------------------------------------
395393 /**
396394 * Tests protected.
397395 */
414412 assertEquals("Hi jakarta!", builder.toString());
415413 }
416414
417 //-----------------------------------------------------------------------
418415 /**
419416 * Tests constructor.
420417 */
448445 assertEquals("Hi < commons", sub.replace("Hi !< <name2||commons>"));
449446 }
450447
451 //-----------------------------------------------------------------------
452448 /**
453449 * Tests get set.
454450 */
526522 assertNull(sub.getValueDelimiterMatcher());
527523 }
528524
529 //-----------------------------------------------------------------------
530525 /**
531526 * Tests static.
532527 */
614609 assertEquals("value $${escaped}", sub.replace(org));
615610 }
616611
617 //-----------------------------------------------------------------------
618612 private void doTestReplace(final String expectedResult, final String replaceTemplate, final boolean substring) {
619613 final String expectedShortResult = expectedResult.substring(1, expectedResult.length() - 1);
620614 final StrSubstitutor sub = new StrSubstitutor(values);
5858 tok.setIgnoreEmptyTokens(false);
5959 final String[] tokens = tok.getTokenArray();
6060
61 final String[] expected = new String[]{"a", "b", "c", "d;\"e", "f", "", "", ""};
61 final String[] expected = {"a", "b", "c", "d;\"e", "f", "", "", ""};
6262
6363 assertEquals(expected.length, tokens.length, ArrayUtils.toString(tokens));
6464 for (int i = 0; i < expected.length; i++) {
7979 tok.setIgnoreEmptyTokens(false);
8080 final String[] tokens = tok.getTokenArray();
8181
82 final String[] expected = new String[]{"a", "b", "c ", "d;\"e", "f", " ", " ", ""};
82 final String[] expected = {"a", "b", "c ", "d;\"e", "f", " ", " ", ""};
8383
8484 assertEquals(expected.length, tokens.length, ArrayUtils.toString(tokens));
8585 for (int i = 0; i < expected.length; i++) {
100100 tok.setIgnoreEmptyTokens(false);
101101 final String[] tokens = tok.getTokenArray();
102102
103 final String[] expected = new String[]{"a", "b", " c", "d;\"e", "f", " ", " ", ""};
103 final String[] expected = {"a", "b", " c", "d;\"e", "f", " ", " ", ""};
104104
105105 assertEquals(expected.length, tokens.length, ArrayUtils.toString(tokens));
106106 for (int i = 0; i < expected.length; i++) {
121121 tok.setIgnoreEmptyTokens(true);
122122 final String[] tokens = tok.getTokenArray();
123123
124 final String[] expected = new String[]{"a", "b", "c", "d;\"e", "f"};
124 final String[] expected = {"a", "b", "c", "d;\"e", "f"};
125125
126126 assertEquals(expected.length, tokens.length, ArrayUtils.toString(tokens));
127127 for (int i = 0; i < expected.length; i++) {
143143 tok.setEmptyTokenAsNull(true);
144144 final String[] tokens = tok.getTokenArray();
145145
146 final String[] expected = new String[]{"a", "b", "c", "d;\"e", "f", null, null, null};
146 final String[] expected = {"a", "b", "c", "d;\"e", "f", null, null, null};
147147
148148 assertEquals(expected.length, tokens.length, ArrayUtils.toString(tokens));
149149 for (int i = 0; i < expected.length; i++) {
165165 // tok.setTreatingEmptyAsNull(true);
166166 final String[] tokens = tok.getTokenArray();
167167
168 final String[] expected = new String[]{"a", "b", " c", "d;\"e", "f", null, null, null};
168 final String[] expected = {"a", "b", " c", "d;\"e", "f", null, null, null};
169169
170170 int nextCount = 0;
171171 while (tok.hasNext()) {
198198 tok.setIgnoreEmptyTokens(false);
199199 final String[] tokens = tok.getTokenArray();
200200
201 final String[] expected = new String[]{"a", "", "", "b", "c", "d e", "f", ""};
201 final String[] expected = {"a", "", "", "b", "c", "d e", "f", ""};
202202
203203 assertEquals(expected.length, tokens.length, ArrayUtils.toString(tokens));
204204 for (int i = 0; i < expected.length; i++) {
219219 tok.setIgnoreEmptyTokens(true);
220220 final String[] tokens = tok.getTokenArray();
221221
222 final String[] expected = new String[]{"a", "b", "c", "d e", "f"};
222 final String[] expected = {"a", "b", "c", "d e", "f"};
223223
224224 assertEquals(expected.length, tokens.length, ArrayUtils.toString(tokens));
225225 for (int i = 0; i < expected.length; i++) {
496496 assertFalse(tok.hasNext());
497497 }
498498
499 //-----------------------------------------------------------------------
500499 @Test
501500 public void testListArray() {
502501 final String input = "a b c";
508507 assertEquals(3, list.size());
509508 }
510509
511 //-----------------------------------------------------------------------
512510 private void testCSV(final String data) {
513511 this.testXSVAbc(StrTokenizer.getCSVInstance(data));
514512 this.testXSVAbc(StrTokenizer.getCSVInstance(data.toCharArray()));
554552 assertNull(tok.getContent());
555553 }
556554
557 //-----------------------------------------------------------------------
558555 @Test
559556 public void testChaining() {
560557 final StrTokenizer tok = new StrTokenizer();
604601
605602 @Test
606603 public void testCloneReset() {
607 final char[] input = new char[]{'a'};
604 final char[] input = {'a'};
608605 final StrTokenizer tokenizer = new StrTokenizer(input);
609606 // Start sanity check
610607 assertEquals("a", tokenizer.nextToken());
633630 assertFalse(tok.hasNext());
634631 }
635632
636 //-----------------------------------------------------------------------
637633 @Test
638634 public void testConstructor_String_char() {
639635 StrTokenizer tok = new StrTokenizer("a b", ' ');
649645 assertFalse(tok.hasNext());
650646 }
651647
652 //-----------------------------------------------------------------------
653648 @Test
654649 public void testConstructor_String_char_char() {
655650 StrTokenizer tok = new StrTokenizer("a b", ' ', '"');
666661 assertFalse(tok.hasNext());
667662 }
668663
669 //-----------------------------------------------------------------------
670664 @Test
671665 public void testConstructor_charArray() {
672666 StrTokenizer tok = new StrTokenizer("a b".toCharArray());
681675 assertFalse(tok.hasNext());
682676 }
683677
684 //-----------------------------------------------------------------------
685678 @Test
686679 public void testConstructor_charArray_char() {
687680 StrTokenizer tok = new StrTokenizer("a b".toCharArray(), ' ');
697690 assertFalse(tok.hasNext());
698691 }
699692
700 //-----------------------------------------------------------------------
701693 @Test
702694 public void testConstructor_charArray_char_char() {
703695 StrTokenizer tok = new StrTokenizer("a b".toCharArray(), ' ', '"');
714706 assertFalse(tok.hasNext());
715707 }
716708
717 //-----------------------------------------------------------------------
718709 @Test
719710 public void testReset() {
720711 final StrTokenizer tok = new StrTokenizer("a b c");
730721 assertFalse(tok.hasNext());
731722 }
732723
733 //-----------------------------------------------------------------------
734724 @Test
735725 public void testReset_String() {
736726 final StrTokenizer tok = new StrTokenizer("x x x");
743733 assertFalse(tok.hasNext());
744734 }
745735
746 //-----------------------------------------------------------------------
747736 @Test
748737 public void testReset_charArray() {
749738 final StrTokenizer tok = new StrTokenizer("x x x");
750739
751 final char[] array = new char[] {'a', 'b', 'c'};
740 final char[] array = {'a', 'b', 'c'};
752741 tok.reset(array);
753742 assertEquals("abc", tok.next());
754743 assertFalse(tok.hasNext());
757746 assertFalse(tok.hasNext());
758747 }
759748
760 //-----------------------------------------------------------------------
761749 @Test
762750 public void testTSV() {
763751 this.testXSVAbc(StrTokenizer.getTSVInstance(TSV_SIMPLE_FIXTURE));
822810 assertFalse(tkn.hasNext());
823811 }
824812
825 //-----------------------------------------------------------------------
826813 @Test
827814 public void testTokenizeSubclassInputChange() {
828815 final StrTokenizer tkn = new StrTokenizer("a b c d e") {
835822 assertEquals("y", tkn.next());
836823 }
837824
838 //-----------------------------------------------------------------------
839825 @Test
840826 public void testTokenizeSubclassOutputChange() {
841827 final StrTokenizer tkn = new StrTokenizer("a b c") {
851837 assertEquals("a", tkn.next());
852838 }
853839
854 //-----------------------------------------------------------------------
855840 @Test
856841 public void testToString() {
857842 final StrTokenizer tkn = new StrTokenizer("a b c d e");
3232 @Deprecated
3333 public class WordUtilsTest {
3434
35 //-----------------------------------------------------------------------
3635 @Test
3736 public void testConstructor() {
3837 assertNotNull(new WordUtils());
4342 assertFalse(Modifier.isFinal(WordUtils.class.getModifiers()));
4443 }
4544
46 //-----------------------------------------------------------------------
4745 @Test
4846 public void testWrap_StringInt() {
4947 assertNull(WordUtils.wrap(null, 20));
181179 assertEquals(expected, WordUtils.wrap(input, 15, "\n", true, "/"));
182180 }
183181
184 //-----------------------------------------------------------------------
185182 @Test
186183 public void testCapitalize_String() {
187184 assertNull(WordUtils.capitalize(null));
202199 assertEquals("", WordUtils.capitalize(""));
203200 assertEquals(" ", WordUtils.capitalize(" "));
204201
205 char[] chars = new char[] { '-', '+', ' ', '@' };
202 char[] chars = { '-', '+', ' ', '@' };
206203 assertEquals("I", WordUtils.capitalize("I", chars) );
207204 assertEquals("I", WordUtils.capitalize("i", chars) );
208205 assertEquals("I-Am Here+123", WordUtils.capitalize("i-am here+123", chars) );
234231 assertEquals("", WordUtils.capitalizeFully(""));
235232 assertEquals(" ", WordUtils.capitalizeFully(" "));
236233
237 char[] chars = new char[] { '-', '+', ' ', '@' };
234 char[] chars = { '-', '+', ' ', '@' };
238235 assertEquals("I", WordUtils.capitalizeFully("I", chars) );
239236 assertEquals("I", WordUtils.capitalizeFully("i", chars) );
240237 assertEquals("I-Am Here+123", WordUtils.capitalizeFully("i-am here+123", chars) );
286283 assertEquals("", WordUtils.uncapitalize(""));
287284 assertEquals(" ", WordUtils.uncapitalize(" "));
288285
289 char[] chars = new char[] { '-', '+', ' ', '@' };
286 char[] chars = { '-', '+', ' ', '@' };
290287 assertEquals("i", WordUtils.uncapitalize("I", chars) );
291288 assertEquals("i", WordUtils.uncapitalize("i", chars) );
292289 assertEquals("i am-here+123", WordUtils.uncapitalize("i am-here+123", chars) );
298295 assertEquals("i aM.FINE", WordUtils.uncapitalize("I AM.FINE", null) );
299296 }
300297
301 //-----------------------------------------------------------------------
302298 @Test
303299 public void testInitials_String() {
304300 assertNull(WordUtils.initials(null));
5555 String expected = "Test \u0030 not test";
5656
5757 String result = neu.translate(input);
58 assertEquals(expected, result, "Failed to support unfinished entities (i.e. missing semi-colon)");
58 assertEquals(expected, result, "Failed to support unfinished entities (i.e. missing semicolon)");
5959
6060 // ignore it
6161 neu = new NumericEntityUnescaper();
6363 expected = input;
6464
6565 result = neu.translate(input);
66 assertEquals(expected, result, "Failed to ignore unfinished entities (i.e. missing semi-colon)");
66 assertEquals(expected, result, "Failed to ignore unfinished entities (i.e. missing semicolon)");
6767
6868 // fail it
6969 final NumericEntityUnescaper failingNeu =
2525 public class CalendarUtilsTest {
2626
2727 @Test
28 public void testGetYear() {
29 assertEquals(Calendar.getInstance().get(Calendar.YEAR), CalendarUtils.INSTANCE.getYear());
28 public void testGetDayOfMonth() {
29 assertEquals(Calendar.getInstance().get(Calendar.DAY_OF_MONTH), CalendarUtils.INSTANCE.getDayOfMonth());
3030 }
3131
3232 @Test
3535 }
3636
3737 @Test
38 public void testGetDayOfMonth() {
39 assertEquals(Calendar.getInstance().get(Calendar.DAY_OF_MONTH), CalendarUtils.INSTANCE.getDayOfMonth());
38 public void testGetYear() {
39 assertEquals(Calendar.getInstance().get(Calendar.YEAR), CalendarUtils.INSTANCE.getYear());
4040 }
4141
4242 }
3737 */
3838 @SuppressWarnings("deprecation") // tests lots of deprecated items
3939 public class DateFormatUtilsTest {
40 //-----------------------------------------------------------------------
40 private void assertFormats(final String expectedValue, final String pattern, final TimeZone timeZone, final Calendar cal) {
41 assertEquals(expectedValue, DateFormatUtils.format(cal.getTime(), pattern, timeZone));
42 assertEquals(expectedValue, DateFormatUtils.format(cal.getTime().getTime(), pattern, timeZone));
43 assertEquals(expectedValue, DateFormatUtils.format(cal, pattern, timeZone));
44 }
45
46 private Calendar createFebruaryTestDate(final TimeZone timeZone) {
47 final Calendar cal = Calendar.getInstance(timeZone);
48 cal.set(2002, Calendar.FEBRUARY, 23, 9, 11, 12);
49 return cal;
50 }
51
52 private Calendar createJuneTestDate(final TimeZone timeZone) {
53 final Calendar cal = Calendar.getInstance(timeZone);
54 cal.set(2003, Calendar.JUNE, 8, 10, 11, 12);
55 return cal;
56 }
57
4158 @Test
4259 public void testConstructor() {
4360 assertNotNull(new DateFormatUtils());
4865 assertFalse(Modifier.isFinal(DateFormatUtils.class.getModifiers()));
4966 }
5067
51 //-----------------------------------------------------------------------
68 @Test
69 public void testDateISO() {
70 testGmtMinus3("2002-02-23", DateFormatUtils.ISO_DATE_FORMAT.getPattern());
71 testGmtMinus3("2002-02-23-03:00", DateFormatUtils.ISO_DATE_TIME_ZONE_FORMAT.getPattern());
72 testUTC("2002-02-23Z", DateFormatUtils.ISO_DATE_TIME_ZONE_FORMAT.getPattern());
73 }
74
75 @Test
76 public void testDateTimeISO() {
77 testGmtMinus3("2002-02-23T09:11:12", DateFormatUtils.ISO_DATETIME_FORMAT.getPattern());
78 testGmtMinus3("2002-02-23T09:11:12-03:00", DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.getPattern());
79 testUTC("2002-02-23T09:11:12Z", DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.getPattern());
80 }
81
5282 @Test
5383 public void testFormat() {
5484 final Calendar c = Calendar.getInstance(FastTimeZone.getGmtTimeZone());
72102 assertEquals(buffer.toString(), DateFormatUtils.format(c.getTime().getTime(), "yyyyMdH", Locale.US));
73103 }
74104
75 //-----------------------------------------------------------------------
76105 @Test
77106 public void testFormatCalendar() {
78107 final Calendar c = Calendar.getInstance(FastTimeZone.getGmtTimeZone());
109138 assertEquals ("2005-01-01T12:00:00", DateFormatUtils.formatUTC(c.getTime().getTime(), DateFormatUtils.ISO_DATETIME_FORMAT.getPattern(), Locale.US));
110139 }
111140
112 private void assertFormats(final String expectedValue, final String pattern, final TimeZone timeZone, final Calendar cal) {
113 assertEquals(expectedValue, DateFormatUtils.format(cal.getTime(), pattern, timeZone));
114 assertEquals(expectedValue, DateFormatUtils.format(cal.getTime().getTime(), pattern, timeZone));
115 assertEquals(expectedValue, DateFormatUtils.format(cal, pattern, timeZone));
116 }
117
118 private Calendar createFebruaryTestDate(final TimeZone timeZone) {
119 final Calendar cal = Calendar.getInstance(timeZone);
120 cal.set(2002, Calendar.FEBRUARY, 23, 9, 11, 12);
121 return cal;
122 }
123
124 private Calendar createJuneTestDate(final TimeZone timeZone) {
125 final Calendar cal = Calendar.getInstance(timeZone);
126 cal.set(2003, Calendar.JUNE, 8, 10, 11, 12);
127 return cal;
128 }
129
130141 private void testGmtMinus3(final String expectedValue, final String pattern) {
131142 final TimeZone timeZone = TimeZone.getTimeZone("GMT-3");
132143 assertFormats(expectedValue, pattern, timeZone, createFebruaryTestDate(timeZone));
133 }
134
135 private void testUTC(final String expectedValue, final String pattern) {
136 final TimeZone timeZone = FastTimeZone.getGmtTimeZone();
137 assertFormats(expectedValue, pattern, timeZone, createFebruaryTestDate(timeZone));
138 }
139
140 @Test
141 public void testDateTimeISO() {
142 testGmtMinus3("2002-02-23T09:11:12", DateFormatUtils.ISO_DATETIME_FORMAT.getPattern());
143 testGmtMinus3("2002-02-23T09:11:12-03:00", DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.getPattern());
144 testUTC("2002-02-23T09:11:12Z", DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.getPattern());
145 }
146
147 @Test
148 public void testDateISO() {
149 testGmtMinus3("2002-02-23", DateFormatUtils.ISO_DATE_FORMAT.getPattern());
150 testGmtMinus3("2002-02-23-03:00", DateFormatUtils.ISO_DATE_TIME_ZONE_FORMAT.getPattern());
151 testUTC("2002-02-23Z", DateFormatUtils.ISO_DATE_TIME_ZONE_FORMAT.getPattern());
152 }
153
154 @Test
155 public void testTimeISO() {
156 testGmtMinus3("T09:11:12", DateFormatUtils.ISO_TIME_FORMAT.getPattern());
157 testGmtMinus3("T09:11:12-03:00", DateFormatUtils.ISO_TIME_TIME_ZONE_FORMAT.getPattern());
158 testUTC("T09:11:12Z", DateFormatUtils.ISO_TIME_TIME_ZONE_FORMAT.getPattern());
159 }
160
161 @Test
162 public void testTimeNoTISO() {
163 testGmtMinus3("09:11:12", DateFormatUtils.ISO_TIME_NO_T_FORMAT.getPattern());
164 testGmtMinus3("09:11:12-03:00", DateFormatUtils.ISO_TIME_NO_T_TIME_ZONE_FORMAT.getPattern());
165 testUTC("09:11:12Z", DateFormatUtils.ISO_TIME_NO_T_TIME_ZONE_FORMAT.getPattern());
166 }
167
168 @DefaultLocale(language = "en")
169 @Test
170 public void testSMTP() {
171 TimeZone timeZone = TimeZone.getTimeZone("GMT-3");
172 Calendar june = createJuneTestDate(timeZone);
173
174 assertFormats("Sun, 08 Jun 2003 10:11:12 -0300", DateFormatUtils.SMTP_DATETIME_FORMAT.getPattern(),
175 timeZone, june);
176
177 timeZone = FastTimeZone.getGmtTimeZone();
178 june = createJuneTestDate(timeZone);
179 assertFormats("Sun, 08 Jun 2003 10:11:12 +0000", DateFormatUtils.SMTP_DATETIME_FORMAT.getPattern(),
180 timeZone, june);
181144 }
182145
183146 @Test
237200 assertEquals("2009-10-16T07:42:16+01:00", value, "calendar");
238201 }
239202 }
203
204 @DefaultLocale(language = "en")
205 @Test
206 public void testSMTP() {
207 TimeZone timeZone = TimeZone.getTimeZone("GMT-3");
208 Calendar june = createJuneTestDate(timeZone);
209
210 assertFormats("Sun, 08 Jun 2003 10:11:12 -0300", DateFormatUtils.SMTP_DATETIME_FORMAT.getPattern(),
211 timeZone, june);
212
213 timeZone = FastTimeZone.getGmtTimeZone();
214 june = createJuneTestDate(timeZone);
215 assertFormats("Sun, 08 Jun 2003 10:11:12 +0000", DateFormatUtils.SMTP_DATETIME_FORMAT.getPattern(),
216 timeZone, june);
217 }
218
219 @Test
220 public void testTimeISO() {
221 testGmtMinus3("T09:11:12", DateFormatUtils.ISO_TIME_FORMAT.getPattern());
222 testGmtMinus3("T09:11:12-03:00", DateFormatUtils.ISO_TIME_TIME_ZONE_FORMAT.getPattern());
223 testUTC("T09:11:12Z", DateFormatUtils.ISO_TIME_TIME_ZONE_FORMAT.getPattern());
224 }
225
226 @Test
227 public void testTimeNoTISO() {
228 testGmtMinus3("09:11:12", DateFormatUtils.ISO_TIME_NO_T_FORMAT.getPattern());
229 testGmtMinus3("09:11:12-03:00", DateFormatUtils.ISO_TIME_NO_T_TIME_ZONE_FORMAT.getPattern());
230 testUTC("09:11:12Z", DateFormatUtils.ISO_TIME_NO_T_TIME_ZONE_FORMAT.getPattern());
231 }
232
233 private void testUTC(final String expectedValue, final String pattern) {
234 final TimeZone timeZone = FastTimeZone.getGmtTimeZone();
235 assertFormats(expectedValue, pattern, timeZone, createFebruaryTestDate(timeZone));
236 }
240237 }
4646 }
4747
4848 @Test
49 public void testNullDate() {
50 assertThrows(
51 NullPointerException.class,
52 () -> DateUtils.getFragmentInMilliseconds((Date) null, Calendar.MILLISECOND));
53
54 assertThrows(
55 NullPointerException.class,
56 () -> DateUtils.getFragmentInSeconds((Date) null, Calendar.MILLISECOND));
57
58 assertThrows(
59 NullPointerException.class,
60 () -> DateUtils.getFragmentInMinutes((Date) null, Calendar.MILLISECOND));
61
62 assertThrows(
63 NullPointerException.class,
64 () -> DateUtils.getFragmentInHours((Date) null, Calendar.MILLISECOND));
65
66 assertThrows(
67 NullPointerException.class,
68 () -> DateUtils.getFragmentInDays((Date) null, Calendar.MILLISECOND));
69 }
70
71 @Test
72 public void testNullCalendar() {
73 assertThrows(
74 IllegalArgumentException.class,
75 () -> DateUtils.getFragmentInMilliseconds((Calendar) null, Calendar.MILLISECOND));
76
77 assertThrows(
78 IllegalArgumentException.class,
79 () -> DateUtils.getFragmentInSeconds((Calendar) null, Calendar.MILLISECOND));
80
81 assertThrows(
82 IllegalArgumentException.class,
83 () -> DateUtils.getFragmentInMinutes((Calendar) null, Calendar.MILLISECOND));
84
85 assertThrows(
86 IllegalArgumentException.class,
87 () -> DateUtils.getFragmentInHours((Calendar) null, Calendar.MILLISECOND));
88
89 assertThrows(
90 IllegalArgumentException.class,
91 () -> DateUtils.getFragmentInDays((Calendar) null, Calendar.MILLISECOND));
49 public void testDateFragmentInLargerUnitWithCalendar() {
50 assertEquals(0, DateUtils.getFragmentInDays(aCalendar, Calendar.DATE));
51 }
52
53 @Test
54 public void testDateFragmentInLargerUnitWithDate() {
55 assertEquals(0, DateUtils.getFragmentInDays(aDate, Calendar.DATE));
56 }
57
58 @Test
59 public void testDayOfYearFragmentInLargerUnitWithCalendar() {
60 assertEquals(0, DateUtils.getFragmentInDays(aCalendar, Calendar.DAY_OF_YEAR));
61 }
62
63 @Test
64 public void testDayOfYearFragmentInLargerUnitWithDate() {
65 assertEquals(0, DateUtils.getFragmentInDays(aDate, Calendar.DAY_OF_YEAR));
66 }
67
68 @Test
69 public void testDaysOfMonthWithCalendar() {
70 final long testResult = DateUtils.getFragmentInDays(aCalendar, Calendar.MONTH);
71 assertEquals(days, testResult);
72 }
73
74 @Test
75 public void testDaysOfMonthWithDate() {
76 final long testResult = DateUtils.getFragmentInDays(aDate, Calendar.MONTH);
77 final Calendar cal = Calendar.getInstance();
78 cal.setTime(aDate);
79 assertEquals(cal.get(Calendar.DAY_OF_MONTH), testResult);
80 }
81
82 @Test
83 public void testDaysOfYearWithCalendar() {
84 final long testResult = DateUtils.getFragmentInDays(aCalendar, Calendar.YEAR);
85 assertEquals(aCalendar.get(Calendar.DAY_OF_YEAR), testResult);
86 }
87
88 @Test
89 public void testDaysOfYearWithDate() {
90 final long testResult = DateUtils.getFragmentInDays(aDate, Calendar.YEAR);
91 final Calendar cal = Calendar.getInstance();
92 cal.setTime(aDate);
93 assertEquals(cal.get(Calendar.DAY_OF_YEAR), testResult);
94 }
95
96 @Test
97 public void testHourOfDayFragmentInLargerUnitWithCalendar() {
98 assertEquals(0, DateUtils.getFragmentInHours(aCalendar, Calendar.HOUR_OF_DAY));
99 assertEquals(0, DateUtils.getFragmentInDays(aCalendar, Calendar.HOUR_OF_DAY));
100 }
101
102 @Test
103 public void testHourOfDayFragmentInLargerUnitWithDate() {
104 assertEquals(0, DateUtils.getFragmentInHours(aDate, Calendar.HOUR_OF_DAY));
105 assertEquals(0, DateUtils.getFragmentInDays(aDate, Calendar.HOUR_OF_DAY));
106 }
107
108 @Test
109 public void testHoursOfDayWithCalendar() {
110 long testResult = DateUtils.getFragmentInHours(aCalendar, Calendar.DATE);
111 final long expectedValue = hours;
112 assertEquals(expectedValue, testResult);
113 testResult = DateUtils.getFragmentInHours(aCalendar, Calendar.DAY_OF_YEAR);
114 assertEquals(expectedValue, testResult);
115 }
116
117 @Test
118 public void testHoursOfDayWithDate() {
119 long testResult = DateUtils.getFragmentInHours(aDate, Calendar.DATE);
120 final long expectedValue = hours;
121 assertEquals(expectedValue, testResult);
122 testResult = DateUtils.getFragmentInHours(aDate, Calendar.DAY_OF_YEAR);
123 assertEquals(expectedValue, testResult);
124 }
125
126 @Test
127 public void testHoursOfMonthWithCalendar() {
128 final long testResult = DateUtils.getFragmentInHours(aCalendar, Calendar.MONTH);
129 assertEquals( hours +(((days - 1) * DateUtils.MILLIS_PER_DAY))
130 / DateUtils.MILLIS_PER_HOUR,
131 testResult);
132 }
133
134 @Test
135 public void testHoursOfMonthWithDate() {
136 final long testResult = DateUtils.getFragmentInHours(aDate, Calendar.MONTH);
137 assertEquals(hours + (((days - 1) * DateUtils.MILLIS_PER_DAY))
138 / DateUtils.MILLIS_PER_HOUR,
139 testResult);
140 }
141
142 @Test
143 public void testHoursOfYearWithCalendar() {
144 final long testResult = DateUtils.getFragmentInHours(aCalendar, Calendar.YEAR);
145 assertEquals( hours +(((aCalendar.get(Calendar.DAY_OF_YEAR) - 1) * DateUtils.MILLIS_PER_DAY))
146 / DateUtils.MILLIS_PER_HOUR,
147 testResult);
148 }
149
150 @Test
151 public void testHoursOfYearWithDate() {
152 final long testResult = DateUtils.getFragmentInHours(aDate, Calendar.YEAR);
153 final Calendar cal = Calendar.getInstance();
154 cal.setTime(aDate);
155 assertEquals(hours + (((cal.get(Calendar.DAY_OF_YEAR) - 1) * DateUtils.MILLIS_PER_DAY))
156 / DateUtils.MILLIS_PER_HOUR,
157 testResult);
158 }
159
160 //Calendar.SECOND as useful fragment
161
162 @Test
163 public void testInvalidFragmentWithCalendar() {
164 assertThrows(IllegalArgumentException.class, () -> DateUtils.getFragmentInMilliseconds(aCalendar, 0));
165 assertThrows(IllegalArgumentException.class, () -> DateUtils.getFragmentInSeconds(aCalendar, 0));
166 assertThrows(IllegalArgumentException.class, () -> DateUtils.getFragmentInMinutes(aCalendar, 0));
167 assertThrows(IllegalArgumentException.class, () -> DateUtils.getFragmentInHours(aCalendar, 0));
168 assertThrows(IllegalArgumentException.class, () -> DateUtils.getFragmentInDays(aCalendar, 0));
92169 }
93170
94171 @Test
100177 assertThrows(IllegalArgumentException.class, () -> DateUtils.getFragmentInDays(aDate, 0));
101178 }
102179
103 @Test
104 public void testInvalidFragmentWithCalendar() {
105 assertThrows(IllegalArgumentException.class, () -> DateUtils.getFragmentInMilliseconds(aCalendar, 0));
106 assertThrows(IllegalArgumentException.class, () -> DateUtils.getFragmentInSeconds(aCalendar, 0));
107 assertThrows(IllegalArgumentException.class, () -> DateUtils.getFragmentInMinutes(aCalendar, 0));
108 assertThrows(IllegalArgumentException.class, () -> DateUtils.getFragmentInHours(aCalendar, 0));
109 assertThrows(IllegalArgumentException.class, () -> DateUtils.getFragmentInDays(aCalendar, 0));
180 //Calendar.MINUTE as useful fragment
181
182 @Test
183 public void testMillisecondFragmentInLargerUnitWithCalendar() {
184 assertEquals(0, DateUtils.getFragmentInMilliseconds(aCalendar, Calendar.MILLISECOND));
185 assertEquals(0, DateUtils.getFragmentInSeconds(aCalendar, Calendar.MILLISECOND));
186 assertEquals(0, DateUtils.getFragmentInMinutes(aCalendar, Calendar.MILLISECOND));
187 assertEquals(0, DateUtils.getFragmentInHours(aCalendar, Calendar.MILLISECOND));
188 assertEquals(0, DateUtils.getFragmentInDays(aCalendar, Calendar.MILLISECOND));
110189 }
111190
112191 @Test
119198 }
120199
121200 @Test
122 public void testMillisecondFragmentInLargerUnitWithCalendar() {
123 assertEquals(0, DateUtils.getFragmentInMilliseconds(aCalendar, Calendar.MILLISECOND));
124 assertEquals(0, DateUtils.getFragmentInSeconds(aCalendar, Calendar.MILLISECOND));
125 assertEquals(0, DateUtils.getFragmentInMinutes(aCalendar, Calendar.MILLISECOND));
126 assertEquals(0, DateUtils.getFragmentInHours(aCalendar, Calendar.MILLISECOND));
127 assertEquals(0, DateUtils.getFragmentInDays(aCalendar, Calendar.MILLISECOND));
128 }
129
130 @Test
131 public void testSecondFragmentInLargerUnitWithDate() {
132 assertEquals(0, DateUtils.getFragmentInSeconds(aDate, Calendar.SECOND));
133 assertEquals(0, DateUtils.getFragmentInMinutes(aDate, Calendar.SECOND));
134 assertEquals(0, DateUtils.getFragmentInHours(aDate, Calendar.SECOND));
135 assertEquals(0, DateUtils.getFragmentInDays(aDate, Calendar.SECOND));
136 }
137
138 @Test
139 public void testSecondFragmentInLargerUnitWithCalendar() {
140 assertEquals(0, DateUtils.getFragmentInSeconds(aCalendar, Calendar.SECOND));
141 assertEquals(0, DateUtils.getFragmentInMinutes(aCalendar, Calendar.SECOND));
142 assertEquals(0, DateUtils.getFragmentInHours(aCalendar, Calendar.SECOND));
143 assertEquals(0, DateUtils.getFragmentInDays(aCalendar, Calendar.SECOND));
144 }
145
146 @Test
147 public void testMinuteFragmentInLargerUnitWithDate() {
148 assertEquals(0, DateUtils.getFragmentInMinutes(aDate, Calendar.MINUTE));
149 assertEquals(0, DateUtils.getFragmentInHours(aDate, Calendar.MINUTE));
150 assertEquals(0, DateUtils.getFragmentInDays(aDate, Calendar.MINUTE));
151 }
152
153 @Test
154 public void testMinuteFragmentInLargerUnitWithCalendar() {
155 assertEquals(0, DateUtils.getFragmentInMinutes(aCalendar, Calendar.MINUTE));
156 assertEquals(0, DateUtils.getFragmentInHours(aCalendar, Calendar.MINUTE));
157 assertEquals(0, DateUtils.getFragmentInDays(aCalendar, Calendar.MINUTE));
158 }
159
160 @Test
161 public void testHourOfDayFragmentInLargerUnitWithDate() {
162 assertEquals(0, DateUtils.getFragmentInHours(aDate, Calendar.HOUR_OF_DAY));
163 assertEquals(0, DateUtils.getFragmentInDays(aDate, Calendar.HOUR_OF_DAY));
164 }
165
166 @Test
167 public void testHourOfDayFragmentInLargerUnitWithCalendar() {
168 assertEquals(0, DateUtils.getFragmentInHours(aCalendar, Calendar.HOUR_OF_DAY));
169 assertEquals(0, DateUtils.getFragmentInDays(aCalendar, Calendar.HOUR_OF_DAY));
170 }
171
172 @Test
173 public void testDayOfYearFragmentInLargerUnitWithDate() {
174 assertEquals(0, DateUtils.getFragmentInDays(aDate, Calendar.DAY_OF_YEAR));
175 }
176
177 @Test
178 public void testDayOfYearFragmentInLargerUnitWithCalendar() {
179 assertEquals(0, DateUtils.getFragmentInDays(aCalendar, Calendar.DAY_OF_YEAR));
180 }
181
182 @Test
183 public void testDateFragmentInLargerUnitWithDate() {
184 assertEquals(0, DateUtils.getFragmentInDays(aDate, Calendar.DATE));
185 }
186
187 @Test
188 public void testDateFragmentInLargerUnitWithCalendar() {
189 assertEquals(0, DateUtils.getFragmentInDays(aCalendar, Calendar.DATE));
190 }
191
192 //Calendar.SECOND as useful fragment
193
194 @Test
195 public void testMillisecondsOfSecondWithDate() {
196 final long testResult = DateUtils.getFragmentInMilliseconds(aDate, Calendar.SECOND);
197 assertEquals(millis, testResult);
198 }
199
200 @Test
201 public void testMillisecondsOfSecondWithCalendar() {
202 final long testResult = DateUtils.getFragmentInMilliseconds(aCalendar, Calendar.SECOND);
203 assertEquals(millis, testResult);
204 assertEquals(aCalendar.get(Calendar.MILLISECOND), testResult);
205 }
206
207 //Calendar.MINUTE as useful fragment
201 public void testMillisecondsOfDayWithCalendar() {
202 long testresult = DateUtils.getFragmentInMilliseconds(aCalendar, Calendar.DATE);
203 final long expectedValue = millis + (seconds * DateUtils.MILLIS_PER_SECOND) + (minutes * DateUtils.MILLIS_PER_MINUTE) + (hours * DateUtils.MILLIS_PER_HOUR);
204 assertEquals(expectedValue, testresult);
205 testresult = DateUtils.getFragmentInMilliseconds(aCalendar, Calendar.DAY_OF_YEAR);
206 assertEquals(expectedValue, testresult);
207 }
208
209 //Calendar.DATE and Calendar.DAY_OF_YEAR as useful fragment
210 @Test
211 public void testMillisecondsOfDayWithDate() {
212 long testresult = DateUtils.getFragmentInMilliseconds(aDate, Calendar.DATE);
213 final long expectedValue = millis + (seconds * DateUtils.MILLIS_PER_SECOND) + (minutes * DateUtils.MILLIS_PER_MINUTE) + (hours * DateUtils.MILLIS_PER_HOUR);
214 assertEquals(expectedValue, testresult);
215 testresult = DateUtils.getFragmentInMilliseconds(aDate, Calendar.DAY_OF_YEAR);
216 assertEquals(expectedValue, testresult);
217 }
218
219 //Calendar.HOUR_OF_DAY as useful fragment
220
221 @Test
222 public void testMillisecondsOfHourWithCalendar() {
223 final long testResult = DateUtils.getFragmentInMilliseconds(aCalendar, Calendar.HOUR_OF_DAY);
224 assertEquals(millis + (seconds * DateUtils.MILLIS_PER_SECOND) + (minutes * DateUtils.MILLIS_PER_MINUTE), testResult);
225 }
226
227 @Test
228 public void testMillisecondsOfHourWithDate() {
229 final long testResult = DateUtils.getFragmentInMilliseconds(aDate, Calendar.HOUR_OF_DAY);
230 assertEquals(millis + (seconds * DateUtils.MILLIS_PER_SECOND) + (minutes * DateUtils.MILLIS_PER_MINUTE), testResult);
231 }
232
233 @Test
234 public void testMillisecondsOfMinuteWithCalender() {
235 final long testResult = DateUtils.getFragmentInMilliseconds(aCalendar, Calendar.MINUTE);
236 assertEquals(millis + (seconds * DateUtils.MILLIS_PER_SECOND), testResult);
237 }
208238
209239 @Test
210240 public void testMillisecondsOfMinuteWithDate() {
211241 final long testResult = DateUtils.getFragmentInMilliseconds(aDate, Calendar.MINUTE);
212242 assertEquals(millis + (seconds * DateUtils.MILLIS_PER_SECOND), testResult);
213 }
214
215 @Test
216 public void testMillisecondsOfMinuteWithCalender() {
217 final long testResult = DateUtils.getFragmentInMilliseconds(aCalendar, Calendar.MINUTE);
218 assertEquals(millis + (seconds * DateUtils.MILLIS_PER_SECOND), testResult);
219 }
220
221 @Test
222 public void testSecondsofMinuteWithDate() {
223 final long testResult = DateUtils.getFragmentInSeconds(aDate, Calendar.MINUTE);
224 assertEquals(seconds, testResult);
225 }
226
227 @Test
228 public void testSecondsofMinuteWithCalendar() {
229 final long testResult = DateUtils.getFragmentInSeconds(aCalendar, Calendar.MINUTE);
230 assertEquals(seconds, testResult);
231 assertEquals(aCalendar.get(Calendar.SECOND), testResult);
232 }
233
234 //Calendar.HOUR_OF_DAY as useful fragment
235
236 @Test
237 public void testMillisecondsOfHourWithDate() {
238 final long testResult = DateUtils.getFragmentInMilliseconds(aDate, Calendar.HOUR_OF_DAY);
239 assertEquals(millis + (seconds * DateUtils.MILLIS_PER_SECOND) + (minutes * DateUtils.MILLIS_PER_MINUTE), testResult);
240 }
241
242 @Test
243 public void testMillisecondsOfHourWithCalendar() {
244 final long testResult = DateUtils.getFragmentInMilliseconds(aCalendar, Calendar.HOUR_OF_DAY);
245 assertEquals(millis + (seconds * DateUtils.MILLIS_PER_SECOND) + (minutes * DateUtils.MILLIS_PER_MINUTE), testResult);
246 }
247
248 @Test
249 public void testSecondsofHourWithDate() {
250 final long testResult = DateUtils.getFragmentInSeconds(aDate, Calendar.HOUR_OF_DAY);
251 assertEquals(
252 seconds
253 + (minutes
254 * DateUtils.MILLIS_PER_MINUTE / DateUtils.MILLIS_PER_SECOND),
255 testResult);
256 }
257
258 @Test
259 public void testSecondsofHourWithCalendar() {
260 final long testResult = DateUtils.getFragmentInSeconds(aCalendar, Calendar.HOUR_OF_DAY);
261 assertEquals(
262 seconds
263 + (minutes
264 * DateUtils.MILLIS_PER_MINUTE / DateUtils.MILLIS_PER_SECOND),
265 testResult);
266 }
267
268 @Test
269 public void testMinutesOfHourWithDate() {
270 final long testResult = DateUtils.getFragmentInMinutes(aDate, Calendar.HOUR_OF_DAY);
271 assertEquals(minutes, testResult);
272 }
273
274 @Test
275 public void testMinutesOfHourWithCalendar() {
276 final long testResult = DateUtils.getFragmentInMinutes(aCalendar, Calendar.HOUR_OF_DAY);
277 assertEquals(minutes, testResult);
278 }
279
280 //Calendar.DATE and Calendar.DAY_OF_YEAR as useful fragment
281 @Test
282 public void testMillisecondsOfDayWithDate() {
283 long testresult = DateUtils.getFragmentInMilliseconds(aDate, Calendar.DATE);
284 final long expectedValue = millis + (seconds * DateUtils.MILLIS_PER_SECOND) + (minutes * DateUtils.MILLIS_PER_MINUTE) + (hours * DateUtils.MILLIS_PER_HOUR);
285 assertEquals(expectedValue, testresult);
286 testresult = DateUtils.getFragmentInMilliseconds(aDate, Calendar.DAY_OF_YEAR);
287 assertEquals(expectedValue, testresult);
288 }
289
290 @Test
291 public void testMillisecondsOfDayWithCalendar() {
292 long testresult = DateUtils.getFragmentInMilliseconds(aCalendar, Calendar.DATE);
293 final long expectedValue = millis + (seconds * DateUtils.MILLIS_PER_SECOND) + (minutes * DateUtils.MILLIS_PER_MINUTE) + (hours * DateUtils.MILLIS_PER_HOUR);
294 assertEquals(expectedValue, testresult);
295 testresult = DateUtils.getFragmentInMilliseconds(aCalendar, Calendar.DAY_OF_YEAR);
296 assertEquals(expectedValue, testresult);
297 }
298
299 @Test
300 public void testSecondsOfDayWithDate() {
301 long testresult = DateUtils.getFragmentInSeconds(aDate, Calendar.DATE);
302 final long expectedValue = seconds + ((minutes * DateUtils.MILLIS_PER_MINUTE) + (hours * DateUtils.MILLIS_PER_HOUR))/ DateUtils.MILLIS_PER_SECOND;
303 assertEquals(expectedValue, testresult);
304 testresult = DateUtils.getFragmentInSeconds(aDate, Calendar.DAY_OF_YEAR);
305 assertEquals(expectedValue, testresult);
306 }
307
308 @Test
309 public void testSecondsOfDayWithCalendar() {
310 long testresult = DateUtils.getFragmentInSeconds(aCalendar, Calendar.DATE);
311 final long expectedValue = seconds + ((minutes * DateUtils.MILLIS_PER_MINUTE) + (hours * DateUtils.MILLIS_PER_HOUR))/ DateUtils.MILLIS_PER_SECOND;
312 assertEquals(expectedValue, testresult);
313 testresult = DateUtils.getFragmentInSeconds(aCalendar, Calendar.DAY_OF_YEAR);
314 assertEquals(expectedValue, testresult);
315 }
316
317 @Test
318 public void testMinutesOfDayWithDate() {
319 long testResult = DateUtils.getFragmentInMinutes(aDate, Calendar.DATE);
320 final long expectedValue = minutes + ((hours * DateUtils.MILLIS_PER_HOUR))/ DateUtils.MILLIS_PER_MINUTE;
321 assertEquals(expectedValue, testResult);
322 testResult = DateUtils.getFragmentInMinutes(aDate, Calendar.DAY_OF_YEAR);
323 assertEquals(expectedValue, testResult);
324 }
325
326 @Test
327 public void testMinutesOfDayWithCalendar() {
328 long testResult = DateUtils.getFragmentInMinutes(aCalendar, Calendar.DATE);
329 final long expectedValue = minutes + ((hours * DateUtils.MILLIS_PER_HOUR))/ DateUtils.MILLIS_PER_MINUTE;
330 assertEquals(expectedValue, testResult);
331 testResult = DateUtils.getFragmentInMinutes(aCalendar, Calendar.DAY_OF_YEAR);
332 assertEquals(expectedValue, testResult);
333 }
334
335 @Test
336 public void testHoursOfDayWithDate() {
337 long testResult = DateUtils.getFragmentInHours(aDate, Calendar.DATE);
338 final long expectedValue = hours;
339 assertEquals(expectedValue, testResult);
340 testResult = DateUtils.getFragmentInHours(aDate, Calendar.DAY_OF_YEAR);
341 assertEquals(expectedValue, testResult);
342 }
343
344 @Test
345 public void testHoursOfDayWithCalendar() {
346 long testResult = DateUtils.getFragmentInHours(aCalendar, Calendar.DATE);
347 final long expectedValue = hours;
348 assertEquals(expectedValue, testResult);
349 testResult = DateUtils.getFragmentInHours(aCalendar, Calendar.DAY_OF_YEAR);
350 assertEquals(expectedValue, testResult);
351 }
352
353
354 //Calendar.MONTH as useful fragment
355 @Test
356 public void testMillisecondsOfMonthWithDate() {
357 final long testResult = DateUtils.getFragmentInMilliseconds(aDate, Calendar.MONTH);
358 assertEquals(millis + (seconds * DateUtils.MILLIS_PER_SECOND) + (minutes * DateUtils.MILLIS_PER_MINUTE)
359 + (hours * DateUtils.MILLIS_PER_HOUR) + ((days - 1) * DateUtils.MILLIS_PER_DAY),
360 testResult);
361243 }
362244
363245 @Test
368250 testResult);
369251 }
370252
371 @Test
372 public void testSecondsOfMonthWithDate() {
373 final long testResult = DateUtils.getFragmentInSeconds(aDate, Calendar.MONTH);
374 assertEquals(
375 seconds
376 + ((minutes * DateUtils.MILLIS_PER_MINUTE)
377 + (hours * DateUtils.MILLIS_PER_HOUR) + ((days - 1) * DateUtils.MILLIS_PER_DAY))
378 / DateUtils.MILLIS_PER_SECOND,
379 testResult);
380 }
381
382 @Test
383 public void testSecondsOfMonthWithCalendar() {
384 final long testResult = DateUtils.getFragmentInSeconds(aCalendar, Calendar.MONTH);
385 assertEquals(
386 seconds
387 + ((minutes * DateUtils.MILLIS_PER_MINUTE)
388 + (hours * DateUtils.MILLIS_PER_HOUR) + ((days - 1) * DateUtils.MILLIS_PER_DAY))
389 / DateUtils.MILLIS_PER_SECOND,
390 testResult);
391 }
392
393 @Test
394 public void testMinutesOfMonthWithDate() {
395 final long testResult = DateUtils.getFragmentInMinutes(aDate, Calendar.MONTH);
396 assertEquals(minutes
397 + ((hours * DateUtils.MILLIS_PER_HOUR) + ((days - 1) * DateUtils.MILLIS_PER_DAY))
398 / DateUtils.MILLIS_PER_MINUTE,
399 testResult);
400 }
401
402 @Test
403 public void testMinutesOfMonthWithCalendar() {
404 final long testResult = DateUtils.getFragmentInMinutes(aCalendar, Calendar.MONTH);
405 assertEquals( minutes +((hours * DateUtils.MILLIS_PER_HOUR) + ((days - 1) * DateUtils.MILLIS_PER_DAY))
406 / DateUtils.MILLIS_PER_MINUTE,
407 testResult);
408 }
409
410 @Test
411 public void testHoursOfMonthWithDate() {
412 final long testResult = DateUtils.getFragmentInHours(aDate, Calendar.MONTH);
413 assertEquals(hours + (((days - 1) * DateUtils.MILLIS_PER_DAY))
414 / DateUtils.MILLIS_PER_HOUR,
415 testResult);
416 }
417
418 @Test
419 public void testHoursOfMonthWithCalendar() {
420 final long testResult = DateUtils.getFragmentInHours(aCalendar, Calendar.MONTH);
421 assertEquals( hours +(((days - 1) * DateUtils.MILLIS_PER_DAY))
422 / DateUtils.MILLIS_PER_HOUR,
423 testResult);
253 //Calendar.MONTH as useful fragment
254 @Test
255 public void testMillisecondsOfMonthWithDate() {
256 final long testResult = DateUtils.getFragmentInMilliseconds(aDate, Calendar.MONTH);
257 assertEquals(millis + (seconds * DateUtils.MILLIS_PER_SECOND) + (minutes * DateUtils.MILLIS_PER_MINUTE)
258 + (hours * DateUtils.MILLIS_PER_HOUR) + ((days - 1) * DateUtils.MILLIS_PER_DAY),
259 testResult);
260 }
261
262 @Test
263 public void testMillisecondsOfSecondWithCalendar() {
264 final long testResult = DateUtils.getFragmentInMilliseconds(aCalendar, Calendar.SECOND);
265 assertEquals(millis, testResult);
266 assertEquals(aCalendar.get(Calendar.MILLISECOND), testResult);
267 }
268
269 @Test
270 public void testMillisecondsOfSecondWithDate() {
271 final long testResult = DateUtils.getFragmentInMilliseconds(aDate, Calendar.SECOND);
272 assertEquals(millis, testResult);
273 }
274
275 @Test
276 public void testMillisecondsOfYearWithCalendar() {
277 final long testResult = DateUtils.getFragmentInMilliseconds(aCalendar, Calendar.YEAR);
278 assertEquals(millis + (seconds * DateUtils.MILLIS_PER_SECOND) + (minutes * DateUtils.MILLIS_PER_MINUTE)
279 + (hours * DateUtils.MILLIS_PER_HOUR) + ((aCalendar.get(Calendar.DAY_OF_YEAR) - 1) * DateUtils.MILLIS_PER_DAY),
280 testResult);
424281 }
425282
426283 //Calendar.YEAR as useful fragment
435292 }
436293
437294 @Test
438 public void testMillisecondsOfYearWithCalendar() {
439 final long testResult = DateUtils.getFragmentInMilliseconds(aCalendar, Calendar.YEAR);
440 assertEquals(millis + (seconds * DateUtils.MILLIS_PER_SECOND) + (minutes * DateUtils.MILLIS_PER_MINUTE)
441 + (hours * DateUtils.MILLIS_PER_HOUR) + ((aCalendar.get(Calendar.DAY_OF_YEAR) - 1) * DateUtils.MILLIS_PER_DAY),
442 testResult);
443 }
444
445 @Test
446 public void testSecondsOfYearWithDate() {
447 final long testResult = DateUtils.getFragmentInSeconds(aDate, Calendar.YEAR);
448 final Calendar cal = Calendar.getInstance();
449 cal.setTime(aDate);
450 assertEquals(
451 seconds
452 + ((minutes * DateUtils.MILLIS_PER_MINUTE)
453 + (hours * DateUtils.MILLIS_PER_HOUR) + ((cal.get(Calendar.DAY_OF_YEAR) - 1) * DateUtils.MILLIS_PER_DAY))
454 / DateUtils.MILLIS_PER_SECOND,
455 testResult);
456 }
457
458 @Test
459 public void testSecondsOfYearWithCalendar() {
460 final long testResult = DateUtils.getFragmentInSeconds(aCalendar, Calendar.YEAR);
461 assertEquals(
462 seconds
463 + ((minutes * DateUtils.MILLIS_PER_MINUTE)
464 + (hours * DateUtils.MILLIS_PER_HOUR) + ((aCalendar.get(Calendar.DAY_OF_YEAR) - 1) * DateUtils.MILLIS_PER_DAY))
465 / DateUtils.MILLIS_PER_SECOND,
295 public void testMinuteFragmentInLargerUnitWithCalendar() {
296 assertEquals(0, DateUtils.getFragmentInMinutes(aCalendar, Calendar.MINUTE));
297 assertEquals(0, DateUtils.getFragmentInHours(aCalendar, Calendar.MINUTE));
298 assertEquals(0, DateUtils.getFragmentInDays(aCalendar, Calendar.MINUTE));
299 }
300
301 @Test
302 public void testMinuteFragmentInLargerUnitWithDate() {
303 assertEquals(0, DateUtils.getFragmentInMinutes(aDate, Calendar.MINUTE));
304 assertEquals(0, DateUtils.getFragmentInHours(aDate, Calendar.MINUTE));
305 assertEquals(0, DateUtils.getFragmentInDays(aDate, Calendar.MINUTE));
306 }
307
308 @Test
309 public void testMinutesOfDayWithCalendar() {
310 long testResult = DateUtils.getFragmentInMinutes(aCalendar, Calendar.DATE);
311 final long expectedValue = minutes + ((hours * DateUtils.MILLIS_PER_HOUR))/ DateUtils.MILLIS_PER_MINUTE;
312 assertEquals(expectedValue, testResult);
313 testResult = DateUtils.getFragmentInMinutes(aCalendar, Calendar.DAY_OF_YEAR);
314 assertEquals(expectedValue, testResult);
315 }
316
317 @Test
318 public void testMinutesOfDayWithDate() {
319 long testResult = DateUtils.getFragmentInMinutes(aDate, Calendar.DATE);
320 final long expectedValue = minutes + ((hours * DateUtils.MILLIS_PER_HOUR))/ DateUtils.MILLIS_PER_MINUTE;
321 assertEquals(expectedValue, testResult);
322 testResult = DateUtils.getFragmentInMinutes(aDate, Calendar.DAY_OF_YEAR);
323 assertEquals(expectedValue, testResult);
324 }
325
326
327 @Test
328 public void testMinutesOfHourWithCalendar() {
329 final long testResult = DateUtils.getFragmentInMinutes(aCalendar, Calendar.HOUR_OF_DAY);
330 assertEquals(minutes, testResult);
331 }
332
333 @Test
334 public void testMinutesOfHourWithDate() {
335 final long testResult = DateUtils.getFragmentInMinutes(aDate, Calendar.HOUR_OF_DAY);
336 assertEquals(minutes, testResult);
337 }
338
339 @Test
340 public void testMinutesOfMonthWithCalendar() {
341 final long testResult = DateUtils.getFragmentInMinutes(aCalendar, Calendar.MONTH);
342 assertEquals( minutes +((hours * DateUtils.MILLIS_PER_HOUR) + ((days - 1) * DateUtils.MILLIS_PER_DAY))
343 / DateUtils.MILLIS_PER_MINUTE,
344 testResult);
345 }
346
347 @Test
348 public void testMinutesOfMonthWithDate() {
349 final long testResult = DateUtils.getFragmentInMinutes(aDate, Calendar.MONTH);
350 assertEquals(minutes
351 + ((hours * DateUtils.MILLIS_PER_HOUR) + ((days - 1) * DateUtils.MILLIS_PER_DAY))
352 / DateUtils.MILLIS_PER_MINUTE,
353 testResult);
354 }
355
356 @Test
357 public void testMinutesOfYearWithCalendar() {
358 final long testResult = DateUtils.getFragmentInMinutes(aCalendar, Calendar.YEAR);
359 assertEquals( minutes +((hours * DateUtils.MILLIS_PER_HOUR) + ((aCalendar.get(Calendar.DAY_OF_YEAR) - 1) * DateUtils.MILLIS_PER_DAY))
360 / DateUtils.MILLIS_PER_MINUTE,
466361 testResult);
467362 }
468363
473368 cal.setTime(aDate);
474369 assertEquals(minutes
475370 + ((hours * DateUtils.MILLIS_PER_HOUR) + ((cal.get(Calendar.DAY_OF_YEAR) - 1) * DateUtils.MILLIS_PER_DAY))
476 / DateUtils.MILLIS_PER_MINUTE,
477 testResult);
478 }
479
480 @Test
481 public void testMinutesOfYearWithCalendar() {
482 final long testResult = DateUtils.getFragmentInMinutes(aCalendar, Calendar.YEAR);
483 assertEquals( minutes +((hours * DateUtils.MILLIS_PER_HOUR) + ((aCalendar.get(Calendar.DAY_OF_YEAR) - 1) * DateUtils.MILLIS_PER_DAY))
484371 / DateUtils.MILLIS_PER_MINUTE,
485372 testResult);
486373 }
499386 }
500387
501388 @Test
502 public void testHoursOfYearWithDate() {
503 final long testResult = DateUtils.getFragmentInHours(aDate, Calendar.YEAR);
389 public void testNullCalendar() {
390 assertThrows(
391 IllegalArgumentException.class,
392 () -> DateUtils.getFragmentInMilliseconds((Calendar) null, Calendar.MILLISECOND));
393
394 assertThrows(
395 IllegalArgumentException.class,
396 () -> DateUtils.getFragmentInSeconds((Calendar) null, Calendar.MILLISECOND));
397
398 assertThrows(
399 IllegalArgumentException.class,
400 () -> DateUtils.getFragmentInMinutes((Calendar) null, Calendar.MILLISECOND));
401
402 assertThrows(
403 IllegalArgumentException.class,
404 () -> DateUtils.getFragmentInHours((Calendar) null, Calendar.MILLISECOND));
405
406 assertThrows(
407 IllegalArgumentException.class,
408 () -> DateUtils.getFragmentInDays((Calendar) null, Calendar.MILLISECOND));
409 }
410
411 @Test
412 public void testNullDate() {
413 assertThrows(
414 NullPointerException.class,
415 () -> DateUtils.getFragmentInMilliseconds((Date) null, Calendar.MILLISECOND));
416
417 assertThrows(
418 NullPointerException.class,
419 () -> DateUtils.getFragmentInSeconds((Date) null, Calendar.MILLISECOND));
420
421 assertThrows(
422 NullPointerException.class,
423 () -> DateUtils.getFragmentInMinutes((Date) null, Calendar.MILLISECOND));
424
425 assertThrows(
426 NullPointerException.class,
427 () -> DateUtils.getFragmentInHours((Date) null, Calendar.MILLISECOND));
428
429 assertThrows(
430 NullPointerException.class,
431 () -> DateUtils.getFragmentInDays((Date) null, Calendar.MILLISECOND));
432 }
433
434 @Test
435 public void testSecondFragmentInLargerUnitWithCalendar() {
436 assertEquals(0, DateUtils.getFragmentInSeconds(aCalendar, Calendar.SECOND));
437 assertEquals(0, DateUtils.getFragmentInMinutes(aCalendar, Calendar.SECOND));
438 assertEquals(0, DateUtils.getFragmentInHours(aCalendar, Calendar.SECOND));
439 assertEquals(0, DateUtils.getFragmentInDays(aCalendar, Calendar.SECOND));
440 }
441
442 @Test
443 public void testSecondFragmentInLargerUnitWithDate() {
444 assertEquals(0, DateUtils.getFragmentInSeconds(aDate, Calendar.SECOND));
445 assertEquals(0, DateUtils.getFragmentInMinutes(aDate, Calendar.SECOND));
446 assertEquals(0, DateUtils.getFragmentInHours(aDate, Calendar.SECOND));
447 assertEquals(0, DateUtils.getFragmentInDays(aDate, Calendar.SECOND));
448 }
449
450 @Test
451 public void testSecondsOfDayWithCalendar() {
452 long testresult = DateUtils.getFragmentInSeconds(aCalendar, Calendar.DATE);
453 final long expectedValue = seconds + ((minutes * DateUtils.MILLIS_PER_MINUTE) + (hours * DateUtils.MILLIS_PER_HOUR))/ DateUtils.MILLIS_PER_SECOND;
454 assertEquals(expectedValue, testresult);
455 testresult = DateUtils.getFragmentInSeconds(aCalendar, Calendar.DAY_OF_YEAR);
456 assertEquals(expectedValue, testresult);
457 }
458
459 @Test
460 public void testSecondsOfDayWithDate() {
461 long testresult = DateUtils.getFragmentInSeconds(aDate, Calendar.DATE);
462 final long expectedValue = seconds + ((minutes * DateUtils.MILLIS_PER_MINUTE) + (hours * DateUtils.MILLIS_PER_HOUR))/ DateUtils.MILLIS_PER_SECOND;
463 assertEquals(expectedValue, testresult);
464 testresult = DateUtils.getFragmentInSeconds(aDate, Calendar.DAY_OF_YEAR);
465 assertEquals(expectedValue, testresult);
466 }
467
468 @Test
469 public void testSecondsofHourWithCalendar() {
470 final long testResult = DateUtils.getFragmentInSeconds(aCalendar, Calendar.HOUR_OF_DAY);
471 assertEquals(
472 seconds
473 + (minutes
474 * DateUtils.MILLIS_PER_MINUTE / DateUtils.MILLIS_PER_SECOND),
475 testResult);
476 }
477
478 @Test
479 public void testSecondsofHourWithDate() {
480 final long testResult = DateUtils.getFragmentInSeconds(aDate, Calendar.HOUR_OF_DAY);
481 assertEquals(
482 seconds
483 + (minutes
484 * DateUtils.MILLIS_PER_MINUTE / DateUtils.MILLIS_PER_SECOND),
485 testResult);
486 }
487
488 @Test
489 public void testSecondsofMinuteWithCalendar() {
490 final long testResult = DateUtils.getFragmentInSeconds(aCalendar, Calendar.MINUTE);
491 assertEquals(seconds, testResult);
492 assertEquals(aCalendar.get(Calendar.SECOND), testResult);
493 }
494
495 @Test
496 public void testSecondsofMinuteWithDate() {
497 final long testResult = DateUtils.getFragmentInSeconds(aDate, Calendar.MINUTE);
498 assertEquals(seconds, testResult);
499 }
500
501 @Test
502 public void testSecondsOfMonthWithCalendar() {
503 final long testResult = DateUtils.getFragmentInSeconds(aCalendar, Calendar.MONTH);
504 assertEquals(
505 seconds
506 + ((minutes * DateUtils.MILLIS_PER_MINUTE)
507 + (hours * DateUtils.MILLIS_PER_HOUR) + ((days - 1) * DateUtils.MILLIS_PER_DAY))
508 / DateUtils.MILLIS_PER_SECOND,
509 testResult);
510 }
511
512 @Test
513 public void testSecondsOfMonthWithDate() {
514 final long testResult = DateUtils.getFragmentInSeconds(aDate, Calendar.MONTH);
515 assertEquals(
516 seconds
517 + ((minutes * DateUtils.MILLIS_PER_MINUTE)
518 + (hours * DateUtils.MILLIS_PER_HOUR) + ((days - 1) * DateUtils.MILLIS_PER_DAY))
519 / DateUtils.MILLIS_PER_SECOND,
520 testResult);
521 }
522
523 @Test
524 public void testSecondsOfYearWithCalendar() {
525 final long testResult = DateUtils.getFragmentInSeconds(aCalendar, Calendar.YEAR);
526 assertEquals(
527 seconds
528 + ((minutes * DateUtils.MILLIS_PER_MINUTE)
529 + (hours * DateUtils.MILLIS_PER_HOUR) + ((aCalendar.get(Calendar.DAY_OF_YEAR) - 1) * DateUtils.MILLIS_PER_DAY))
530 / DateUtils.MILLIS_PER_SECOND,
531 testResult);
532 }
533
534 @Test
535 public void testSecondsOfYearWithDate() {
536 final long testResult = DateUtils.getFragmentInSeconds(aDate, Calendar.YEAR);
504537 final Calendar cal = Calendar.getInstance();
505538 cal.setTime(aDate);
506 assertEquals(hours + (((cal.get(Calendar.DAY_OF_YEAR) - 1) * DateUtils.MILLIS_PER_DAY))
507 / DateUtils.MILLIS_PER_HOUR,
508 testResult);
509 }
510
511 @Test
512 public void testHoursOfYearWithCalendar() {
513 final long testResult = DateUtils.getFragmentInHours(aCalendar, Calendar.YEAR);
514 assertEquals( hours +(((aCalendar.get(Calendar.DAY_OF_YEAR) - 1) * DateUtils.MILLIS_PER_DAY))
515 / DateUtils.MILLIS_PER_HOUR,
516 testResult);
517 }
518
519 @Test
520 public void testDaysOfMonthWithCalendar() {
521 final long testResult = DateUtils.getFragmentInDays(aCalendar, Calendar.MONTH);
522 assertEquals(days, testResult);
523 }
524
525 @Test
526 public void testDaysOfMonthWithDate() {
527 final long testResult = DateUtils.getFragmentInDays(aDate, Calendar.MONTH);
528 final Calendar cal = Calendar.getInstance();
529 cal.setTime(aDate);
530 assertEquals(cal.get(Calendar.DAY_OF_MONTH), testResult);
531 }
532
533 @Test
534 public void testDaysOfYearWithCalendar() {
535 final long testResult = DateUtils.getFragmentInDays(aCalendar, Calendar.YEAR);
536 assertEquals(aCalendar.get(Calendar.DAY_OF_YEAR), testResult);
537 }
538
539 @Test
540 public void testDaysOfYearWithDate() {
541 final long testResult = DateUtils.getFragmentInDays(aDate, Calendar.YEAR);
542 final Calendar cal = Calendar.getInstance();
543 cal.setTime(aDate);
544 assertEquals(cal.get(Calendar.DAY_OF_YEAR), testResult);
539 assertEquals(
540 seconds
541 + ((minutes * DateUtils.MILLIS_PER_MINUTE)
542 + (hours * DateUtils.MILLIS_PER_HOUR) + ((cal.get(Calendar.DAY_OF_YEAR) - 1) * DateUtils.MILLIS_PER_DAY))
543 / DateUtils.MILLIS_PER_SECOND,
544 testResult);
545545 }
546546 }
5757 FastDateFormat fdf = DateFormatUtils.ISO_DATETIME_FORMAT;
5858
5959
60 @BeforeEach
61 public void setUp() throws Exception {
62
63 dateTimeParser = new SimpleDateFormat("MMM dd, yyyy H:mm:ss.SSS", Locale.ENGLISH);
64
65 targetYearDate = dateTimeParser.parse("January 1, 2007 0:00:00.000");
66 targetDateDate = targetDayOfMonthDate = dateTimeParser.parse("June 1, 2008 0:00:00.000");
67 targetAmDate = dateTimeParser.parse("June 1, 2008 0:00:00.000");
68 targetPmDate = dateTimeParser.parse("June 1, 2008 12:00:00.000");
69 targetHourDate = dateTimeParser.parse("June 1, 2008 8:00:00.000");
70 targetHourOfDayDate = dateTimeParser.parse("June 1, 2008 8:00:00.000");
71 targetMinuteDate = dateTimeParser.parse("June 1, 2008 8:15:00.000");
72 targetSecondDate = dateTimeParser.parse("June 1, 2008 8:15:14.000");
73 targetMilliSecondDate = dateTimeParser.parse("June 1, 2008 8:15:14.231");
74
75 januaryOneDate = dateTimeParser.parse("January 1, 2008 0:00:00.000");
76 januaryOneCalendar = Calendar.getInstance();
77 januaryOneCalendar.setTime(januaryOneDate);
78 }
79
80 /**
81 * Tests DateUtils.round()-method with Calendar.Year
82 *
83 * @throws Exception so we don't have to catch it
84 * @since 3.0
85 */
86 @Test
87 public void testRoundYear() throws Exception {
88 final int calendarField = Calendar.YEAR;
89 final Date roundedUpDate = dateTimeParser.parse("January 1, 2008 0:00:00.000");
90 final Date roundedDownDate = targetYearDate;
91 final Date lastRoundedDownDate = dateTimeParser.parse("June 30, 2007 23:59:59.999");
92 baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField);
93 }
94
95 /**
96 * Tests DateUtils.round()-method with Calendar.MONTH
97 * Includes rounding months with 28, 29, 30 and 31 days
98 * Includes rounding to January 1
99 *
100 * @throws Exception so we don't have to catch it
101 * @since 3.0
102 */
103 @Test
104 public void testRoundMonth() throws Exception {
105 final int calendarField = Calendar.MONTH;
106 Date roundedUpDate, roundedDownDate, lastRoundedDownDate;
107 Date minDate, maxDate;
108
109 //month with 28 days
110 roundedUpDate = dateTimeParser.parse("March 1, 2007 0:00:00.000");
111 roundedDownDate = dateTimeParser.parse("February 1, 2007 0:00:00.000");
112 lastRoundedDownDate = dateTimeParser.parse("February 14, 2007 23:59:59.999");
113 baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField);
114
115 //month with 29 days
116 roundedUpDate = dateTimeParser.parse("March 1, 2008 0:00:00.000");
117 roundedDownDate = dateTimeParser.parse("February 1, 2008 0:00:00.000");
118 lastRoundedDownDate = dateTimeParser.parse("February 15, 2008 23:59:59.999");
119 baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField);
120
121 //month with 30 days
122 roundedUpDate = dateTimeParser.parse("May 1, 2008 0:00:00.000");
123 roundedDownDate = dateTimeParser.parse("April 1, 2008 0:00:00.000");
124 lastRoundedDownDate = dateTimeParser.parse("April 15, 2008 23:59:59.999");
125 baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField);
126
127 //month with 31 days
128 roundedUpDate = dateTimeParser.parse("June 1, 2008 0:00:00.000");
129 roundedDownDate = dateTimeParser.parse("May 1, 2008 0:00:00.000");
130 lastRoundedDownDate = dateTimeParser.parse("May 16, 2008 23:59:59.999");
131 baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField);
132
133 //round to January 1
134 minDate = dateTimeParser.parse("December 17, 2007 00:00:00.000");
135 maxDate = dateTimeParser.parse("January 16, 2008 23:59:59.999");
136 roundToJanuaryFirst(minDate, maxDate, calendarField);
137 }
138
139 /**
140 * Tests DateUtils.round()-method with DateUtils.SEMI_MONTH
141 * Includes rounding months with 28, 29, 30 and 31 days, each with first and second half
142 * Includes rounding to January 1
143 *
144 * @throws Exception so we don't have to catch it
145 * @since 3.0
146 */
147 @Test
148 public void testRoundSemiMonth() throws Exception {
149 final int calendarField = DateUtils.SEMI_MONTH;
150 Date roundedUpDate, roundedDownDate, lastRoundedDownDate;
151 Date minDate, maxDate;
152
153 //month with 28 days (1)
154 roundedUpDate = dateTimeParser.parse("February 16, 2007 0:00:00.000");
155 roundedDownDate = dateTimeParser.parse("February 1, 2007 0:00:00.000");
156 lastRoundedDownDate = dateTimeParser.parse("February 8, 2007 23:59:59.999");
157 baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField);
158
159 //month with 28 days (2)
160 roundedUpDate = dateTimeParser.parse("March 1, 2007 0:00:00.000");
161 roundedDownDate = dateTimeParser.parse("February 16, 2007 0:00:00.000");
162 lastRoundedDownDate = dateTimeParser.parse("February 23, 2007 23:59:59.999");
163 baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField);
164
165 //month with 29 days (1)
166 roundedUpDate = dateTimeParser.parse("February 16, 2008 0:00:00.000");
167 roundedDownDate = dateTimeParser.parse("February 1, 2008 0:00:00.000");
168 lastRoundedDownDate = dateTimeParser.parse("February 8, 2008 23:59:59.999");
169 baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField);
170
171 //month with 29 days (2)
172 roundedUpDate = dateTimeParser.parse("March 1, 2008 0:00:00.000");
173 roundedDownDate = dateTimeParser.parse("February 16, 2008 0:00:00.000");
174 lastRoundedDownDate = dateTimeParser.parse("February 23, 2008 23:59:59.999");
175 baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField);
176
177 //month with 30 days (1)
178 roundedUpDate = dateTimeParser.parse("April 16, 2008 0:00:00.000");
179 roundedDownDate = dateTimeParser.parse("April 1, 2008 0:00:00.000");
180 lastRoundedDownDate = dateTimeParser.parse("April 8, 2008 23:59:59.999");
181 baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField);
182
183 //month with 30 days (2)
184 roundedUpDate = dateTimeParser.parse("May 1, 2008 0:00:00.000");
185 roundedDownDate = dateTimeParser.parse("April 16, 2008 0:00:00.000");
186 lastRoundedDownDate = dateTimeParser.parse("April 23, 2008 23:59:59.999");
187 baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField);
188
189 //month with 31 days (1)
190 roundedUpDate = dateTimeParser.parse("May 16, 2008 0:00:00.000");
191 roundedDownDate = dateTimeParser.parse("May 1, 2008 0:00:00.000");
192 lastRoundedDownDate = dateTimeParser.parse("May 8, 2008 23:59:59.999");
193 baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField);
194
195 //month with 31 days (2)
196 roundedUpDate = dateTimeParser.parse("June 1, 2008 0:00:00.000");
197 roundedDownDate = dateTimeParser.parse("May 16, 2008 0:00:00.000");
198 lastRoundedDownDate = dateTimeParser.parse("May 23, 2008 23:59:59.999");
199 baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField);
200
201 //round to January 1
202 minDate = dateTimeParser.parse("December 24, 2007 00:00:00.000");
203 maxDate = dateTimeParser.parse("January 8, 2008 23:59:59.999");
204 roundToJanuaryFirst(minDate, maxDate, calendarField);
205 }
206
207 /**
208 * Tests DateUtils.round()-method with Calendar.DATE
209 * Includes rounding the extremes of one day
210 * Includes rounding to January 1
211 *
212 * @throws Exception so we don't have to catch it
213 * @since 3.0
214 */
215 @Test
216 public void testRoundDate() throws Exception {
217 final int calendarField = Calendar.DATE;
218 Date roundedUpDate, roundedDownDate, lastRoundedDownDate;
219 Date minDate, maxDate;
220
221 roundedUpDate = dateTimeParser.parse("June 2, 2008 0:00:00.000");
222 roundedDownDate = targetDateDate;
223 lastRoundedDownDate = dateTimeParser.parse("June 1, 2008 11:59:59.999");
224 baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField);
225
226 //round to January 1
227 minDate = dateTimeParser.parse("December 31, 2007 12:00:00.000");
228 maxDate = dateTimeParser.parse("January 1, 2008 11:59:59.999");
229 roundToJanuaryFirst(minDate, maxDate, calendarField);
230 }
231
232 /**
233 * Tests DateUtils.round()-method with Calendar.DAY_OF_MONTH
234 * Includes rounding the extremes of one day
235 * Includes rounding to January 1
236 *
237 * @throws Exception so we don't have to catch it
238 * @since 3.0
239 */
240 @Test
241 public void testRoundDayOfMonth() throws Exception {
242 final int calendarField = Calendar.DAY_OF_MONTH;
243 Date roundedUpDate, roundedDownDate, lastRoundedDownDate;
244 Date minDate, maxDate;
245
246 roundedUpDate = dateTimeParser.parse("June 2, 2008 0:00:00.000");
247 roundedDownDate = targetDayOfMonthDate;
248 lastRoundedDownDate = dateTimeParser.parse("June 1, 2008 11:59:59.999");
249 baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField);
250
251 //round to January 1
252 minDate = dateTimeParser.parse("December 31, 2007 12:00:00.000");
253 maxDate = dateTimeParser.parse("January 1, 2008 11:59:59.999");
254 roundToJanuaryFirst(minDate, maxDate, calendarField);
255 }
256
257 /**
258 * Tests DateUtils.round()-method with Calendar.AM_PM
259 * Includes rounding the extremes of both AM and PM of one day
260 * Includes rounding to January 1
261 *
262 * @throws Exception so we don't have to catch it
263 * @since 3.0
264 */
265 @Test
266 public void testRoundAmPm() throws Exception {
267 final int calendarField = Calendar.AM_PM;
268 Date roundedUpDate, roundedDownDate, lastRoundedDownDate;
269 Date minDate, maxDate;
270
271 //AM
272 roundedUpDate = dateTimeParser.parse("June 1, 2008 12:00:00.000");
273 roundedDownDate = targetAmDate;
274 lastRoundedDownDate = dateTimeParser.parse("June 1, 2008 5:59:59.999");
275 baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField);
276
277 //PM
278 roundedUpDate = dateTimeParser.parse("June 2, 2008 0:00:00.000");
279 roundedDownDate = targetPmDate;
280 lastRoundedDownDate = dateTimeParser.parse("June 1, 2008 17:59:59.999");
281 baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField);
282
283 //round to January 1
284 minDate = dateTimeParser.parse("December 31, 2007 18:00:00.000");
285 maxDate = dateTimeParser.parse("January 1, 2008 5:59:59.999");
286 roundToJanuaryFirst(minDate, maxDate, calendarField);
287 }
288
289 /**
290 * Tests DateUtils.round()-method with Calendar.HOUR_OF_DAY
291 * Includes rounding the extremes of one hour
292 * Includes rounding to January 1
293 *
294 * @throws Exception so we don't have to catch it
295 * @since 3.0
296 */
297 @Test
298 public void testRoundHourOfDay() throws Exception {
299 final int calendarField = Calendar.HOUR_OF_DAY;
300 Date roundedUpDate, roundedDownDate, lastRoundedDownDate;
301 Date minDate, maxDate;
302
303 roundedUpDate = dateTimeParser.parse("June 1, 2008 9:00:00.000");
304 roundedDownDate = targetHourOfDayDate;
305 lastRoundedDownDate = dateTimeParser.parse("June 1, 2008 8:29:59.999");
306 baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField);
307
308 //round to January 1
309 minDate = dateTimeParser.parse("December 31, 2007 23:30:00.000");
310 maxDate = dateTimeParser.parse("January 1, 2008 0:29:59.999");
311 roundToJanuaryFirst(minDate, maxDate, calendarField);
312 }
313
314 /**
315 * Tests DateUtils.round()-method with Calendar.HOUR
316 * Includes rounding the extremes of one hour
317 * Includes rounding to January 1
318 *
319 * @throws Exception so we don't have to catch it
320 * @since 3.0
321 */
322 @Test
323 public void testRoundHour() throws Exception {
324 final int calendarField = Calendar.HOUR;
325 Date roundedUpDate, roundedDownDate, lastRoundedDownDate;
326 Date minDate, maxDate;
327
328 roundedUpDate = dateTimeParser.parse("June 1, 2008 9:00:00.000");
329 roundedDownDate = targetHourDate;
330 lastRoundedDownDate = dateTimeParser.parse("June 1, 2008 8:29:59.999");
331 baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField);
332
333 //round to January 1
334 minDate = dateTimeParser.parse("December 31, 2007 23:30:00.000");
335 maxDate = dateTimeParser.parse("January 1, 2008 0:29:59.999");
336 roundToJanuaryFirst(minDate, maxDate, calendarField);
337 }
338
339 /**
340 * Tests DateUtils.round()-method with Calendar.MINUTE
341 * Includes rounding the extremes of one minute
342 * Includes rounding to January 1
343 *
344 * @throws Exception so we don't have to catch it
345 * @since 3.0
346 */
347 @Test
348 public void testRoundMinute() throws Exception {
349 final int calendarField = Calendar.MINUTE;
350 Date roundedUpDate, roundedDownDate, lastRoundedDownDate;
351 Date minDate, maxDate;
352
353 roundedUpDate = dateTimeParser.parse("June 1, 2008 8:16:00.000");
354 roundedDownDate = targetMinuteDate;
355 lastRoundedDownDate = dateTimeParser.parse("June 1, 2008 8:15:29.999");
356 baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField);
357
358 //round to January 1
359 minDate = dateTimeParser.parse("December 31, 2007 23:59:30.000");
360 maxDate = dateTimeParser.parse("January 1, 2008 0:00:29.999");
361 roundToJanuaryFirst(minDate, maxDate, calendarField);
362 }
363
364 /**
365 * Tests DateUtils.round()-method with Calendar.SECOND
366 * Includes rounding the extremes of one second
367 * Includes rounding to January 1
368 *
369 * @throws Exception so we don't have to catch it
370 * @since 3.0
371 */
372 @Test
373 public void testRoundSecond() throws Exception {
374 final int calendarField = Calendar.SECOND;
375 Date roundedUpDate, roundedDownDate, lastRoundedDownDate;
376 Date minDate, maxDate;
377
378 roundedUpDate = dateTimeParser.parse("June 1, 2008 8:15:15.000");
379 roundedDownDate = targetSecondDate;
380 lastRoundedDownDate = dateTimeParser.parse("June 1, 2008 8:15:14.499");
381 baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField);
382
383 //round to January 1
384 minDate = dateTimeParser.parse("December 31, 2007 23:59:59.500");
385 maxDate = dateTimeParser.parse("January 1, 2008 0:00:00.499");
386 roundToJanuaryFirst(minDate, maxDate, calendarField);
387 }
388
389 /**
390 * Tests DateUtils.round()-method with Calendar.MILLISECOND
391 * Includes rounding the extremes of one second
392 * Includes rounding to January 1
393 *
394 * @throws Exception so we don't have to catch it
395 * @since 3.0
396 */
397 @Test
398 public void testRoundMilliSecond() throws Exception {
399 final int calendarField = Calendar.MILLISECOND;
400 Date roundedUpDate, roundedDownDate, lastRoundedDownDate;
401 Date minDate, maxDate;
402
403 roundedDownDate = lastRoundedDownDate = targetMilliSecondDate;
404 roundedUpDate = dateTimeParser.parse("June 1, 2008 8:15:14.232");
405 baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField);
406
407 //round to January 1
408 minDate = maxDate = januaryOneDate;
409 roundToJanuaryFirst(minDate, maxDate, calendarField);
410 }
411
412 /**
413 * Test DateUtils.truncate()-method with Calendar.YEAR
414 *
415 * @throws Exception so we don't have to catch it
416 * @since 3.0
417 */
418 @Test
419 public void testTruncateYear() throws Exception {
420 final int calendarField = Calendar.YEAR;
421 final Date lastTruncateDate = dateTimeParser.parse("December 31, 2007 23:59:59.999");
422 baseTruncateTest(targetYearDate, lastTruncateDate, calendarField);
423 }
424
425 /**
426 * Test DateUtils.truncate()-method with Calendar.MONTH
427 *
428 * @throws Exception so we don't have to catch it
429 * @since 3.0
430 */
431 @Test
432 public void testTruncateMonth() throws Exception {
433 final int calendarField = Calendar.MONTH;
434 final Date truncatedDate = dateTimeParser.parse("March 1, 2008 0:00:00.000");
435 final Date lastTruncateDate = dateTimeParser.parse("March 31, 2008 23:59:59.999");
436 baseTruncateTest(truncatedDate, lastTruncateDate, calendarField);
437 }
438
439 /**
440 * Test DateUtils.truncate()-method with DateUtils.SEMI_MONTH
441 * Includes truncating months with 28, 29, 30 and 31 days, each with first and second half
442 *
443 * @throws Exception so we don't have to catch it
444 * @since 3.0
445 */
446 @Test
447 public void testTruncateSemiMonth() throws Exception {
448 final int calendarField = DateUtils.SEMI_MONTH;
449 Date truncatedDate, lastTruncateDate;
450
451 //month with 28 days (1)
452 truncatedDate = dateTimeParser.parse("February 1, 2007 0:00:00.000");
453 lastTruncateDate = dateTimeParser.parse("February 15, 2007 23:59:59.999");
454 baseTruncateTest(truncatedDate, lastTruncateDate, calendarField);
455
456 //month with 28 days (2)
457 truncatedDate = dateTimeParser.parse("February 16, 2007 0:00:00.000");
458 lastTruncateDate = dateTimeParser.parse("February 28, 2007 23:59:59.999");
459 baseTruncateTest(truncatedDate, lastTruncateDate, calendarField);
460
461 //month with 29 days (1)
462 truncatedDate = dateTimeParser.parse("February 1, 2008 0:00:00.000");
463 lastTruncateDate = dateTimeParser.parse("February 15, 2008 23:59:59.999");
464 baseTruncateTest(truncatedDate, lastTruncateDate, calendarField);
465
466 //month with 29 days (2)
467 truncatedDate = dateTimeParser.parse("February 16, 2008 0:00:00.000");
468 lastTruncateDate = dateTimeParser.parse("February 29, 2008 23:59:59.999");
469 baseTruncateTest(truncatedDate, lastTruncateDate, calendarField);
470
471 //month with 30 days (1)
472 truncatedDate = dateTimeParser.parse("April 1, 2008 0:00:00.000");
473 lastTruncateDate = dateTimeParser.parse("April 15, 2008 23:59:59.999");
474 baseTruncateTest(truncatedDate, lastTruncateDate, calendarField);
475
476 //month with 30 days (2)
477 truncatedDate = dateTimeParser.parse("April 16, 2008 0:00:00.000");
478 lastTruncateDate = dateTimeParser.parse("April 30, 2008 23:59:59.999");
479 baseTruncateTest(truncatedDate, lastTruncateDate, calendarField);
480
481 //month with 31 days (1)
482 truncatedDate = dateTimeParser.parse("March 1, 2008 0:00:00.000");
483 lastTruncateDate = dateTimeParser.parse("March 15, 2008 23:59:59.999");
484 baseTruncateTest(truncatedDate, lastTruncateDate, calendarField);
485
486 //month with 31 days (2)
487 truncatedDate = dateTimeParser.parse("March 16, 2008 0:00:00.000");
488 lastTruncateDate = dateTimeParser.parse("March 31, 2008 23:59:59.999");
489 baseTruncateTest(truncatedDate, lastTruncateDate, calendarField);
490
491 }
492
493 /**
494 * Test DateUtils.truncate()-method with Calendar.DATE
495 *
496 * @throws Exception so we don't have to catch it
497 * @since 3.0
498 */
499 @Test
500 public void testTruncateDate() throws Exception {
501 final int calendarField = Calendar.DATE;
502 final Date lastTruncateDate = dateTimeParser.parse("June 1, 2008 23:59:59.999");
503 baseTruncateTest(targetDateDate, lastTruncateDate, calendarField);
504 }
505
506 /**
507 * Test DateUtils.truncate()-method with Calendar.DAY_OF_MONTH
508 *
509 * @throws Exception so we don't have to catch it
510 * @since 3.0
511 */
512 @Test
513 public void testTruncateDayOfMonth() throws Exception {
514 final int calendarField = Calendar.DAY_OF_MONTH;
515 final Date lastTruncateDate = dateTimeParser.parse("June 1, 2008 23:59:59.999");
516 baseTruncateTest(targetDayOfMonthDate, lastTruncateDate, calendarField);
517 }
518
519 /**
520 * Test DateUtils.truncate()-method with Calendar.AM_PM
521 * Includes truncating the extremes of both AM and PM of one day
522 *
523 * @throws Exception so we don't have to catch it
524 * @since 3.0
525 */
526 @Test
527 public void testTruncateAmPm() throws Exception {
528 final int calendarField = Calendar.AM_PM;
529
530 //AM
531 Date lastTruncateDate = dateTimeParser.parse("June 1, 2008 11:59:59.999");
532 baseTruncateTest(targetAmDate, lastTruncateDate, calendarField);
533
534 //PM
535 lastTruncateDate = dateTimeParser.parse("June 1, 2008 23:59:59.999");
536 baseTruncateTest(targetPmDate, lastTruncateDate, calendarField);
537 }
538
539 /**
540 * Test DateUtils.truncate()-method with Calendar.HOUR
541 *
542 * @throws Exception so we don't have to catch it
543 * @since 3.0
544 */
545 @Test
546 public void testTruncateHour() throws Exception {
547 final int calendarField = Calendar.HOUR;
548 final Date lastTruncateDate = dateTimeParser.parse("June 1, 2008 8:59:59.999");
549 baseTruncateTest(targetHourDate, lastTruncateDate, calendarField);
550 }
551
552 /**
553 * Test DateUtils.truncate()-method with Calendar.HOUR_OF_DAY
554 *
555 * @throws Exception so we don't have to catch it
556 * @since 3.0
557 */
558 @Test
559 public void testTruncateHourOfDay() throws Exception {
560 final int calendarField = Calendar.HOUR_OF_DAY;
561 final Date lastTruncateDate = dateTimeParser.parse("June 1, 2008 8:59:59.999");
562 baseTruncateTest(targetHourOfDayDate, lastTruncateDate, calendarField);
563 }
564
565 /**
566 * Test DateUtils.truncate()-method with Calendar.MINUTE
567 *
568 * @throws Exception so we don't have to catch it
569 * @since 3.0
570 */
571 @Test
572 public void testTruncateMinute() throws Exception {
573 final int calendarField = Calendar.MINUTE;
574 final Date lastTruncateDate = dateTimeParser.parse("June 1, 2008 8:15:59.999");
575 baseTruncateTest(targetMinuteDate, lastTruncateDate, calendarField);
576 }
577
578 /**
579 * Test DateUtils.truncate()-method with Calendar.SECOND
580 *
581 * @throws Exception so we don't have to catch it
582 * @since 3.0
583 */
584 @Test
585 public void testTruncateSecond() throws Exception {
586 final int calendarField = Calendar.SECOND;
587 final Date lastTruncateDate = dateTimeParser.parse("June 1, 2008 8:15:14.999");
588 baseTruncateTest(targetSecondDate, lastTruncateDate, calendarField);
589 }
590
591 /**
592 * Test DateUtils.truncate()-method with Calendar.SECOND
593 *
594 * @since 3.0
595 */
596 @Test
597 public void testTruncateMilliSecond() {
598 final int calendarField = Calendar.MILLISECOND;
599 baseTruncateTest(targetMilliSecondDate, targetMilliSecondDate, calendarField);
600 }
601
60260 /**
60361 * When using this basetest all extremes are tested.<br>
60462 * It will test the Date, Calendar and Object-implementation<br>
725183 assertNotEquals(januaryOneDate, DateUtils.round(toPrevRoundDate, calendarField), fdf.format(minCalendar) + " is not an lower-extreme when rounding as Date with CalendarField-value " + calendarField);
726184 assertNotEquals(januaryOneDate, DateUtils.round(toNextRoundDate, calendarField), fdf.format(maxCalendar) + " is not an upper-extreme when rounding as Date with CalendarField-value " + calendarField);
727185 }
186
187 @BeforeEach
188 public void setUp() throws Exception {
189
190 dateTimeParser = new SimpleDateFormat("MMM dd, yyyy H:mm:ss.SSS", Locale.ENGLISH);
191
192 targetYearDate = dateTimeParser.parse("January 1, 2007 0:00:00.000");
193 targetDateDate = targetDayOfMonthDate = dateTimeParser.parse("June 1, 2008 0:00:00.000");
194 targetAmDate = dateTimeParser.parse("June 1, 2008 0:00:00.000");
195 targetPmDate = dateTimeParser.parse("June 1, 2008 12:00:00.000");
196 targetHourDate = dateTimeParser.parse("June 1, 2008 8:00:00.000");
197 targetHourOfDayDate = dateTimeParser.parse("June 1, 2008 8:00:00.000");
198 targetMinuteDate = dateTimeParser.parse("June 1, 2008 8:15:00.000");
199 targetSecondDate = dateTimeParser.parse("June 1, 2008 8:15:14.000");
200 targetMilliSecondDate = dateTimeParser.parse("June 1, 2008 8:15:14.231");
201
202 januaryOneDate = dateTimeParser.parse("January 1, 2008 0:00:00.000");
203 januaryOneCalendar = Calendar.getInstance();
204 januaryOneCalendar.setTime(januaryOneDate);
205 }
206
207 /**
208 * Tests DateUtils.round()-method with Calendar.AM_PM
209 * Includes rounding the extremes of both AM and PM of one day
210 * Includes rounding to January 1
211 *
212 * @throws Exception so we don't have to catch it
213 * @since 3.0
214 */
215 @Test
216 public void testRoundAmPm() throws Exception {
217 final int calendarField = Calendar.AM_PM;
218 Date roundedUpDate, roundedDownDate, lastRoundedDownDate;
219 Date minDate, maxDate;
220
221 //AM
222 roundedUpDate = dateTimeParser.parse("June 1, 2008 12:00:00.000");
223 roundedDownDate = targetAmDate;
224 lastRoundedDownDate = dateTimeParser.parse("June 1, 2008 5:59:59.999");
225 baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField);
226
227 //PM
228 roundedUpDate = dateTimeParser.parse("June 2, 2008 0:00:00.000");
229 roundedDownDate = targetPmDate;
230 lastRoundedDownDate = dateTimeParser.parse("June 1, 2008 17:59:59.999");
231 baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField);
232
233 //round to January 1
234 minDate = dateTimeParser.parse("December 31, 2007 18:00:00.000");
235 maxDate = dateTimeParser.parse("January 1, 2008 5:59:59.999");
236 roundToJanuaryFirst(minDate, maxDate, calendarField);
237 }
238
239 /**
240 * Tests DateUtils.round()-method with Calendar.DATE
241 * Includes rounding the extremes of one day
242 * Includes rounding to January 1
243 *
244 * @throws Exception so we don't have to catch it
245 * @since 3.0
246 */
247 @Test
248 public void testRoundDate() throws Exception {
249 final int calendarField = Calendar.DATE;
250 Date roundedUpDate, roundedDownDate, lastRoundedDownDate;
251 Date minDate, maxDate;
252
253 roundedUpDate = dateTimeParser.parse("June 2, 2008 0:00:00.000");
254 roundedDownDate = targetDateDate;
255 lastRoundedDownDate = dateTimeParser.parse("June 1, 2008 11:59:59.999");
256 baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField);
257
258 //round to January 1
259 minDate = dateTimeParser.parse("December 31, 2007 12:00:00.000");
260 maxDate = dateTimeParser.parse("January 1, 2008 11:59:59.999");
261 roundToJanuaryFirst(minDate, maxDate, calendarField);
262 }
263
264 /**
265 * Tests DateUtils.round()-method with Calendar.DAY_OF_MONTH
266 * Includes rounding the extremes of one day
267 * Includes rounding to January 1
268 *
269 * @throws Exception so we don't have to catch it
270 * @since 3.0
271 */
272 @Test
273 public void testRoundDayOfMonth() throws Exception {
274 final int calendarField = Calendar.DAY_OF_MONTH;
275 Date roundedUpDate, roundedDownDate, lastRoundedDownDate;
276 Date minDate, maxDate;
277
278 roundedUpDate = dateTimeParser.parse("June 2, 2008 0:00:00.000");
279 roundedDownDate = targetDayOfMonthDate;
280 lastRoundedDownDate = dateTimeParser.parse("June 1, 2008 11:59:59.999");
281 baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField);
282
283 //round to January 1
284 minDate = dateTimeParser.parse("December 31, 2007 12:00:00.000");
285 maxDate = dateTimeParser.parse("January 1, 2008 11:59:59.999");
286 roundToJanuaryFirst(minDate, maxDate, calendarField);
287 }
288
289 /**
290 * Tests DateUtils.round()-method with Calendar.HOUR
291 * Includes rounding the extremes of one hour
292 * Includes rounding to January 1
293 *
294 * @throws Exception so we don't have to catch it
295 * @since 3.0
296 */
297 @Test
298 public void testRoundHour() throws Exception {
299 final int calendarField = Calendar.HOUR;
300 Date roundedUpDate, roundedDownDate, lastRoundedDownDate;
301 Date minDate, maxDate;
302
303 roundedUpDate = dateTimeParser.parse("June 1, 2008 9:00:00.000");
304 roundedDownDate = targetHourDate;
305 lastRoundedDownDate = dateTimeParser.parse("June 1, 2008 8:29:59.999");
306 baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField);
307
308 //round to January 1
309 minDate = dateTimeParser.parse("December 31, 2007 23:30:00.000");
310 maxDate = dateTimeParser.parse("January 1, 2008 0:29:59.999");
311 roundToJanuaryFirst(minDate, maxDate, calendarField);
312 }
313
314 /**
315 * Tests DateUtils.round()-method with Calendar.HOUR_OF_DAY
316 * Includes rounding the extremes of one hour
317 * Includes rounding to January 1
318 *
319 * @throws Exception so we don't have to catch it
320 * @since 3.0
321 */
322 @Test
323 public void testRoundHourOfDay() throws Exception {
324 final int calendarField = Calendar.HOUR_OF_DAY;
325 Date roundedUpDate, roundedDownDate, lastRoundedDownDate;
326 Date minDate, maxDate;
327
328 roundedUpDate = dateTimeParser.parse("June 1, 2008 9:00:00.000");
329 roundedDownDate = targetHourOfDayDate;
330 lastRoundedDownDate = dateTimeParser.parse("June 1, 2008 8:29:59.999");
331 baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField);
332
333 //round to January 1
334 minDate = dateTimeParser.parse("December 31, 2007 23:30:00.000");
335 maxDate = dateTimeParser.parse("January 1, 2008 0:29:59.999");
336 roundToJanuaryFirst(minDate, maxDate, calendarField);
337 }
338
339 /**
340 * Tests DateUtils.round()-method with Calendar.MILLISECOND
341 * Includes rounding the extremes of one second
342 * Includes rounding to January 1
343 *
344 * @throws Exception so we don't have to catch it
345 * @since 3.0
346 */
347 @Test
348 public void testRoundMilliSecond() throws Exception {
349 final int calendarField = Calendar.MILLISECOND;
350 Date roundedUpDate, roundedDownDate, lastRoundedDownDate;
351 Date minDate, maxDate;
352
353 roundedDownDate = lastRoundedDownDate = targetMilliSecondDate;
354 roundedUpDate = dateTimeParser.parse("June 1, 2008 8:15:14.232");
355 baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField);
356
357 //round to January 1
358 minDate = maxDate = januaryOneDate;
359 roundToJanuaryFirst(minDate, maxDate, calendarField);
360 }
361
362 /**
363 * Tests DateUtils.round()-method with Calendar.MINUTE
364 * Includes rounding the extremes of one minute
365 * Includes rounding to January 1
366 *
367 * @throws Exception so we don't have to catch it
368 * @since 3.0
369 */
370 @Test
371 public void testRoundMinute() throws Exception {
372 final int calendarField = Calendar.MINUTE;
373 Date roundedUpDate, roundedDownDate, lastRoundedDownDate;
374 Date minDate, maxDate;
375
376 roundedUpDate = dateTimeParser.parse("June 1, 2008 8:16:00.000");
377 roundedDownDate = targetMinuteDate;
378 lastRoundedDownDate = dateTimeParser.parse("June 1, 2008 8:15:29.999");
379 baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField);
380
381 //round to January 1
382 minDate = dateTimeParser.parse("December 31, 2007 23:59:30.000");
383 maxDate = dateTimeParser.parse("January 1, 2008 0:00:29.999");
384 roundToJanuaryFirst(minDate, maxDate, calendarField);
385 }
386
387 /**
388 * Tests DateUtils.round()-method with Calendar.MONTH
389 * Includes rounding months with 28, 29, 30 and 31 days
390 * Includes rounding to January 1
391 *
392 * @throws Exception so we don't have to catch it
393 * @since 3.0
394 */
395 @Test
396 public void testRoundMonth() throws Exception {
397 final int calendarField = Calendar.MONTH;
398 Date roundedUpDate, roundedDownDate, lastRoundedDownDate;
399 Date minDate, maxDate;
400
401 //month with 28 days
402 roundedUpDate = dateTimeParser.parse("March 1, 2007 0:00:00.000");
403 roundedDownDate = dateTimeParser.parse("February 1, 2007 0:00:00.000");
404 lastRoundedDownDate = dateTimeParser.parse("February 14, 2007 23:59:59.999");
405 baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField);
406
407 //month with 29 days
408 roundedUpDate = dateTimeParser.parse("March 1, 2008 0:00:00.000");
409 roundedDownDate = dateTimeParser.parse("February 1, 2008 0:00:00.000");
410 lastRoundedDownDate = dateTimeParser.parse("February 15, 2008 23:59:59.999");
411 baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField);
412
413 //month with 30 days
414 roundedUpDate = dateTimeParser.parse("May 1, 2008 0:00:00.000");
415 roundedDownDate = dateTimeParser.parse("April 1, 2008 0:00:00.000");
416 lastRoundedDownDate = dateTimeParser.parse("April 15, 2008 23:59:59.999");
417 baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField);
418
419 //month with 31 days
420 roundedUpDate = dateTimeParser.parse("June 1, 2008 0:00:00.000");
421 roundedDownDate = dateTimeParser.parse("May 1, 2008 0:00:00.000");
422 lastRoundedDownDate = dateTimeParser.parse("May 16, 2008 23:59:59.999");
423 baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField);
424
425 //round to January 1
426 minDate = dateTimeParser.parse("December 17, 2007 00:00:00.000");
427 maxDate = dateTimeParser.parse("January 16, 2008 23:59:59.999");
428 roundToJanuaryFirst(minDate, maxDate, calendarField);
429 }
430
431 /**
432 * Tests DateUtils.round()-method with Calendar.SECOND
433 * Includes rounding the extremes of one second
434 * Includes rounding to January 1
435 *
436 * @throws Exception so we don't have to catch it
437 * @since 3.0
438 */
439 @Test
440 public void testRoundSecond() throws Exception {
441 final int calendarField = Calendar.SECOND;
442 Date roundedUpDate, roundedDownDate, lastRoundedDownDate;
443 Date minDate, maxDate;
444
445 roundedUpDate = dateTimeParser.parse("June 1, 2008 8:15:15.000");
446 roundedDownDate = targetSecondDate;
447 lastRoundedDownDate = dateTimeParser.parse("June 1, 2008 8:15:14.499");
448 baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField);
449
450 //round to January 1
451 minDate = dateTimeParser.parse("December 31, 2007 23:59:59.500");
452 maxDate = dateTimeParser.parse("January 1, 2008 0:00:00.499");
453 roundToJanuaryFirst(minDate, maxDate, calendarField);
454 }
455
456 /**
457 * Tests DateUtils.round()-method with DateUtils.SEMI_MONTH
458 * Includes rounding months with 28, 29, 30 and 31 days, each with first and second half
459 * Includes rounding to January 1
460 *
461 * @throws Exception so we don't have to catch it
462 * @since 3.0
463 */
464 @Test
465 public void testRoundSemiMonth() throws Exception {
466 final int calendarField = DateUtils.SEMI_MONTH;
467 Date roundedUpDate, roundedDownDate, lastRoundedDownDate;
468 Date minDate, maxDate;
469
470 //month with 28 days (1)
471 roundedUpDate = dateTimeParser.parse("February 16, 2007 0:00:00.000");
472 roundedDownDate = dateTimeParser.parse("February 1, 2007 0:00:00.000");
473 lastRoundedDownDate = dateTimeParser.parse("February 8, 2007 23:59:59.999");
474 baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField);
475
476 //month with 28 days (2)
477 roundedUpDate = dateTimeParser.parse("March 1, 2007 0:00:00.000");
478 roundedDownDate = dateTimeParser.parse("February 16, 2007 0:00:00.000");
479 lastRoundedDownDate = dateTimeParser.parse("February 23, 2007 23:59:59.999");
480 baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField);
481
482 //month with 29 days (1)
483 roundedUpDate = dateTimeParser.parse("February 16, 2008 0:00:00.000");
484 roundedDownDate = dateTimeParser.parse("February 1, 2008 0:00:00.000");
485 lastRoundedDownDate = dateTimeParser.parse("February 8, 2008 23:59:59.999");
486 baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField);
487
488 //month with 29 days (2)
489 roundedUpDate = dateTimeParser.parse("March 1, 2008 0:00:00.000");
490 roundedDownDate = dateTimeParser.parse("February 16, 2008 0:00:00.000");
491 lastRoundedDownDate = dateTimeParser.parse("February 23, 2008 23:59:59.999");
492 baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField);
493
494 //month with 30 days (1)
495 roundedUpDate = dateTimeParser.parse("April 16, 2008 0:00:00.000");
496 roundedDownDate = dateTimeParser.parse("April 1, 2008 0:00:00.000");
497 lastRoundedDownDate = dateTimeParser.parse("April 8, 2008 23:59:59.999");
498 baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField);
499
500 //month with 30 days (2)
501 roundedUpDate = dateTimeParser.parse("May 1, 2008 0:00:00.000");
502 roundedDownDate = dateTimeParser.parse("April 16, 2008 0:00:00.000");
503 lastRoundedDownDate = dateTimeParser.parse("April 23, 2008 23:59:59.999");
504 baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField);
505
506 //month with 31 days (1)
507 roundedUpDate = dateTimeParser.parse("May 16, 2008 0:00:00.000");
508 roundedDownDate = dateTimeParser.parse("May 1, 2008 0:00:00.000");
509 lastRoundedDownDate = dateTimeParser.parse("May 8, 2008 23:59:59.999");
510 baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField);
511
512 //month with 31 days (2)
513 roundedUpDate = dateTimeParser.parse("June 1, 2008 0:00:00.000");
514 roundedDownDate = dateTimeParser.parse("May 16, 2008 0:00:00.000");
515 lastRoundedDownDate = dateTimeParser.parse("May 23, 2008 23:59:59.999");
516 baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField);
517
518 //round to January 1
519 minDate = dateTimeParser.parse("December 24, 2007 00:00:00.000");
520 maxDate = dateTimeParser.parse("January 8, 2008 23:59:59.999");
521 roundToJanuaryFirst(minDate, maxDate, calendarField);
522 }
523
524 /**
525 * Tests DateUtils.round()-method with Calendar.Year
526 *
527 * @throws Exception so we don't have to catch it
528 * @since 3.0
529 */
530 @Test
531 public void testRoundYear() throws Exception {
532 final int calendarField = Calendar.YEAR;
533 final Date roundedUpDate = dateTimeParser.parse("January 1, 2008 0:00:00.000");
534 final Date roundedDownDate = targetYearDate;
535 final Date lastRoundedDownDate = dateTimeParser.parse("June 30, 2007 23:59:59.999");
536 baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField);
537 }
538
539 /**
540 * Test DateUtils.truncate()-method with Calendar.AM_PM
541 * Includes truncating the extremes of both AM and PM of one day
542 *
543 * @throws Exception so we don't have to catch it
544 * @since 3.0
545 */
546 @Test
547 public void testTruncateAmPm() throws Exception {
548 final int calendarField = Calendar.AM_PM;
549
550 //AM
551 Date lastTruncateDate = dateTimeParser.parse("June 1, 2008 11:59:59.999");
552 baseTruncateTest(targetAmDate, lastTruncateDate, calendarField);
553
554 //PM
555 lastTruncateDate = dateTimeParser.parse("June 1, 2008 23:59:59.999");
556 baseTruncateTest(targetPmDate, lastTruncateDate, calendarField);
557 }
558
559 /**
560 * Test DateUtils.truncate()-method with Calendar.DATE
561 *
562 * @throws Exception so we don't have to catch it
563 * @since 3.0
564 */
565 @Test
566 public void testTruncateDate() throws Exception {
567 final int calendarField = Calendar.DATE;
568 final Date lastTruncateDate = dateTimeParser.parse("June 1, 2008 23:59:59.999");
569 baseTruncateTest(targetDateDate, lastTruncateDate, calendarField);
570 }
571
572 /**
573 * Test DateUtils.truncate()-method with Calendar.DAY_OF_MONTH
574 *
575 * @throws Exception so we don't have to catch it
576 * @since 3.0
577 */
578 @Test
579 public void testTruncateDayOfMonth() throws Exception {
580 final int calendarField = Calendar.DAY_OF_MONTH;
581 final Date lastTruncateDate = dateTimeParser.parse("June 1, 2008 23:59:59.999");
582 baseTruncateTest(targetDayOfMonthDate, lastTruncateDate, calendarField);
583 }
584
585 /**
586 * Test DateUtils.truncate()-method with Calendar.HOUR
587 *
588 * @throws Exception so we don't have to catch it
589 * @since 3.0
590 */
591 @Test
592 public void testTruncateHour() throws Exception {
593 final int calendarField = Calendar.HOUR;
594 final Date lastTruncateDate = dateTimeParser.parse("June 1, 2008 8:59:59.999");
595 baseTruncateTest(targetHourDate, lastTruncateDate, calendarField);
596 }
597
598 /**
599 * Test DateUtils.truncate()-method with Calendar.HOUR_OF_DAY
600 *
601 * @throws Exception so we don't have to catch it
602 * @since 3.0
603 */
604 @Test
605 public void testTruncateHourOfDay() throws Exception {
606 final int calendarField = Calendar.HOUR_OF_DAY;
607 final Date lastTruncateDate = dateTimeParser.parse("June 1, 2008 8:59:59.999");
608 baseTruncateTest(targetHourOfDayDate, lastTruncateDate, calendarField);
609 }
610
611 /**
612 * Test DateUtils.truncate()-method with Calendar.SECOND
613 *
614 * @since 3.0
615 */
616 @Test
617 public void testTruncateMilliSecond() {
618 final int calendarField = Calendar.MILLISECOND;
619 baseTruncateTest(targetMilliSecondDate, targetMilliSecondDate, calendarField);
620 }
621
622 /**
623 * Test DateUtils.truncate()-method with Calendar.MINUTE
624 *
625 * @throws Exception so we don't have to catch it
626 * @since 3.0
627 */
628 @Test
629 public void testTruncateMinute() throws Exception {
630 final int calendarField = Calendar.MINUTE;
631 final Date lastTruncateDate = dateTimeParser.parse("June 1, 2008 8:15:59.999");
632 baseTruncateTest(targetMinuteDate, lastTruncateDate, calendarField);
633 }
634
635 /**
636 * Test DateUtils.truncate()-method with Calendar.MONTH
637 *
638 * @throws Exception so we don't have to catch it
639 * @since 3.0
640 */
641 @Test
642 public void testTruncateMonth() throws Exception {
643 final int calendarField = Calendar.MONTH;
644 final Date truncatedDate = dateTimeParser.parse("March 1, 2008 0:00:00.000");
645 final Date lastTruncateDate = dateTimeParser.parse("March 31, 2008 23:59:59.999");
646 baseTruncateTest(truncatedDate, lastTruncateDate, calendarField);
647 }
648
649 /**
650 * Test DateUtils.truncate()-method with Calendar.SECOND
651 *
652 * @throws Exception so we don't have to catch it
653 * @since 3.0
654 */
655 @Test
656 public void testTruncateSecond() throws Exception {
657 final int calendarField = Calendar.SECOND;
658 final Date lastTruncateDate = dateTimeParser.parse("June 1, 2008 8:15:14.999");
659 baseTruncateTest(targetSecondDate, lastTruncateDate, calendarField);
660 }
661
662 /**
663 * Test DateUtils.truncate()-method with DateUtils.SEMI_MONTH
664 * Includes truncating months with 28, 29, 30 and 31 days, each with first and second half
665 *
666 * @throws Exception so we don't have to catch it
667 * @since 3.0
668 */
669 @Test
670 public void testTruncateSemiMonth() throws Exception {
671 final int calendarField = DateUtils.SEMI_MONTH;
672 Date truncatedDate, lastTruncateDate;
673
674 //month with 28 days (1)
675 truncatedDate = dateTimeParser.parse("February 1, 2007 0:00:00.000");
676 lastTruncateDate = dateTimeParser.parse("February 15, 2007 23:59:59.999");
677 baseTruncateTest(truncatedDate, lastTruncateDate, calendarField);
678
679 //month with 28 days (2)
680 truncatedDate = dateTimeParser.parse("February 16, 2007 0:00:00.000");
681 lastTruncateDate = dateTimeParser.parse("February 28, 2007 23:59:59.999");
682 baseTruncateTest(truncatedDate, lastTruncateDate, calendarField);
683
684 //month with 29 days (1)
685 truncatedDate = dateTimeParser.parse("February 1, 2008 0:00:00.000");
686 lastTruncateDate = dateTimeParser.parse("February 15, 2008 23:59:59.999");
687 baseTruncateTest(truncatedDate, lastTruncateDate, calendarField);
688
689 //month with 29 days (2)
690 truncatedDate = dateTimeParser.parse("February 16, 2008 0:00:00.000");
691 lastTruncateDate = dateTimeParser.parse("February 29, 2008 23:59:59.999");
692 baseTruncateTest(truncatedDate, lastTruncateDate, calendarField);
693
694 //month with 30 days (1)
695 truncatedDate = dateTimeParser.parse("April 1, 2008 0:00:00.000");
696 lastTruncateDate = dateTimeParser.parse("April 15, 2008 23:59:59.999");
697 baseTruncateTest(truncatedDate, lastTruncateDate, calendarField);
698
699 //month with 30 days (2)
700 truncatedDate = dateTimeParser.parse("April 16, 2008 0:00:00.000");
701 lastTruncateDate = dateTimeParser.parse("April 30, 2008 23:59:59.999");
702 baseTruncateTest(truncatedDate, lastTruncateDate, calendarField);
703
704 //month with 31 days (1)
705 truncatedDate = dateTimeParser.parse("March 1, 2008 0:00:00.000");
706 lastTruncateDate = dateTimeParser.parse("March 15, 2008 23:59:59.999");
707 baseTruncateTest(truncatedDate, lastTruncateDate, calendarField);
708
709 //month with 31 days (2)
710 truncatedDate = dateTimeParser.parse("March 16, 2008 0:00:00.000");
711 lastTruncateDate = dateTimeParser.parse("March 31, 2008 23:59:59.999");
712 baseTruncateTest(truncatedDate, lastTruncateDate, calendarField);
713
714 }
715
716 /**
717 * Test DateUtils.truncate()-method with Calendar.YEAR
718 *
719 * @throws Exception so we don't have to catch it
720 * @since 3.0
721 */
722 @Test
723 public void testTruncateYear() throws Exception {
724 final int calendarField = Calendar.YEAR;
725 final Date lastTruncateDate = dateTimeParser.parse("December 31, 2007 23:59:59.999");
726 baseTruncateTest(targetYearDate, lastTruncateDate, calendarField);
727 }
728728 }
4747
4848 private static Date BASE_DATE;
4949
50 /**
51 * Used to check that Calendar objects are close enough
52 * delta is in milliseconds
53 */
54 private static void assertCalendarsEquals(final String message, final Calendar cal1, final Calendar cal2, final long delta) {
55 assertFalse(Math.abs(cal1.getTime().getTime() - cal2.getTime().getTime()) > delta,
56 message + " expected " + cal1.getTime() + " but got " + cal2.getTime());
57 }
58
59 /**
60 * This checks that this is a 7 element iterator of Calendar objects
61 * that are dates (no time), and exactly 1 day spaced after each other.
62 */
63 private static void assertWeekIterator(final Iterator<?> it, final Calendar start) {
64 final Calendar end = (Calendar) start.clone();
65 end.add(Calendar.DATE, 6);
66
67 assertWeekIterator(it, start, end);
68 }
69 /**
70 * This checks that this is a 7 divisble iterator of Calendar objects
71 * that are dates (no time), and exactly 1 day spaced after each other
72 * (in addition to the proper start and stop dates)
73 */
74 private static void assertWeekIterator(final Iterator<?> it, final Calendar start, final Calendar end) {
75 Calendar cal = (Calendar) it.next();
76 assertCalendarsEquals("", start, cal, 0);
77 Calendar last = null;
78 int count = 1;
79 while (it.hasNext()) {
80 //Check this is just a date (no time component)
81 assertCalendarsEquals("", cal, DateUtils.truncate(cal, Calendar.DATE), 0);
82
83 last = cal;
84 cal = (Calendar) it.next();
85 count++;
86
87 //Check that this is one day more than the last date
88 last.add(Calendar.DATE, 1);
89 assertCalendarsEquals("", last, cal, 0);
90 }
91
92 assertFalse(count % 7 != 0, "There were " + count + " days in this iterator");
93 assertCalendarsEquals("", end, cal, 0);
94 }
95 /**
96 * Convenience method for when working with Date objects
97 */
98 private static void assertWeekIterator(final Iterator<?> it, final Date start, final Date end) {
99 final Calendar calStart = Calendar.getInstance();
100 calStart.setTime(start);
101 final Calendar calEnd = Calendar.getInstance();
102 calEnd.setTime(end);
103
104 assertWeekIterator(it, calStart, calEnd);
105 }
50106 @BeforeAll
51107 public static void classSetup() {
52108 final GregorianCalendar cal = new GregorianCalendar(2000, 6, 5, 4, 3, 2);
53109 cal.set(Calendar.MILLISECOND, 1);
54110 BASE_DATE = cal.getTime();
55111 }
56
57112 private DateFormat dateParser = null;
58113 private DateFormat dateTimeParser = null;
59114 private Date dateAmPm1 = null;
79134 private Calendar cal4 = null;
80135 private Calendar cal5 = null;
81136 private Calendar cal6 = null;
137
82138 private Calendar cal7 = null;
139
83140 private Calendar cal8 = null;
141
84142 private TimeZone zone = null;
143
85144 private TimeZone defaultZone = null;
145
146 private void assertDate(final Date date, final int year, final int month, final int day, final int hour, final int min, final int sec, final int mil) {
147 final GregorianCalendar cal = new GregorianCalendar();
148 cal.setTime(date);
149 assertEquals(year, cal.get(Calendar.YEAR));
150 assertEquals(month, cal.get(Calendar.MONTH));
151 assertEquals(day, cal.get(Calendar.DAY_OF_MONTH));
152 assertEquals(hour, cal.get(Calendar.HOUR_OF_DAY));
153 assertEquals(min, cal.get(Calendar.MINUTE));
154 assertEquals(sec, cal.get(Calendar.SECOND));
155 assertEquals(mil, cal.get(Calendar.MILLISECOND));
156 }
86157
87158 @BeforeEach
88159 public void setUp() throws Exception {
142213 }
143214 }
144215
145 //-----------------------------------------------------------------------
216 @Test
217 public void testAddDays() throws Exception {
218 Date result = DateUtils.addDays(BASE_DATE, 0);
219 assertNotSame(BASE_DATE, result);
220 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
221 assertDate(result, 2000, 6, 5, 4, 3, 2, 1);
222
223 result = DateUtils.addDays(BASE_DATE, 1);
224 assertNotSame(BASE_DATE, result);
225 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
226 assertDate(result, 2000, 6, 6, 4, 3, 2, 1);
227
228 result = DateUtils.addDays(BASE_DATE, -1);
229 assertNotSame(BASE_DATE, result);
230 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
231 assertDate(result, 2000, 6, 4, 4, 3, 2, 1);
232 }
233
234 @Test
235 public void testAddHours() throws Exception {
236 Date result = DateUtils.addHours(BASE_DATE, 0);
237 assertNotSame(BASE_DATE, result);
238 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
239 assertDate(result, 2000, 6, 5, 4, 3, 2, 1);
240
241 result = DateUtils.addHours(BASE_DATE, 1);
242 assertNotSame(BASE_DATE, result);
243 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
244 assertDate(result, 2000, 6, 5, 5, 3, 2, 1);
245
246 result = DateUtils.addHours(BASE_DATE, -1);
247 assertNotSame(BASE_DATE, result);
248 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
249 assertDate(result, 2000, 6, 5, 3, 3, 2, 1);
250 }
251
252 @Test
253 public void testAddMilliseconds() throws Exception {
254 Date result = DateUtils.addMilliseconds(BASE_DATE, 0);
255 assertNotSame(BASE_DATE, result);
256 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
257 assertDate(result, 2000, 6, 5, 4, 3, 2, 1);
258
259 result = DateUtils.addMilliseconds(BASE_DATE, 1);
260 assertNotSame(BASE_DATE, result);
261 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
262 assertDate(result, 2000, 6, 5, 4, 3, 2, 2);
263
264 result = DateUtils.addMilliseconds(BASE_DATE, -1);
265 assertNotSame(BASE_DATE, result);
266 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
267 assertDate(result, 2000, 6, 5, 4, 3, 2, 0);
268 }
269
270 @Test
271 public void testAddMinutes() throws Exception {
272 Date result = DateUtils.addMinutes(BASE_DATE, 0);
273 assertNotSame(BASE_DATE, result);
274 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
275 assertDate(result, 2000, 6, 5, 4, 3, 2, 1);
276
277 result = DateUtils.addMinutes(BASE_DATE, 1);
278 assertNotSame(BASE_DATE, result);
279 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
280 assertDate(result, 2000, 6, 5, 4, 4, 2, 1);
281
282 result = DateUtils.addMinutes(BASE_DATE, -1);
283 assertNotSame(BASE_DATE, result);
284 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
285 assertDate(result, 2000, 6, 5, 4, 2, 2, 1);
286 }
287
288 @Test
289 public void testAddMonths() throws Exception {
290 Date result = DateUtils.addMonths(BASE_DATE, 0);
291 assertNotSame(BASE_DATE, result);
292 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
293 assertDate(result, 2000, 6, 5, 4, 3, 2, 1);
294
295 result = DateUtils.addMonths(BASE_DATE, 1);
296 assertNotSame(BASE_DATE, result);
297 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
298 assertDate(result, 2000, 7, 5, 4, 3, 2, 1);
299
300 result = DateUtils.addMonths(BASE_DATE, -1);
301 assertNotSame(BASE_DATE, result);
302 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
303 assertDate(result, 2000, 5, 5, 4, 3, 2, 1);
304 }
305
306 @Test
307 public void testAddSeconds() throws Exception {
308 Date result = DateUtils.addSeconds(BASE_DATE, 0);
309 assertNotSame(BASE_DATE, result);
310 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
311 assertDate(result, 2000, 6, 5, 4, 3, 2, 1);
312
313 result = DateUtils.addSeconds(BASE_DATE, 1);
314 assertNotSame(BASE_DATE, result);
315 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
316 assertDate(result, 2000, 6, 5, 4, 3, 3, 1);
317
318 result = DateUtils.addSeconds(BASE_DATE, -1);
319 assertNotSame(BASE_DATE, result);
320 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
321 assertDate(result, 2000, 6, 5, 4, 3, 1, 1);
322 }
323
324 @Test
325 public void testAddWeeks() throws Exception {
326 Date result = DateUtils.addWeeks(BASE_DATE, 0);
327 assertNotSame(BASE_DATE, result);
328 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
329 assertDate(result, 2000, 6, 5, 4, 3, 2, 1);
330
331 result = DateUtils.addWeeks(BASE_DATE, 1);
332 assertNotSame(BASE_DATE, result);
333 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
334 assertDate(result, 2000, 6, 12, 4, 3, 2, 1);
335
336 result = DateUtils.addWeeks(BASE_DATE, -1);
337 assertNotSame(BASE_DATE, result);
338 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1); // july
339 assertDate(result, 2000, 5, 28, 4, 3, 2, 1); // june
340 }
341
342 @Test
343 public void testAddYears() throws Exception {
344 Date result = DateUtils.addYears(BASE_DATE, 0);
345 assertNotSame(BASE_DATE, result);
346 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
347 assertDate(result, 2000, 6, 5, 4, 3, 2, 1);
348
349 result = DateUtils.addYears(BASE_DATE, 1);
350 assertNotSame(BASE_DATE, result);
351 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
352 assertDate(result, 2001, 6, 5, 4, 3, 2, 1);
353
354 result = DateUtils.addYears(BASE_DATE, -1);
355 assertNotSame(BASE_DATE, result);
356 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
357 assertDate(result, 1999, 6, 5, 4, 3, 2, 1);
358 }
359
360 /**
361 * Tests various values with the ceiling method
362 *
363 * @throws java.lang.Exception so we don't have to catch it
364 */
365 @Test
366 public void testCeil() throws Exception {
367 // test javadoc
368 assertEquals(dateTimeParser.parse("March 28, 2002 14:00:00.000"),
369 DateUtils.ceiling(
370 dateTimeParser.parse("March 28, 2002 13:45:01.231"),
371 Calendar.HOUR),
372 "ceiling javadoc-1 failed");
373 assertEquals(dateTimeParser.parse("April 1, 2002 00:00:00.000"),
374 DateUtils.ceiling(
375 dateTimeParser.parse("March 28, 2002 13:45:01.231"),
376 Calendar.MONTH),
377 "ceiling javadoc-2 failed");
378
379 // tests public static Date ceiling(Date date, int field)
380 assertEquals(dateParser.parse("January 1, 2003"),
381 DateUtils.ceiling(date1, Calendar.YEAR),
382 "ceiling year-1 failed");
383 assertEquals(dateParser.parse("January 1, 2002"),
384 DateUtils.ceiling(date2, Calendar.YEAR),
385 "ceiling year-2 failed");
386 assertEquals(dateParser.parse("March 1, 2002"),
387 DateUtils.ceiling(date1, Calendar.MONTH),
388 "ceiling month-1 failed");
389 assertEquals(dateParser.parse("December 1, 2001"),
390 DateUtils.ceiling(date2, Calendar.MONTH),
391 "ceiling month-2 failed");
392 assertEquals(dateParser.parse("February 16, 2002"),
393 DateUtils.ceiling(date1, DateUtils.SEMI_MONTH),
394 "ceiling semimonth-1 failed");
395 assertEquals(dateParser.parse("December 1, 2001"),
396 DateUtils.ceiling(date2, DateUtils.SEMI_MONTH),
397 "ceiling semimonth-2 failed");
398 assertEquals(dateParser.parse("February 13, 2002"),
399 DateUtils.ceiling(date1, Calendar.DATE),
400 "ceiling date-1 failed");
401 assertEquals(dateParser.parse("November 19, 2001"),
402 DateUtils.ceiling(date2, Calendar.DATE),
403 "ceiling date-2 failed");
404 assertEquals(dateTimeParser.parse("February 12, 2002 13:00:00.000"),
405 DateUtils.ceiling(date1, Calendar.HOUR),
406 "ceiling hour-1 failed");
407 assertEquals(dateTimeParser.parse("November 18, 2001 2:00:00.000"),
408 DateUtils.ceiling(date2, Calendar.HOUR),
409 "ceiling hour-2 failed");
410 assertEquals(dateTimeParser.parse("February 12, 2002 12:35:00.000"),
411 DateUtils.ceiling(date1, Calendar.MINUTE),
412 "ceiling minute-1 failed");
413 assertEquals(dateTimeParser.parse("November 18, 2001 1:24:00.000"),
414 DateUtils.ceiling(date2, Calendar.MINUTE),
415 "ceiling minute-2 failed");
416 assertEquals(dateTimeParser.parse("February 12, 2002 12:34:57.000"),
417 DateUtils.ceiling(date1, Calendar.SECOND),
418 "ceiling second-1 failed");
419 assertEquals(dateTimeParser.parse("November 18, 2001 1:23:12.000"),
420 DateUtils.ceiling(date2, Calendar.SECOND),
421 "ceiling second-2 failed");
422 assertEquals(dateTimeParser.parse("February 3, 2002 12:00:00.000"),
423 DateUtils.ceiling(dateAmPm1, Calendar.AM_PM),
424 "ceiling ampm-1 failed");
425 assertEquals(dateTimeParser.parse("February 3, 2002 12:00:00.000"),
426 DateUtils.ceiling(dateAmPm2, Calendar.AM_PM),
427 "ceiling ampm-2 failed");
428 assertEquals(dateTimeParser.parse("February 4, 2002 00:00:00.000"),
429 DateUtils.ceiling(dateAmPm3, Calendar.AM_PM),
430 "ceiling ampm-3 failed");
431 assertEquals(dateTimeParser.parse("February 4, 2002 00:00:00.000"),
432 DateUtils.ceiling(dateAmPm4, Calendar.AM_PM),
433 "ceiling ampm-4 failed");
434
435 // tests public static Date ceiling(Object date, int field)
436 assertEquals(dateParser.parse("January 1, 2003"),
437 DateUtils.ceiling((Object) date1, Calendar.YEAR),
438 "ceiling year-1 failed");
439 assertEquals(dateParser.parse("January 1, 2002"),
440 DateUtils.ceiling((Object) date2, Calendar.YEAR),
441 "ceiling year-2 failed");
442 assertEquals(dateParser.parse("March 1, 2002"),
443 DateUtils.ceiling((Object) date1, Calendar.MONTH),
444 "ceiling month-1 failed");
445 assertEquals(dateParser.parse("December 1, 2001"),
446 DateUtils.ceiling((Object) date2, Calendar.MONTH),
447 "ceiling month-2 failed");
448 assertEquals(dateParser.parse("February 16, 2002"),
449 DateUtils.ceiling((Object) date1, DateUtils.SEMI_MONTH),
450 "ceiling semimonth-1 failed");
451 assertEquals(dateParser.parse("December 1, 2001"),
452 DateUtils.ceiling((Object) date2, DateUtils.SEMI_MONTH),
453 "ceiling semimonth-2 failed");
454 assertEquals(dateParser.parse("February 13, 2002"),
455 DateUtils.ceiling((Object) date1, Calendar.DATE),
456 "ceiling date-1 failed");
457 assertEquals(dateParser.parse("November 19, 2001"),
458 DateUtils.ceiling((Object) date2, Calendar.DATE),
459 "ceiling date-2 failed");
460 assertEquals(dateTimeParser.parse("February 12, 2002 13:00:00.000"),
461 DateUtils.ceiling((Object) date1, Calendar.HOUR),
462 "ceiling hour-1 failed");
463 assertEquals(dateTimeParser.parse("November 18, 2001 2:00:00.000"),
464 DateUtils.ceiling((Object) date2, Calendar.HOUR),
465 "ceiling hour-2 failed");
466 assertEquals(dateTimeParser.parse("February 12, 2002 12:35:00.000"),
467 DateUtils.ceiling((Object) date1, Calendar.MINUTE),
468 "ceiling minute-1 failed");
469 assertEquals(dateTimeParser.parse("November 18, 2001 1:24:00.000"),
470 DateUtils.ceiling((Object) date2, Calendar.MINUTE),
471 "ceiling minute-2 failed");
472 assertEquals(dateTimeParser.parse("February 12, 2002 12:34:57.000"),
473 DateUtils.ceiling((Object) date1, Calendar.SECOND),
474 "ceiling second-1 failed");
475 assertEquals(dateTimeParser.parse("November 18, 2001 1:23:12.000"),
476 DateUtils.ceiling((Object) date2, Calendar.SECOND),
477 "ceiling second-2 failed");
478 assertEquals(dateTimeParser.parse("February 3, 2002 12:00:00.000"),
479 DateUtils.ceiling((Object) dateAmPm1, Calendar.AM_PM),
480 "ceiling ampm-1 failed");
481 assertEquals(dateTimeParser.parse("February 3, 2002 12:00:00.000"),
482 DateUtils.ceiling((Object) dateAmPm2, Calendar.AM_PM),
483 "ceiling ampm-2 failed");
484 assertEquals(dateTimeParser.parse("February 4, 2002 00:00:00.000"),
485 DateUtils.ceiling((Object) dateAmPm3, Calendar.AM_PM),
486 "ceiling ampm-3 failed");
487 assertEquals(dateTimeParser.parse("February 4, 2002 00:00:00.000"),
488 DateUtils.ceiling((Object) dateAmPm4, Calendar.AM_PM),
489 "ceiling ampm-4 failed");
490
491 assertEquals(dateTimeParser.parse("February 12, 2002 12:34:57.000"),
492 DateUtils.ceiling((Object) cal1, Calendar.SECOND),
493 "ceiling calendar second-1 failed");
494 assertEquals(dateTimeParser.parse("November 18, 2001 1:23:12.000"),
495 DateUtils.ceiling((Object) cal2, Calendar.SECOND),
496 "ceiling calendar second-2 failed");
497
498 assertEquals(dateTimeParser.parse("February 3, 2002 12:00:00.000"),
499 DateUtils.ceiling((Object) calAmPm1, Calendar.AM_PM),
500 "ceiling ampm-1 failed");
501 assertEquals(dateTimeParser.parse("February 3, 2002 12:00:00.000"),
502 DateUtils.ceiling((Object) calAmPm2, Calendar.AM_PM),
503 "ceiling ampm-2 failed");
504 assertEquals(dateTimeParser.parse("February 4, 2002 00:00:00.000"),
505 DateUtils.ceiling((Object) calAmPm3, Calendar.AM_PM),
506 "ceiling ampm-3 failed");
507 assertEquals(dateTimeParser.parse("February 4, 2002 00:00:00.000"),
508 DateUtils.ceiling((Object) calAmPm4, Calendar.AM_PM),
509 "ceiling ampm-4 failed");
510
511 assertThrows(NullPointerException.class, () -> DateUtils.ceiling((Date) null, Calendar.SECOND));
512 assertThrows(IllegalArgumentException.class, () -> DateUtils.ceiling((Calendar) null, Calendar.SECOND));
513 assertThrows(IllegalArgumentException.class, () -> DateUtils.ceiling((Object) null, Calendar.SECOND));
514 assertThrows(ClassCastException.class, () -> DateUtils.ceiling("", Calendar.SECOND));
515 assertThrows(IllegalArgumentException.class, () -> DateUtils.ceiling(date1, -9999));
516
517 // Fix for https://issues.apache.org/bugzilla/show_bug.cgi?id=25560
518 // Test ceiling across the beginning of daylight saving time
519 try {
520 TimeZone.setDefault(zone);
521 dateTimeParser.setTimeZone(zone);
522
523 assertEquals(dateTimeParser.parse("March 31, 2003 00:00:00.000"),
524 DateUtils.ceiling(date4, Calendar.DATE),
525 "ceiling MET date across DST change-over");
526 assertEquals(dateTimeParser.parse("March 31, 2003 00:00:00.000"),
527 DateUtils.ceiling((Object) cal4, Calendar.DATE),
528 "ceiling MET date across DST change-over");
529 assertEquals(dateTimeParser.parse("March 31, 2003 00:00:00.000"),
530 DateUtils.ceiling(date5, Calendar.DATE),
531 "ceiling MET date across DST change-over");
532 assertEquals(dateTimeParser.parse("March 31, 2003 00:00:00.000"),
533 DateUtils.ceiling((Object) cal5, Calendar.DATE),
534 "ceiling MET date across DST change-over");
535 assertEquals(dateTimeParser.parse("March 31, 2003 00:00:00.000"),
536 DateUtils.ceiling(date6, Calendar.DATE),
537 "ceiling MET date across DST change-over");
538 assertEquals(dateTimeParser.parse("March 31, 2003 00:00:00.000"),
539 DateUtils.ceiling((Object) cal6, Calendar.DATE),
540 "ceiling MET date across DST change-over");
541 assertEquals(dateTimeParser.parse("March 31, 2003 00:00:00.000"),
542 DateUtils.ceiling(date7, Calendar.DATE),
543 "ceiling MET date across DST change-over");
544 assertEquals(dateTimeParser.parse("March 31, 2003 00:00:00.000"),
545 DateUtils.ceiling((Object) cal7, Calendar.DATE),
546 "ceiling MET date across DST change-over");
547
548 assertEquals(dateTimeParser.parse("March 30, 2003 03:00:00.000"),
549 DateUtils.ceiling(date4, Calendar.HOUR_OF_DAY),
550 "ceiling MET date across DST change-over");
551 assertEquals(dateTimeParser.parse("March 30, 2003 03:00:00.000"),
552 DateUtils.ceiling((Object) cal4, Calendar.HOUR_OF_DAY),
553 "ceiling MET date across DST change-over");
554 assertEquals(dateTimeParser.parse("March 30, 2003 03:00:00.000"),
555 DateUtils.ceiling(date5, Calendar.HOUR_OF_DAY),
556 "ceiling MET date across DST change-over");
557 assertEquals(dateTimeParser.parse("March 30, 2003 03:00:00.000"),
558 DateUtils.ceiling((Object) cal5, Calendar.HOUR_OF_DAY),
559 "ceiling MET date across DST change-over");
560 assertEquals(dateTimeParser.parse("March 30, 2003 04:00:00.000"),
561 DateUtils.ceiling(date6, Calendar.HOUR_OF_DAY),
562 "ceiling MET date across DST change-over");
563 assertEquals(dateTimeParser.parse("March 30, 2003 04:00:00.000"),
564 DateUtils.ceiling((Object) cal6, Calendar.HOUR_OF_DAY),
565 "ceiling MET date across DST change-over");
566 assertEquals(dateTimeParser.parse("March 30, 2003 04:00:00.000"),
567 DateUtils.ceiling(date7, Calendar.HOUR_OF_DAY),
568 "ceiling MET date across DST change-over");
569 assertEquals(dateTimeParser.parse("March 30, 2003 04:00:00.000"),
570 DateUtils.ceiling((Object) cal7, Calendar.HOUR_OF_DAY),
571 "ceiling MET date across DST change-over");
572
573 } finally {
574 TimeZone.setDefault(defaultZone);
575 dateTimeParser.setTimeZone(defaultZone);
576 }
577
578 // Bug 31395, large dates
579 final Date endOfTime = new Date(Long.MAX_VALUE); // fyi: Sun Aug 17 07:12:55 CET 292278994 -- 807 millis
580 final GregorianCalendar endCal = new GregorianCalendar();
581 endCal.setTime(endOfTime);
582 assertThrows(ArithmeticException.class, () -> DateUtils.ceiling(endCal, Calendar.DATE));
583 endCal.set(Calendar.YEAR, 280000001);
584 assertThrows(ArithmeticException.class, () -> DateUtils.ceiling(endCal, Calendar.DATE));
585 endCal.set(Calendar.YEAR, 280000000);
586 final Calendar cal = DateUtils.ceiling(endCal, Calendar.DATE);
587 assertEquals(0, cal.get(Calendar.HOUR));
588 }
589
146590 @Test
147591 public void testConstructor() {
148592 assertNotNull(new DateUtils());
153597 assertFalse(Modifier.isFinal(DateUtils.class.getModifiers()));
154598 }
155599
156 //-----------------------------------------------------------------------
600 @Test
601 public void testIsSameDay_Cal() {
602 final GregorianCalendar cala = new GregorianCalendar(2004, 6, 9, 13, 45);
603 final GregorianCalendar calb = new GregorianCalendar(2004, 6, 9, 13, 45);
604 assertTrue(DateUtils.isSameDay(cala, calb));
605 calb.add(Calendar.DAY_OF_YEAR, 1);
606 assertFalse(DateUtils.isSameDay(cala, calb));
607 cala.add(Calendar.DAY_OF_YEAR, 1);
608 assertTrue(DateUtils.isSameDay(cala, calb));
609 calb.add(Calendar.YEAR, 1);
610 assertFalse(DateUtils.isSameDay(cala, calb));
611 }
612
613 @Test
614 public void testIsSameDay_CalNotNullNull() {
615 assertThrows(IllegalArgumentException.class, () -> DateUtils.isSameDay(Calendar.getInstance(), null));
616 }
617
618 @Test
619 public void testIsSameDay_CalNullNotNull() {
620 assertThrows(IllegalArgumentException.class, () -> DateUtils.isSameDay(null, Calendar.getInstance()));
621 }
622
623 @Test
624 public void testIsSameDay_CalNullNull() {
625 assertThrows(IllegalArgumentException.class, () -> DateUtils.isSameDay((Calendar) null, null));
626 }
627
157628 @Test
158629 public void testIsSameDay_Date() {
159630 Date datea = new GregorianCalendar(2004, 6, 9, 13, 45).getTime();
168639 }
169640
170641 @Test
642 public void testIsSameDay_DateNotNullNull() {
643 assertThrows(IllegalArgumentException.class, () -> DateUtils.isSameDay(new Date(), null));
644 }
645
646 @Test
647 public void testIsSameDay_DateNullNotNull() {
648 assertThrows(IllegalArgumentException.class, () -> DateUtils.isSameDay(null, new Date()));
649 }
650
651 @Test
171652 public void testIsSameDay_DateNullNull() {
172653 assertThrows(IllegalArgumentException.class, () -> DateUtils.isSameDay((Date) null, null));
173654 }
174655
175656 @Test
176 public void testIsSameDay_DateNullNotNull() {
177 assertThrows(IllegalArgumentException.class, () -> DateUtils.isSameDay(null, new Date()));
178 }
179
180 @Test
181 public void testIsSameDay_DateNotNullNull() {
182 assertThrows(IllegalArgumentException.class, () -> DateUtils.isSameDay(new Date(), null));
183 }
184
185 //-----------------------------------------------------------------------
186 @Test
187 public void testIsSameDay_Cal() {
188 final GregorianCalendar cala = new GregorianCalendar(2004, 6, 9, 13, 45);
189 final GregorianCalendar calb = new GregorianCalendar(2004, 6, 9, 13, 45);
190 assertTrue(DateUtils.isSameDay(cala, calb));
191 calb.add(Calendar.DAY_OF_YEAR, 1);
192 assertFalse(DateUtils.isSameDay(cala, calb));
193 cala.add(Calendar.DAY_OF_YEAR, 1);
194 assertTrue(DateUtils.isSameDay(cala, calb));
195 calb.add(Calendar.YEAR, 1);
196 assertFalse(DateUtils.isSameDay(cala, calb));
197 }
198
199 @Test
200 public void testIsSameDay_CalNullNull() {
201 assertThrows(IllegalArgumentException.class, () -> DateUtils.isSameDay((Calendar) null, null));
202 }
203
204 @Test
205 public void testIsSameDay_CalNullNotNull() {
206 assertThrows(IllegalArgumentException.class, () -> DateUtils.isSameDay(null, Calendar.getInstance()));
207 }
208
209 @Test
210 public void testIsSameDay_CalNotNullNull() {
211 assertThrows(IllegalArgumentException.class, () -> DateUtils.isSameDay(Calendar.getInstance(), null));
212 }
213
214 //-----------------------------------------------------------------------
657 public void testIsSameInstant_Cal() {
658 final GregorianCalendar cala = new GregorianCalendar(TimeZone.getTimeZone("GMT+1"));
659 final GregorianCalendar calb = new GregorianCalendar(TimeZone.getTimeZone("GMT-1"));
660 cala.set(2004, Calendar.JULY, 9, 13, 45, 0);
661 cala.set(Calendar.MILLISECOND, 0);
662 calb.set(2004, Calendar.JULY, 9, 13, 45, 0);
663 calb.set(Calendar.MILLISECOND, 0);
664 assertFalse(DateUtils.isSameInstant(cala, calb));
665
666 calb.set(2004, Calendar.JULY, 9, 11, 45, 0);
667 assertTrue(DateUtils.isSameInstant(cala, calb));
668 }
669
670 @Test
671 public void testIsSameInstant_CalNotNullNull() {
672 assertThrows(IllegalArgumentException.class, () -> DateUtils.isSameInstant(Calendar.getInstance(), null));
673 }
674
675 @Test
676 public void testIsSameInstant_CalNullNotNull() {
677 assertThrows(IllegalArgumentException.class, () -> DateUtils.isSameInstant(null, Calendar.getInstance()));
678 }
679
680 @Test
681 public void testIsSameInstant_CalNullNull() {
682 assertThrows(IllegalArgumentException.class, () -> DateUtils.isSameInstant((Calendar) null, null));
683 }
684
215685 @Test
216686 public void testIsSameInstant_Date() {
217687 Date datea = new GregorianCalendar(2004, 6, 9, 13, 45).getTime();
226696 }
227697
228698 @Test
699 public void testIsSameInstant_DateNotNullNull() {
700 assertThrows(IllegalArgumentException.class, () -> DateUtils.isSameInstant(new Date(), null));
701 }
702
703 @Test
704 public void testIsSameInstant_DateNullNotNull() {
705 assertThrows(IllegalArgumentException.class, () -> DateUtils.isSameInstant(null, new Date()));
706 }
707
708 @Test
229709 public void testIsSameInstant_DateNullNull() {
230710 assertThrows(IllegalArgumentException.class, () -> DateUtils.isSameInstant((Date) null, null));
231711 }
232712
233 @Test
234 public void testIsSameInstant_DateNullNotNull() {
235 assertThrows(IllegalArgumentException.class, () -> DateUtils.isSameInstant(null, new Date()));
236 }
237
238 @Test
239 public void testIsSameInstant_DateNotNullNull() {
240 assertThrows(IllegalArgumentException.class, () -> DateUtils.isSameInstant(new Date(), null));
241 }
242
243 //-----------------------------------------------------------------------
244 @Test
245 public void testIsSameInstant_Cal() {
246 final GregorianCalendar cala = new GregorianCalendar(TimeZone.getTimeZone("GMT+1"));
247 final GregorianCalendar calb = new GregorianCalendar(TimeZone.getTimeZone("GMT-1"));
248 cala.set(2004, Calendar.JULY, 9, 13, 45, 0);
249 cala.set(Calendar.MILLISECOND, 0);
250 calb.set(2004, Calendar.JULY, 9, 13, 45, 0);
251 calb.set(Calendar.MILLISECOND, 0);
252 assertFalse(DateUtils.isSameInstant(cala, calb));
253
254 calb.set(2004, Calendar.JULY, 9, 11, 45, 0);
255 assertTrue(DateUtils.isSameInstant(cala, calb));
256 }
257
258 @Test
259 public void testIsSameInstant_CalNullNull() {
260 assertThrows(IllegalArgumentException.class, () -> DateUtils.isSameInstant((Calendar) null, null));
261 }
262
263 @Test
264 public void testIsSameInstant_CalNullNotNull() {
265 assertThrows(IllegalArgumentException.class, () -> DateUtils.isSameInstant(null, Calendar.getInstance()));
266 }
267
268 @Test
269 public void testIsSameInstant_CalNotNullNull() {
270 assertThrows(IllegalArgumentException.class, () -> DateUtils.isSameInstant(Calendar.getInstance(), null));
271 }
272
273 //-----------------------------------------------------------------------
274713 @Test
275714 public void testIsSameLocalTime_Cal() {
276715 final GregorianCalendar cala = new GregorianCalendar(TimeZone.getTimeZone("GMT+1"));
294733 }
295734
296735 @Test
736 public void testIsSameLocalTime_CalNotNullNull() {
737 assertThrows(IllegalArgumentException.class, () -> DateUtils.isSameLocalTime(Calendar.getInstance(), null));
738 }
739
740 @Test
741 public void testIsSameLocalTime_CalNullNotNull() {
742 assertThrows(IllegalArgumentException.class, () -> DateUtils.isSameLocalTime(null, Calendar.getInstance()));
743 }
744
745 @Test
297746 public void testIsSameLocalTime_CalNullNull() {
298747 assertThrows(IllegalArgumentException.class, () -> DateUtils.isSameLocalTime(null, null));
299748 }
300749
301 @Test
302 public void testIsSameLocalTime_CalNullNotNull() {
303 assertThrows(IllegalArgumentException.class, () -> DateUtils.isSameLocalTime(null, Calendar.getInstance()));
304 }
305
306 @Test
307 public void testIsSameLocalTime_CalNotNullNull() {
308 assertThrows(IllegalArgumentException.class, () -> DateUtils.isSameLocalTime(Calendar.getInstance(), null));
309 }
310
311 //-----------------------------------------------------------------------
750 /**
751 * Tests the iterator exceptions
752 */
753 @Test
754 public void testIteratorEx() {
755 assertThrows(IllegalArgumentException.class, () -> DateUtils.iterator(Calendar.getInstance(), -9999));
756 assertThrows
757 (NullPointerException.class, () -> DateUtils.iterator((Date) null, DateUtils.RANGE_WEEK_CENTER));
758 assertThrows
759 (IllegalArgumentException.class, () -> DateUtils.iterator((Calendar) null, DateUtils.RANGE_WEEK_CENTER));
760 assertThrows
761 (IllegalArgumentException.class, () -> DateUtils.iterator((Object) null, DateUtils.RANGE_WEEK_CENTER));
762 assertThrows(ClassCastException.class, () -> DateUtils.iterator("", DateUtils.RANGE_WEEK_CENTER));
763 }
764
765 // https://issues.apache.org/jira/browse/LANG-530
766 @SuppressWarnings("deprecation")
767 @Test
768 public void testLang530() throws ParseException {
769 final Date d = new Date();
770 final String isoDateStr = DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.format(d);
771 final Date d2 = DateUtils.parseDate(isoDateStr, DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.getPattern());
772 // the format loses milliseconds so have to reintroduce them
773 assertEquals(d.getTime(), d2.getTime() + d.getTime() % 1000, "Date not equal to itself ISO formatted and parsed");
774 }
775
776 @Test
777 public void testLANG799() throws ParseException {
778 DateUtils.parseDateStrictly("09 abril 2008 23:55:38 GMT", new Locale("es"), "dd MMM yyyy HH:mm:ss zzz");
779 }
780
781 // Parse English date with German Locale
782 @DefaultLocale(language = "de")
783 @Test
784 public void testLANG799_DE_FAIL() {
785 assertThrows(ParseException.class, () -> DateUtils.parseDate("Wed, 09 Apr 2008 23:55:38 GMT", "EEE, dd MMM yyyy HH:mm:ss zzz"));
786 }
787
788 @DefaultLocale(language = "de")
789 @Test
790 public void testLANG799_DE_OK() throws ParseException {
791 DateUtils.parseDate("Mi, 09 Apr 2008 23:55:38 GMT", "EEE, dd MMM yyyy HH:mm:ss zzz");
792 DateUtils.parseDateStrictly("Mi, 09 Apr 2008 23:55:38 GMT", "EEE, dd MMM yyyy HH:mm:ss zzz");
793 }
794
795 // Parse German date with English Locale
796 @DefaultLocale(language = "en")
797 @Test
798 public void testLANG799_EN_FAIL() {
799 assertThrows(ParseException.class, () -> DateUtils.parseDate("Mi, 09 Apr 2008 23:55:38 GMT", "EEE, dd MMM yyyy HH:mm:ss zzz"));
800 }
801
802 @DefaultLocale(language = "en")
803 @Test
804 public void testLANG799_EN_OK() throws ParseException {
805 DateUtils.parseDate("Wed, 09 Apr 2008 23:55:38 GMT", "EEE, dd MMM yyyy HH:mm:ss zzz");
806 DateUtils.parseDateStrictly("Wed, 09 Apr 2008 23:55:38 GMT", "EEE, dd MMM yyyy HH:mm:ss zzz");
807 }
808
809 // Parse German date with English Locale, specifying German Locale override
810 @DefaultLocale(language = "en")
811 @Test
812 public void testLANG799_EN_WITH_DE_LOCALE() throws ParseException {
813 DateUtils.parseDate("Mi, 09 Apr 2008 23:55:38 GMT", Locale.GERMAN, "EEE, dd MMM yyyy HH:mm:ss zzz");
814 }
815
816 /**
817 * Tests the calendar iterator for month-based ranges
818 *
819 * @throws java.lang.Exception so we don't have to catch it
820 */
821 @Test
822 public void testMonthIterator() throws Exception {
823 Iterator<?> it = DateUtils.iterator(date1, DateUtils.RANGE_MONTH_SUNDAY);
824 assertWeekIterator(it,
825 dateParser.parse("January 27, 2002"),
826 dateParser.parse("March 2, 2002"));
827
828 it = DateUtils.iterator(date1, DateUtils.RANGE_MONTH_MONDAY);
829 assertWeekIterator(it,
830 dateParser.parse("January 28, 2002"),
831 dateParser.parse("March 3, 2002"));
832
833 it = DateUtils.iterator(date2, DateUtils.RANGE_MONTH_SUNDAY);
834 assertWeekIterator(it,
835 dateParser.parse("October 28, 2001"),
836 dateParser.parse("December 1, 2001"));
837
838 it = DateUtils.iterator(date2, DateUtils.RANGE_MONTH_MONDAY);
839 assertWeekIterator(it,
840 dateParser.parse("October 29, 2001"),
841 dateParser.parse("December 2, 2001"));
842 }
843
844 @Test
845 public void testParse_EmptyParsers() {
846 assertThrows(ParseException.class, () -> DateUtils.parseDate("19721203"));
847 }
848
849 @Test
850 public void testParse_NullParsers() {
851 assertThrows(IllegalArgumentException.class, () -> DateUtils.parseDate("19721203", (String[]) null));
852 }
853
312854 @Test
313855 public void testParseDate() throws Exception {
314856 final GregorianCalendar cal = new GregorianCalendar(1972, 11, 3);
315857 String dateStr = "1972-12-03";
316 final String[] parsers = new String[] {"yyyy'-'DDD", "yyyy'-'MM'-'dd", "yyyyMMdd"};
858 final String[] parsers = {"yyyy'-'DDD", "yyyy'-'MM'-'dd", "yyyyMMdd"};
317859 Date date = DateUtils.parseDate(dateStr, parsers);
318860 assertEquals(cal.getTime(), date);
319861
327869 }
328870
329871 @Test
872 public void testParseDate_InvalidDateString() {
873 final String[] parsers = {"yyyy'-'DDD", "yyyy'-'MM'-'dd", "yyyyMMdd"};
874 assertThrows(ParseException.class, () -> DateUtils.parseDate("197212AB", parsers));
875 }
876
877 @Test
330878 public void testParseDate_NoDateString() {
331 final String[] parsers = new String[] {"yyyy'-'DDD", "yyyy'-'MM'-'dd", "yyyyMMdd"};
879 final String[] parsers = {"yyyy'-'DDD", "yyyy'-'MM'-'dd", "yyyyMMdd"};
332880 assertThrows(ParseException.class, () -> DateUtils.parseDate("PURPLE", parsers));
333881 }
334882
335883 @Test
336 public void testParseDate_InvalidDateString() {
337 final String[] parsers = new String[] {"yyyy'-'DDD", "yyyy'-'MM'-'dd", "yyyyMMdd"};
338 assertThrows(ParseException.class, () -> DateUtils.parseDate("197212AB", parsers));
339 }
340
341 @Test
342884 public void testParseDate_Null() {
343 final String[] parsers = new String[] {"yyyy'-'DDD", "yyyy'-'MM'-'dd", "yyyyMMdd"};
885 final String[] parsers = {"yyyy'-'DDD", "yyyy'-'MM'-'dd", "yyyyMMdd"};
344886 assertThrows(IllegalArgumentException.class, () -> DateUtils.parseDate(null, parsers));
345 }
346
347 @Test
348 public void testParse_NullParsers() {
349 assertThrows(IllegalArgumentException.class, () -> DateUtils.parseDate("19721203", (String[]) null));
350 }
351
352 @Test
353 public void testParse_EmptyParsers() {
354 assertThrows(ParseException.class, () -> DateUtils.parseDate("19721203"));
355887 }
356888
357889 // LANG-486
359891 public void testParseDateWithLeniency() throws Exception {
360892 final GregorianCalendar cal = new GregorianCalendar(1998, 6, 30);
361893 final String dateStr = "02 942, 1996";
362 final String[] parsers = new String[] {"MM DDD, yyyy"};
894 final String[] parsers = {"MM DDD, yyyy"};
363895
364896 final Date date = DateUtils.parseDate(dateStr, parsers);
365897 assertEquals(cal.getTime(), date);
367899 assertThrows(ParseException.class, () -> DateUtils.parseDateStrictly(dateStr, parsers));
368900 }
369901
370 //-----------------------------------------------------------------------
371 @Test
372 public void testAddYears() throws Exception {
373 Date result = DateUtils.addYears(BASE_DATE, 0);
374 assertNotSame(BASE_DATE, result);
375 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
376 assertDate(result, 2000, 6, 5, 4, 3, 2, 1);
377
378 result = DateUtils.addYears(BASE_DATE, 1);
379 assertNotSame(BASE_DATE, result);
380 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
381 assertDate(result, 2001, 6, 5, 4, 3, 2, 1);
382
383 result = DateUtils.addYears(BASE_DATE, -1);
384 assertNotSame(BASE_DATE, result);
385 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
386 assertDate(result, 1999, 6, 5, 4, 3, 2, 1);
387 }
388
389 //-----------------------------------------------------------------------
390 @Test
391 public void testAddMonths() throws Exception {
392 Date result = DateUtils.addMonths(BASE_DATE, 0);
393 assertNotSame(BASE_DATE, result);
394 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
395 assertDate(result, 2000, 6, 5, 4, 3, 2, 1);
396
397 result = DateUtils.addMonths(BASE_DATE, 1);
398 assertNotSame(BASE_DATE, result);
399 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
400 assertDate(result, 2000, 7, 5, 4, 3, 2, 1);
401
402 result = DateUtils.addMonths(BASE_DATE, -1);
403 assertNotSame(BASE_DATE, result);
404 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
405 assertDate(result, 2000, 5, 5, 4, 3, 2, 1);
406 }
407
408 //-----------------------------------------------------------------------
409 @Test
410 public void testAddWeeks() throws Exception {
411 Date result = DateUtils.addWeeks(BASE_DATE, 0);
412 assertNotSame(BASE_DATE, result);
413 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
414 assertDate(result, 2000, 6, 5, 4, 3, 2, 1);
415
416 result = DateUtils.addWeeks(BASE_DATE, 1);
417 assertNotSame(BASE_DATE, result);
418 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
419 assertDate(result, 2000, 6, 12, 4, 3, 2, 1);
420
421 result = DateUtils.addWeeks(BASE_DATE, -1);
422 assertNotSame(BASE_DATE, result);
423 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1); // july
424 assertDate(result, 2000, 5, 28, 4, 3, 2, 1); // june
425 }
426
427 //-----------------------------------------------------------------------
428 @Test
429 public void testAddDays() throws Exception {
430 Date result = DateUtils.addDays(BASE_DATE, 0);
431 assertNotSame(BASE_DATE, result);
432 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
433 assertDate(result, 2000, 6, 5, 4, 3, 2, 1);
434
435 result = DateUtils.addDays(BASE_DATE, 1);
436 assertNotSame(BASE_DATE, result);
437 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
438 assertDate(result, 2000, 6, 6, 4, 3, 2, 1);
439
440 result = DateUtils.addDays(BASE_DATE, -1);
441 assertNotSame(BASE_DATE, result);
442 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
443 assertDate(result, 2000, 6, 4, 4, 3, 2, 1);
444 }
445
446 //-----------------------------------------------------------------------
447 @Test
448 public void testAddHours() throws Exception {
449 Date result = DateUtils.addHours(BASE_DATE, 0);
450 assertNotSame(BASE_DATE, result);
451 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
452 assertDate(result, 2000, 6, 5, 4, 3, 2, 1);
453
454 result = DateUtils.addHours(BASE_DATE, 1);
455 assertNotSame(BASE_DATE, result);
456 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
457 assertDate(result, 2000, 6, 5, 5, 3, 2, 1);
458
459 result = DateUtils.addHours(BASE_DATE, -1);
460 assertNotSame(BASE_DATE, result);
461 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
462 assertDate(result, 2000, 6, 5, 3, 3, 2, 1);
463 }
464
465 //-----------------------------------------------------------------------
466 @Test
467 public void testAddMinutes() throws Exception {
468 Date result = DateUtils.addMinutes(BASE_DATE, 0);
469 assertNotSame(BASE_DATE, result);
470 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
471 assertDate(result, 2000, 6, 5, 4, 3, 2, 1);
472
473 result = DateUtils.addMinutes(BASE_DATE, 1);
474 assertNotSame(BASE_DATE, result);
475 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
476 assertDate(result, 2000, 6, 5, 4, 4, 2, 1);
477
478 result = DateUtils.addMinutes(BASE_DATE, -1);
479 assertNotSame(BASE_DATE, result);
480 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
481 assertDate(result, 2000, 6, 5, 4, 2, 2, 1);
482 }
483
484 //-----------------------------------------------------------------------
485 @Test
486 public void testAddSeconds() throws Exception {
487 Date result = DateUtils.addSeconds(BASE_DATE, 0);
488 assertNotSame(BASE_DATE, result);
489 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
490 assertDate(result, 2000, 6, 5, 4, 3, 2, 1);
491
492 result = DateUtils.addSeconds(BASE_DATE, 1);
493 assertNotSame(BASE_DATE, result);
494 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
495 assertDate(result, 2000, 6, 5, 4, 3, 3, 1);
496
497 result = DateUtils.addSeconds(BASE_DATE, -1);
498 assertNotSame(BASE_DATE, result);
499 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
500 assertDate(result, 2000, 6, 5, 4, 3, 1, 1);
501 }
502
503 //-----------------------------------------------------------------------
504 @Test
505 public void testAddMilliseconds() throws Exception {
506 Date result = DateUtils.addMilliseconds(BASE_DATE, 0);
507 assertNotSame(BASE_DATE, result);
508 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
509 assertDate(result, 2000, 6, 5, 4, 3, 2, 1);
510
511 result = DateUtils.addMilliseconds(BASE_DATE, 1);
512 assertNotSame(BASE_DATE, result);
513 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
514 assertDate(result, 2000, 6, 5, 4, 3, 2, 2);
515
516 result = DateUtils.addMilliseconds(BASE_DATE, -1);
517 assertNotSame(BASE_DATE, result);
518 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
519 assertDate(result, 2000, 6, 5, 4, 3, 2, 0);
520 }
521
522 // -----------------------------------------------------------------------
523 @Test
524 public void testSetYears() throws Exception {
525 Date result = DateUtils.setYears(BASE_DATE, 2000);
526 assertNotSame(BASE_DATE, result);
527 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
528 assertDate(result, 2000, 6, 5, 4, 3, 2, 1);
529
530 result = DateUtils.setYears(BASE_DATE, 2008);
531 assertNotSame(BASE_DATE, result);
532 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
533 assertDate(result, 2008, 6, 5, 4, 3, 2, 1);
534
535 result = DateUtils.setYears(BASE_DATE, 2005);
536 assertNotSame(BASE_DATE, result);
537 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
538 assertDate(result, 2005, 6, 5, 4, 3, 2, 1);
539 }
540
541 // -----------------------------------------------------------------------
542 @Test
543 public void testSetMonths() throws Exception {
544 Date result = DateUtils.setMonths(BASE_DATE, 5);
545 assertNotSame(BASE_DATE, result);
546 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
547 assertDate(result, 2000, 5, 5, 4, 3, 2, 1);
548
549 result = DateUtils.setMonths(BASE_DATE, 1);
550 assertNotSame(BASE_DATE, result);
551 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
552 assertDate(result, 2000, 1, 5, 4, 3, 2, 1);
553
554 assertThrows(
555 IllegalArgumentException.class,
556 () -> DateUtils.setMonths(BASE_DATE, 12),
557 "DateUtils.setMonths did not throw an expected IllegalArgumentException.");
558 }
559
560 // -----------------------------------------------------------------------
561 @Test
562 public void testSetDays() throws Exception {
563 Date result = DateUtils.setDays(BASE_DATE, 1);
564 assertNotSame(BASE_DATE, result);
565 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
566 assertDate(result, 2000, 6, 1, 4, 3, 2, 1);
567
568 result = DateUtils.setDays(BASE_DATE, 29);
569 assertNotSame(BASE_DATE, result);
570 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
571 assertDate(result, 2000, 6, 29, 4, 3, 2, 1);
572
573 assertThrows(
574 IllegalArgumentException.class,
575 () -> DateUtils.setDays(BASE_DATE, 32),
576 "DateUtils.setDays did not throw an expected IllegalArgumentException.");
577 }
578
579 // -----------------------------------------------------------------------
580 @Test
581 public void testSetHours() throws Exception {
582 Date result = DateUtils.setHours(BASE_DATE, 0);
583 assertNotSame(BASE_DATE, result);
584 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
585 assertDate(result, 2000, 6, 5, 0, 3, 2, 1);
586
587 result = DateUtils.setHours(BASE_DATE, 23);
588 assertNotSame(BASE_DATE, result);
589 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
590 assertDate(result, 2000, 6, 5, 23, 3, 2, 1);
591
592 assertThrows(
593 IllegalArgumentException.class,
594 () -> DateUtils.setHours(BASE_DATE, 24),
595 "DateUtils.setHours did not throw an expected IllegalArgumentException.");
596 }
597
598 // -----------------------------------------------------------------------
599 @Test
600 public void testSetMinutes() throws Exception {
601 Date result = DateUtils.setMinutes(BASE_DATE, 0);
602 assertNotSame(BASE_DATE, result);
603 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
604 assertDate(result, 2000, 6, 5, 4, 0, 2, 1);
605
606 result = DateUtils.setMinutes(BASE_DATE, 59);
607 assertNotSame(BASE_DATE, result);
608 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
609 assertDate(result, 2000, 6, 5, 4, 59, 2, 1);
610
611 assertThrows(
612 IllegalArgumentException.class,
613 () -> DateUtils.setMinutes(BASE_DATE, 60),
614 "DateUtils.setMinutes did not throw an expected IllegalArgumentException.");
615 }
616
617 // -----------------------------------------------------------------------
618 @Test
619 public void testSetSeconds() throws Exception {
620 Date result = DateUtils.setSeconds(BASE_DATE, 0);
621 assertNotSame(BASE_DATE, result);
622 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
623 assertDate(result, 2000, 6, 5, 4, 3, 0, 1);
624
625 result = DateUtils.setSeconds(BASE_DATE, 59);
626 assertNotSame(BASE_DATE, result);
627 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
628 assertDate(result, 2000, 6, 5, 4, 3, 59, 1);
629
630 assertThrows(
631 IllegalArgumentException.class,
632 () -> DateUtils.setSeconds(BASE_DATE, 60),
633 "DateUtils.setSeconds did not throw an expected IllegalArgumentException.");
634 }
635
636 // -----------------------------------------------------------------------
637 @Test
638 public void testSetMilliseconds() throws Exception {
639 Date result = DateUtils.setMilliseconds(BASE_DATE, 0);
640 assertNotSame(BASE_DATE, result);
641 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
642 assertDate(result, 2000, 6, 5, 4, 3, 2, 0);
643
644 result = DateUtils.setMilliseconds(BASE_DATE, 999);
645 assertNotSame(BASE_DATE, result);
646 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
647 assertDate(result, 2000, 6, 5, 4, 3, 2, 999);
648
649 assertThrows(
650 IllegalArgumentException.class,
651 () -> DateUtils.setMilliseconds(BASE_DATE, 1000),
652 "DateUtils.setMilliseconds did not throw an expected IllegalArgumentException.");
653 }
654
655 //-----------------------------------------------------------------------
656 private void assertDate(final Date date, final int year, final int month, final int day, final int hour, final int min, final int sec, final int mil) {
657 final GregorianCalendar cal = new GregorianCalendar();
658 cal.setTime(date);
659 assertEquals(year, cal.get(Calendar.YEAR));
660 assertEquals(month, cal.get(Calendar.MONTH));
661 assertEquals(day, cal.get(Calendar.DAY_OF_MONTH));
662 assertEquals(hour, cal.get(Calendar.HOUR_OF_DAY));
663 assertEquals(min, cal.get(Calendar.MINUTE));
664 assertEquals(sec, cal.get(Calendar.SECOND));
665 assertEquals(mil, cal.get(Calendar.MILLISECOND));
666 }
667
668 //-----------------------------------------------------------------------
669 @Test
670 public void testToCalendar() {
671 assertEquals(date1, DateUtils.toCalendar(date1).getTime(), "Failed to convert to a Calendar and back");
672 assertThrows(NullPointerException.class, () -> DateUtils.toCalendar(null));
673 }
674
675 //-----------------------------------------------------------------------
676 @Test
677 public void testToCalendarWithDateNull() {
678 assertThrows(NullPointerException.class, () -> DateUtils.toCalendar(null, zone));
679 }
680
681 //-----------------------------------------------------------------------
682 @Test
683 public void testToCalendarWithTimeZoneNull() {
684 assertThrows(NullPointerException.class, () -> DateUtils.toCalendar(date1, null));
685 }
686
687 //-----------------------------------------------------------------------
688 @Test
689 public void testToCalendarWithDateAndTimeZoneNotNull() {
690 final Calendar c = DateUtils.toCalendar(date2, defaultZone);
691 assertEquals(date2, c.getTime(), "Convert Date and TimeZone to a Calendar, but failed to get the Date back");
692 assertEquals(defaultZone, c.getTimeZone(), "Convert Date and TimeZone to a Calendar, but failed to get the TimeZone back");
693 }
694
695 //-----------------------------------------------------------------------
696 @Test
697 public void testToCalendarWithDateAndTimeZoneNull() {
698 assertThrows(NullPointerException.class, () -> DateUtils.toCalendar(null, null));
699 }
700
701 //-----------------------------------------------------------------------
702902 /**
703903 * Tests various values with the round method
704904 *
9711171 "Hour Round Up Failed");
9721172 }
9731173
1174 // -----------------------------------------------------------------------
1175 @Test
1176 public void testSetDays() throws Exception {
1177 Date result = DateUtils.setDays(BASE_DATE, 1);
1178 assertNotSame(BASE_DATE, result);
1179 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
1180 assertDate(result, 2000, 6, 1, 4, 3, 2, 1);
1181
1182 result = DateUtils.setDays(BASE_DATE, 29);
1183 assertNotSame(BASE_DATE, result);
1184 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
1185 assertDate(result, 2000, 6, 29, 4, 3, 2, 1);
1186
1187 assertThrows(
1188 IllegalArgumentException.class,
1189 () -> DateUtils.setDays(BASE_DATE, 32),
1190 "DateUtils.setDays did not throw an expected IllegalArgumentException.");
1191 }
1192
1193 // -----------------------------------------------------------------------
1194 @Test
1195 public void testSetHours() throws Exception {
1196 Date result = DateUtils.setHours(BASE_DATE, 0);
1197 assertNotSame(BASE_DATE, result);
1198 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
1199 assertDate(result, 2000, 6, 5, 0, 3, 2, 1);
1200
1201 result = DateUtils.setHours(BASE_DATE, 23);
1202 assertNotSame(BASE_DATE, result);
1203 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
1204 assertDate(result, 2000, 6, 5, 23, 3, 2, 1);
1205
1206 assertThrows(
1207 IllegalArgumentException.class,
1208 () -> DateUtils.setHours(BASE_DATE, 24),
1209 "DateUtils.setHours did not throw an expected IllegalArgumentException.");
1210 }
1211
1212 // -----------------------------------------------------------------------
1213 @Test
1214 public void testSetMilliseconds() throws Exception {
1215 Date result = DateUtils.setMilliseconds(BASE_DATE, 0);
1216 assertNotSame(BASE_DATE, result);
1217 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
1218 assertDate(result, 2000, 6, 5, 4, 3, 2, 0);
1219
1220 result = DateUtils.setMilliseconds(BASE_DATE, 999);
1221 assertNotSame(BASE_DATE, result);
1222 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
1223 assertDate(result, 2000, 6, 5, 4, 3, 2, 999);
1224
1225 assertThrows(
1226 IllegalArgumentException.class,
1227 () -> DateUtils.setMilliseconds(BASE_DATE, 1000),
1228 "DateUtils.setMilliseconds did not throw an expected IllegalArgumentException.");
1229 }
1230
1231 // -----------------------------------------------------------------------
1232 @Test
1233 public void testSetMinutes() throws Exception {
1234 Date result = DateUtils.setMinutes(BASE_DATE, 0);
1235 assertNotSame(BASE_DATE, result);
1236 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
1237 assertDate(result, 2000, 6, 5, 4, 0, 2, 1);
1238
1239 result = DateUtils.setMinutes(BASE_DATE, 59);
1240 assertNotSame(BASE_DATE, result);
1241 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
1242 assertDate(result, 2000, 6, 5, 4, 59, 2, 1);
1243
1244 assertThrows(
1245 IllegalArgumentException.class,
1246 () -> DateUtils.setMinutes(BASE_DATE, 60),
1247 "DateUtils.setMinutes did not throw an expected IllegalArgumentException.");
1248 }
1249
1250 // -----------------------------------------------------------------------
1251 @Test
1252 public void testSetMonths() throws Exception {
1253 Date result = DateUtils.setMonths(BASE_DATE, 5);
1254 assertNotSame(BASE_DATE, result);
1255 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
1256 assertDate(result, 2000, 5, 5, 4, 3, 2, 1);
1257
1258 result = DateUtils.setMonths(BASE_DATE, 1);
1259 assertNotSame(BASE_DATE, result);
1260 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
1261 assertDate(result, 2000, 1, 5, 4, 3, 2, 1);
1262
1263 assertThrows(
1264 IllegalArgumentException.class,
1265 () -> DateUtils.setMonths(BASE_DATE, 12),
1266 "DateUtils.setMonths did not throw an expected IllegalArgumentException.");
1267 }
1268
1269 // -----------------------------------------------------------------------
1270 @Test
1271 public void testSetSeconds() throws Exception {
1272 Date result = DateUtils.setSeconds(BASE_DATE, 0);
1273 assertNotSame(BASE_DATE, result);
1274 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
1275 assertDate(result, 2000, 6, 5, 4, 3, 0, 1);
1276
1277 result = DateUtils.setSeconds(BASE_DATE, 59);
1278 assertNotSame(BASE_DATE, result);
1279 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
1280 assertDate(result, 2000, 6, 5, 4, 3, 59, 1);
1281
1282 assertThrows(
1283 IllegalArgumentException.class,
1284 () -> DateUtils.setSeconds(BASE_DATE, 60),
1285 "DateUtils.setSeconds did not throw an expected IllegalArgumentException.");
1286 }
1287
1288 // -----------------------------------------------------------------------
1289 @Test
1290 public void testSetYears() throws Exception {
1291 Date result = DateUtils.setYears(BASE_DATE, 2000);
1292 assertNotSame(BASE_DATE, result);
1293 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
1294 assertDate(result, 2000, 6, 5, 4, 3, 2, 1);
1295
1296 result = DateUtils.setYears(BASE_DATE, 2008);
1297 assertNotSame(BASE_DATE, result);
1298 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
1299 assertDate(result, 2008, 6, 5, 4, 3, 2, 1);
1300
1301 result = DateUtils.setYears(BASE_DATE, 2005);
1302 assertNotSame(BASE_DATE, result);
1303 assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
1304 assertDate(result, 2005, 6, 5, 4, 3, 2, 1);
1305 }
1306
1307 @Test
1308 public void testToCalendar() {
1309 assertEquals(date1, DateUtils.toCalendar(date1).getTime(), "Failed to convert to a Calendar and back");
1310 assertThrows(NullPointerException.class, () -> DateUtils.toCalendar(null));
1311 }
1312
1313 @Test
1314 public void testToCalendarWithDateAndTimeZoneNotNull() {
1315 final Calendar c = DateUtils.toCalendar(date2, defaultZone);
1316 assertEquals(date2, c.getTime(), "Convert Date and TimeZone to a Calendar, but failed to get the Date back");
1317 assertEquals(defaultZone, c.getTimeZone(), "Convert Date and TimeZone to a Calendar, but failed to get the TimeZone back");
1318 }
1319
1320 @Test
1321 public void testToCalendarWithDateAndTimeZoneNull() {
1322 assertThrows(NullPointerException.class, () -> DateUtils.toCalendar(null, null));
1323 }
1324
1325 @Test
1326 public void testToCalendarWithDateNull() {
1327 assertThrows(NullPointerException.class, () -> DateUtils.toCalendar(null, zone));
1328 }
1329
1330 @Test
1331 public void testToCalendarWithTimeZoneNull() {
1332 assertThrows(NullPointerException.class, () -> DateUtils.toCalendar(date1, null));
1333 }
1334
9741335 /**
9751336 * Tests various values with the trunc method
9761337 *
12261587 }
12271588 }
12281589
1229 // https://issues.apache.org/jira/browse/LANG-530
1230 @SuppressWarnings("deprecation")
1231 @Test
1232 public void testLang530() throws ParseException {
1233 final Date d = new Date();
1234 final String isoDateStr = DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.format(d);
1235 final Date d2 = DateUtils.parseDate(isoDateStr, DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.getPattern());
1236 // the format loses milliseconds so have to reintroduce them
1237 assertEquals(d.getTime(), d2.getTime() + d.getTime() % 1000, "Date not equal to itself ISO formatted and parsed");
1238 }
1239
1240 /**
1241 * Tests various values with the ceiling method
1242 *
1243 * @throws java.lang.Exception so we don't have to catch it
1244 */
1245 @Test
1246 public void testCeil() throws Exception {
1247 // test javadoc
1248 assertEquals(dateTimeParser.parse("March 28, 2002 14:00:00.000"),
1249 DateUtils.ceiling(
1250 dateTimeParser.parse("March 28, 2002 13:45:01.231"),
1251 Calendar.HOUR),
1252 "ceiling javadoc-1 failed");
1253 assertEquals(dateTimeParser.parse("April 1, 2002 00:00:00.000"),
1254 DateUtils.ceiling(
1255 dateTimeParser.parse("March 28, 2002 13:45:01.231"),
1256 Calendar.MONTH),
1257 "ceiling javadoc-2 failed");
1258
1259 // tests public static Date ceiling(Date date, int field)
1260 assertEquals(dateParser.parse("January 1, 2003"),
1261 DateUtils.ceiling(date1, Calendar.YEAR),
1262 "ceiling year-1 failed");
1263 assertEquals(dateParser.parse("January 1, 2002"),
1264 DateUtils.ceiling(date2, Calendar.YEAR),
1265 "ceiling year-2 failed");
1266 assertEquals(dateParser.parse("March 1, 2002"),
1267 DateUtils.ceiling(date1, Calendar.MONTH),
1268 "ceiling month-1 failed");
1269 assertEquals(dateParser.parse("December 1, 2001"),
1270 DateUtils.ceiling(date2, Calendar.MONTH),
1271 "ceiling month-2 failed");
1272 assertEquals(dateParser.parse("February 16, 2002"),
1273 DateUtils.ceiling(date1, DateUtils.SEMI_MONTH),
1274 "ceiling semimonth-1 failed");
1275 assertEquals(dateParser.parse("December 1, 2001"),
1276 DateUtils.ceiling(date2, DateUtils.SEMI_MONTH),
1277 "ceiling semimonth-2 failed");
1278 assertEquals(dateParser.parse("February 13, 2002"),
1279 DateUtils.ceiling(date1, Calendar.DATE),
1280 "ceiling date-1 failed");
1281 assertEquals(dateParser.parse("November 19, 2001"),
1282 DateUtils.ceiling(date2, Calendar.DATE),
1283 "ceiling date-2 failed");
1284 assertEquals(dateTimeParser.parse("February 12, 2002 13:00:00.000"),
1285 DateUtils.ceiling(date1, Calendar.HOUR),
1286 "ceiling hour-1 failed");
1287 assertEquals(dateTimeParser.parse("November 18, 2001 2:00:00.000"),
1288 DateUtils.ceiling(date2, Calendar.HOUR),
1289 "ceiling hour-2 failed");
1290 assertEquals(dateTimeParser.parse("February 12, 2002 12:35:00.000"),
1291 DateUtils.ceiling(date1, Calendar.MINUTE),
1292 "ceiling minute-1 failed");
1293 assertEquals(dateTimeParser.parse("November 18, 2001 1:24:00.000"),
1294 DateUtils.ceiling(date2, Calendar.MINUTE),
1295 "ceiling minute-2 failed");
1296 assertEquals(dateTimeParser.parse("February 12, 2002 12:34:57.000"),
1297 DateUtils.ceiling(date1, Calendar.SECOND),
1298 "ceiling second-1 failed");
1299 assertEquals(dateTimeParser.parse("November 18, 2001 1:23:12.000"),
1300 DateUtils.ceiling(date2, Calendar.SECOND),
1301 "ceiling second-2 failed");
1302 assertEquals(dateTimeParser.parse("February 3, 2002 12:00:00.000"),
1303 DateUtils.ceiling(dateAmPm1, Calendar.AM_PM),
1304 "ceiling ampm-1 failed");
1305 assertEquals(dateTimeParser.parse("February 3, 2002 12:00:00.000"),
1306 DateUtils.ceiling(dateAmPm2, Calendar.AM_PM),
1307 "ceiling ampm-2 failed");
1308 assertEquals(dateTimeParser.parse("February 4, 2002 00:00:00.000"),
1309 DateUtils.ceiling(dateAmPm3, Calendar.AM_PM),
1310 "ceiling ampm-3 failed");
1311 assertEquals(dateTimeParser.parse("February 4, 2002 00:00:00.000"),
1312 DateUtils.ceiling(dateAmPm4, Calendar.AM_PM),
1313 "ceiling ampm-4 failed");
1314
1315 // tests public static Date ceiling(Object date, int field)
1316 assertEquals(dateParser.parse("January 1, 2003"),
1317 DateUtils.ceiling((Object) date1, Calendar.YEAR),
1318 "ceiling year-1 failed");
1319 assertEquals(dateParser.parse("January 1, 2002"),
1320 DateUtils.ceiling((Object) date2, Calendar.YEAR),
1321 "ceiling year-2 failed");
1322 assertEquals(dateParser.parse("March 1, 2002"),
1323 DateUtils.ceiling((Object) date1, Calendar.MONTH),
1324 "ceiling month-1 failed");
1325 assertEquals(dateParser.parse("December 1, 2001"),
1326 DateUtils.ceiling((Object) date2, Calendar.MONTH),
1327 "ceiling month-2 failed");
1328 assertEquals(dateParser.parse("February 16, 2002"),
1329 DateUtils.ceiling((Object) date1, DateUtils.SEMI_MONTH),
1330 "ceiling semimonth-1 failed");
1331 assertEquals(dateParser.parse("December 1, 2001"),
1332 DateUtils.ceiling((Object) date2, DateUtils.SEMI_MONTH),
1333 "ceiling semimonth-2 failed");
1334 assertEquals(dateParser.parse("February 13, 2002"),
1335 DateUtils.ceiling((Object) date1, Calendar.DATE),
1336 "ceiling date-1 failed");
1337 assertEquals(dateParser.parse("November 19, 2001"),
1338 DateUtils.ceiling((Object) date2, Calendar.DATE),
1339 "ceiling date-2 failed");
1340 assertEquals(dateTimeParser.parse("February 12, 2002 13:00:00.000"),
1341 DateUtils.ceiling((Object) date1, Calendar.HOUR),
1342 "ceiling hour-1 failed");
1343 assertEquals(dateTimeParser.parse("November 18, 2001 2:00:00.000"),
1344 DateUtils.ceiling((Object) date2, Calendar.HOUR),
1345 "ceiling hour-2 failed");
1346 assertEquals(dateTimeParser.parse("February 12, 2002 12:35:00.000"),
1347 DateUtils.ceiling((Object) date1, Calendar.MINUTE),
1348 "ceiling minute-1 failed");
1349 assertEquals(dateTimeParser.parse("November 18, 2001 1:24:00.000"),
1350 DateUtils.ceiling((Object) date2, Calendar.MINUTE),
1351 "ceiling minute-2 failed");
1352 assertEquals(dateTimeParser.parse("February 12, 2002 12:34:57.000"),
1353 DateUtils.ceiling((Object) date1, Calendar.SECOND),
1354 "ceiling second-1 failed");
1355 assertEquals(dateTimeParser.parse("November 18, 2001 1:23:12.000"),
1356 DateUtils.ceiling((Object) date2, Calendar.SECOND),
1357 "ceiling second-2 failed");
1358 assertEquals(dateTimeParser.parse("February 3, 2002 12:00:00.000"),
1359 DateUtils.ceiling((Object) dateAmPm1, Calendar.AM_PM),
1360 "ceiling ampm-1 failed");
1361 assertEquals(dateTimeParser.parse("February 3, 2002 12:00:00.000"),
1362 DateUtils.ceiling((Object) dateAmPm2, Calendar.AM_PM),
1363 "ceiling ampm-2 failed");
1364 assertEquals(dateTimeParser.parse("February 4, 2002 00:00:00.000"),
1365 DateUtils.ceiling((Object) dateAmPm3, Calendar.AM_PM),
1366 "ceiling ampm-3 failed");
1367 assertEquals(dateTimeParser.parse("February 4, 2002 00:00:00.000"),
1368 DateUtils.ceiling((Object) dateAmPm4, Calendar.AM_PM),
1369 "ceiling ampm-4 failed");
1370
1371 assertEquals(dateTimeParser.parse("February 12, 2002 12:34:57.000"),
1372 DateUtils.ceiling((Object) cal1, Calendar.SECOND),
1373 "ceiling calendar second-1 failed");
1374 assertEquals(dateTimeParser.parse("November 18, 2001 1:23:12.000"),
1375 DateUtils.ceiling((Object) cal2, Calendar.SECOND),
1376 "ceiling calendar second-2 failed");
1377
1378 assertEquals(dateTimeParser.parse("February 3, 2002 12:00:00.000"),
1379 DateUtils.ceiling((Object) calAmPm1, Calendar.AM_PM),
1380 "ceiling ampm-1 failed");
1381 assertEquals(dateTimeParser.parse("February 3, 2002 12:00:00.000"),
1382 DateUtils.ceiling((Object) calAmPm2, Calendar.AM_PM),
1383 "ceiling ampm-2 failed");
1384 assertEquals(dateTimeParser.parse("February 4, 2002 00:00:00.000"),
1385 DateUtils.ceiling((Object) calAmPm3, Calendar.AM_PM),
1386 "ceiling ampm-3 failed");
1387 assertEquals(dateTimeParser.parse("February 4, 2002 00:00:00.000"),
1388 DateUtils.ceiling((Object) calAmPm4, Calendar.AM_PM),
1389 "ceiling ampm-4 failed");
1390
1391 assertThrows(NullPointerException.class, () -> DateUtils.ceiling((Date) null, Calendar.SECOND));
1392 assertThrows(IllegalArgumentException.class, () -> DateUtils.ceiling((Calendar) null, Calendar.SECOND));
1393 assertThrows(IllegalArgumentException.class, () -> DateUtils.ceiling((Object) null, Calendar.SECOND));
1394 assertThrows(ClassCastException.class, () -> DateUtils.ceiling("", Calendar.SECOND));
1395 assertThrows(IllegalArgumentException.class, () -> DateUtils.ceiling(date1, -9999));
1396
1397 // Fix for https://issues.apache.org/bugzilla/show_bug.cgi?id=25560
1398 // Test ceiling across the beginning of daylight saving time
1399 try {
1400 TimeZone.setDefault(zone);
1401 dateTimeParser.setTimeZone(zone);
1402
1403 assertEquals(dateTimeParser.parse("March 31, 2003 00:00:00.000"),
1404 DateUtils.ceiling(date4, Calendar.DATE),
1405 "ceiling MET date across DST change-over");
1406 assertEquals(dateTimeParser.parse("March 31, 2003 00:00:00.000"),
1407 DateUtils.ceiling((Object) cal4, Calendar.DATE),
1408 "ceiling MET date across DST change-over");
1409 assertEquals(dateTimeParser.parse("March 31, 2003 00:00:00.000"),
1410 DateUtils.ceiling(date5, Calendar.DATE),
1411 "ceiling MET date across DST change-over");
1412 assertEquals(dateTimeParser.parse("March 31, 2003 00:00:00.000"),
1413 DateUtils.ceiling((Object) cal5, Calendar.DATE),
1414 "ceiling MET date across DST change-over");
1415 assertEquals(dateTimeParser.parse("March 31, 2003 00:00:00.000"),
1416 DateUtils.ceiling(date6, Calendar.DATE),
1417 "ceiling MET date across DST change-over");
1418 assertEquals(dateTimeParser.parse("March 31, 2003 00:00:00.000"),
1419 DateUtils.ceiling((Object) cal6, Calendar.DATE),
1420 "ceiling MET date across DST change-over");
1421 assertEquals(dateTimeParser.parse("March 31, 2003 00:00:00.000"),
1422 DateUtils.ceiling(date7, Calendar.DATE),
1423 "ceiling MET date across DST change-over");
1424 assertEquals(dateTimeParser.parse("March 31, 2003 00:00:00.000"),
1425 DateUtils.ceiling((Object) cal7, Calendar.DATE),
1426 "ceiling MET date across DST change-over");
1427
1428 assertEquals(dateTimeParser.parse("March 30, 2003 03:00:00.000"),
1429 DateUtils.ceiling(date4, Calendar.HOUR_OF_DAY),
1430 "ceiling MET date across DST change-over");
1431 assertEquals(dateTimeParser.parse("March 30, 2003 03:00:00.000"),
1432 DateUtils.ceiling((Object) cal4, Calendar.HOUR_OF_DAY),
1433 "ceiling MET date across DST change-over");
1434 assertEquals(dateTimeParser.parse("March 30, 2003 03:00:00.000"),
1435 DateUtils.ceiling(date5, Calendar.HOUR_OF_DAY),
1436 "ceiling MET date across DST change-over");
1437 assertEquals(dateTimeParser.parse("March 30, 2003 03:00:00.000"),
1438 DateUtils.ceiling((Object) cal5, Calendar.HOUR_OF_DAY),
1439 "ceiling MET date across DST change-over");
1440 assertEquals(dateTimeParser.parse("March 30, 2003 04:00:00.000"),
1441 DateUtils.ceiling(date6, Calendar.HOUR_OF_DAY),
1442 "ceiling MET date across DST change-over");
1443 assertEquals(dateTimeParser.parse("March 30, 2003 04:00:00.000"),
1444 DateUtils.ceiling((Object) cal6, Calendar.HOUR_OF_DAY),
1445 "ceiling MET date across DST change-over");
1446 assertEquals(dateTimeParser.parse("March 30, 2003 04:00:00.000"),
1447 DateUtils.ceiling(date7, Calendar.HOUR_OF_DAY),
1448 "ceiling MET date across DST change-over");
1449 assertEquals(dateTimeParser.parse("March 30, 2003 04:00:00.000"),
1450 DateUtils.ceiling((Object) cal7, Calendar.HOUR_OF_DAY),
1451 "ceiling MET date across DST change-over");
1452
1453 } finally {
1454 TimeZone.setDefault(defaultZone);
1455 dateTimeParser.setTimeZone(defaultZone);
1456 }
1457
1458 // Bug 31395, large dates
1459 final Date endOfTime = new Date(Long.MAX_VALUE); // fyi: Sun Aug 17 07:12:55 CET 292278994 -- 807 millis
1460 final GregorianCalendar endCal = new GregorianCalendar();
1461 endCal.setTime(endOfTime);
1462 assertThrows(ArithmeticException.class, () -> DateUtils.ceiling(endCal, Calendar.DATE));
1463 endCal.set(Calendar.YEAR, 280000001);
1464 assertThrows(ArithmeticException.class, () -> DateUtils.ceiling(endCal, Calendar.DATE));
1465 endCal.set(Calendar.YEAR, 280000000);
1466 final Calendar cal = DateUtils.ceiling(endCal, Calendar.DATE);
1467 assertEquals(0, cal.get(Calendar.HOUR));
1468 }
1469
1470 /**
1471 * Tests the iterator exceptions
1472 */
1473 @Test
1474 public void testIteratorEx() {
1475 assertThrows(IllegalArgumentException.class, () -> DateUtils.iterator(Calendar.getInstance(), -9999));
1476 assertThrows
1477 (NullPointerException.class, () -> DateUtils.iterator((Date) null, DateUtils.RANGE_WEEK_CENTER));
1478 assertThrows
1479 (IllegalArgumentException.class, () -> DateUtils.iterator((Calendar) null, DateUtils.RANGE_WEEK_CENTER));
1480 assertThrows
1481 (IllegalArgumentException.class, () -> DateUtils.iterator((Object) null, DateUtils.RANGE_WEEK_CENTER));
1482 assertThrows(ClassCastException.class, () -> DateUtils.iterator("", DateUtils.RANGE_WEEK_CENTER));
1483 }
1484
14851590 /**
14861591 * Tests the calendar iterator for week ranges
14871592 */
15231628 now.add(Calendar.DATE, 1);
15241629 }
15251630 }
1526
1527 /**
1528 * Tests the calendar iterator for month-based ranges
1529 *
1530 * @throws java.lang.Exception so we don't have to catch it
1531 */
1532 @Test
1533 public void testMonthIterator() throws Exception {
1534 Iterator<?> it = DateUtils.iterator(date1, DateUtils.RANGE_MONTH_SUNDAY);
1535 assertWeekIterator(it,
1536 dateParser.parse("January 27, 2002"),
1537 dateParser.parse("March 2, 2002"));
1538
1539 it = DateUtils.iterator(date1, DateUtils.RANGE_MONTH_MONDAY);
1540 assertWeekIterator(it,
1541 dateParser.parse("January 28, 2002"),
1542 dateParser.parse("March 3, 2002"));
1543
1544 it = DateUtils.iterator(date2, DateUtils.RANGE_MONTH_SUNDAY);
1545 assertWeekIterator(it,
1546 dateParser.parse("October 28, 2001"),
1547 dateParser.parse("December 1, 2001"));
1548
1549 it = DateUtils.iterator(date2, DateUtils.RANGE_MONTH_MONDAY);
1550 assertWeekIterator(it,
1551 dateParser.parse("October 29, 2001"),
1552 dateParser.parse("December 2, 2001"));
1553 }
1554
1555 @DefaultLocale(language = "en")
1556 @Test
1557 public void testLANG799_EN_OK() throws ParseException {
1558 DateUtils.parseDate("Wed, 09 Apr 2008 23:55:38 GMT", "EEE, dd MMM yyyy HH:mm:ss zzz");
1559 DateUtils.parseDateStrictly("Wed, 09 Apr 2008 23:55:38 GMT", "EEE, dd MMM yyyy HH:mm:ss zzz");
1560 }
1561
1562 // Parse German date with English Locale
1563 @DefaultLocale(language = "en")
1564 @Test
1565 public void testLANG799_EN_FAIL() {
1566 assertThrows(ParseException.class, () -> DateUtils.parseDate("Mi, 09 Apr 2008 23:55:38 GMT", "EEE, dd MMM yyyy HH:mm:ss zzz"));
1567 }
1568
1569 @DefaultLocale(language = "de")
1570 @Test
1571 public void testLANG799_DE_OK() throws ParseException {
1572 DateUtils.parseDate("Mi, 09 Apr 2008 23:55:38 GMT", "EEE, dd MMM yyyy HH:mm:ss zzz");
1573 DateUtils.parseDateStrictly("Mi, 09 Apr 2008 23:55:38 GMT", "EEE, dd MMM yyyy HH:mm:ss zzz");
1574 }
1575
1576 // Parse English date with German Locale
1577 @DefaultLocale(language = "de")
1578 @Test
1579 public void testLANG799_DE_FAIL() {
1580 assertThrows(ParseException.class, () -> DateUtils.parseDate("Wed, 09 Apr 2008 23:55:38 GMT", "EEE, dd MMM yyyy HH:mm:ss zzz"));
1581 }
1582
1583 // Parse German date with English Locale, specifying German Locale override
1584 @DefaultLocale(language = "en")
1585 @Test
1586 public void testLANG799_EN_WITH_DE_LOCALE() throws ParseException {
1587 DateUtils.parseDate("Mi, 09 Apr 2008 23:55:38 GMT", Locale.GERMAN, "EEE, dd MMM yyyy HH:mm:ss zzz");
1588 }
1589
1590 /**
1591 * This checks that this is a 7 element iterator of Calendar objects
1592 * that are dates (no time), and exactly 1 day spaced after each other.
1593 */
1594 private static void assertWeekIterator(final Iterator<?> it, final Calendar start) {
1595 final Calendar end = (Calendar) start.clone();
1596 end.add(Calendar.DATE, 6);
1597
1598 assertWeekIterator(it, start, end);
1599 }
1600
1601 /**
1602 * Convenience method for when working with Date objects
1603 */
1604 private static void assertWeekIterator(final Iterator<?> it, final Date start, final Date end) {
1605 final Calendar calStart = Calendar.getInstance();
1606 calStart.setTime(start);
1607 final Calendar calEnd = Calendar.getInstance();
1608 calEnd.setTime(end);
1609
1610 assertWeekIterator(it, calStart, calEnd);
1611 }
1612
1613 /**
1614 * This checks that this is a 7 divisble iterator of Calendar objects
1615 * that are dates (no time), and exactly 1 day spaced after each other
1616 * (in addition to the proper start and stop dates)
1617 */
1618 private static void assertWeekIterator(final Iterator<?> it, final Calendar start, final Calendar end) {
1619 Calendar cal = (Calendar) it.next();
1620 assertCalendarsEquals("", start, cal, 0);
1621 Calendar last = null;
1622 int count = 1;
1623 while (it.hasNext()) {
1624 //Check this is just a date (no time component)
1625 assertCalendarsEquals("", cal, DateUtils.truncate(cal, Calendar.DATE), 0);
1626
1627 last = cal;
1628 cal = (Calendar) it.next();
1629 count++;
1630
1631 //Check that this is one day more than the last date
1632 last.add(Calendar.DATE, 1);
1633 assertCalendarsEquals("", last, cal, 0);
1634 }
1635
1636 assertFalse(count % 7 != 0, "There were " + count + " days in this iterator");
1637 assertCalendarsEquals("", end, cal, 0);
1638 }
1639
1640 /**
1641 * Used to check that Calendar objects are close enough
1642 * delta is in milliseconds
1643 */
1644 private static void assertCalendarsEquals(final String message, final Calendar cal1, final Calendar cal2, final long delta) {
1645 assertFalse(Math.abs(cal1.getTime().getTime() - cal2.getTime().getTime()) > delta,
1646 message + " expected " + cal1.getTime() + " but got " + cal2.getTime());
1647 }
1648
1649 @Test
1650 public void testLANG799() throws ParseException {
1651 DateUtils.parseDateStrictly("09 abril 2008 23:55:38 GMT", new Locale("es"), "dd MMM yyyy HH:mm:ss zzz");
1652 }
16531631 }
16541632
3636 */
3737 public class DurationFormatUtilsTest {
3838
39 private static final int FOUR_YEARS = 365 * 3 + 366;
40
41 private void assertEqualDuration(final String expected, final int[] start, final int[] end, final String format) {
42 assertEqualDuration(null, expected, start, end, format);
43 }
44
45 private void assertEqualDuration(final String message, final String expected, final int[] start, final int[] end, final String format) {
46 final Calendar cal1 = Calendar.getInstance();
47 cal1.set(start[0], start[1], start[2], start[3], start[4], start[5]);
48 cal1.set(Calendar.MILLISECOND, 0);
49 final Calendar cal2 = Calendar.getInstance();
50 cal2.set(end[0], end[1], end[2], end[3], end[4], end[5]);
51 cal2.set(Calendar.MILLISECOND, 0);
52 final long milli1 = cal1.getTime().getTime();
53 final long milli2 = cal2.getTime().getTime();
54 final String result = DurationFormatUtils.formatPeriod(milli1, milli2, format);
55 if (message == null) {
56 assertEquals(expected, result);
57 } else {
58 assertEquals(expected, result, message);
59 }
60 }
61
62 private void bruteForce(final int year, final int month, final int day, final String format, final int calendarType) {
63 final String msg = year + "-" + month + "-" + day + " to ";
64 final Calendar c = Calendar.getInstance();
65 c.set(year, month, day, 0, 0, 0);
66 final int[] array1 = { year, month, day, 0, 0, 0 };
67 final int[] array2 = { year, month, day, 0, 0, 0 };
68 for (int i=0; i < FOUR_YEARS; i++) {
69 array2[0] = c.get(Calendar.YEAR);
70 array2[1] = c.get(Calendar.MONTH);
71 array2[2] = c.get(Calendar.DAY_OF_MONTH);
72 final String tmpMsg = msg + array2[0] + "-" + array2[1] + "-" + array2[2] + " at ";
73 assertEqualDuration( tmpMsg + i, Integer.toString(i), array1, array2, format );
74 c.add(calendarType, 1);
75 }
76 }
77
78 // https://issues.apache.org/bugzilla/show_bug.cgi?id=38401
79 @Test
80 public void testBugzilla38401() {
81 assertEqualDuration( "0000/00/30 16:00:00 000", new int[] { 2006, 0, 26, 18, 47, 34 },
82 new int[] { 2006, 1, 26, 10, 47, 34 }, "yyyy/MM/dd HH:mm:ss SSS");
83 }
84
3985 // -----------------------------------------------------------------------
4086 @Test
4187 public void testConstructor() {
4793 assertFalse(Modifier.isFinal(DurationFormatUtils.class.getModifiers()));
4894 }
4995
96 @Test
97 public void testDurationsByBruteForce() {
98 bruteForce(2006, 0, 1, "d", Calendar.DAY_OF_MONTH);
99 bruteForce(2006, 0, 2, "d", Calendar.DAY_OF_MONTH);
100 bruteForce(2007, 1, 2, "d", Calendar.DAY_OF_MONTH);
101 bruteForce(2004, 1, 29, "d", Calendar.DAY_OF_MONTH);
102 bruteForce(1996, 1, 29, "d", Calendar.DAY_OF_MONTH);
103
104 bruteForce(1969, 1, 28, "M", Calendar.MONTH); // tests for 48 years
105 //bruteForce(1996, 1, 29, "M", Calendar.MONTH); // this will fail
106 }
107
108 // Attempting to test edge cases in DurationFormatUtils.formatPeriod
109 @Test
110 public void testEdgeDurations() {
111 // This test case must use a time zone without DST
112 TimeZone.setDefault(FastTimeZone.getGmtTimeZone());
113 assertEqualDuration( "01", new int[] { 2006, 0, 15, 0, 0, 0 },
114 new int[] { 2006, 2, 10, 0, 0, 0 }, "MM");
115 assertEqualDuration( "12", new int[] { 2005, 0, 15, 0, 0, 0 },
116 new int[] { 2006, 0, 15, 0, 0, 0 }, "MM");
117 assertEqualDuration( "12", new int[] { 2005, 0, 15, 0, 0, 0 },
118 new int[] { 2006, 0, 16, 0, 0, 0 }, "MM");
119 assertEqualDuration( "11", new int[] { 2005, 0, 15, 0, 0, 0 },
120 new int[] { 2006, 0, 14, 0, 0, 0 }, "MM");
121
122 assertEqualDuration( "01 26", new int[] { 2006, 0, 15, 0, 0, 0 },
123 new int[] { 2006, 2, 10, 0, 0, 0 }, "MM dd");
124 assertEqualDuration( "54", new int[] { 2006, 0, 15, 0, 0, 0 },
125 new int[] { 2006, 2, 10, 0, 0, 0 }, "dd");
126
127 assertEqualDuration( "09 12", new int[] { 2006, 1, 20, 0, 0, 0 },
128 new int[] { 2006, 11, 4, 0, 0, 0 }, "MM dd");
129 assertEqualDuration( "287", new int[] { 2006, 1, 20, 0, 0, 0 },
130 new int[] { 2006, 11, 4, 0, 0, 0 }, "dd");
131
132 assertEqualDuration( "11 30", new int[] { 2006, 0, 2, 0, 0, 0 },
133 new int[] { 2007, 0, 1, 0, 0, 0 }, "MM dd");
134 assertEqualDuration( "364", new int[] { 2006, 0, 2, 0, 0, 0 },
135 new int[] { 2007, 0, 1, 0, 0, 0 }, "dd");
136
137 assertEqualDuration( "12 00", new int[] { 2006, 0, 1, 0, 0, 0 },
138 new int[] { 2007, 0, 1, 0, 0, 0 }, "MM dd");
139 assertEqualDuration( "365", new int[] { 2006, 0, 1, 0, 0, 0 },
140 new int[] { 2007, 0, 1, 0, 0, 0 }, "dd");
141
142 assertEqualDuration( "31", new int[] { 2006, 0, 1, 0, 0, 0 },
143 new int[] { 2006, 1, 1, 0, 0, 0 }, "dd");
144
145 assertEqualDuration( "92", new int[] { 2005, 9, 1, 0, 0, 0 },
146 new int[] { 2006, 0, 1, 0, 0, 0 }, "dd");
147 assertEqualDuration( "77", new int[] { 2005, 9, 16, 0, 0, 0 },
148 new int[] { 2006, 0, 1, 0, 0, 0 }, "dd");
149
150 // test month larger in start than end
151 assertEqualDuration( "136", new int[] { 2005, 9, 16, 0, 0, 0 },
152 new int[] { 2006, 2, 1, 0, 0, 0 }, "dd");
153 // test when start in leap year
154 assertEqualDuration( "136", new int[] { 2004, 9, 16, 0, 0, 0 },
155 new int[] { 2005, 2, 1, 0, 0, 0 }, "dd");
156 // test when end in leap year
157 assertEqualDuration( "137", new int[] { 2003, 9, 16, 0, 0, 0 },
158 new int[] { 2004, 2, 1, 0, 0, 0 }, "dd");
159 // test when end in leap year but less than end of feb
160 assertEqualDuration( "135", new int[] { 2003, 9, 16, 0, 0, 0 },
161 new int[] { 2004, 1, 28, 0, 0, 0 }, "dd");
162
163 assertEqualDuration( "364", new int[] { 2007, 0, 2, 0, 0, 0 },
164 new int[] { 2008, 0, 1, 0, 0, 0 }, "dd");
165 assertEqualDuration( "729", new int[] { 2006, 0, 2, 0, 0, 0 },
166 new int[] { 2008, 0, 1, 0, 0, 0 }, "dd");
167
168 assertEqualDuration( "365", new int[] { 2007, 2, 2, 0, 0, 0 },
169 new int[] { 2008, 2, 1, 0, 0, 0 }, "dd");
170 assertEqualDuration( "333", new int[] { 2007, 1, 2, 0, 0, 0 },
171 new int[] { 2008, 0, 1, 0, 0, 0 }, "dd");
172
173 assertEqualDuration( "28", new int[] { 2008, 1, 2, 0, 0, 0 },
174 new int[] { 2008, 2, 1, 0, 0, 0 }, "dd");
175 assertEqualDuration( "393", new int[] { 2007, 1, 2, 0, 0, 0 },
176 new int[] { 2008, 2, 1, 0, 0, 0 }, "dd");
177
178 assertEqualDuration( "369", new int[] { 2004, 0, 29, 0, 0, 0 },
179 new int[] { 2005, 1, 1, 0, 0, 0 }, "dd");
180
181 assertEqualDuration( "338", new int[] { 2004, 1, 29, 0, 0, 0 },
182 new int[] { 2005, 1, 1, 0, 0, 0 }, "dd");
183
184 assertEqualDuration( "28", new int[] { 2004, 2, 8, 0, 0, 0 },
185 new int[] { 2004, 3, 5, 0, 0, 0 }, "dd");
186
187 assertEqualDuration( "48", new int[] { 1992, 1, 29, 0, 0, 0 },
188 new int[] { 1996, 1, 29, 0, 0, 0 }, "M");
189
190
191 // this seems odd - and will fail if I throw it in as a brute force
192 // below as it expects the answer to be 12. It's a tricky edge case
193 assertEqualDuration( "11", new int[] { 1996, 1, 29, 0, 0, 0 },
194 new int[] { 1997, 1, 28, 0, 0, 0 }, "M");
195 // again - this seems odd
196 assertEqualDuration( "11 28", new int[] { 1996, 1, 29, 0, 0, 0 },
197 new int[] { 1997, 1, 28, 0, 0, 0 }, "M d");
198
199 }
200
201 @Test
202 public void testFormatDuration() {
203 long duration = 0;
204 assertEquals("0", DurationFormatUtils.formatDuration(duration, "y"));
205 assertEquals("0", DurationFormatUtils.formatDuration(duration, "M"));
206 assertEquals("0", DurationFormatUtils.formatDuration(duration, "d"));
207 assertEquals("0", DurationFormatUtils.formatDuration(duration, "H"));
208 assertEquals("0", DurationFormatUtils.formatDuration(duration, "m"));
209 assertEquals("0", DurationFormatUtils.formatDuration(duration, "s"));
210 assertEquals("0", DurationFormatUtils.formatDuration(duration, "S"));
211 assertEquals("0000", DurationFormatUtils.formatDuration(duration, "SSSS"));
212 assertEquals("0000", DurationFormatUtils.formatDuration(duration, "yyyy"));
213 assertEquals("0000", DurationFormatUtils.formatDuration(duration, "yyMM"));
214
215 duration = 60 * 1000;
216 assertEquals("0", DurationFormatUtils.formatDuration(duration, "y"));
217 assertEquals("0", DurationFormatUtils.formatDuration(duration, "M"));
218 assertEquals("0", DurationFormatUtils.formatDuration(duration, "d"));
219 assertEquals("0", DurationFormatUtils.formatDuration(duration, "H"));
220 assertEquals("1", DurationFormatUtils.formatDuration(duration, "m"));
221 assertEquals("60", DurationFormatUtils.formatDuration(duration, "s"));
222 assertEquals("60000", DurationFormatUtils.formatDuration(duration, "S"));
223 assertEquals("01:00", DurationFormatUtils.formatDuration(duration, "mm:ss"));
224
225 final Calendar base = Calendar.getInstance();
226 base.set(2000, Calendar.JANUARY, 1, 0, 0, 0);
227 base.set(Calendar.MILLISECOND, 0);
228
229 final Calendar cal = Calendar.getInstance();
230 cal.set(2003, Calendar.FEBRUARY, 1, 0, 0, 0);
231 cal.set(Calendar.MILLISECOND, 0);
232 duration = cal.getTime().getTime() - base.getTime().getTime(); // duration from 2000-01-01 to cal
233 // don't use 1970 in test as time zones were less reliable in 1970 than now
234 // remember that duration formatting ignores time zones, working on strict hour lengths
235 final int days = 366 + 365 + 365 + 31;
236 assertEquals("0 0 " + days, DurationFormatUtils.formatDuration(duration, "y M d"));
237 }
238
239 @Test
240 public void testFormatDurationHMS() {
241 long time = 0;
242 assertEquals("00:00:00.000", DurationFormatUtils.formatDurationHMS(time));
243
244 time = 1;
245 assertEquals("00:00:00.001", DurationFormatUtils.formatDurationHMS(time));
246
247 time = 15;
248 assertEquals("00:00:00.015", DurationFormatUtils.formatDurationHMS(time));
249
250 time = 165;
251 assertEquals("00:00:00.165", DurationFormatUtils.formatDurationHMS(time));
252
253 time = 1675;
254 assertEquals("00:00:01.675", DurationFormatUtils.formatDurationHMS(time));
255
256 time = 13465;
257 assertEquals("00:00:13.465", DurationFormatUtils.formatDurationHMS(time));
258
259 time = 72789;
260 assertEquals("00:01:12.789", DurationFormatUtils.formatDurationHMS(time));
261
262 time = 12789 + 32 * 60000;
263 assertEquals("00:32:12.789", DurationFormatUtils.formatDurationHMS(time));
264
265 time = 12789 + 62 * 60000;
266 assertEquals("01:02:12.789", DurationFormatUtils.formatDurationHMS(time));
267 }
268
269 @Test
270 public void testFormatDurationISO() {
271 assertEquals("P0Y0M0DT0H0M0.000S", DurationFormatUtils.formatDurationISO(0L));
272 assertEquals("P0Y0M0DT0H0M0.001S", DurationFormatUtils.formatDurationISO(1L));
273 assertEquals("P0Y0M0DT0H0M0.010S", DurationFormatUtils.formatDurationISO(10L));
274 assertEquals("P0Y0M0DT0H0M0.100S", DurationFormatUtils.formatDurationISO(100L));
275 assertEquals("P0Y0M0DT0H1M15.321S", DurationFormatUtils.formatDurationISO(75321L));
276 }
277
278 /**
279 * Tests that "1 &lt;unit&gt;s" gets converted to "1 &lt;unit&gt;" but that "11 &lt;unit&gt;s" is left alone.
280 */
281 @Test
282 public void testFormatDurationPluralWords() {
283 final long oneSecond = 1000;
284 final long oneMinute = oneSecond * 60;
285 final long oneHour = oneMinute * 60;
286 final long oneDay = oneHour * 24;
287 String text;
288
289 text = DurationFormatUtils.formatDurationWords(oneSecond, false, false);
290 assertEquals("0 days 0 hours 0 minutes 1 second", text);
291 text = DurationFormatUtils.formatDurationWords(oneSecond * 2, false, false);
292 assertEquals("0 days 0 hours 0 minutes 2 seconds", text);
293 text = DurationFormatUtils.formatDurationWords(oneSecond * 11, false, false);
294 assertEquals("0 days 0 hours 0 minutes 11 seconds", text);
295
296 text = DurationFormatUtils.formatDurationWords(oneMinute, false, false);
297 assertEquals("0 days 0 hours 1 minute 0 seconds", text);
298 text = DurationFormatUtils.formatDurationWords(oneMinute * 2, false, false);
299 assertEquals("0 days 0 hours 2 minutes 0 seconds", text);
300 text = DurationFormatUtils.formatDurationWords(oneMinute * 11, false, false);
301 assertEquals("0 days 0 hours 11 minutes 0 seconds", text);
302 text = DurationFormatUtils.formatDurationWords(oneMinute + oneSecond, false, false);
303 assertEquals("0 days 0 hours 1 minute 1 second", text);
304
305 text = DurationFormatUtils.formatDurationWords(oneHour, false, false);
306 assertEquals("0 days 1 hour 0 minutes 0 seconds", text);
307 text = DurationFormatUtils.formatDurationWords(oneHour * 2, false, false);
308 assertEquals("0 days 2 hours 0 minutes 0 seconds", text);
309 text = DurationFormatUtils.formatDurationWords(oneHour * 11, false, false);
310 assertEquals("0 days 11 hours 0 minutes 0 seconds", text);
311 text = DurationFormatUtils.formatDurationWords(oneHour + oneMinute + oneSecond, false, false);
312 assertEquals("0 days 1 hour 1 minute 1 second", text);
313
314 text = DurationFormatUtils.formatDurationWords(oneDay, false, false);
315 assertEquals("1 day 0 hours 0 minutes 0 seconds", text);
316 text = DurationFormatUtils.formatDurationWords(oneDay * 2, false, false);
317 assertEquals("2 days 0 hours 0 minutes 0 seconds", text);
318 text = DurationFormatUtils.formatDurationWords(oneDay * 11, false, false);
319 assertEquals("11 days 0 hours 0 minutes 0 seconds", text);
320 text = DurationFormatUtils.formatDurationWords(oneDay + oneHour + oneMinute + oneSecond, false, false);
321 assertEquals("1 day 1 hour 1 minute 1 second", text);
322 }
323
50324 // -----------------------------------------------------------------------
51325 @Test
52326 public void testFormatDurationWords() {
53 String text = null;
327 String text;
54328
55329 text = DurationFormatUtils.formatDurationWords(50 * 1000, true, false);
56330 assertEquals("50 seconds", text);
111385 }
112386 }
113387
114 /**
115 * Tests that "1 &lt;unit&gt;s" gets converted to "1 &lt;unit&gt;" but that "11 &lt;unit&gt;s" is left alone.
116 */
117 @Test
118 public void testFormatDurationPluralWords() {
119 final long oneSecond = 1000;
120 final long oneMinute = oneSecond * 60;
121 final long oneHour = oneMinute * 60;
122 final long oneDay = oneHour * 24;
123 String text = null;
124
125 text = DurationFormatUtils.formatDurationWords(oneSecond, false, false);
126 assertEquals("0 days 0 hours 0 minutes 1 second", text);
127 text = DurationFormatUtils.formatDurationWords(oneSecond * 2, false, false);
128 assertEquals("0 days 0 hours 0 minutes 2 seconds", text);
129 text = DurationFormatUtils.formatDurationWords(oneSecond * 11, false, false);
130 assertEquals("0 days 0 hours 0 minutes 11 seconds", text);
131
132 text = DurationFormatUtils.formatDurationWords(oneMinute, false, false);
133 assertEquals("0 days 0 hours 1 minute 0 seconds", text);
134 text = DurationFormatUtils.formatDurationWords(oneMinute * 2, false, false);
135 assertEquals("0 days 0 hours 2 minutes 0 seconds", text);
136 text = DurationFormatUtils.formatDurationWords(oneMinute * 11, false, false);
137 assertEquals("0 days 0 hours 11 minutes 0 seconds", text);
138 text = DurationFormatUtils.formatDurationWords(oneMinute + oneSecond, false, false);
139 assertEquals("0 days 0 hours 1 minute 1 second", text);
140
141 text = DurationFormatUtils.formatDurationWords(oneHour, false, false);
142 assertEquals("0 days 1 hour 0 minutes 0 seconds", text);
143 text = DurationFormatUtils.formatDurationWords(oneHour * 2, false, false);
144 assertEquals("0 days 2 hours 0 minutes 0 seconds", text);
145 text = DurationFormatUtils.formatDurationWords(oneHour * 11, false, false);
146 assertEquals("0 days 11 hours 0 minutes 0 seconds", text);
147 text = DurationFormatUtils.formatDurationWords(oneHour + oneMinute + oneSecond, false, false);
148 assertEquals("0 days 1 hour 1 minute 1 second", text);
149
150 text = DurationFormatUtils.formatDurationWords(oneDay, false, false);
151 assertEquals("1 day 0 hours 0 minutes 0 seconds", text);
152 text = DurationFormatUtils.formatDurationWords(oneDay * 2, false, false);
153 assertEquals("2 days 0 hours 0 minutes 0 seconds", text);
154 text = DurationFormatUtils.formatDurationWords(oneDay * 11, false, false);
155 assertEquals("11 days 0 hours 0 minutes 0 seconds", text);
156 text = DurationFormatUtils.formatDurationWords(oneDay + oneHour + oneMinute + oneSecond, false, false);
157 assertEquals("1 day 1 hour 1 minute 1 second", text);
158 }
388 @Test
389 public void testFormatNegativeDuration() {
390 assertThrows(IllegalArgumentException.class, () -> DurationFormatUtils.formatDuration(-5000, "S", true));
391 }
392
393 @Test
394 public void testFormatNegativeDurationHMS() {
395 assertThrows(IllegalArgumentException.class, () -> DurationFormatUtils.formatDurationHMS(-5000));
396 }
397
398 @Test
399 public void testFormatNegativeDurationISO() {
400 assertThrows(IllegalArgumentException.class, () -> DurationFormatUtils.formatDurationISO(-5000));
401 }
402
159403
160404 @Test
161405 public void testFormatNegativeDurationWords() {
163407 }
164408
165409 @Test
166 public void testFormatDurationHMS() {
167 long time = 0;
168 assertEquals("00:00:00.000", DurationFormatUtils.formatDurationHMS(time));
169
170 time = 1;
171 assertEquals("00:00:00.001", DurationFormatUtils.formatDurationHMS(time));
172
173 time = 15;
174 assertEquals("00:00:00.015", DurationFormatUtils.formatDurationHMS(time));
175
176 time = 165;
177 assertEquals("00:00:00.165", DurationFormatUtils.formatDurationHMS(time));
178
179 time = 1675;
180 assertEquals("00:00:01.675", DurationFormatUtils.formatDurationHMS(time));
181
182 time = 13465;
183 assertEquals("00:00:13.465", DurationFormatUtils.formatDurationHMS(time));
184
185 time = 72789;
186 assertEquals("00:01:12.789", DurationFormatUtils.formatDurationHMS(time));
187
188 time = 12789 + 32 * 60000;
189 assertEquals("00:32:12.789", DurationFormatUtils.formatDurationHMS(time));
190
191 time = 12789 + 62 * 60000;
192 assertEquals("01:02:12.789", DurationFormatUtils.formatDurationHMS(time));
193 }
194
195 @Test
196 public void testFormatNegativeDurationHMS() {
197 assertThrows(IllegalArgumentException.class, () -> DurationFormatUtils.formatDurationHMS(-5000));
198 }
199
200 @Test
201 public void testFormatDurationISO() {
202 assertEquals("P0Y0M0DT0H0M0.000S", DurationFormatUtils.formatDurationISO(0L));
203 assertEquals("P0Y0M0DT0H0M0.001S", DurationFormatUtils.formatDurationISO(1L));
204 assertEquals("P0Y0M0DT0H0M0.010S", DurationFormatUtils.formatDurationISO(10L));
205 assertEquals("P0Y0M0DT0H0M0.100S", DurationFormatUtils.formatDurationISO(100L));
206 assertEquals("P0Y0M0DT0H1M15.321S", DurationFormatUtils.formatDurationISO(75321L));
207 }
208
209 @Test
210 public void testFormatNegativeDurationISO() {
211 assertThrows(IllegalArgumentException.class, () -> DurationFormatUtils.formatDurationISO(-5000));
212 }
213
214 @Test
215 public void testFormatDuration() {
216 long duration = 0;
217 assertEquals("0", DurationFormatUtils.formatDuration(duration, "y"));
218 assertEquals("0", DurationFormatUtils.formatDuration(duration, "M"));
219 assertEquals("0", DurationFormatUtils.formatDuration(duration, "d"));
220 assertEquals("0", DurationFormatUtils.formatDuration(duration, "H"));
221 assertEquals("0", DurationFormatUtils.formatDuration(duration, "m"));
222 assertEquals("0", DurationFormatUtils.formatDuration(duration, "s"));
223 assertEquals("0", DurationFormatUtils.formatDuration(duration, "S"));
224 assertEquals("0000", DurationFormatUtils.formatDuration(duration, "SSSS"));
225 assertEquals("0000", DurationFormatUtils.formatDuration(duration, "yyyy"));
226 assertEquals("0000", DurationFormatUtils.formatDuration(duration, "yyMM"));
227
228 duration = 60 * 1000;
229 assertEquals("0", DurationFormatUtils.formatDuration(duration, "y"));
230 assertEquals("0", DurationFormatUtils.formatDuration(duration, "M"));
231 assertEquals("0", DurationFormatUtils.formatDuration(duration, "d"));
232 assertEquals("0", DurationFormatUtils.formatDuration(duration, "H"));
233 assertEquals("1", DurationFormatUtils.formatDuration(duration, "m"));
234 assertEquals("60", DurationFormatUtils.formatDuration(duration, "s"));
235 assertEquals("60000", DurationFormatUtils.formatDuration(duration, "S"));
236 assertEquals("01:00", DurationFormatUtils.formatDuration(duration, "mm:ss"));
237
238 final Calendar base = Calendar.getInstance();
239 base.set(2000, Calendar.JANUARY, 1, 0, 0, 0);
240 base.set(Calendar.MILLISECOND, 0);
410 public void testFormatPeriod() {
411 final Calendar cal1970 = Calendar.getInstance();
412 cal1970.set(1970, Calendar.JANUARY, 1, 0, 0, 0);
413 cal1970.set(Calendar.MILLISECOND, 0);
414 final long time1970 = cal1970.getTime().getTime();
415
416 assertEquals("0", DurationFormatUtils.formatPeriod(time1970, time1970, "y"));
417 assertEquals("0", DurationFormatUtils.formatPeriod(time1970, time1970, "M"));
418 assertEquals("0", DurationFormatUtils.formatPeriod(time1970, time1970, "d"));
419 assertEquals("0", DurationFormatUtils.formatPeriod(time1970, time1970, "H"));
420 assertEquals("0", DurationFormatUtils.formatPeriod(time1970, time1970, "m"));
421 assertEquals("0", DurationFormatUtils.formatPeriod(time1970, time1970, "s"));
422 assertEquals("0", DurationFormatUtils.formatPeriod(time1970, time1970, "S"));
423 assertEquals("0000", DurationFormatUtils.formatPeriod(time1970, time1970, "SSSS"));
424 assertEquals("0000", DurationFormatUtils.formatPeriod(time1970, time1970, "yyyy"));
425 assertEquals("0000", DurationFormatUtils.formatPeriod(time1970, time1970, "yyMM"));
426
427 long time = time1970 + 60 * 1000;
428 assertEquals("0", DurationFormatUtils.formatPeriod(time1970, time, "y"));
429 assertEquals("0", DurationFormatUtils.formatPeriod(time1970, time, "M"));
430 assertEquals("0", DurationFormatUtils.formatPeriod(time1970, time, "d"));
431 assertEquals("0", DurationFormatUtils.formatPeriod(time1970, time, "H"));
432 assertEquals("1", DurationFormatUtils.formatPeriod(time1970, time, "m"));
433 assertEquals("60", DurationFormatUtils.formatPeriod(time1970, time, "s"));
434 assertEquals("60000", DurationFormatUtils.formatPeriod(time1970, time, "S"));
435 assertEquals("01:00", DurationFormatUtils.formatPeriod(time1970, time, "mm:ss"));
241436
242437 final Calendar cal = Calendar.getInstance();
243 cal.set(2003, Calendar.FEBRUARY, 1, 0, 0, 0);
438 cal.set(1973, Calendar.JULY, 1, 0, 0, 0);
244439 cal.set(Calendar.MILLISECOND, 0);
245 duration = cal.getTime().getTime() - base.getTime().getTime(); // duration from 2000-01-01 to cal
246 // don't use 1970 in test as time zones were less reliable in 1970 than now
247 // remember that duration formatting ignores time zones, working on strict hour lengths
248 final int days = 366 + 365 + 365 + 31;
249 assertEquals("0 0 " + days, DurationFormatUtils.formatDuration(duration, "y M d"));
250 }
251
252 @Test
253 public void testFormatNegativeDuration() {
254 assertThrows(IllegalArgumentException.class, () -> DurationFormatUtils.formatDuration(-5000, "S", true));
440 time = cal.getTime().getTime();
441 assertEquals("36", DurationFormatUtils.formatPeriod(time1970, time, "yM"));
442 assertEquals("3 years 6 months", DurationFormatUtils.formatPeriod(time1970, time, "y' years 'M' months'"));
443 assertEquals("03/06", DurationFormatUtils.formatPeriod(time1970, time, "yy/MM"));
444
445 cal.set(1973, Calendar.NOVEMBER, 1, 0, 0, 0);
446 cal.set(Calendar.MILLISECOND, 0);
447 time = cal.getTime().getTime();
448 assertEquals("310", DurationFormatUtils.formatPeriod(time1970, time, "yM"));
449 assertEquals("3 years 10 months", DurationFormatUtils.formatPeriod(time1970, time, "y' years 'M' months'"));
450 assertEquals("03/10", DurationFormatUtils.formatPeriod(time1970, time, "yy/MM"));
451
452 cal.set(1974, Calendar.JANUARY, 1, 0, 0, 0);
453 cal.set(Calendar.MILLISECOND, 0);
454 time = cal.getTime().getTime();
455 assertEquals("40", DurationFormatUtils.formatPeriod(time1970, time, "yM"));
456 assertEquals("4 years 0 months", DurationFormatUtils.formatPeriod(time1970, time, "y' years 'M' months'"));
457 assertEquals("04/00", DurationFormatUtils.formatPeriod(time1970, time, "yy/MM"));
458 assertEquals("48", DurationFormatUtils.formatPeriod(time1970, time, "M"));
459 assertEquals("48", DurationFormatUtils.formatPeriod(time1970, time, "MM"));
460 assertEquals("048", DurationFormatUtils.formatPeriod(time1970, time, "MMM"));
461 }
462
463 @Test
464 public void testFormatPeriodeStartGreaterEnd() {
465 assertThrows(IllegalArgumentException.class, () -> DurationFormatUtils.formatPeriod(5000, 2500, "yy/MM"));
255466 }
256467
257468 @SuppressWarnings("deprecation")
284495 }
285496
286497 @Test
287 public void testFormatPeriodISOStartGreaterEnd() {
288 assertThrows(IllegalArgumentException.class, () -> DurationFormatUtils.formatPeriodISO(5000, 2000));
289 }
290
291 @Test
292498 public void testFormatPeriodISOMethod() {
293499 assertEquals("P0Y0M0DT0H0M0.000S", DurationFormatUtils.formatPeriodISO(0L, 0L));
294500 assertEquals("P0Y0M0DT0H0M1.000S", DurationFormatUtils.formatPeriodISO(0L, 1000L));
296502 }
297503
298504 @Test
299 public void testFormatPeriod() {
300 final Calendar cal1970 = Calendar.getInstance();
301 cal1970.set(1970, Calendar.JANUARY, 1, 0, 0, 0);
302 cal1970.set(Calendar.MILLISECOND, 0);
303 final long time1970 = cal1970.getTime().getTime();
304
305 assertEquals("0", DurationFormatUtils.formatPeriod(time1970, time1970, "y"));
306 assertEquals("0", DurationFormatUtils.formatPeriod(time1970, time1970, "M"));
307 assertEquals("0", DurationFormatUtils.formatPeriod(time1970, time1970, "d"));
308 assertEquals("0", DurationFormatUtils.formatPeriod(time1970, time1970, "H"));
309 assertEquals("0", DurationFormatUtils.formatPeriod(time1970, time1970, "m"));
310 assertEquals("0", DurationFormatUtils.formatPeriod(time1970, time1970, "s"));
311 assertEquals("0", DurationFormatUtils.formatPeriod(time1970, time1970, "S"));
312 assertEquals("0000", DurationFormatUtils.formatPeriod(time1970, time1970, "SSSS"));
313 assertEquals("0000", DurationFormatUtils.formatPeriod(time1970, time1970, "yyyy"));
314 assertEquals("0000", DurationFormatUtils.formatPeriod(time1970, time1970, "yyMM"));
315
316 long time = time1970 + 60 * 1000;
317 assertEquals("0", DurationFormatUtils.formatPeriod(time1970, time, "y"));
318 assertEquals("0", DurationFormatUtils.formatPeriod(time1970, time, "M"));
319 assertEquals("0", DurationFormatUtils.formatPeriod(time1970, time, "d"));
320 assertEquals("0", DurationFormatUtils.formatPeriod(time1970, time, "H"));
321 assertEquals("1", DurationFormatUtils.formatPeriod(time1970, time, "m"));
322 assertEquals("60", DurationFormatUtils.formatPeriod(time1970, time, "s"));
323 assertEquals("60000", DurationFormatUtils.formatPeriod(time1970, time, "S"));
324 assertEquals("01:00", DurationFormatUtils.formatPeriod(time1970, time, "mm:ss"));
325
326 final Calendar cal = Calendar.getInstance();
327 cal.set(1973, Calendar.JULY, 1, 0, 0, 0);
328 cal.set(Calendar.MILLISECOND, 0);
329 time = cal.getTime().getTime();
330 assertEquals("36", DurationFormatUtils.formatPeriod(time1970, time, "yM"));
331 assertEquals("3 years 6 months", DurationFormatUtils.formatPeriod(time1970, time, "y' years 'M' months'"));
332 assertEquals("03/06", DurationFormatUtils.formatPeriod(time1970, time, "yy/MM"));
333
334 cal.set(1973, Calendar.NOVEMBER, 1, 0, 0, 0);
335 cal.set(Calendar.MILLISECOND, 0);
336 time = cal.getTime().getTime();
337 assertEquals("310", DurationFormatUtils.formatPeriod(time1970, time, "yM"));
338 assertEquals("3 years 10 months", DurationFormatUtils.formatPeriod(time1970, time, "y' years 'M' months'"));
339 assertEquals("03/10", DurationFormatUtils.formatPeriod(time1970, time, "yy/MM"));
340
341 cal.set(1974, Calendar.JANUARY, 1, 0, 0, 0);
342 cal.set(Calendar.MILLISECOND, 0);
343 time = cal.getTime().getTime();
344 assertEquals("40", DurationFormatUtils.formatPeriod(time1970, time, "yM"));
345 assertEquals("4 years 0 months", DurationFormatUtils.formatPeriod(time1970, time, "y' years 'M' months'"));
346 assertEquals("04/00", DurationFormatUtils.formatPeriod(time1970, time, "yy/MM"));
347 assertEquals("48", DurationFormatUtils.formatPeriod(time1970, time, "M"));
348 assertEquals("48", DurationFormatUtils.formatPeriod(time1970, time, "MM"));
349 assertEquals("048", DurationFormatUtils.formatPeriod(time1970, time, "MMM"));
350 }
351
352 @Test
353 public void testFormatPeriodeStartGreaterEnd() {
354 assertThrows(IllegalArgumentException.class, () -> DurationFormatUtils.formatPeriod(5000, 2500, "yy/MM"));
505 public void testFormatPeriodISOStartGreaterEnd() {
506 assertThrows(IllegalArgumentException.class, () -> DurationFormatUtils.formatPeriodISO(5000, 2000));
507 }
508
509 // https://issues.apache.org/jira/browse/LANG-281
510 @Test
511 public void testJiraLang281() {
512 assertEqualDuration( "09", new int[] { 2005, 11, 31, 0, 0, 0 },
513 new int[] { 2006, 9, 6, 0, 0, 0 }, "MM");
514 }
515
516 @Test
517 public void testLANG815() {
518 final Calendar calendar = Calendar.getInstance();
519 calendar.set(2012, Calendar.JULY, 30, 0, 0, 0);
520 final long startMillis = calendar.getTimeInMillis();
521
522 calendar.set(2012, Calendar.SEPTEMBER, 8);
523 final long endMillis = calendar.getTimeInMillis();
524
525 assertEquals("1 9", DurationFormatUtils.formatPeriod(startMillis, endMillis, "M d"));
526 }
527
528 @Test
529 public void testLANG981() { // unmatched quote char in lexx
530 assertThrows(IllegalArgumentException.class, () -> DurationFormatUtils.lexx("'yMdHms''S"));
531 }
532
533 @Test
534 public void testLANG982() { // More than 3 millisecond digits following a second
535 assertEquals("61.999", DurationFormatUtils.formatDuration(61999, "s.S"));
536 assertEquals("1 1999", DurationFormatUtils.formatDuration(61999, "m S"));
537 assertEquals("61.999", DurationFormatUtils.formatDuration(61999, "s.SSS"));
538 assertEquals("1 1999", DurationFormatUtils.formatDuration(61999, "m SSS"));
539 assertEquals("61.0999", DurationFormatUtils.formatDuration(61999, "s.SSSS"));
540 assertEquals("1 1999", DurationFormatUtils.formatDuration(61999, "m SSSS"));
541 assertEquals("61.00999", DurationFormatUtils.formatDuration(61999, "s.SSSSS"));
542 assertEquals("1 01999", DurationFormatUtils.formatDuration(61999, "m SSSSS"));
543 }
544
545 // Takes a minute to run, so generally turned off
546 // public void testBrutally() {
547 // Calendar c = Calendar.getInstance();
548 // c.set(2004, 0, 1, 0, 0, 0);
549 // for (int i=0; i < FOUR_YEARS; i++) {
550 // bruteForce(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH), "d", Calendar.DAY_OF_MONTH );
551 // c.add(Calendar.DAY_OF_MONTH, 1);
552 // }
553 // }
554
555 @Test
556 public void testLANG984() { // Long durations
557 assertEquals("0", DurationFormatUtils.formatDuration(0, "S"));
558 assertEquals(Integer.toString(Integer.MAX_VALUE), DurationFormatUtils.formatDuration(Integer.MAX_VALUE, "S"));
559 long maxIntPlus=Integer.MAX_VALUE;
560 maxIntPlus++;
561 assertEquals(Long.toString(maxIntPlus), DurationFormatUtils.formatDuration(maxIntPlus, "S"));
562 assertEquals(Long.toString(Long.MAX_VALUE), DurationFormatUtils.formatDuration(Long.MAX_VALUE, "S"));
355563 }
356564
357565 @Test
403611 final DurationFormatUtils.Token numToken = new DurationFormatUtils.Token(Integer.valueOf(1), 4);
404612 assertEquals(numToken, numToken, "Token with Number value not equal to itself. ");
405613 }
406
407
408 // https://issues.apache.org/bugzilla/show_bug.cgi?id=38401
409 @Test
410 public void testBugzilla38401() {
411 assertEqualDuration( "0000/00/30 16:00:00 000", new int[] { 2006, 0, 26, 18, 47, 34 },
412 new int[] { 2006, 1, 26, 10, 47, 34 }, "yyyy/MM/dd HH:mm:ss SSS");
413 }
414
415 // https://issues.apache.org/jira/browse/LANG-281
416 @Test
417 public void testJiraLang281() {
418 assertEqualDuration( "09", new int[] { 2005, 11, 31, 0, 0, 0 },
419 new int[] { 2006, 9, 6, 0, 0, 0 }, "MM");
420 }
421
422 @Test
423 public void testLANG815() {
424 final Calendar calendar = Calendar.getInstance();
425 calendar.set(2012, Calendar.JULY, 30, 0, 0, 0);
426 final long startMillis = calendar.getTimeInMillis();
427
428 calendar.set(2012, Calendar.SEPTEMBER, 8);
429 final long endMillis = calendar.getTimeInMillis();
430
431 assertEquals("1 9", DurationFormatUtils.formatPeriod(startMillis, endMillis, "M d"));
432 }
433
434614 // Testing the under a day range in DurationFormatUtils.formatPeriod
435615 @Test
436616 public void testLowDurations() {
447627 }
448628 }
449629
450 // Attempting to test edge cases in DurationFormatUtils.formatPeriod
451 @Test
452 public void testEdgeDurations() {
453 // This test case must use a time zone without DST
454 TimeZone.setDefault(FastTimeZone.getGmtTimeZone());
455 assertEqualDuration( "01", new int[] { 2006, 0, 15, 0, 0, 0 },
456 new int[] { 2006, 2, 10, 0, 0, 0 }, "MM");
457 assertEqualDuration( "12", new int[] { 2005, 0, 15, 0, 0, 0 },
458 new int[] { 2006, 0, 15, 0, 0, 0 }, "MM");
459 assertEqualDuration( "12", new int[] { 2005, 0, 15, 0, 0, 0 },
460 new int[] { 2006, 0, 16, 0, 0, 0 }, "MM");
461 assertEqualDuration( "11", new int[] { 2005, 0, 15, 0, 0, 0 },
462 new int[] { 2006, 0, 14, 0, 0, 0 }, "MM");
463
464 assertEqualDuration( "01 26", new int[] { 2006, 0, 15, 0, 0, 0 },
465 new int[] { 2006, 2, 10, 0, 0, 0 }, "MM dd");
466 assertEqualDuration( "54", new int[] { 2006, 0, 15, 0, 0, 0 },
467 new int[] { 2006, 2, 10, 0, 0, 0 }, "dd");
468
469 assertEqualDuration( "09 12", new int[] { 2006, 1, 20, 0, 0, 0 },
470 new int[] { 2006, 11, 4, 0, 0, 0 }, "MM dd");
471 assertEqualDuration( "287", new int[] { 2006, 1, 20, 0, 0, 0 },
472 new int[] { 2006, 11, 4, 0, 0, 0 }, "dd");
473
474 assertEqualDuration( "11 30", new int[] { 2006, 0, 2, 0, 0, 0 },
475 new int[] { 2007, 0, 1, 0, 0, 0 }, "MM dd");
476 assertEqualDuration( "364", new int[] { 2006, 0, 2, 0, 0, 0 },
477 new int[] { 2007, 0, 1, 0, 0, 0 }, "dd");
478
479 assertEqualDuration( "12 00", new int[] { 2006, 0, 1, 0, 0, 0 },
480 new int[] { 2007, 0, 1, 0, 0, 0 }, "MM dd");
481 assertEqualDuration( "365", new int[] { 2006, 0, 1, 0, 0, 0 },
482 new int[] { 2007, 0, 1, 0, 0, 0 }, "dd");
483
484 assertEqualDuration( "31", new int[] { 2006, 0, 1, 0, 0, 0 },
485 new int[] { 2006, 1, 1, 0, 0, 0 }, "dd");
486
487 assertEqualDuration( "92", new int[] { 2005, 9, 1, 0, 0, 0 },
488 new int[] { 2006, 0, 1, 0, 0, 0 }, "dd");
489 assertEqualDuration( "77", new int[] { 2005, 9, 16, 0, 0, 0 },
490 new int[] { 2006, 0, 1, 0, 0, 0 }, "dd");
491
492 // test month larger in start than end
493 assertEqualDuration( "136", new int[] { 2005, 9, 16, 0, 0, 0 },
494 new int[] { 2006, 2, 1, 0, 0, 0 }, "dd");
495 // test when start in leap year
496 assertEqualDuration( "136", new int[] { 2004, 9, 16, 0, 0, 0 },
497 new int[] { 2005, 2, 1, 0, 0, 0 }, "dd");
498 // test when end in leap year
499 assertEqualDuration( "137", new int[] { 2003, 9, 16, 0, 0, 0 },
500 new int[] { 2004, 2, 1, 0, 0, 0 }, "dd");
501 // test when end in leap year but less than end of feb
502 assertEqualDuration( "135", new int[] { 2003, 9, 16, 0, 0, 0 },
503 new int[] { 2004, 1, 28, 0, 0, 0 }, "dd");
504
505 assertEqualDuration( "364", new int[] { 2007, 0, 2, 0, 0, 0 },
506 new int[] { 2008, 0, 1, 0, 0, 0 }, "dd");
507 assertEqualDuration( "729", new int[] { 2006, 0, 2, 0, 0, 0 },
508 new int[] { 2008, 0, 1, 0, 0, 0 }, "dd");
509
510 assertEqualDuration( "365", new int[] { 2007, 2, 2, 0, 0, 0 },
511 new int[] { 2008, 2, 1, 0, 0, 0 }, "dd");
512 assertEqualDuration( "333", new int[] { 2007, 1, 2, 0, 0, 0 },
513 new int[] { 2008, 0, 1, 0, 0, 0 }, "dd");
514
515 assertEqualDuration( "28", new int[] { 2008, 1, 2, 0, 0, 0 },
516 new int[] { 2008, 2, 1, 0, 0, 0 }, "dd");
517 assertEqualDuration( "393", new int[] { 2007, 1, 2, 0, 0, 0 },
518 new int[] { 2008, 2, 1, 0, 0, 0 }, "dd");
519
520 assertEqualDuration( "369", new int[] { 2004, 0, 29, 0, 0, 0 },
521 new int[] { 2005, 1, 1, 0, 0, 0 }, "dd");
522
523 assertEqualDuration( "338", new int[] { 2004, 1, 29, 0, 0, 0 },
524 new int[] { 2005, 1, 1, 0, 0, 0 }, "dd");
525
526 assertEqualDuration( "28", new int[] { 2004, 2, 8, 0, 0, 0 },
527 new int[] { 2004, 3, 5, 0, 0, 0 }, "dd");
528
529 assertEqualDuration( "48", new int[] { 1992, 1, 29, 0, 0, 0 },
530 new int[] { 1996, 1, 29, 0, 0, 0 }, "M");
531
532
533 // this seems odd - and will fail if I throw it in as a brute force
534 // below as it expects the answer to be 12. It's a tricky edge case
535 assertEqualDuration( "11", new int[] { 1996, 1, 29, 0, 0, 0 },
536 new int[] { 1997, 1, 28, 0, 0, 0 }, "M");
537 // again - this seems odd
538 assertEqualDuration( "11 28", new int[] { 1996, 1, 29, 0, 0, 0 },
539 new int[] { 1997, 1, 28, 0, 0, 0 }, "M d");
540
541 }
542
543 @Test
544 public void testLANG984() { // Long durations
545 assertEquals("0", DurationFormatUtils.formatDuration(0, "S"));
546 assertEquals(Integer.toString(Integer.MAX_VALUE), DurationFormatUtils.formatDuration(Integer.MAX_VALUE, "S"));
547 long maxIntPlus=Integer.MAX_VALUE;
548 maxIntPlus++;
549 assertEquals(Long.toString(maxIntPlus), DurationFormatUtils.formatDuration(maxIntPlus, "S"));
550 assertEquals(Long.toString(Long.MAX_VALUE), DurationFormatUtils.formatDuration(Long.MAX_VALUE, "S"));
551 }
552
553 @Test
554 public void testLANG982() { // More than 3 millisecond digits following a second
555 assertEquals("61.999", DurationFormatUtils.formatDuration(61999, "s.S"));
556 assertEquals("1 1999", DurationFormatUtils.formatDuration(61999, "m S"));
557 assertEquals("61.999", DurationFormatUtils.formatDuration(61999, "s.SSS"));
558 assertEquals("1 1999", DurationFormatUtils.formatDuration(61999, "m SSS"));
559 assertEquals("61.0999", DurationFormatUtils.formatDuration(61999, "s.SSSS"));
560 assertEquals("1 1999", DurationFormatUtils.formatDuration(61999, "m SSSS"));
561 assertEquals("61.00999", DurationFormatUtils.formatDuration(61999, "s.SSSSS"));
562 assertEquals("1 01999", DurationFormatUtils.formatDuration(61999, "m SSSSS"));
563 }
564
565 @Test
566 public void testDurationsByBruteForce() {
567 bruteForce(2006, 0, 1, "d", Calendar.DAY_OF_MONTH);
568 bruteForce(2006, 0, 2, "d", Calendar.DAY_OF_MONTH);
569 bruteForce(2007, 1, 2, "d", Calendar.DAY_OF_MONTH);
570 bruteForce(2004, 1, 29, "d", Calendar.DAY_OF_MONTH);
571 bruteForce(1996, 1, 29, "d", Calendar.DAY_OF_MONTH);
572
573 bruteForce(1969, 1, 28, "M", Calendar.MONTH); // tests for 48 years
574 //bruteForce(1996, 1, 29, "M", Calendar.MONTH); // this will fail
575 }
576
577 @Test
578 public void testLANG981() { // unmatched quote char in lexx
579 assertThrows(IllegalArgumentException.class, () -> DurationFormatUtils.lexx("'yMdHms''S"));
580 }
581
582 private static final int FOUR_YEARS = 365 * 3 + 366;
583
584 // Takes a minute to run, so generally turned off
585 // public void testBrutally() {
586 // Calendar c = Calendar.getInstance();
587 // c.set(2004, 0, 1, 0, 0, 0);
588 // for (int i=0; i < FOUR_YEARS; i++) {
589 // bruteForce(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH), "d", Calendar.DAY_OF_MONTH );
590 // c.add(Calendar.DAY_OF_MONTH, 1);
591 // }
592 // }
593
594 private void bruteForce(final int year, final int month, final int day, final String format, final int calendarType) {
595 final String msg = year + "-" + month + "-" + day + " to ";
596 final Calendar c = Calendar.getInstance();
597 c.set(year, month, day, 0, 0, 0);
598 final int[] array1 = new int[] { year, month, day, 0, 0, 0 };
599 final int[] array2 = new int[] { year, month, day, 0, 0, 0 };
600 for (int i=0; i < FOUR_YEARS; i++) {
601 array2[0] = c.get(Calendar.YEAR);
602 array2[1] = c.get(Calendar.MONTH);
603 array2[2] = c.get(Calendar.DAY_OF_MONTH);
604 final String tmpMsg = msg + array2[0] + "-" + array2[1] + "-" + array2[2] + " at ";
605 assertEqualDuration( tmpMsg + i, Integer.toString(i), array1, array2, format );
606 c.add(calendarType, 1);
607 }
608 }
609
610 private void assertEqualDuration(final String expected, final int[] start, final int[] end, final String format) {
611 assertEqualDuration(null, expected, start, end, format);
612 }
613 private void assertEqualDuration(final String message, final String expected, final int[] start, final int[] end, final String format) {
614 final Calendar cal1 = Calendar.getInstance();
615 cal1.set(start[0], start[1], start[2], start[3], start[4], start[5]);
616 cal1.set(Calendar.MILLISECOND, 0);
617 final Calendar cal2 = Calendar.getInstance();
618 cal2.set(end[0], end[1], end[2], end[3], end[4], end[5]);
619 cal2.set(Calendar.MILLISECOND, 0);
620 final long milli1 = cal1.getTime().getTime();
621 final long milli2 = cal2.getTime().getTime();
622 final String result = DurationFormatUtils.formatPeriod(milli1, milli2, format);
623 if (message == null) {
624 assertEquals(expected, result);
625 } else {
626 assertEquals(expected, result, message);
627 }
628 }
629
630630 }
0 /*
1 * Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package org.apache.commons.lang3.time;
18
19 import static org.junit.jupiter.api.Assertions.assertEquals;
20 import static org.junit.jupiter.api.Assertions.assertFalse;
21 import static org.junit.jupiter.api.Assertions.assertTrue;
22
23 import java.time.Duration;
24 import java.util.concurrent.TimeUnit;
25
26 import org.apache.commons.lang3.math.NumberUtils;
27 import org.junit.jupiter.api.Test;
28
29 /**
30 * Tests {@link DurationUtils}.
31 */
32 public class DurationUtilsTest {
33
34 @Test
35 public void testGetNanosOfMilli() {
36 assertEquals(0, DurationUtils.getNanosOfMiili(Duration.ZERO));
37 assertEquals(1, DurationUtils.getNanosOfMiili(Duration.ofNanos(1)));
38 assertEquals(10, DurationUtils.getNanosOfMiili(Duration.ofNanos(10)));
39 assertEquals(100, DurationUtils.getNanosOfMiili(Duration.ofNanos(100)));
40 assertEquals(1_000, DurationUtils.getNanosOfMiili(Duration.ofNanos(1_000)));
41 assertEquals(10_000, DurationUtils.getNanosOfMiili(Duration.ofNanos(10_000)));
42 assertEquals(100_000, DurationUtils.getNanosOfMiili(Duration.ofNanos(100_000)));
43 assertEquals(0, DurationUtils.getNanosOfMiili(Duration.ofNanos(1_000_000)));
44 assertEquals(1, DurationUtils.getNanosOfMiili(Duration.ofNanos(1_000_001)));
45 }
46
47 @Test
48 public void testIsPositive() {
49 assertFalse(DurationUtils.isPositive(Duration.ZERO));
50 assertFalse(DurationUtils.isPositive(Duration.ofMillis(-1)));
51 assertTrue(DurationUtils.isPositive(Duration.ofMillis(1)));
52 }
53
54 @Test
55 public void testLongToIntRangeFit() {
56 assertEquals(0, DurationUtils.LONG_TO_INT_RANGE.fit(0L));
57 //
58 assertEquals(Integer.MIN_VALUE, DurationUtils.LONG_TO_INT_RANGE.fit(NumberUtils.LONG_INT_MIN_VALUE));
59 assertEquals(Integer.MIN_VALUE, DurationUtils.LONG_TO_INT_RANGE.fit(NumberUtils.LONG_INT_MIN_VALUE - 1));
60 assertEquals(Integer.MIN_VALUE, DurationUtils.LONG_TO_INT_RANGE.fit(NumberUtils.LONG_INT_MIN_VALUE - 2));
61 assertEquals(Integer.MAX_VALUE, DurationUtils.LONG_TO_INT_RANGE.fit(NumberUtils.LONG_INT_MAX_VALUE));
62 assertEquals(Integer.MAX_VALUE, DurationUtils.LONG_TO_INT_RANGE.fit(NumberUtils.LONG_INT_MAX_VALUE + 1));
63 assertEquals(Integer.MAX_VALUE, DurationUtils.LONG_TO_INT_RANGE.fit(NumberUtils.LONG_INT_MAX_VALUE + 2));
64 //
65 assertEquals(Integer.MIN_VALUE, DurationUtils.LONG_TO_INT_RANGE.fit(Long.MIN_VALUE));
66 assertEquals(Integer.MAX_VALUE, DurationUtils.LONG_TO_INT_RANGE.fit(Long.MAX_VALUE));
67 //
68 assertEquals(Short.MIN_VALUE, DurationUtils.LONG_TO_INT_RANGE.fit((long) Short.MIN_VALUE));
69 assertEquals(Short.MAX_VALUE, DurationUtils.LONG_TO_INT_RANGE.fit((long) Short.MAX_VALUE));
70 }
71
72 @Test
73 public void testToDuration() {
74 assertEquals(Duration.ofDays(1), DurationUtils.toDuration(1, TimeUnit.DAYS));
75 assertEquals(Duration.ofHours(1), DurationUtils.toDuration(1, TimeUnit.HOURS));
76 assertEquals(Duration.ofMillis(1), DurationUtils.toDuration(1_000, TimeUnit.MICROSECONDS));
77 assertEquals(Duration.ofMillis(1), DurationUtils.toDuration(1, TimeUnit.MILLISECONDS));
78 assertEquals(Duration.ofMinutes(1), DurationUtils.toDuration(1, TimeUnit.MINUTES));
79 assertEquals(Duration.ofNanos(1), DurationUtils.toDuration(1, TimeUnit.NANOSECONDS));
80 assertEquals(Duration.ofSeconds(1), DurationUtils.toDuration(1, TimeUnit.SECONDS));
81 assertEquals(1, DurationUtils.toDuration(1, TimeUnit.MILLISECONDS).toMillis());
82 assertEquals(-1, DurationUtils.toDuration(-1, TimeUnit.MILLISECONDS).toMillis());
83 assertEquals(0, DurationUtils.toDuration(0, TimeUnit.SECONDS).toMillis());
84 }
85
86 @Test
87 public void testToMillisInt() {
88 assertEquals(0, DurationUtils.toMillisInt(Duration.ZERO));
89 assertEquals(1, DurationUtils.toMillisInt(Duration.ofMillis(1)));
90 //
91 assertEquals(Integer.MIN_VALUE, DurationUtils.toMillisInt(Duration.ofMillis(Integer.MIN_VALUE)));
92 assertEquals(Integer.MAX_VALUE, DurationUtils.toMillisInt(Duration.ofMillis(Integer.MAX_VALUE)));
93 assertEquals(Integer.MAX_VALUE, DurationUtils.toMillisInt(Duration.ofMillis(NumberUtils.LONG_INT_MAX_VALUE + 1)));
94 assertEquals(Integer.MAX_VALUE, DurationUtils.toMillisInt(Duration.ofMillis(NumberUtils.LONG_INT_MAX_VALUE + 2)));
95 assertEquals(Integer.MIN_VALUE, DurationUtils.toMillisInt(Duration.ofMillis(NumberUtils.LONG_INT_MIN_VALUE - 1)));
96 assertEquals(Integer.MIN_VALUE, DurationUtils.toMillisInt(Duration.ofMillis(NumberUtils.LONG_INT_MIN_VALUE - 2)));
97 //
98 assertEquals(Integer.MIN_VALUE, DurationUtils.toMillisInt(Duration.ofNanos(Long.MIN_VALUE)));
99 assertEquals(Integer.MAX_VALUE, DurationUtils.toMillisInt(Duration.ofNanos(Long.MAX_VALUE)));
100 }
101
102 @Test
103 public void testZeroIfNull() {
104 assertEquals(Duration.ZERO, DurationUtils.zeroIfNull(null));
105 assertEquals(Duration.ofDays(1), DurationUtils.zeroIfNull(Duration.ofDays(1)));
106 }
107 }
4444 * @since 2.0
4545 */
4646 public class FastDateFormatTest {
47 /*
48 * Only the cache methods need to be tested here.
49 * The print methods are tested by {@link FastDateFormat_PrinterTest}
50 * and the parse methods are tested by {@link FastDateFormat_ParserTest}
51 */
52 @Test
53 public void test_getInstance() {
54 final FastDateFormat format1 = FastDateFormat.getInstance();
55 final FastDateFormat format2 = FastDateFormat.getInstance();
56 assertSame(format1, format2);
57 }
58
59 @Test
60 public void test_getInstance_String() {
61 final FastDateFormat format1 = FastDateFormat.getInstance("MM/DD/yyyy");
62 final FastDateFormat format2 = FastDateFormat.getInstance("MM-DD-yyyy");
63 final FastDateFormat format3 = FastDateFormat.getInstance("MM-DD-yyyy");
64
65 assertNotSame(format1, format2);
66 assertSame(format2, format3);
67 assertEquals("MM/DD/yyyy", format1.getPattern());
68 assertEquals(TimeZone.getDefault(), format1.getTimeZone());
69 assertEquals(TimeZone.getDefault(), format2.getTimeZone());
70 }
71
72 @DefaultLocale(language = "en", country = "US")
73 @DefaultTimeZone("America/New_York")
74 @Test
75 public void test_getInstance_String_TimeZone() {
76
77 final FastDateFormat format1 = FastDateFormat.getInstance("MM/DD/yyyy",
78 TimeZone.getTimeZone("Atlantic/Reykjavik"));
79 final FastDateFormat format2 = FastDateFormat.getInstance("MM/DD/yyyy");
80 final FastDateFormat format3 = FastDateFormat.getInstance("MM/DD/yyyy", TimeZone.getDefault());
81 final FastDateFormat format4 = FastDateFormat.getInstance("MM/DD/yyyy", TimeZone.getDefault());
82 final FastDateFormat format5 = FastDateFormat.getInstance("MM-DD-yyyy", TimeZone.getDefault());
83 final FastDateFormat format6 = FastDateFormat.getInstance("MM-DD-yyyy");
84
85 assertNotSame(format1, format2);
86 assertEquals(TimeZone.getTimeZone("Atlantic/Reykjavik"), format1.getTimeZone());
87 assertEquals(TimeZone.getDefault(), format2.getTimeZone());
88 assertSame(format3, format4);
89 assertNotSame(format3, format5);
90 assertNotSame(format4, format6);
91 }
92
93 @DefaultLocale(language = "en", country = "US")
94 @Test
95 public void test_getInstance_String_Locale() {
96 final FastDateFormat format1 = FastDateFormat.getInstance("MM/DD/yyyy", Locale.GERMANY);
97 final FastDateFormat format2 = FastDateFormat.getInstance("MM/DD/yyyy");
98 final FastDateFormat format3 = FastDateFormat.getInstance("MM/DD/yyyy", Locale.GERMANY);
99
100 assertNotSame(format1, format2);
101 assertSame(format1, format3);
102 assertEquals(Locale.GERMANY, format1.getLocale());
103 }
104
105 @DefaultLocale(language = "en", country = "US")
106 @Test
107 public void test_changeDefault_Locale_DateInstance() {
108 final FastDateFormat format1 = FastDateFormat.getDateInstance(FastDateFormat.FULL, Locale.GERMANY);
109 final FastDateFormat format2 = FastDateFormat.getDateInstance(FastDateFormat.FULL);
110 Locale.setDefault(Locale.GERMANY);
111 final FastDateFormat format3 = FastDateFormat.getDateInstance(FastDateFormat.FULL);
112
113 assertSame(Locale.GERMANY, format1.getLocale());
114 assertEquals(Locale.US, format2.getLocale());
115 assertSame(Locale.GERMANY, format3.getLocale());
116 assertNotSame(format1, format2);
117 assertNotSame(format2, format3);
118 }
119
120 @DefaultLocale(language = "en", country = "US")
121 @Test
122 public void test_changeDefault_Locale_DateTimeInstance() {
123 final FastDateFormat format1 = FastDateFormat.getDateTimeInstance(FastDateFormat.FULL, FastDateFormat.FULL, Locale.GERMANY);
124 final FastDateFormat format2 = FastDateFormat.getDateTimeInstance(FastDateFormat.FULL, FastDateFormat.FULL);
125 Locale.setDefault(Locale.GERMANY);
126 final FastDateFormat format3 = FastDateFormat.getDateTimeInstance(FastDateFormat.FULL, FastDateFormat.FULL);
127
128 assertSame(Locale.GERMANY, format1.getLocale());
129 assertEquals(Locale.US, format2.getLocale());
130 assertSame(Locale.GERMANY, format3.getLocale());
131 assertNotSame(format1, format2);
132 assertNotSame(format2, format3);
133 }
134
135 @DefaultLocale(language = "en", country = "US")
136 @DefaultTimeZone("America/New_York")
137 @Test
138 public void test_getInstance_String_TimeZone_Locale() {
139 final FastDateFormat format1 = FastDateFormat.getInstance("MM/DD/yyyy",
140 TimeZone.getTimeZone("Atlantic/Reykjavik"), Locale.GERMANY);
141 final FastDateFormat format2 = FastDateFormat.getInstance("MM/DD/yyyy", Locale.GERMANY);
142 final FastDateFormat format3 = FastDateFormat.getInstance("MM/DD/yyyy",
143 TimeZone.getDefault(), Locale.GERMANY);
144
145 assertNotSame(format1, format2);
146 assertEquals(TimeZone.getTimeZone("Atlantic/Reykjavik"), format1.getTimeZone());
147 assertEquals(TimeZone.getDefault(), format2.getTimeZone());
148 assertEquals(TimeZone.getDefault(), format3.getTimeZone());
149 assertEquals(Locale.GERMANY, format1.getLocale());
150 assertEquals(Locale.GERMANY, format2.getLocale());
151 assertEquals(Locale.GERMANY, format3.getLocale());
152 }
153
154 @Test
155 public void testCheckDefaults() {
156 final FastDateFormat format = FastDateFormat.getInstance();
157 final FastDateFormat medium = FastDateFormat.getDateTimeInstance(FastDateFormat.SHORT, FastDateFormat.SHORT);
158 assertEquals(medium, format);
159
160 final SimpleDateFormat sdf = new SimpleDateFormat();
161 assertEquals(sdf.toPattern(), format.getPattern());
162
163 assertEquals(Locale.getDefault(), format.getLocale());
164 assertEquals(TimeZone.getDefault(), format.getTimeZone());
165 }
166
167 @Test
168 public void testCheckDifferingStyles() {
169 final FastDateFormat shortShort = FastDateFormat.getDateTimeInstance(FastDateFormat.SHORT, FastDateFormat.SHORT, Locale.US);
170 final FastDateFormat shortLong = FastDateFormat.getDateTimeInstance(FastDateFormat.SHORT, FastDateFormat.LONG, Locale.US);
171 final FastDateFormat longShort = FastDateFormat.getDateTimeInstance(FastDateFormat.LONG, FastDateFormat.SHORT, Locale.US);
172 final FastDateFormat longLong = FastDateFormat.getDateTimeInstance(FastDateFormat.LONG, FastDateFormat.LONG, Locale.US);
173
174 assertNotEquals(shortShort, shortLong);
175 assertNotEquals(shortShort, longShort);
176 assertNotEquals(shortShort, longLong);
177 assertNotEquals(shortLong, longShort);
178 assertNotEquals(shortLong, longLong);
179 assertNotEquals(longShort, longLong);
180 }
181
182 @Test
183 public void testDateDefaults() {
184 assertEquals(FastDateFormat.getDateInstance(FastDateFormat.LONG, Locale.CANADA),
185 FastDateFormat.getDateInstance(FastDateFormat.LONG, TimeZone.getDefault(), Locale.CANADA));
186
187 assertEquals(FastDateFormat.getDateInstance(FastDateFormat.LONG, TimeZone.getTimeZone("America/New_York")),
188 FastDateFormat.getDateInstance(FastDateFormat.LONG, TimeZone.getTimeZone("America/New_York"), Locale.getDefault()));
189
190 assertEquals(FastDateFormat.getDateInstance(FastDateFormat.LONG),
191 FastDateFormat.getDateInstance(FastDateFormat.LONG, TimeZone.getDefault(), Locale.getDefault()));
192 }
193
194 @Test
195 public void testTimeDefaults() {
196 assertEquals(FastDateFormat.getTimeInstance(FastDateFormat.LONG, Locale.CANADA),
197 FastDateFormat.getTimeInstance(FastDateFormat.LONG, TimeZone.getDefault(), Locale.CANADA));
198
199 assertEquals(FastDateFormat.getTimeInstance(FastDateFormat.LONG, TimeZone.getTimeZone("America/New_York")),
200 FastDateFormat.getTimeInstance(FastDateFormat.LONG, TimeZone.getTimeZone("America/New_York"), Locale.getDefault()));
201
202 assertEquals(FastDateFormat.getTimeInstance(FastDateFormat.LONG),
203 FastDateFormat.getTimeInstance(FastDateFormat.LONG, TimeZone.getDefault(), Locale.getDefault()));
204 }
205
206 @Test
207 public void testTimeDateDefaults() {
208 assertEquals(FastDateFormat.getDateTimeInstance(FastDateFormat.LONG, FastDateFormat.MEDIUM, Locale.CANADA),
209 FastDateFormat.getDateTimeInstance(FastDateFormat.LONG, FastDateFormat.MEDIUM, TimeZone.getDefault(), Locale.CANADA));
210
211 assertEquals(FastDateFormat.getDateTimeInstance(FastDateFormat.LONG, FastDateFormat.MEDIUM, TimeZone.getTimeZone("America/New_York")),
212 FastDateFormat.getDateTimeInstance(FastDateFormat.LONG, FastDateFormat.MEDIUM, TimeZone.getTimeZone("America/New_York"), Locale.getDefault()));
213
214 assertEquals(FastDateFormat.getDateTimeInstance(FastDateFormat.LONG, FastDateFormat.MEDIUM),
215 FastDateFormat.getDateTimeInstance(FastDateFormat.LONG, FastDateFormat.MEDIUM, TimeZone.getDefault(), Locale.getDefault()));
216 }
217
218 @Test
219 public void testParseSync() throws InterruptedException {
220 final String pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS";
221 final SimpleDateFormat inner = new SimpleDateFormat(pattern);
222 final Format sdf= new Format() {
223 private static final long serialVersionUID = 1L;
224
225 @Override
226 public StringBuffer format(final Object obj,
227 final StringBuffer toAppendTo,
228 final FieldPosition fieldPosition) {
229 synchronized(this) {
230 return inner.format(obj, toAppendTo, fieldPosition);
231 }
232 }
233
234 @Override
235 public Object parseObject(final String source, final ParsePosition pos) {
236 synchronized(this) {
237 return inner.parseObject(source, pos);
238 }
239 }
240 };
241 final AtomicLongArray sdfTime= measureTime(sdf, sdf);
242
243 final Format fdf = FastDateFormat.getInstance(pattern);
244 final AtomicLongArray fdfTime= measureTime(fdf, fdf);
245
246 //System.out.println(">>FastDateFormatTest: FastDatePrinter:"+fdfTime.get(0)+" SimpleDateFormat:"+sdfTime.get(0));
247 //System.out.println(">>FastDateFormatTest: FastDateParser:"+fdfTime.get(1)+" SimpleDateFormat:"+sdfTime.get(1));
248 }
249
25047 private static final int NTHREADS = 10;
48
25149 private static final int NROUNDS = 10000;
25250
25351 private AtomicLongArray measureTime(final Format printer, final Format parser) throws InterruptedException {
26159 try {
26260 final Date date = new Date();
26361
264 final long t0 = System.currentTimeMillis();
62 final long t0Millis = System.currentTimeMillis();
26563 final String formattedDate = printer.format(date);
266 totalElapsed.addAndGet(0, System.currentTimeMillis() - t0);
267
268 final long t1 = System.currentTimeMillis();
64 totalElapsed.addAndGet(0, System.currentTimeMillis() - t0Millis);
65
66 final long t1Millis = System.currentTimeMillis();
26967 final Object pd = parser.parseObject(formattedDate);
270 totalElapsed.addAndGet(1, System.currentTimeMillis() - t1);
68 totalElapsed.addAndGet(1, System.currentTimeMillis() - t1Millis);
27169
27270 if (!date.equals(pd)) {
27371 failures.incrementAndGet();
29391 return totalElapsed;
29492 }
29593
94 @DefaultLocale(language = "en", country = "US")
95 @Test
96 public void test_changeDefault_Locale_DateInstance() {
97 final FastDateFormat format1 = FastDateFormat.getDateInstance(FastDateFormat.FULL, Locale.GERMANY);
98 final FastDateFormat format2 = FastDateFormat.getDateInstance(FastDateFormat.FULL);
99 Locale.setDefault(Locale.GERMANY);
100 final FastDateFormat format3 = FastDateFormat.getDateInstance(FastDateFormat.FULL);
101
102 assertSame(Locale.GERMANY, format1.getLocale());
103 assertEquals(Locale.US, format2.getLocale());
104 assertSame(Locale.GERMANY, format3.getLocale());
105 assertNotSame(format1, format2);
106 assertNotSame(format2, format3);
107 }
108
109 @DefaultLocale(language = "en", country = "US")
110 @Test
111 public void test_changeDefault_Locale_DateTimeInstance() {
112 final FastDateFormat format1 = FastDateFormat.getDateTimeInstance(FastDateFormat.FULL, FastDateFormat.FULL, Locale.GERMANY);
113 final FastDateFormat format2 = FastDateFormat.getDateTimeInstance(FastDateFormat.FULL, FastDateFormat.FULL);
114 Locale.setDefault(Locale.GERMANY);
115 final FastDateFormat format3 = FastDateFormat.getDateTimeInstance(FastDateFormat.FULL, FastDateFormat.FULL);
116
117 assertSame(Locale.GERMANY, format1.getLocale());
118 assertEquals(Locale.US, format2.getLocale());
119 assertSame(Locale.GERMANY, format3.getLocale());
120 assertNotSame(format1, format2);
121 assertNotSame(format2, format3);
122 }
123
124 /*
125 * Only the cache methods need to be tested here.
126 * The print methods are tested by {@link FastDateFormat_PrinterTest}
127 * and the parse methods are tested by {@link FastDateFormat_ParserTest}
128 */
129 @Test
130 public void test_getInstance() {
131 final FastDateFormat format1 = FastDateFormat.getInstance();
132 final FastDateFormat format2 = FastDateFormat.getInstance();
133 assertSame(format1, format2);
134 }
135
136 @Test
137 public void test_getInstance_String() {
138 final FastDateFormat format1 = FastDateFormat.getInstance("MM/DD/yyyy");
139 final FastDateFormat format2 = FastDateFormat.getInstance("MM-DD-yyyy");
140 final FastDateFormat format3 = FastDateFormat.getInstance("MM-DD-yyyy");
141
142 assertNotSame(format1, format2);
143 assertSame(format2, format3);
144 assertEquals("MM/DD/yyyy", format1.getPattern());
145 assertEquals(TimeZone.getDefault(), format1.getTimeZone());
146 assertEquals(TimeZone.getDefault(), format2.getTimeZone());
147 }
148
149 @DefaultLocale(language = "en", country = "US")
150 @Test
151 public void test_getInstance_String_Locale() {
152 final FastDateFormat format1 = FastDateFormat.getInstance("MM/DD/yyyy", Locale.GERMANY);
153 final FastDateFormat format2 = FastDateFormat.getInstance("MM/DD/yyyy");
154 final FastDateFormat format3 = FastDateFormat.getInstance("MM/DD/yyyy", Locale.GERMANY);
155
156 assertNotSame(format1, format2);
157 assertSame(format1, format3);
158 assertEquals(Locale.GERMANY, format1.getLocale());
159 }
160
161 @DefaultLocale(language = "en", country = "US")
162 @DefaultTimeZone("America/New_York")
163 @Test
164 public void test_getInstance_String_TimeZone() {
165
166 final FastDateFormat format1 = FastDateFormat.getInstance("MM/DD/yyyy",
167 TimeZone.getTimeZone("Atlantic/Reykjavik"));
168 final FastDateFormat format2 = FastDateFormat.getInstance("MM/DD/yyyy");
169 final FastDateFormat format3 = FastDateFormat.getInstance("MM/DD/yyyy", TimeZone.getDefault());
170 final FastDateFormat format4 = FastDateFormat.getInstance("MM/DD/yyyy", TimeZone.getDefault());
171 final FastDateFormat format5 = FastDateFormat.getInstance("MM-DD-yyyy", TimeZone.getDefault());
172 final FastDateFormat format6 = FastDateFormat.getInstance("MM-DD-yyyy");
173
174 assertNotSame(format1, format2);
175 assertEquals(TimeZone.getTimeZone("Atlantic/Reykjavik"), format1.getTimeZone());
176 assertEquals(TimeZone.getDefault(), format2.getTimeZone());
177 assertSame(format3, format4);
178 assertNotSame(format3, format5);
179 assertNotSame(format4, format6);
180 }
181
182 @DefaultLocale(language = "en", country = "US")
183 @DefaultTimeZone("America/New_York")
184 @Test
185 public void test_getInstance_String_TimeZone_Locale() {
186 final FastDateFormat format1 = FastDateFormat.getInstance("MM/DD/yyyy",
187 TimeZone.getTimeZone("Atlantic/Reykjavik"), Locale.GERMANY);
188 final FastDateFormat format2 = FastDateFormat.getInstance("MM/DD/yyyy", Locale.GERMANY);
189 final FastDateFormat format3 = FastDateFormat.getInstance("MM/DD/yyyy",
190 TimeZone.getDefault(), Locale.GERMANY);
191
192 assertNotSame(format1, format2);
193 assertEquals(TimeZone.getTimeZone("Atlantic/Reykjavik"), format1.getTimeZone());
194 assertEquals(TimeZone.getDefault(), format2.getTimeZone());
195 assertEquals(TimeZone.getDefault(), format3.getTimeZone());
196 assertEquals(Locale.GERMANY, format1.getLocale());
197 assertEquals(Locale.GERMANY, format2.getLocale());
198 assertEquals(Locale.GERMANY, format3.getLocale());
199 }
200
201 @Test
202 public void testCheckDefaults() {
203 final FastDateFormat format = FastDateFormat.getInstance();
204 final FastDateFormat medium = FastDateFormat.getDateTimeInstance(FastDateFormat.SHORT, FastDateFormat.SHORT);
205 assertEquals(medium, format);
206
207 final SimpleDateFormat sdf = new SimpleDateFormat();
208 assertEquals(sdf.toPattern(), format.getPattern());
209
210 assertEquals(Locale.getDefault(), format.getLocale());
211 assertEquals(TimeZone.getDefault(), format.getTimeZone());
212 }
213
214 @Test
215 public void testCheckDifferingStyles() {
216 final FastDateFormat shortShort = FastDateFormat.getDateTimeInstance(FastDateFormat.SHORT, FastDateFormat.SHORT, Locale.US);
217 final FastDateFormat shortLong = FastDateFormat.getDateTimeInstance(FastDateFormat.SHORT, FastDateFormat.LONG, Locale.US);
218 final FastDateFormat longShort = FastDateFormat.getDateTimeInstance(FastDateFormat.LONG, FastDateFormat.SHORT, Locale.US);
219 final FastDateFormat longLong = FastDateFormat.getDateTimeInstance(FastDateFormat.LONG, FastDateFormat.LONG, Locale.US);
220
221 assertNotEquals(shortShort, shortLong);
222 assertNotEquals(shortShort, longShort);
223 assertNotEquals(shortShort, longLong);
224 assertNotEquals(shortLong, longShort);
225 assertNotEquals(shortLong, longLong);
226 assertNotEquals(longShort, longLong);
227 }
228
229 @Test
230 public void testDateDefaults() {
231 assertEquals(FastDateFormat.getDateInstance(FastDateFormat.LONG, Locale.CANADA),
232 FastDateFormat.getDateInstance(FastDateFormat.LONG, TimeZone.getDefault(), Locale.CANADA));
233
234 assertEquals(FastDateFormat.getDateInstance(FastDateFormat.LONG, TimeZone.getTimeZone("America/New_York")),
235 FastDateFormat.getDateInstance(FastDateFormat.LONG, TimeZone.getTimeZone("America/New_York"), Locale.getDefault()));
236
237 assertEquals(FastDateFormat.getDateInstance(FastDateFormat.LONG),
238 FastDateFormat.getDateInstance(FastDateFormat.LONG, TimeZone.getDefault(), Locale.getDefault()));
239 }
240
241 @Test
242 public void testLANG_1152() {
243 final TimeZone utc = FastTimeZone.getGmtTimeZone();
244 final Date date = new Date(Long.MAX_VALUE);
245
246 String dateAsString = FastDateFormat.getInstance("yyyy-MM-dd", utc, Locale.US).format(date);
247 assertEquals("292278994-08-17", dateAsString);
248
249 dateAsString = FastDateFormat.getInstance("dd/MM/yyyy", utc, Locale.US).format(date);
250 assertEquals("17/08/292278994", dateAsString);
251 }
252 @Test
253 public void testLANG_1267() {
254 FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
255 }
256
296257 /**
297258 * According to LANG-954 (https://issues.apache.org/jira/browse/LANG-954) this is broken in Android 2.1.
298259 */
303264 }
304265
305266 @Test
306 public void testLANG_1152() {
307 final TimeZone utc = FastTimeZone.getGmtTimeZone();
308 final Date date = new Date(Long.MAX_VALUE);
309
310 String dateAsString = FastDateFormat.getInstance("yyyy-MM-dd", utc, Locale.US).format(date);
311 assertEquals("292278994-08-17", dateAsString);
312
313 dateAsString = FastDateFormat.getInstance("dd/MM/yyyy", utc, Locale.US).format(date);
314 assertEquals("17/08/292278994", dateAsString);
315 }
316
317 @Test
318 public void testLANG_1267() {
319 FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
267 public void testParseSync() throws InterruptedException {
268 final String pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS";
269 final SimpleDateFormat inner = new SimpleDateFormat(pattern);
270 final Format sdf= new Format() {
271 private static final long serialVersionUID = 1L;
272
273 @Override
274 public StringBuffer format(final Object obj,
275 final StringBuffer toAppendTo,
276 final FieldPosition fieldPosition) {
277 synchronized(this) {
278 return inner.format(obj, toAppendTo, fieldPosition);
279 }
280 }
281
282 @Override
283 public Object parseObject(final String source, final ParsePosition pos) {
284 synchronized(this) {
285 return inner.parseObject(source, pos);
286 }
287 }
288 };
289 final AtomicLongArray sdfTime= measureTime(sdf, sdf);
290
291 final Format fdf = FastDateFormat.getInstance(pattern);
292 final AtomicLongArray fdfTime= measureTime(fdf, fdf);
293
294 //System.out.println(">>FastDateFormatTest: FastDatePrinter:"+fdfTime.get(0)+" SimpleDateFormat:"+sdfTime.get(0));
295 //System.out.println(">>FastDateFormatTest: FastDateParser:"+fdfTime.get(1)+" SimpleDateFormat:"+sdfTime.get(1));
296 }
297
298 @Test
299 public void testTimeDateDefaults() {
300 assertEquals(FastDateFormat.getDateTimeInstance(FastDateFormat.LONG, FastDateFormat.MEDIUM, Locale.CANADA),
301 FastDateFormat.getDateTimeInstance(FastDateFormat.LONG, FastDateFormat.MEDIUM, TimeZone.getDefault(), Locale.CANADA));
302
303 assertEquals(FastDateFormat.getDateTimeInstance(FastDateFormat.LONG, FastDateFormat.MEDIUM, TimeZone.getTimeZone("America/New_York")),
304 FastDateFormat.getDateTimeInstance(FastDateFormat.LONG, FastDateFormat.MEDIUM, TimeZone.getTimeZone("America/New_York"), Locale.getDefault()));
305
306 assertEquals(FastDateFormat.getDateTimeInstance(FastDateFormat.LONG, FastDateFormat.MEDIUM),
307 FastDateFormat.getDateTimeInstance(FastDateFormat.LONG, FastDateFormat.MEDIUM, TimeZone.getDefault(), Locale.getDefault()));
308 }
309
310 @Test
311 public void testTimeDefaults() {
312 assertEquals(FastDateFormat.getTimeInstance(FastDateFormat.LONG, Locale.CANADA),
313 FastDateFormat.getTimeInstance(FastDateFormat.LONG, TimeZone.getDefault(), Locale.CANADA));
314
315 assertEquals(FastDateFormat.getTimeInstance(FastDateFormat.LONG, TimeZone.getTimeZone("America/New_York")),
316 FastDateFormat.getTimeInstance(FastDateFormat.LONG, TimeZone.getTimeZone("America/New_York"), Locale.getDefault()));
317
318 assertEquals(FastDateFormat.getTimeInstance(FastDateFormat.LONG),
319 FastDateFormat.getTimeInstance(FastDateFormat.LONG, TimeZone.getDefault(), Locale.getDefault()));
320320 }
321321 }
+0
-33
src/test/java/org/apache/commons/lang3/time/FastDateFormat_ParserTest.java less more
0 /*
1 * Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package org.apache.commons.lang3.time;
17
18 import java.util.Locale;
19 import java.util.TimeZone;
20
21 /**
22 * Unit tests for the parse methods of FastDateFormat
23 *
24 * @since 3.2
25 */
26 public class FastDateFormat_ParserTest extends FastDateParserTest {
27
28 @Override
29 protected DateParser getInstance(final String format, final TimeZone timeZone, final Locale locale) {
30 return FastDateFormat.getInstance(format, timeZone, locale);
31 }
32 }
3737 */
3838 public class FastDateParserSDFTest {
3939
40 private static final TimeZone timeZone = TimeZone.getDefault();
41
4042 public static Stream<Arguments> data() {
4143 return Stream.of(
4244 // General Time zone tests
101103 );
102104 }
103105
104 private static final TimeZone timeZone = TimeZone.getDefault();
105
106 @ParameterizedTest
107 @MethodSource("data")
108 public void testOriginal(final String format, final String input, final Locale locale, final boolean valid) {
109 checkParse(input, format, locale, valid);
110 }
111
112 @ParameterizedTest
113 @MethodSource("data")
114 public void testOriginalPP(final String format, final String input, final Locale locale, final boolean valid) {
115 checkParsePosition(input, format, locale, valid);
116 }
117
118 @ParameterizedTest
119 @MethodSource("data")
120 public void testUpperCase(final String format, final String input, final Locale locale, final boolean valid) {
121 checkParse(input.toUpperCase(locale), format, locale, valid);
122 }
123
124 @ParameterizedTest
125 @MethodSource("data")
126 public void testUpperCasePP(final String format, final String input, final Locale locale, final boolean valid) {
127 checkParsePosition(input.toUpperCase(locale), format, locale, valid);
128 }
129
130 @ParameterizedTest
131 @MethodSource("data")
132 public void testLowerCase(final String format, final String input, final Locale locale, final boolean valid) {
133 checkParse(input.toLowerCase(locale), format, locale, valid);
134 }
135
136 @ParameterizedTest
137 @MethodSource("data")
138 public void testLowerCasePP(final String format, final String input, final Locale locale, final boolean valid) {
139 checkParsePosition(input.toLowerCase(locale), format, locale, valid);
140 }
141
142106 private void checkParse(final String formattedDate, final String format, final Locale locale, final boolean valid) {
143107 final SimpleDateFormat sdf = new SimpleDateFormat(format, locale);
144108 sdf.setTimeZone(timeZone);
175139 assertEquals(sdfE, fdfE, locale.toString()+" "+formattedDate + " expected same Exception ");
176140 }
177141 }
142
178143 private void checkParsePosition(final String formattedDate, final String format, final Locale locale, final boolean valid) {
179144 final SimpleDateFormat sdf = new SimpleDateFormat(format, locale);
180145 sdf.setTimeZone(timeZone);
213178 "FDF error index ("+ fdferrorIndex + ") should approximate SDF index (" + sdferrorIndex + ")");
214179 }
215180 }
181
182 @ParameterizedTest
183 @MethodSource("data")
184 public void testLowerCase(final String format, final String input, final Locale locale, final boolean valid) {
185 checkParse(input.toLowerCase(locale), format, locale, valid);
186 }
187
188 @ParameterizedTest
189 @MethodSource("data")
190 public void testLowerCasePP(final String format, final String input, final Locale locale, final boolean valid) {
191 checkParsePosition(input.toLowerCase(locale), format, locale, valid);
192 }
193
194 @ParameterizedTest
195 @MethodSource("data")
196 public void testOriginal(final String format, final String input, final Locale locale, final boolean valid) {
197 checkParse(input, format, locale, valid);
198 }
199
200 @ParameterizedTest
201 @MethodSource("data")
202 public void testOriginalPP(final String format, final String input, final Locale locale, final boolean valid) {
203 checkParsePosition(input, format, locale, valid);
204 }
205
206 @ParameterizedTest
207 @MethodSource("data")
208 public void testUpperCase(final String format, final String input, final Locale locale, final boolean valid) {
209 checkParse(input.toUpperCase(locale), format, locale, valid);
210 }
211 @ParameterizedTest
212 @MethodSource("data")
213 public void testUpperCasePP(final String format, final String input, final Locale locale, final boolean valid) {
214 checkParsePosition(input.toUpperCase(locale), format, locale, valid);
215 }
216216 }
1818 import static org.junit.jupiter.api.Assertions.assertEquals;
1919 import static org.junit.jupiter.api.Assertions.assertFalse;
2020 import static org.junit.jupiter.api.Assertions.assertNotEquals;
21 import static org.junit.jupiter.api.Assertions.assertNotNull;
2122 import static org.junit.jupiter.api.Assertions.assertThrows;
2223 import static org.junit.jupiter.api.Assertions.assertTrue;
2324 import static org.junit.jupiter.api.Assertions.fail;
3334 import java.util.Locale;
3435 import java.util.Map;
3536 import java.util.TimeZone;
37 import java.util.stream.Stream;
3638
3739 import org.apache.commons.lang3.LocaleUtils;
3840 import org.apache.commons.lang3.SerializationUtils;
41 import org.apache.commons.lang3.SystemUtils;
42 import org.apache.commons.lang3.function.TriFunction;
3943 import org.junit.jupiter.api.Test;
44 import org.junit.jupiter.params.ParameterizedTest;
45 import org.junit.jupiter.params.provider.Arguments;
46 import org.junit.jupiter.params.provider.MethodSource;
4047
4148 /**
4249 * Unit tests {@link org.apache.commons.lang3.time.FastDateParser}.
4451 * @since 3.2
4552 */
4653 public class FastDateParserTest {
47 private static final String SHORT_FORMAT_NOERA = "y/M/d/h/a/m/s/E";
48 private static final String LONG_FORMAT_NOERA = "yyyy/MMMM/dddd/hhhh/mmmm/ss/aaaa/EEEE";
49 private static final String SHORT_FORMAT = "G/" + SHORT_FORMAT_NOERA;
50 private static final String LONG_FORMAT = "GGGG/" + LONG_FORMAT_NOERA;
54
55 private enum Expected1806 {
56 India(INDIA, "+05", "+0530", "+05:30", true), Greenwich(GMT, "Z", "Z", "Z", false),
57 NewYork(NEW_YORK, "-05", "-0500", "-05:00", false);
58
59 final TimeZone zone;
60
61 final String one;
62 final String two;
63 final String three;
64 final long offset;
65
66 Expected1806(final TimeZone zone, final String one, final String two, final String three,
67 final boolean hasHalfHourOffset) {
68 this.zone = zone;
69 this.one = one;
70 this.two = two;
71 this.three = three;
72 this.offset = hasHalfHourOffset ? 30 * 60 * 1000 : 0;
73 }
74 }
75
76 static final String DATE_PARSER_PARAMETERS = "dateParserParameters";
77
78 static final String SHORT_FORMAT_NOERA = "y/M/d/h/a/m/s/E";
79
80 static final String LONG_FORMAT_NOERA = "yyyy/MMMM/dddd/hhhh/mmmm/ss/aaaa/EEEE";
81 static final String SHORT_FORMAT = "G/" + SHORT_FORMAT_NOERA;
82 static final String LONG_FORMAT = "GGGG/" + LONG_FORMAT_NOERA;
5183
5284 private static final String yMdHmsSZ = "yyyy-MM-dd'T'HH:mm:ss.SSS Z";
5385 private static final String DMY_DOT = "dd.MM.yyyy";
5789
5890 private static final TimeZone REYKJAVIK = TimeZone.getTimeZone("Atlantic/Reykjavik");
5991 private static final TimeZone NEW_YORK = TimeZone.getTimeZone("America/New_York");
60 private static final TimeZone GMT = TimeZone.getTimeZone("GMT");
92 static final TimeZone GMT = TimeZone.getTimeZone("GMT");
6193 private static final TimeZone INDIA = TimeZone.getTimeZone("Asia/Calcutta");
6294
6395 private static final Locale SWEDEN = new Locale("sv", "SE");
6496
97 static void checkParse(final Locale locale, final Calendar cal, final SimpleDateFormat simpleDateFormat,
98 final DateParser dateParser) {
99 final String formattedDate = simpleDateFormat.format(cal.getTime());
100 checkParse(locale, simpleDateFormat, dateParser, formattedDate, formattedDate);
101 checkParse(locale, simpleDateFormat, dateParser, formattedDate.toLowerCase(locale), formattedDate);
102 checkParse(locale, simpleDateFormat, dateParser, formattedDate.toUpperCase(locale), formattedDate);
103 }
104
105 static void checkParse(final Locale locale, final SimpleDateFormat simpleDateFormat, final DateParser dateParser,
106 final String formattedDate, final String originalFormattedDate) {
107 try {
108 final Date expectedTime = simpleDateFormat.parse(formattedDate);
109 final Date actualTime = dateParser.parse(formattedDate);
110 assertEquals(expectedTime, actualTime,
111 "locale: " + locale + ", formattedDate: '" + formattedDate + "', originalFormattedDate: '"
112 + originalFormattedDate + ", simpleDateFormat.pattern: '" + simpleDateFormat + "', Java: "
113 + SystemUtils.JAVA_RUNTIME_VERSION + "\n");
114 } catch (final Exception e) {
115 fail("locale: " + locale + ", formattedDate: '" + formattedDate + "', error : " + e + "\n", e);
116 }
117 }
118
119 static Stream<Arguments> dateParserParameters() {
120 return Stream.of(
121 // @formatter:off
122 Arguments.of((TriFunction<String, TimeZone, Locale, DateParser>) (format, timeZone, locale)
123 -> new FastDateParser(format, timeZone, locale, null)),
124 Arguments.of((TriFunction<String, TimeZone, Locale, DateParser>) FastDateFormat::getInstance)
125 // @formatter:on
126 );
127 }
128
129 private static Calendar initializeCalendar(final TimeZone timeZone) {
130 final Calendar cal = Calendar.getInstance(timeZone);
131 cal.set(Calendar.YEAR, 2001);
132 cal.set(Calendar.MONTH, 1); // not daylight savings
133 cal.set(Calendar.DAY_OF_MONTH, 4);
134 cal.set(Calendar.HOUR_OF_DAY, 12);
135 cal.set(Calendar.MINUTE, 8);
136 cal.set(Calendar.SECOND, 56);
137 cal.set(Calendar.MILLISECOND, 235);
138 return cal;
139 }
140
141 private final TriFunction<String, TimeZone, Locale, DateParser> dateParserProvider = (format, timeZone,
142 locale) -> new FastDateParser(format, timeZone, locale, null);
143
144 private DateParser getDateInstance(final int dateStyle, final Locale locale) {
145 return getInstance(null, FormatCache.getPatternForStyle(Integer.valueOf(dateStyle), null, locale),
146 TimeZone.getDefault(), Locale.getDefault());
147 }
148
149 private Calendar getEraStart(int year, final TimeZone zone, final Locale locale) {
150 final Calendar cal = Calendar.getInstance(zone, locale);
151 cal.clear();
152
153 // http://docs.oracle.com/javase/6/docs/technotes/guides/intl/calendar.doc.html
154 if (locale.equals(FastDateParser.JAPANESE_IMPERIAL)) {
155 if (year < 1868) {
156 cal.set(Calendar.ERA, 0);
157 cal.set(Calendar.YEAR, 1868 - year);
158 }
159 } else {
160 if (year < 0) {
161 cal.set(Calendar.ERA, GregorianCalendar.BC);
162 year = -year;
163 }
164 cal.set(Calendar.YEAR, year / 100 * 100);
165 }
166 return cal;
167 }
168
65169 DateParser getInstance(final String format) {
66 return getInstance(format, TimeZone.getDefault(), Locale.getDefault());
67 }
68
69 private DateParser getDateInstance(final int dateStyle, final Locale locale) {
70 return getInstance(FormatCache.getPatternForStyle(Integer.valueOf(dateStyle), null, locale), TimeZone.getDefault(), Locale.getDefault());
71 }
72
73 private DateParser getInstance(final String format, final Locale locale) {
74 return getInstance(format, TimeZone.getDefault(), locale);
170 return getInstance(null, format, TimeZone.getDefault(), Locale.getDefault());
171 }
172
173 DateParser getInstance(final String format, final Locale locale) {
174 return getInstance(null, format, TimeZone.getDefault(), locale);
75175 }
76176
77177 private DateParser getInstance(final String format, final TimeZone timeZone) {
78 return getInstance(format, timeZone, Locale.getDefault());
178 return getInstance(null, format, timeZone, Locale.getDefault());
79179 }
80180
81181 /**
82182 * Override this method in derived tests to change the construction of instances
83183 *
184 * @param dpProvider TODO
84185 * @param format the format string to use
85186 * @param timeZone the time zone to use
86187 * @param locale the locale to use
87188 *
88189 * @return the DateParser instance to use for testing
89190 */
90 protected DateParser getInstance(final String format, final TimeZone timeZone, final Locale locale) {
91 return new FastDateParser(format, timeZone, locale, null);
92 }
93
94 @Test
95 public void test_Equality_Hash() {
96 final DateParser[] parsers= {
97 getInstance(yMdHmsSZ, NEW_YORK, Locale.US),
98 getInstance(DMY_DOT, NEW_YORK, Locale.US),
99 getInstance(YMD_SLASH, NEW_YORK, Locale.US),
100 getInstance(MDY_DASH, NEW_YORK, Locale.US),
101 getInstance(MDY_SLASH, NEW_YORK, Locale.US),
102 getInstance(MDY_SLASH, REYKJAVIK, Locale.US),
103 getInstance(MDY_SLASH, REYKJAVIK, SWEDEN)
104 };
105
106 final Map<DateParser, Integer> map= new HashMap<>();
107 int i= 0;
108 for (final DateParser parser:parsers) {
191 protected DateParser getInstance(final TriFunction<String, TimeZone, Locale, DateParser> dpProvider,
192 final String format, final TimeZone timeZone, final Locale locale) {
193 return (dpProvider == null ? this.dateParserProvider : dpProvider).apply(format, timeZone, locale);
194 }
195
196 @ParameterizedTest
197 @MethodSource(DATE_PARSER_PARAMETERS)
198 public void test_Equality_Hash(final TriFunction<String, TimeZone, Locale, DateParser> dpProvider) {
199 final DateParser[] parsers = {getInstance(dpProvider, yMdHmsSZ, NEW_YORK, Locale.US),
200 getInstance(dpProvider, DMY_DOT, NEW_YORK, Locale.US),
201 getInstance(dpProvider, YMD_SLASH, NEW_YORK, Locale.US),
202 getInstance(dpProvider, MDY_DASH, NEW_YORK, Locale.US),
203 getInstance(dpProvider, MDY_SLASH, NEW_YORK, Locale.US),
204 getInstance(dpProvider, MDY_SLASH, REYKJAVIK, Locale.US),
205 getInstance(dpProvider, MDY_SLASH, REYKJAVIK, SWEDEN)};
206
207 final Map<DateParser, Integer> map = new HashMap<>();
208 int i = 0;
209 for (final DateParser parser : parsers) {
109210 map.put(parser, Integer.valueOf(i++));
110211 }
111212
112 i= 0;
113 for (final DateParser parser:parsers) {
213 i = 0;
214 for (final DateParser parser : parsers) {
114215 assertEquals(i++, map.get(parser).intValue());
115216 }
116217 }
117218
118219 @Test
119 public void testParseZone() throws ParseException {
120 final Calendar cal= Calendar.getInstance(NEW_YORK, Locale.US);
121 cal.clear();
122 cal.set(2003, Calendar.JULY, 10, 16, 33, 20);
123
124 final DateParser fdf = getInstance(yMdHmsSZ, NEW_YORK, Locale.US);
125
126 assertEquals(cal.getTime(), fdf.parse("2003-07-10T15:33:20.000 -0500"));
127 assertEquals(cal.getTime(), fdf.parse("2003-07-10T15:33:20.000 GMT-05:00"));
128 assertEquals(cal.getTime(), fdf.parse("2003-07-10T16:33:20.000 Eastern Daylight Time"));
129 assertEquals(cal.getTime(), fdf.parse("2003-07-10T16:33:20.000 EDT"));
130
131 cal.setTimeZone(TimeZone.getTimeZone("GMT-3"));
132 cal.set(2003, Calendar.FEBRUARY, 10, 9, 0, 0);
133
134 assertEquals(cal.getTime(), fdf.parse("2003-02-10T09:00:00.000 -0300"));
135
136 cal.setTimeZone(TimeZone.getTimeZone("GMT+5"));
137 cal.set(2003, Calendar.FEBRUARY, 10, 15, 5, 6);
138
139 assertEquals(cal.getTime(), fdf.parse("2003-02-10T15:05:06.000 +0500"));
140 }
141
142 @Test
143 public void testParseLongShort() throws ParseException {
144 final Calendar cal= Calendar.getInstance(NEW_YORK, Locale.US);
145 cal.clear();
146 cal.set(2003, Calendar.FEBRUARY, 10, 15, 33, 20);
147 cal.set(Calendar.MILLISECOND, 989);
148 cal.setTimeZone(NEW_YORK);
149
150 DateParser fdf = getInstance("yyyy GGGG MMMM dddd aaaa EEEE HHHH mmmm ssss SSSS ZZZZ", NEW_YORK, Locale.US);
151
152 assertEquals(cal.getTime(), fdf.parse("2003 AD February 0010 PM Monday 0015 0033 0020 0989 GMT-05:00"));
153 cal.set(Calendar.ERA, GregorianCalendar.BC);
154
155 final Date parse = fdf.parse("2003 BC February 0010 PM Saturday 0015 0033 0020 0989 GMT-05:00");
156 assertEquals(cal.getTime(), parse);
157
158 fdf = getInstance("y G M d a E H m s S Z", NEW_YORK, Locale.US);
159 assertEquals(cal.getTime(), fdf.parse("03 BC 2 10 PM Sat 15 33 20 989 -0500"));
160
161 cal.set(Calendar.ERA, GregorianCalendar.AD);
162 assertEquals(cal.getTime(), fdf.parse("03 AD 2 10 PM Saturday 15 33 20 989 -0500"));
163 }
164
165 @Test
166 public void testAmPm() throws ParseException {
167 final Calendar cal= Calendar.getInstance(NEW_YORK, Locale.US);
168 cal.clear();
169
170 final DateParser h = getInstance("yyyy-MM-dd hh a mm:ss", NEW_YORK, Locale.US);
171 final DateParser K = getInstance("yyyy-MM-dd KK a mm:ss", NEW_YORK, Locale.US);
172 final DateParser k = getInstance("yyyy-MM-dd kk:mm:ss", NEW_YORK, Locale.US);
173 final DateParser H = getInstance("yyyy-MM-dd HH:mm:ss", NEW_YORK, Locale.US);
220 public void test1806() throws ParseException {
221 final String formatStub = "yyyy-MM-dd'T'HH:mm:ss.SSS";
222 final String dateStub = "2001-02-04T12:08:56.235";
223
224 for (final Expected1806 trial : Expected1806.values()) {
225 final Calendar cal = initializeCalendar(trial.zone);
226
227 final String message = trial.zone.getDisplayName() + ";";
228
229 DateParser parser = getInstance(formatStub + "X", trial.zone);
230 assertEquals(cal.getTime().getTime(), parser.parse(dateStub + trial.one).getTime() - trial.offset,
231 message + trial.one);
232
233 parser = getInstance(formatStub + "XX", trial.zone);
234 assertEquals(cal.getTime(), parser.parse(dateStub + trial.two), message + trial.two);
235
236 parser = getInstance(formatStub + "XXX", trial.zone);
237 assertEquals(cal.getTime(), parser.parse(dateStub + trial.three), message + trial.three);
238 }
239 }
240
241 @Test
242 public void test1806Argument() {
243 assertThrows(IllegalArgumentException.class, () -> getInstance("XXXX"));
244 }
245
246 @ParameterizedTest
247 @MethodSource(DATE_PARSER_PARAMETERS)
248 public void testAmPm(final TriFunction<String, TimeZone, Locale, DateParser> dpProvider) throws ParseException {
249 final Calendar cal = Calendar.getInstance(NEW_YORK, Locale.US);
250 cal.clear();
251
252 final DateParser h = getInstance(dpProvider, "yyyy-MM-dd hh a mm:ss", NEW_YORK, Locale.US);
253 final DateParser K = getInstance(dpProvider, "yyyy-MM-dd KK a mm:ss", NEW_YORK, Locale.US);
254 final DateParser k = getInstance(dpProvider, "yyyy-MM-dd kk:mm:ss", NEW_YORK, Locale.US);
255 final DateParser H = getInstance(dpProvider, "yyyy-MM-dd HH:mm:ss", NEW_YORK, Locale.US);
174256
175257 cal.set(2010, Calendar.AUGUST, 1, 0, 33, 20);
176258 assertEquals(cal.getTime(), h.parse("2010-08-01 12 AM 33:20"));
197279 assertEquals(cal.getTime(), H.parse("2010-08-01 12:33:20"));
198280 }
199281
200 private Calendar getEraStart(int year, final TimeZone zone, final Locale locale) {
201 final Calendar cal = Calendar.getInstance(zone, locale);
202 cal.clear();
203
204 // http://docs.oracle.com/javase/6/docs/technotes/guides/intl/calendar.doc.html
205 if (locale.equals(FastDateParser.JAPANESE_IMPERIAL)) {
206 if (year < 1868) {
207 cal.set(Calendar.ERA, 0);
208 cal.set(Calendar.YEAR, 1868-year);
209 }
210 } else {
211 if (year < 0) {
212 cal.set(Calendar.ERA, GregorianCalendar.BC);
213 year= -year;
214 }
215 cal.set(Calendar.YEAR, year/100 * 100);
216 }
217 return cal;
218 }
219
220 private void validateSdfFormatFdpParseEquality(final String format, final Locale locale, final TimeZone tz, final DateParser fdp, final Date in, final int year, final Date cs) throws ParseException {
221 final SimpleDateFormat sdf = new SimpleDateFormat(format, locale);
222 sdf.setTimeZone(tz);
223 if (format.equals(SHORT_FORMAT)) {
224 sdf.set2DigitYearStart( cs );
225 }
226 final String fmt = sdf.format(in);
227 try {
228 final Date out = fdp.parse(fmt);
229 assertEquals(in, out, locale.toString()+" "+in+" "+ format+ " "+tz.getID());
230 } catch (final ParseException pe) {
231 if (year >= 1868 || !locale.getCountry().equals("JP")) {// LANG-978
232 throw pe;
233 }
234 }
235 }
236
237 @Test
238 // Check that all Locales can parse the formats we use
239 public void testParses() throws Exception {
240 for (final String format : new String[]{LONG_FORMAT, SHORT_FORMAT}) {
241 for (final Locale locale : Locale.getAvailableLocales()) {
242 for (final TimeZone tz : new TimeZone[]{NEW_YORK, REYKJAVIK, GMT}) {
243 for (final int year : new int[]{2003, 1940, 1868, 1867, 1, -1, -1940}) {
244 final Calendar cal= getEraStart(year, tz, locale);
245 final Date centuryStart= cal.getTime();
246
247 cal.set(Calendar.MONTH, 1);
248 cal.set(Calendar.DAY_OF_MONTH, 10);
249 final Date in= cal.getTime();
250
251 final FastDateParser fdp= new FastDateParser(format, tz, locale, centuryStart);
252 validateSdfFormatFdpParseEquality(format, locale, tz, fdp, in, year, centuryStart);
253 }
254 }
255 }
256 }
257 }
258
259 // we cannot use historic dates to test timezone parsing, some timezones have second offsets
260 // as well as hours and minutes which makes the z formats a low fidelity round trip
261 @Test
262 public void testTzParses() throws Exception {
263 // Check that all Locales can parse the time formats we use
264 for (final Locale locale : Locale.getAvailableLocales()) {
265 final FastDateParser fdp= new FastDateParser("yyyy/MM/dd z", TimeZone.getDefault(), locale);
266
267 for (final TimeZone tz : new TimeZone[]{NEW_YORK, REYKJAVIK, GMT}) {
268 final Calendar cal= Calendar.getInstance(tz, locale);
269 cal.clear();
270 cal.set(Calendar.YEAR, 2000);
271 cal.set(Calendar.MONTH, 1);
272 cal.set(Calendar.DAY_OF_MONTH, 10);
273 final Date expected= cal.getTime();
274
275 final Date actual = fdp.parse("2000/02/10 "+tz.getDisplayName(locale));
276 assertEquals(expected, actual, "tz:"+tz.getID()+" locale:"+locale.getDisplayName());
277 }
278 }
279 }
280
281
282 @Test
283 public void testLocales_Long_AD() throws Exception {
284 testLocales(LONG_FORMAT, false);
285 }
286
287 @Test
288 public void testLocales_Long_BC() throws Exception {
289 testLocales(LONG_FORMAT, true);
290 }
291
292 @Test
293 public void testLocales_Short_AD() throws Exception {
294 testLocales(SHORT_FORMAT, false);
295 }
296
297 @Test
298 public void testLocales_Short_BC() throws Exception {
299 testLocales(SHORT_FORMAT, true);
300 }
301
302 @Test
303 public void testLocales_LongNoEra_AD() throws Exception {
304 testLocales(LONG_FORMAT_NOERA, false);
305 }
306
307 @Test
308 public void testLocales_LongNoEra_BC() throws Exception {
309 testLocales(LONG_FORMAT_NOERA, true);
310 }
311
312 @Test
313 public void testLocales_ShortNoEra_AD() throws Exception {
314 testLocales(SHORT_FORMAT_NOERA, false);
315 }
316
317 @Test
318 public void testLocales_ShortNoEra_BC() throws Exception {
319 testLocales(SHORT_FORMAT_NOERA, true);
320 }
321
322 private void testLocales(final String format, final boolean eraBC) throws Exception {
323
324 final Calendar cal= Calendar.getInstance(GMT);
282 @Test
283 public void testDayNumberOfWeek() throws ParseException {
284 final DateParser parser = getInstance("u");
285 final Calendar calendar = Calendar.getInstance();
286
287 calendar.setTime(parser.parse("1"));
288 assertEquals(Calendar.MONDAY, calendar.get(Calendar.DAY_OF_WEEK));
289
290 calendar.setTime(parser.parse("6"));
291 assertEquals(Calendar.SATURDAY, calendar.get(Calendar.DAY_OF_WEEK));
292
293 calendar.setTime(parser.parse("7"));
294 assertEquals(Calendar.SUNDAY, calendar.get(Calendar.DAY_OF_WEEK));
295 }
296
297 @ParameterizedTest
298 @MethodSource(DATE_PARSER_PARAMETERS)
299 public void testDayOf(final TriFunction<String, TimeZone, Locale, DateParser> dpProvider) throws ParseException {
300 final Calendar cal = Calendar.getInstance(NEW_YORK, Locale.US);
325301 cal.clear();
326302 cal.set(2003, Calendar.FEBRUARY, 10);
327 if (eraBC) {
328 cal.set(Calendar.ERA, GregorianCalendar.BC);
329 }
330
331 for (final Locale locale : Locale.getAvailableLocales() ) {
332 // ja_JP_JP cannot handle dates before 1868 properly
333 if (eraBC && locale.equals(FastDateParser.JAPANESE_IMPERIAL)) {
334 continue;
335 }
336 final SimpleDateFormat sdf = new SimpleDateFormat(format, locale);
337 final DateParser fdf = getInstance(format, locale);
338
339 // If parsing fails, a ParseException will be thrown and the test will fail
340 checkParse(locale, cal, sdf, fdf);
341 }
303
304 final DateParser fdf = getInstance(dpProvider, "W w F D y", NEW_YORK, Locale.US);
305 assertEquals(cal.getTime(), fdf.parse("3 7 2 41 03"));
306 }
307
308 @Test
309 public void testEquals() {
310 final DateParser parser1 = getInstance(YMD_SLASH);
311 final DateParser parser2 = getInstance(YMD_SLASH);
312
313 assertEquals(parser1, parser2);
314 assertEquals(parser1.hashCode(), parser2.hashCode());
315
316 assertNotEquals(parser1, new Object());
342317 }
343318
344319 @Test
345320 public void testJpLocales() throws ParseException {
346321
347 final Calendar cal= Calendar.getInstance(GMT);
322 final Calendar cal = Calendar.getInstance(GMT);
348323 cal.clear();
349324 cal.set(2003, Calendar.FEBRUARY, 10);
350325 cal.set(Calendar.ERA, GregorianCalendar.BC);
359334 checkParse(locale, cal, sdf, fdf);
360335 }
361336
362 private void checkParse(final Locale locale, final Calendar cal, final SimpleDateFormat sdf, final DateParser fdf) throws ParseException {
363 final String formattedDate= sdf.format(cal.getTime());
364 checkParse(locale, sdf, fdf, formattedDate);
365 checkParse(locale, sdf, fdf, formattedDate.toLowerCase(locale));
366 checkParse(locale, sdf, fdf, formattedDate.toUpperCase(locale));
367 }
368
369 private void checkParse(final Locale locale, final SimpleDateFormat sdf, final DateParser fdf, final String formattedDate) throws ParseException {
370 try {
371 final Date expectedTime = sdf.parse(formattedDate);
372 final Date actualTime = fdf.parse(formattedDate);
373 assertEquals(expectedTime, actualTime, "locale : " + locale + " formattedDate : " + formattedDate + "\n");
374 } catch (Exception e) {
375 fail("locale : " + locale + " formattedDate : " + formattedDate + " error : " + e + "\n", e);
376 }
377 }
378
379 @Test
380 public void testParseNumerics() throws ParseException {
381 final Calendar cal= Calendar.getInstance(NEW_YORK, Locale.US);
382 cal.clear();
383 cal.set(2003, Calendar.FEBRUARY, 10, 15, 33, 20);
384 cal.set(Calendar.MILLISECOND, 989);
385
386 final DateParser fdf = getInstance("yyyyMMddHHmmssSSS", NEW_YORK, Locale.US);
387 assertEquals(cal.getTime(), fdf.parse("20030210153320989"));
388 }
389
390 @Test
391 public void testQuotes() throws ParseException {
392 final Calendar cal= Calendar.getInstance(NEW_YORK, Locale.US);
393 cal.clear();
394 cal.set(2003, Calendar.FEBRUARY, 10, 15, 33, 20);
395 cal.set(Calendar.MILLISECOND, 989);
396
397 final DateParser fdf = getInstance("''yyyyMMdd'A''B'HHmmssSSS''", NEW_YORK, Locale.US);
398 assertEquals(cal.getTime(), fdf.parse("'20030210A'B153320989'"));
399 }
400
401 @Test
402 public void testSpecialCharacters() throws Exception {
403 testSdfAndFdp("q", "", true); // bad pattern character (at present)
404 testSdfAndFdp("Q", "", true); // bad pattern character
405 testSdfAndFdp("$", "$", false); // OK
406 testSdfAndFdp("?.d", "?.12", false); // OK
407 testSdfAndFdp("''yyyyMMdd'A''B'HHmmssSSS''", "'20030210A'B153320989'", false); // OK
408 testSdfAndFdp("''''yyyyMMdd'A''B'HHmmssSSS''", "''20030210A'B153320989'", false); // OK
409 testSdfAndFdp("'$\\Ed'", "$\\Ed", false); // OK
410
411 // quoted charaters are case sensitive
412 testSdfAndFdp("'QED'", "QED", false);
413 testSdfAndFdp("'QED'", "qed", true);
414 // case sensitive after insensitive Month field
415 testSdfAndFdp("yyyy-MM-dd 'QED'", "2003-02-10 QED", false);
416 testSdfAndFdp("yyyy-MM-dd 'QED'", "2003-02-10 qed", true);
417 }
418
419 @Test
420 public void testLANG_832() throws Exception {
421 testSdfAndFdp("'d'd", "d3", false); // OK
422 testSdfAndFdp("'d'd'", "d3", true); // should fail (unterminated quote)
423 }
424
425 @Test
426 public void testLANG_831() throws Exception {
427 testSdfAndFdp("M E", "3 Tue", true);
428 }
429
430 private void testSdfAndFdp(final String format, final String date, final boolean shouldFail)
431 throws Exception {
432 Date dfdp = null;
433 Date dsdf = null;
434 Throwable f = null;
435 Throwable s = null;
436
437 try {
438 final SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.US);
439 sdf.setTimeZone(NEW_YORK);
440 dsdf = sdf.parse(date);
441 assertFalse(shouldFail, "Expected SDF failure, but got " + dsdf + " for ["+format+", "+date+"]");
442 } catch (final Exception e) {
443 s = e;
444 if (!shouldFail) {
445 throw e;
446 }
447 }
448
449 try {
450 final DateParser fdp = getInstance(format, NEW_YORK, Locale.US);
451 dfdp = fdp.parse(date);
452 assertFalse(shouldFail, "Expected FDF failure, but got " + dfdp + " for ["+format+", "+date+"]");
453 } catch (final Exception e) {
454 f = e;
455 if (!shouldFail) {
456 throw e;
457 }
458 }
459 // SDF and FDF should produce equivalent results
460 assertEquals((f == null), (s == null), "Should both or neither throw Exceptions");
461 assertEquals(dsdf, dfdp, "Parsed dates should be equal");
462 }
463
464 @Test
465 public void testDayOf() throws ParseException {
466 final Calendar cal= Calendar.getInstance(NEW_YORK, Locale.US);
467 cal.clear();
468 cal.set(2003, Calendar.FEBRUARY, 10);
469
470 final DateParser fdf = getInstance("W w F D y", NEW_YORK, Locale.US);
471 assertEquals(cal.getTime(), fdf.parse("3 7 2 41 03"));
472 }
473
474 /**
475 * Test case for {@link FastDateParser#FastDateParser(String, TimeZone, Locale)}.
476 * @throws ParseException so we don't have to catch it
477 */
478 @Test
479 public void testShortDateStyleWithLocales() throws ParseException {
480 DateParser fdf = getDateInstance(FastDateFormat.SHORT, Locale.US);
337 @ParameterizedTest
338 @MethodSource(DATE_PARSER_PARAMETERS)
339 public void testLANG_831(final TriFunction<String, TimeZone, Locale, DateParser> dpProvider) throws Exception {
340 testSdfAndFdp(dpProvider, "M E", "3 Tue", true);
341 }
342
343 @ParameterizedTest
344 @MethodSource(DATE_PARSER_PARAMETERS)
345 public void testLANG_832(final TriFunction<String, TimeZone, Locale, DateParser> dpProvider) throws Exception {
346 testSdfAndFdp(dpProvider, "'d'd", "d3", false); // OK
347 testSdfAndFdp(dpProvider, "'d'd'", "d3", true); // should fail (unterminated quote)
348 }
349
350 @ParameterizedTest
351 @MethodSource(DATE_PARSER_PARAMETERS)
352 public void testLang1121(final TriFunction<String, TimeZone, Locale, DateParser> dpProvider) throws ParseException {
353 final TimeZone kst = TimeZone.getTimeZone("KST");
354 final DateParser fdp = getInstance(dpProvider, "yyyyMMdd", kst, Locale.KOREA);
355
356 assertThrows(ParseException.class, () -> fdp.parse("2015"));
357
358 // Wed Apr 29 00:00:00 KST 2015
359 Date actual = fdp.parse("20150429");
360 final Calendar cal = Calendar.getInstance(kst, Locale.KOREA);
361 cal.clear();
362 cal.set(2015, 3, 29);
363 Date expected = cal.getTime();
364 assertEquals(expected, actual);
365
366 final SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd", Locale.KOREA);
367 df.setTimeZone(kst);
368 expected = df.parse("20150429113100");
369
370 // Thu Mar 16 00:00:00 KST 81724
371 actual = fdp.parse("20150429113100");
372 assertEquals(expected, actual);
373 }
374
375 @ParameterizedTest
376 @MethodSource(DATE_PARSER_PARAMETERS)
377 public void testLang1380(final TriFunction<String, TimeZone, Locale, DateParser> dpProvider) throws ParseException {
378 final Calendar expected = Calendar.getInstance(GMT, Locale.FRANCE);
379 expected.clear();
380 expected.set(2014, Calendar.APRIL, 14);
381
382 final DateParser fdp = getInstance(dpProvider, "dd MMM yyyy", GMT, Locale.FRANCE);
383 assertEquals(expected.getTime(), fdp.parse("14 avril 2014"));
384 assertEquals(expected.getTime(), fdp.parse("14 avr. 2014"));
385 assertEquals(expected.getTime(), fdp.parse("14 avr 2014"));
386 }
387
388 @Test
389 public void testLang303() throws ParseException {
390 DateParser parser = getInstance(YMD_SLASH);
481391 final Calendar cal = Calendar.getInstance();
482 cal.clear();
483
484 cal.set(2004, Calendar.FEBRUARY, 3);
485 assertEquals(cal.getTime(), fdf.parse("2/3/04"));
486
487 fdf = getDateInstance(FastDateFormat.SHORT, SWEDEN);
488 assertEquals(cal.getTime(), fdf.parse("2004-02-03"));
392 cal.set(2004, Calendar.DECEMBER, 31);
393
394 final Date date = parser.parse("2004/11/31");
395
396 parser = SerializationUtils.deserialize(SerializationUtils.serialize((Serializable) parser));
397 assertEquals(date, parser.parse("2004/11/31"));
398 }
399
400 @Test
401 public void testLang538() throws ParseException {
402 final DateParser parser = getInstance("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", GMT);
403
404 final Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT-8"));
405 cal.clear();
406 cal.set(2009, Calendar.OCTOBER, 16, 8, 42, 16);
407
408 assertEquals(cal.getTime(), parser.parse("2009-10-16T16:42:16.000Z"));
409 }
410
411 @ParameterizedTest
412 @MethodSource(DATE_PARSER_PARAMETERS)
413 public void testLang996(final TriFunction<String, TimeZone, Locale, DateParser> dpProvider) throws ParseException {
414 final Calendar expected = Calendar.getInstance(NEW_YORK, Locale.US);
415 expected.clear();
416 expected.set(2014, Calendar.MAY, 14);
417
418 final DateParser fdp = getInstance(dpProvider, "ddMMMyyyy", NEW_YORK, Locale.US);
419 assertEquals(expected.getTime(), fdp.parse("14may2014"));
420 assertEquals(expected.getTime(), fdp.parse("14MAY2014"));
421 assertEquals(expected.getTime(), fdp.parse("14May2014"));
422 }
423
424 @Test
425 public void testLocaleMatches() {
426 final DateParser parser = getInstance(yMdHmsSZ, SWEDEN);
427 assertEquals(SWEDEN, parser.getLocale());
489428 }
490429
491430 /**
492431 * Tests that pre-1000AD years get padded with yyyy
432 *
493433 * @throws ParseException so we don't have to catch it
494434 */
495435 @Test
518458 assertEquals(cal.getTime(), parser.parse("01.01.1000"));
519459 }
520460
521 @Test
522 public void testLang303() throws ParseException {
523 DateParser parser = getInstance(YMD_SLASH);
524 final Calendar cal = Calendar.getInstance();
525 cal.set(2004, Calendar.DECEMBER, 31);
526
527 final Date date = parser.parse("2004/11/31");
528
529 parser = SerializationUtils.deserialize(SerializationUtils.serialize((Serializable) parser));
530 assertEquals(date, parser.parse("2004/11/31"));
531 }
532
533 @Test
534 public void testLang538() throws ParseException {
535 final DateParser parser = getInstance("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", GMT);
536
537 final Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT-8"));
538 cal.clear();
539 cal.set(2009, Calendar.OCTOBER, 16, 8, 42, 16);
540
541 assertEquals(cal.getTime(), parser.parse("2009-10-16T16:42:16.000Z"));
542 }
543
544 @Test
545 public void testEquals() {
546 final DateParser parser1= getInstance(YMD_SLASH);
547 final DateParser parser2= getInstance(YMD_SLASH);
548
549 assertEquals(parser1, parser2);
550 assertEquals(parser1.hashCode(), parser2.hashCode());
551
552 assertNotEquals(parser1, new Object());
553 }
554
555 @Test
556 public void testToStringContainsName() {
557 final DateParser parser= getInstance(YMD_SLASH);
558 assertTrue(parser.toString().startsWith("FastDate"));
559 }
560
561 @Test
562 public void testPatternMatches() {
563 final DateParser parser= getInstance(yMdHmsSZ);
564 assertEquals(yMdHmsSZ, parser.getPattern());
565 }
566
567 @Test
568 public void testLocaleMatches() {
569 final DateParser parser= getInstance(yMdHmsSZ, SWEDEN);
570 assertEquals(SWEDEN, parser.getLocale());
571 }
572
573 @Test
574 public void testTimeZoneMatches() {
575 final DateParser parser= getInstance(yMdHmsSZ, REYKJAVIK);
576 assertEquals(REYKJAVIK, parser.getTimeZone());
577 }
578
579 @Test
580 public void testLang996() throws ParseException {
581 final Calendar expected = Calendar.getInstance(NEW_YORK, Locale.US);
582 expected.clear();
583 expected.set(2014, Calendar.MAY, 14);
584
585 final DateParser fdp = getInstance("ddMMMyyyy", NEW_YORK, Locale.US);
586 assertEquals(expected.getTime(), fdp.parse("14may2014"));
587 assertEquals(expected.getTime(), fdp.parse("14MAY2014"));
588 assertEquals(expected.getTime(), fdp.parse("14May2014"));
589 }
590
591 @Test
592 public void test1806Argument() {
593 assertThrows(IllegalArgumentException.class, () -> getInstance("XXXX"));
594 }
595
596 private static Calendar initializeCalendar(final TimeZone tz) {
597 final Calendar cal = Calendar.getInstance(tz);
598 cal.set(Calendar.YEAR, 2001);
599 cal.set(Calendar.MONTH, 1); // not daylight savings
600 cal.set(Calendar.DAY_OF_MONTH, 4);
601 cal.set(Calendar.HOUR_OF_DAY, 12);
602 cal.set(Calendar.MINUTE, 8);
603 cal.set(Calendar.SECOND, 56);
604 cal.set(Calendar.MILLISECOND, 235);
605 return cal;
606 }
607
608 private enum Expected1806 {
609 India(INDIA, "+05", "+0530", "+05:30", true),
610 Greenwich(GMT, "Z", "Z", "Z", false),
611 NewYork(NEW_YORK, "-05", "-0500", "-05:00", false);
612
613 Expected1806(final TimeZone zone, final String one, final String two, final String three, final boolean hasHalfHourOffset) {
614 this.zone = zone;
615 this.one = one;
616 this.two = two;
617 this.three = three;
618 this.offset = hasHalfHourOffset ?30*60*1000 :0;
619 }
620
621 final TimeZone zone;
622 final String one;
623 final String two;
624 final String three;
625 final long offset;
626 }
627
628 @Test
629 public void test1806() throws ParseException {
630 final String formatStub = "yyyy-MM-dd'T'HH:mm:ss.SSS";
631 final String dateStub = "2001-02-04T12:08:56.235";
632
633 for (final Expected1806 trial : Expected1806.values()) {
634 final Calendar cal = initializeCalendar(trial.zone);
635
636 final String message = trial.zone.getDisplayName()+";";
637
638 DateParser parser = getInstance(formatStub+"X", trial.zone);
639 assertEquals(cal.getTime().getTime(), parser.parse(dateStub+trial.one).getTime()-trial.offset, message+trial.one);
640
641 parser = getInstance(formatStub+"XX", trial.zone);
642 assertEquals(cal.getTime(), parser.parse(dateStub+trial.two), message+trial.two);
643
644 parser = getInstance(formatStub+"XXX", trial.zone);
645 assertEquals(cal.getTime(), parser.parse(dateStub+trial.three), message+trial.three);
646 }
647 }
648
649 @Test
650 public void testLang1121() throws ParseException {
651 final TimeZone kst = TimeZone.getTimeZone("KST");
652 final DateParser fdp = getInstance("yyyyMMdd", kst, Locale.KOREA);
653
654 assertThrows(ParseException.class, () -> fdp.parse("2015"));
655
656 // Wed Apr 29 00:00:00 KST 2015
657 Date actual = fdp.parse("20150429");
658 final Calendar cal = Calendar.getInstance(kst, Locale.KOREA);
659 cal.clear();
660 cal.set(2015, 3, 29);
661 Date expected = cal.getTime();
662 assertEquals(expected, actual);
663
664 final SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd", Locale.KOREA);
665 df.setTimeZone(kst);
666 expected = df.parse("20150429113100");
667
668 // Thu Mar 16 00:00:00 KST 81724
669 actual = fdp.parse("20150429113100");
670 assertEquals(expected, actual);
461 @ParameterizedTest
462 @MethodSource(DATE_PARSER_PARAMETERS)
463 public void testParseLongShort(final TriFunction<String, TimeZone, Locale, DateParser> dpProvider)
464 throws ParseException {
465 final Calendar cal = Calendar.getInstance(NEW_YORK, Locale.US);
466 cal.clear();
467 cal.set(2003, Calendar.FEBRUARY, 10, 15, 33, 20);
468 cal.set(Calendar.MILLISECOND, 989);
469 cal.setTimeZone(NEW_YORK);
470
471 DateParser fdf = getInstance(dpProvider, "yyyy GGGG MMMM dddd aaaa EEEE HHHH mmmm ssss SSSS ZZZZ", NEW_YORK,
472 Locale.US);
473
474 assertEquals(cal.getTime(), fdf.parse("2003 AD February 0010 PM Monday 0015 0033 0020 0989 GMT-05:00"));
475 cal.set(Calendar.ERA, GregorianCalendar.BC);
476
477 final Date parse = fdf.parse("2003 BC February 0010 PM Saturday 0015 0033 0020 0989 GMT-05:00");
478 assertEquals(cal.getTime(), parse);
479
480 fdf = getInstance(null, "y G M d a E H m s S Z", NEW_YORK, Locale.US);
481 assertEquals(cal.getTime(), fdf.parse("03 BC 2 10 PM Sat 15 33 20 989 -0500"));
482
483 cal.set(Calendar.ERA, GregorianCalendar.AD);
484 assertEquals(cal.getTime(), fdf.parse("03 AD 2 10 PM Saturday 15 33 20 989 -0500"));
485 }
486
487 @ParameterizedTest
488 @MethodSource(DATE_PARSER_PARAMETERS)
489 public void testParseNumerics(final TriFunction<String, TimeZone, Locale, DateParser> dpProvider)
490 throws ParseException {
491 final Calendar cal = Calendar.getInstance(NEW_YORK, Locale.US);
492 cal.clear();
493 cal.set(2003, Calendar.FEBRUARY, 10, 15, 33, 20);
494 cal.set(Calendar.MILLISECOND, 989);
495
496 final DateParser fdf = getInstance(dpProvider, "yyyyMMddHHmmssSSS", NEW_YORK, Locale.US);
497 assertEquals(cal.getTime(), fdf.parse("20030210153320989"));
671498 }
672499
673500 @Test
682509 }
683510
684511 @Test
685 public void testDayNumberOfWeek() throws ParseException {
686 final DateParser parser = getInstance("u");
687 final Calendar calendar = Calendar.getInstance();
688
689 calendar.setTime(parser.parse("1"));
690 assertEquals(Calendar.MONDAY, calendar.get(Calendar.DAY_OF_WEEK));
691
692 calendar.setTime(parser.parse("6"));
693 assertEquals(Calendar.SATURDAY, calendar.get(Calendar.DAY_OF_WEEK));
694
695 calendar.setTime(parser.parse("7"));
696 assertEquals(Calendar.SUNDAY, calendar.get(Calendar.DAY_OF_WEEK));
697 }
698
699 @Test
700 public void testLang1380() throws ParseException {
701 final Calendar expected = Calendar.getInstance(GMT, Locale.FRANCE);
702 expected.clear();
703 expected.set(2014, Calendar.APRIL, 14);
704
705 final DateParser fdp = getInstance("dd MMM yyyy", GMT, Locale.FRANCE);
706 assertEquals(expected.getTime(), fdp.parse("14 avril 2014"));
707 assertEquals(expected.getTime(), fdp.parse("14 avr. 2014"));
708 assertEquals(expected.getTime(), fdp.parse("14 avr 2014"));
709 }
710
711 @Test
712 public void java15BuggyLocaleTestAll() throws ParseException {
512 // Check that all Locales can parse the formats we use
513 public void testParses() throws Exception {
514 for (final String format : new String[] {LONG_FORMAT, SHORT_FORMAT}) {
515 for (final Locale locale : Locale.getAvailableLocales()) {
516 for (final TimeZone timeZone : new TimeZone[] {NEW_YORK, REYKJAVIK, GMT}) {
517 for (final int year : new int[] {2003, 1940, 1868, 1867, 1, -1, -1940}) {
518 final Calendar cal = getEraStart(year, timeZone, locale);
519 final Date centuryStart = cal.getTime();
520
521 cal.set(Calendar.MONTH, 1);
522 cal.set(Calendar.DAY_OF_MONTH, 10);
523 final Date in = cal.getTime();
524
525 final FastDateParser fastDateParser = new FastDateParser(format, timeZone, locale,
526 centuryStart);
527 validateSdfFormatFdpParseEquality(format, locale, timeZone, fastDateParser, in, year,
528 centuryStart);
529 }
530 }
531 }
532 }
533 }
534
535 /**
536 * Fails on Java 16 Early Access build 25 and above, last tested with build 36.
537 */
538 @Test
539 public void testParsesKnownJava16Ea25Failure() throws Exception {
540 final String format = LONG_FORMAT;
541 final int year = 2003;
542 final Locale locale = new Locale.Builder().setLanguage("sq").setRegion("MK").build();
543 assertEquals("sq_MK", locale.toString());
544 assertNotNull(locale);
545 final TimeZone timeZone = NEW_YORK;
546 final Calendar cal = getEraStart(year, timeZone, locale);
547 final Date centuryStart = cal.getTime();
548
549 cal.set(Calendar.MONTH, 1);
550 cal.set(Calendar.DAY_OF_MONTH, 10);
551 final Date in = cal.getTime();
552
553 final FastDateParser fastDateParser = new FastDateParser(format, timeZone, locale, centuryStart);
554 validateSdfFormatFdpParseEquality(format, locale, timeZone, fastDateParser, in, year, centuryStart);
555 }
556
557 @ParameterizedTest
558 @MethodSource(DATE_PARSER_PARAMETERS)
559 public void testParseZone(final TriFunction<String, TimeZone, Locale, DateParser> dpProvider)
560 throws ParseException {
561 final Calendar cal = Calendar.getInstance(NEW_YORK, Locale.US);
562 cal.clear();
563 cal.set(2003, Calendar.JULY, 10, 16, 33, 20);
564
565 final DateParser fdf = getInstance(dpProvider, yMdHmsSZ, NEW_YORK, Locale.US);
566
567 assertEquals(cal.getTime(), fdf.parse("2003-07-10T15:33:20.000 -0500"));
568 assertEquals(cal.getTime(), fdf.parse("2003-07-10T15:33:20.000 GMT-05:00"));
569 assertEquals(cal.getTime(), fdf.parse("2003-07-10T16:33:20.000 Eastern Daylight Time"));
570 assertEquals(cal.getTime(), fdf.parse("2003-07-10T16:33:20.000 EDT"));
571
572 cal.setTimeZone(TimeZone.getTimeZone("GMT-3"));
573 cal.set(2003, Calendar.FEBRUARY, 10, 9, 0, 0);
574
575 assertEquals(cal.getTime(), fdf.parse("2003-02-10T09:00:00.000 -0300"));
576
577 cal.setTimeZone(TimeZone.getTimeZone("GMT+5"));
578 cal.set(2003, Calendar.FEBRUARY, 10, 15, 5, 6);
579
580 assertEquals(cal.getTime(), fdf.parse("2003-02-10T15:05:06.000 +0500"));
581 }
582
583 @Test
584 public void testPatternMatches() {
585 final DateParser parser = getInstance(yMdHmsSZ);
586 assertEquals(yMdHmsSZ, parser.getPattern());
587 }
588
589 @ParameterizedTest
590 @MethodSource(DATE_PARSER_PARAMETERS)
591 public void testQuotes(final TriFunction<String, TimeZone, Locale, DateParser> dpProvider) throws ParseException {
592 final Calendar cal = Calendar.getInstance(NEW_YORK, Locale.US);
593 cal.clear();
594 cal.set(2003, Calendar.FEBRUARY, 10, 15, 33, 20);
595 cal.set(Calendar.MILLISECOND, 989);
596
597 final DateParser fdf = getInstance(dpProvider, "''yyyyMMdd'A''B'HHmmssSSS''", NEW_YORK, Locale.US);
598 assertEquals(cal.getTime(), fdf.parse("'20030210A'B153320989'"));
599 }
600
601 private void testSdfAndFdp(final TriFunction<String, TimeZone, Locale, DateParser> dbProvider, final String format,
602 final String date, final boolean shouldFail) throws Exception {
603 Date dfdp = null;
604 Date dsdf = null;
605 Throwable f = null;
606 Throwable s = null;
607
608 try {
609 final SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.US);
610 sdf.setTimeZone(NEW_YORK);
611 dsdf = sdf.parse(date);
612 assertFalse(shouldFail, "Expected SDF failure, but got " + dsdf + " for [" + format + ", " + date + "]");
613 } catch (final Exception e) {
614 s = e;
615 if (!shouldFail) {
616 throw e;
617 }
618 }
619
620 try {
621 final DateParser fdp = getInstance(dbProvider, format, NEW_YORK, Locale.US);
622 dfdp = fdp.parse(date);
623 assertFalse(shouldFail, "Expected FDF failure, but got " + dfdp + " for [" + format + ", " + date + "]");
624 } catch (final Exception e) {
625 f = e;
626 if (!shouldFail) {
627 throw e;
628 }
629 }
630 // SDF and FDF should produce equivalent results
631 assertEquals((f == null), (s == null), "Should both or neither throw Exceptions");
632 assertEquals(dsdf, dfdp, "Parsed dates should be equal");
633 }
634
635 /**
636 * Test case for {@link FastDateParser#FastDateParser(String, TimeZone, Locale)}.
637 *
638 * @throws ParseException so we don't have to catch it
639 */
640 @Test
641 public void testShortDateStyleWithLocales() throws ParseException {
642 DateParser fdf = getDateInstance(FastDateFormat.SHORT, Locale.US);
643 final Calendar cal = Calendar.getInstance();
644 cal.clear();
645
646 cal.set(2004, Calendar.FEBRUARY, 3);
647 assertEquals(cal.getTime(), fdf.parse("2/3/04"));
648
649 fdf = getDateInstance(FastDateFormat.SHORT, SWEDEN);
650 assertEquals(cal.getTime(), fdf.parse("2004-02-03"));
651 }
652
653 @ParameterizedTest
654 @MethodSource(DATE_PARSER_PARAMETERS)
655 public void testSpecialCharacters(final TriFunction<String, TimeZone, Locale, DateParser> dpProvider)
656 throws Exception {
657 testSdfAndFdp(dpProvider, "q", "", true); // bad pattern character (at present)
658 testSdfAndFdp(dpProvider, "Q", "", true); // bad pattern character
659 testSdfAndFdp(dpProvider, "$", "$", false); // OK
660 testSdfAndFdp(dpProvider, "?.d", "?.12", false); // OK
661 testSdfAndFdp(dpProvider, "''yyyyMMdd'A''B'HHmmssSSS''", "'20030210A'B153320989'", false); // OK
662 testSdfAndFdp(dpProvider, "''''yyyyMMdd'A''B'HHmmssSSS''", "''20030210A'B153320989'", false); // OK
663 testSdfAndFdp(dpProvider, "'$\\Ed'", "$\\Ed", false); // OK
664
665 // quoted charaters are case sensitive
666 testSdfAndFdp(dpProvider, "'QED'", "QED", false);
667 testSdfAndFdp(dpProvider, "'QED'", "qed", true);
668 // case sensitive after insensitive Month field
669 testSdfAndFdp(dpProvider, "yyyy-MM-dd 'QED'", "2003-02-10 QED", false);
670 testSdfAndFdp(dpProvider, "yyyy-MM-dd 'QED'", "2003-02-10 qed", true);
671 }
672
673 @Test
674 public void testTimeZoneMatches() {
675 final DateParser parser = getInstance(yMdHmsSZ, REYKJAVIK);
676 assertEquals(REYKJAVIK, parser.getTimeZone());
677 }
678
679 @Test
680 public void testToStringContainsName() {
681 final DateParser parser = getInstance(YMD_SLASH);
682 assertTrue(parser.toString().startsWith("FastDate"));
683 }
684
685 // we cannot use historic dates to test time zone parsing, some time zones have second offsets
686 // as well as hours and minutes which makes the z formats a low fidelity round trip
687 @Test
688 public void testTzParses() throws Exception {
689 // Check that all Locales can parse the time formats we use
713690 for (final Locale locale : Locale.getAvailableLocales()) {
714 testSingleLocale(locale);
715 }
716 }
717
718 @Test
719 public void java15BuggyLocaleTest() throws ParseException {
720 final String buggyLocaleName = "ff_LR_#Adlm";
721 Locale buggyLocale = null;
722 for (final Locale locale : Locale.getAvailableLocales()) {
723 if (buggyLocaleName.equals(locale.toString())) {
724 buggyLocale = locale;
725 break;
691 final FastDateParser fdp = new FastDateParser("yyyy/MM/dd z", TimeZone.getDefault(), locale);
692
693 for (final TimeZone timeZone : new TimeZone[] {NEW_YORK, REYKJAVIK, GMT}) {
694 final Calendar cal = Calendar.getInstance(timeZone, locale);
695 cal.clear();
696 cal.set(Calendar.YEAR, 2000);
697 cal.set(Calendar.MONTH, 1);
698 cal.set(Calendar.DAY_OF_MONTH, 10);
699 final Date expected = cal.getTime();
700
701 final Date actual = fdp.parse("2000/02/10 " + timeZone.getDisplayName(locale));
702 assertEquals(expected, actual, "timeZone:" + timeZone.getID() + " locale:" + locale.getDisplayName());
726703 }
727704 }
728 if (buggyLocale == null) {
729 return;
730 }
731 testSingleLocale(buggyLocale);
732 }
733
734 private void testSingleLocale(final Locale locale) throws ParseException {
735 final Calendar cal = Calendar.getInstance(GMT);
736 cal.clear();
737 cal.set(2003, Calendar.FEBRUARY, 10);
738 final SimpleDateFormat sdf = new SimpleDateFormat(LONG_FORMAT, locale);
739 final String formattedDate = sdf.format(cal.getTime());
740 sdf.parse(formattedDate);
741 sdf.parse(formattedDate.toUpperCase(locale));
742 sdf.parse(formattedDate.toLowerCase(locale));
705 }
706
707 private void validateSdfFormatFdpParseEquality(final String formatStr, final Locale locale, final TimeZone timeZone,
708 final FastDateParser dateParser, final Date inDate, final int year, final Date csDate) throws ParseException {
709 final SimpleDateFormat sdf = new SimpleDateFormat(formatStr, locale);
710 sdf.setTimeZone(timeZone);
711 if (formatStr.equals(SHORT_FORMAT)) {
712 sdf.set2DigitYearStart(csDate);
713 }
714 final String fmt = sdf.format(inDate);
715 // System.out.printf("[Java %s] Date: '%s' formated with '%s' -> '%s'%n", SystemUtils.JAVA_RUNTIME_VERSION, inDate,
716 // formatStr, fmt);
717 try {
718 final Date out = dateParser.parse(fmt);
719 assertEquals(inDate, out, "format: '" + formatStr + "', locale: '" + locale + "', time zone: '"
720 + timeZone.getID() + "', year: " + year + ", parse: '" + fmt);
721 } catch (final ParseException pe) {
722 if (year >= 1868 || !locale.getCountry().equals("JP")) {
723 // LANG-978
724 throw pe;
725 }
726 }
743727 }
744728 }
729
3232 private static final TimeZone NEW_YORK = TimeZone.getTimeZone("America/New_York");
3333
3434 @Test
35 public void testInputHasLessCharacters() {
36 final FastDateParser parser = new FastDateParser("MM/dd/yyy", TimeZone.getDefault(), Locale.getDefault());
37 final ParsePosition parsePosition = new ParsePosition(0);
38 assertNull(parser.parse("03/23", parsePosition));
39 assertEquals(5, parsePosition.getErrorIndex());
40 }
41
42 @Test
43 public void testInputHasMoreCharacters() {
44 final FastDateParser parser = new FastDateParser("MM/dd", TimeZone.getDefault(), Locale.getDefault());
45 final ParsePosition parsePosition = new ParsePosition(0);
46 final Date date = parser.parse("3/23/61", parsePosition);
47 assertEquals(4, parsePosition.getIndex());
48
49 final Calendar calendar = Calendar.getInstance();
50 calendar.setTime(date);
51 assertEquals(2, calendar.get(Calendar.MONTH));
52 assertEquals(23, calendar.get(Calendar.DATE));
53 }
54
55 @Test
3556 public void testInputHasPrecedingCharacters() {
3657 final FastDateParser parser = new FastDateParser("MM/dd", TimeZone.getDefault(), Locale.getDefault());
3758 final ParsePosition parsePosition = new ParsePosition(0);
5778 }
5879
5980 @Test
60 public void testInputHasMoreCharacters() {
61 final FastDateParser parser = new FastDateParser("MM/dd", TimeZone.getDefault(), Locale.getDefault());
62 final ParsePosition parsePosition = new ParsePosition(0);
63 final Date date = parser.parse("3/23/61", parsePosition);
64 assertEquals(4, parsePosition.getIndex());
65
66 final Calendar calendar = Calendar.getInstance();
67 calendar.setTime(date);
68 assertEquals(2, calendar.get(Calendar.MONTH));
69 assertEquals(23, calendar.get(Calendar.DATE));
70 }
71
72 @Test
7381 public void testInputHasWrongCharacters() {
7482 final FastDateParser parser = new FastDateParser("MM-dd-yyy", TimeZone.getDefault(), Locale.getDefault());
7583 final ParsePosition parsePosition = new ParsePosition(0);
7886 }
7987
8088 @Test
81 public void testInputHasLessCharacters() {
82 final FastDateParser parser = new FastDateParser("MM/dd/yyy", TimeZone.getDefault(), Locale.getDefault());
89 public void testInputHasWrongDay() {
90 final FastDateParser parser = new FastDateParser("EEEE, MM/dd/yyy", NEW_YORK, Locale.US);
91 final String input = "Thursday, 03/23/61";
8392 final ParsePosition parsePosition = new ParsePosition(0);
84 assertNull(parser.parse("03/23", parsePosition));
85 assertEquals(5, parsePosition.getErrorIndex());
93 assertNotNull(parser.parse(input, parsePosition));
94 assertEquals(input.length(), parsePosition.getIndex());
95
96 parsePosition.setIndex(0);
97 assertNull(parser.parse( "Thorsday, 03/23/61", parsePosition));
98 assertEquals(0, parsePosition.getErrorIndex());
8699 }
87100
88101 @Test
98111 assertNull(parser.parse( "11:23 Pacific Standard ", parsePosition));
99112 assertEquals(6, parsePosition.getErrorIndex());
100113 }
101
102 @Test
103 public void testInputHasWrongDay() {
104 final FastDateParser parser = new FastDateParser("EEEE, MM/dd/yyy", NEW_YORK, Locale.US);
105 final String input = "Thursday, 03/23/61";
106 final ParsePosition parsePosition = new ParsePosition(0);
107 assertNotNull(parser.parse(input, parsePosition));
108 assertEquals(input.length(), parsePosition.getIndex());
109
110 parsePosition.setIndex(0);
111 assertNull(parser.parse( "Thorsday, 03/23/61", parsePosition));
112 assertEquals(0, parsePosition.getErrorIndex());
113 }
114114 }
2929
3030 class FastDateParser_TimeZoneStrategyTest {
3131
32 @Test
33 void testLang1219() throws ParseException {
34 final FastDateParser parser = new FastDateParser("dd.MM.yyyy HH:mm:ss z", TimeZone.getDefault(), Locale.GERMAN);
35
36 final Date summer = parser.parse("26.10.2014 02:00:00 MESZ");
37 final Date standard = parser.parse("26.10.2014 02:00:00 MEZ");
38 assertNotEquals(summer.getTime(), standard.getTime());
39 }
40
3241 @ParameterizedTest
3342 @MethodSource("java.util.Locale#getAvailableLocales")
3443 void testTimeZoneStrategyPattern(final Locale locale) throws ParseException {
4554 }
4655 }
4756 }
48
49 @Test
50 void testLang1219() throws ParseException {
51 final FastDateParser parser = new FastDateParser("dd.MM.yyyy HH:mm:ss z", TimeZone.getDefault(), Locale.GERMAN);
52
53 final Date summer = parser.parse("26.10.2014 02:00:00 MESZ");
54 final Date standard = parser.parse("26.10.2014 02:00:00 MEZ");
55 assertNotEquals(summer.getTime(), standard.getTime());
56 }
5757 }
4141 */
4242 public class FastDatePrinterTest {
4343
44 private enum Expected1806 {
45 India(INDIA, "+05", "+0530", "+05:30"), Greenwich(GMT, "Z", "Z", "Z"), NewYork(
46 NEW_YORK, "-05", "-0500", "-05:00");
47
48 final TimeZone zone;
49
50 final String one;
51 final String two;
52 final String three;
53 Expected1806(final TimeZone zone, final String one, final String two, final String three) {
54 this.zone = zone;
55 this.one = one;
56 this.two = two;
57 this.three = three;
58 }
59 }
4460 private static final String YYYY_MM_DD = "yyyy/MM/dd";
4561 private static final TimeZone NEW_YORK = TimeZone.getTimeZone("America/New_York");
4662 private static final TimeZone GMT = TimeZone.getTimeZone("GMT");
4763 private static final TimeZone INDIA = TimeZone.getTimeZone("Asia/Calcutta");
64
4865 private static final Locale SWEDEN = new Locale("sv", "SE");
49
50 DatePrinter getInstance(final String format) {
51 return getInstance(format, TimeZone.getDefault(), Locale.getDefault());
52 }
53
54 private DatePrinter getDateInstance(final int dateStyle, final Locale locale) {
55 return getInstance(FormatCache.getPatternForStyle(Integer.valueOf(dateStyle), null, locale), TimeZone.getDefault(), Locale.getDefault());
56 }
57
58 private DatePrinter getInstance(final String format, final Locale locale) {
59 return getInstance(format, TimeZone.getDefault(), locale);
60 }
61
62 private DatePrinter getInstance(final String format, final TimeZone timeZone) {
63 return getInstance(format, timeZone, Locale.getDefault());
64 }
65
66 /**
67 * Override this method in derived tests to change the construction of instances
68 * @param format the format string to use
69 * @param timeZone the time zone to use
70 * @param locale the locale to use
71 * @return the DatePrinter to use for testing
72 */
73 protected DatePrinter getInstance(final String format, final TimeZone timeZone, final Locale locale) {
74 return new FastDatePrinter(format, timeZone, locale);
75 }
76
77 @DefaultLocale(language = "en", country = "US")
78 @DefaultTimeZone("America/New_York")
79 @Test
80 public void testFormat() {
81 final GregorianCalendar cal1 = new GregorianCalendar(2003, 0, 10, 15, 33, 20);
82 final GregorianCalendar cal2 = new GregorianCalendar(2003, 6, 10, 9, 0, 0);
83 final Date date1 = cal1.getTime();
84 final Date date2 = cal2.getTime();
85 final long millis1 = date1.getTime();
86 final long millis2 = date2.getTime();
87
88 DatePrinter fdf = getInstance("yyyy-MM-dd'T'HH:mm:ss");
89 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
90 assertEquals(sdf.format(date1), fdf.format(date1));
91 assertEquals("2003-01-10T15:33:20", fdf.format(date1));
92 assertEquals("2003-01-10T15:33:20", fdf.format(cal1));
93 assertEquals("2003-01-10T15:33:20", fdf.format(millis1));
94 assertEquals("2003-07-10T09:00:00", fdf.format(date2));
95 assertEquals("2003-07-10T09:00:00", fdf.format(cal2));
96 assertEquals("2003-07-10T09:00:00", fdf.format(millis2));
97
98 fdf = getInstance("Z");
99 assertEquals("-0500", fdf.format(date1));
100 assertEquals("-0500", fdf.format(cal1));
101 assertEquals("-0500", fdf.format(millis1));
102
103 assertEquals("-0400", fdf.format(date2));
104 assertEquals("-0400", fdf.format(cal2));
105 assertEquals("-0400", fdf.format(millis2));
106
107 fdf = getInstance("ZZ");
108 assertEquals("-05:00", fdf.format(date1));
109 assertEquals("-05:00", fdf.format(cal1));
110 assertEquals("-05:00", fdf.format(millis1));
111
112 assertEquals("-04:00", fdf.format(date2));
113 assertEquals("-04:00", fdf.format(cal2));
114 assertEquals("-04:00", fdf.format(millis2));
115
116 final String pattern = "GGGG GGG GG G yyyy yyy yy y MMMM MMM MM M" +
117 " dddd ddd dd d DDDD DDD DD D EEEE EEE EE E aaaa aaa aa a zzzz zzz zz z";
118 fdf = getInstance(pattern);
119 sdf = new SimpleDateFormat(pattern);
120 // SDF bug fix starting with Java 7
121 assertEquals(sdf.format(date1).replaceAll("2003 03 03 03", "2003 2003 03 2003"), fdf.format(date1));
122 assertEquals(sdf.format(date2).replaceAll("2003 03 03 03", "2003 2003 03 2003"), fdf.format(date2));
123 }
124
125 /**
126 * Test case for {@link FastDateParser#FastDateParser(String, TimeZone, Locale)}.
127 */
128 @Test
129 public void testShortDateStyleWithLocales() {
130 final Locale usLocale = Locale.US;
131 final Locale swedishLocale = new Locale("sv", "SE");
132 final Calendar cal = Calendar.getInstance();
133 cal.set(2004, Calendar.FEBRUARY, 3);
134 DatePrinter fdf = getDateInstance(FastDateFormat.SHORT, usLocale);
135 assertEquals("2/3/04", fdf.format(cal));
136
137 fdf = getDateInstance(FastDateFormat.SHORT, swedishLocale);
138 assertEquals("2004-02-03", fdf.format(cal));
139
140 }
141
142 /**
143 * Tests that pre-1000AD years get padded with yyyy
144 */
145 @Test
146 public void testLowYearPadding() {
147 final Calendar cal = Calendar.getInstance();
148 final DatePrinter format = getInstance(YYYY_MM_DD);
149
150 cal.set(1, Calendar.JANUARY, 1);
151 assertEquals("0001/01/01", format.format(cal));
152 cal.set(10, Calendar.JANUARY, 1);
153 assertEquals("0010/01/01", format.format(cal));
154 cal.set(100, Calendar.JANUARY, 1);
155 assertEquals("0100/01/01", format.format(cal));
156 cal.set(999, Calendar.JANUARY, 1);
157 assertEquals("0999/01/01", format.format(cal));
158 }
159 /**
160 * Show Bug #39410 is solved
161 */
162 @Test
163 public void testMilleniumBug() {
164 final Calendar cal = Calendar.getInstance();
165 final DatePrinter format = getInstance("dd.MM.yyyy");
166
167 cal.set(1000, Calendar.JANUARY, 1);
168 assertEquals("01.01.1000", format.format(cal));
169 }
170
171 /**
172 * testLowYearPadding showed that the date was buggy
173 * This test confirms it, getting 366 back as a date
174 */
175 @Test
176 public void testSimpleDate() {
177 final Calendar cal = Calendar.getInstance();
178 final DatePrinter format = getInstance(YYYY_MM_DD);
179
180 cal.set(2004, Calendar.DECEMBER, 31);
181 assertEquals("2004/12/31", format.format(cal));
182 cal.set(999, Calendar.DECEMBER, 31);
183 assertEquals("0999/12/31", format.format(cal));
184 cal.set(1, Calendar.MARCH, 2);
185 assertEquals("0001/03/02", format.format(cal));
186 }
187
188 @Test
189 public void testLang303() {
190 final Calendar cal = Calendar.getInstance();
191 cal.set(2004, Calendar.DECEMBER, 31);
192
193 DatePrinter format = getInstance(YYYY_MM_DD);
194 final String output = format.format(cal);
195
196 format = SerializationUtils.deserialize(SerializationUtils.serialize((Serializable) format));
197 assertEquals(output, format.format(cal));
198 }
199
200 @Test
201 public void testLang538() {
202 // more commonly constructed with: cal = new GregorianCalendar(2009, 9, 16, 8, 42, 16)
203 // for the unit test to work in any time zone, constructing with GMT-8 rather than default locale time zone
204 final GregorianCalendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT-8"));
205 cal.clear();
206 cal.set(2009, Calendar.OCTOBER, 16, 8, 42, 16);
207
208 final DatePrinter format = getInstance("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", TimeZone.getTimeZone("GMT"));
209 assertEquals("2009-10-16T16:42:16.000Z", format.format(cal.getTime()), "dateTime");
210 assertEquals("2009-10-16T16:42:16.000Z", format.format(cal), "dateTime");
211 }
212
213 @Test
214 public void testLang645() {
215 final Locale locale = new Locale("sv", "SE");
216
217 final Calendar cal = Calendar.getInstance();
218 cal.set(2010, Calendar.JANUARY, 1, 12, 0, 0);
219 final Date d = cal.getTime();
220
221 final DatePrinter fdf = getInstance("EEEE', week 'ww", locale);
222
223 assertEquals("fredag, week 53", fdf.format(d));
224 }
225
226 @Test
227 public void testEquals() {
228 final DatePrinter printer1= getInstance(YYYY_MM_DD);
229 final DatePrinter printer2= getInstance(YYYY_MM_DD);
230
231 assertEquals(printer1, printer2);
232 assertEquals(printer1.hashCode(), printer2.hashCode());
233
234 assertNotEquals(printer1, new Object());
235 }
236
237 @Test
238 public void testToStringContainsName() {
239 final DatePrinter printer= getInstance(YYYY_MM_DD);
240 assertTrue(printer.toString().startsWith("FastDate"));
241 }
242
243 @Test
244 public void testPatternMatches() {
245 final DatePrinter printer= getInstance(YYYY_MM_DD);
246 assertEquals(YYYY_MM_DD, printer.getPattern());
247 }
248
249 @Test
250 public void testLocaleMatches() {
251 final DatePrinter printer= getInstance(YYYY_MM_DD, SWEDEN);
252 assertEquals(SWEDEN, printer.getLocale());
253 }
254
255 @Test
256 public void testTimeZoneMatches() {
257 final DatePrinter printer= getInstance(YYYY_MM_DD, NEW_YORK);
258 assertEquals(NEW_YORK, printer.getTimeZone());
259 }
260
261 @DefaultTimeZone("UTC")
262 @Test
263 public void testTimeZoneAsZ() {
264 final Calendar c = Calendar.getInstance(FastTimeZone.getGmtTimeZone());
265 final FastDateFormat noColonFormat = FastDateFormat.getInstance("Z");
266 assertEquals("+0000", noColonFormat.format(c));
267
268 final FastDateFormat isoFormat = FastDateFormat.getInstance("ZZ");
269 assertEquals("Z", isoFormat.format(c));
270
271 final FastDateFormat colonFormat = FastDateFormat.getInstance("ZZZ");
272 assertEquals("+00:00", colonFormat.format(c));
273 }
27466
27567 private static Calendar initializeCalendar(final TimeZone tz) {
27668 final Calendar cal = Calendar.getInstance(tz);
28476 return cal;
28577 }
28678
287 @Test
288 public void test1806Argument() {
289 assertThrows(IllegalArgumentException.class, () -> getInstance("XXXX"));
290 }
291
292 private enum Expected1806 {
293 India(INDIA, "+05", "+0530", "+05:30"), Greenwich(GMT, "Z", "Z", "Z"), NewYork(
294 NEW_YORK, "-05", "-0500", "-05:00");
295
296 Expected1806(final TimeZone zone, final String one, final String two, final String three) {
297 this.zone = zone;
298 this.one = one;
299 this.two = two;
300 this.three = three;
301 }
302
303 final TimeZone zone;
304 final String one;
305 final String two;
306 final String three;
79 private DatePrinter getDateInstance(final int dateStyle, final Locale locale) {
80 return getInstance(FormatCache.getPatternForStyle(Integer.valueOf(dateStyle), null, locale), TimeZone.getDefault(), Locale.getDefault());
81 }
82
83 DatePrinter getInstance(final String format) {
84 return getInstance(format, TimeZone.getDefault(), Locale.getDefault());
85 }
86
87 private DatePrinter getInstance(final String format, final Locale locale) {
88 return getInstance(format, TimeZone.getDefault(), locale);
89 }
90
91 private DatePrinter getInstance(final String format, final TimeZone timeZone) {
92 return getInstance(format, timeZone, Locale.getDefault());
93 }
94
95 /**
96 * Override this method in derived tests to change the construction of instances
97 * @param format the format string to use
98 * @param timeZone the time zone to use
99 * @param locale the locale to use
100 * @return the DatePrinter to use for testing
101 */
102 protected DatePrinter getInstance(final String format, final TimeZone timeZone, final Locale locale) {
103 return new FastDatePrinter(format, timeZone, locale);
307104 }
308105
309106 @Test
320117 printer = getInstance("XXX", trial.zone);
321118 assertEquals(trial.three, printer.format(cal));
322119 }
120 }
121 @Test
122 public void test1806Argument() {
123 assertThrows(IllegalArgumentException.class, () -> getInstance("XXXX"));
124 }
125
126 @Test
127 public void testAppendableOptions() {
128 final DatePrinter format = getInstance("yyyy-MM-dd HH:mm:ss.SSS Z", TimeZone.getTimeZone("GMT"));
129 final Calendar calendar = Calendar.getInstance();
130 final StringBuilder sb = new StringBuilder();
131 final String expected = format.format(calendar, sb).toString();
132 sb.setLength(0);
133
134 final Date date = calendar.getTime();
135 assertEquals(expected, format.format(date, sb).toString());
136 sb.setLength(0);
137
138 final long epoch = date.getTime();
139 assertEquals(expected, format.format(epoch, sb).toString());
140 }
141
142 @Test
143 public void testDayNumberOfWeek() {
144 final DatePrinter printer = getInstance("u");
145 final Calendar calendar = Calendar.getInstance();
146
147 calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
148 assertEquals("1", printer.format(calendar.getTime()));
149
150 calendar.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
151 assertEquals("6", printer.format(calendar.getTime()));
152
153 calendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
154 assertEquals("7", printer.format(calendar.getTime()));
155 }
156
157 @Test
158 public void testEquals() {
159 final DatePrinter printer1= getInstance(YYYY_MM_DD);
160 final DatePrinter printer2= getInstance(YYYY_MM_DD);
161
162 assertEquals(printer1, printer2);
163 assertEquals(printer1.hashCode(), printer2.hashCode());
164
165 assertNotEquals(printer1, new Object());
166 }
167
168 @DefaultLocale(language = "en", country = "US")
169 @DefaultTimeZone("America/New_York")
170 @Test
171 public void testFormat() {
172 final GregorianCalendar cal1 = new GregorianCalendar(2003, 0, 10, 15, 33, 20);
173 final GregorianCalendar cal2 = new GregorianCalendar(2003, 6, 10, 9, 0, 0);
174 final Date date1 = cal1.getTime();
175 final Date date2 = cal2.getTime();
176 final long millis1 = date1.getTime();
177 final long millis2 = date2.getTime();
178
179 DatePrinter fdf = getInstance("yyyy-MM-dd'T'HH:mm:ss");
180 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
181 assertEquals(sdf.format(date1), fdf.format(date1));
182 assertEquals("2003-01-10T15:33:20", fdf.format(date1));
183 assertEquals("2003-01-10T15:33:20", fdf.format(cal1));
184 assertEquals("2003-01-10T15:33:20", fdf.format(millis1));
185 assertEquals("2003-07-10T09:00:00", fdf.format(date2));
186 assertEquals("2003-07-10T09:00:00", fdf.format(cal2));
187 assertEquals("2003-07-10T09:00:00", fdf.format(millis2));
188
189 fdf = getInstance("Z");
190 assertEquals("-0500", fdf.format(date1));
191 assertEquals("-0500", fdf.format(cal1));
192 assertEquals("-0500", fdf.format(millis1));
193
194 assertEquals("-0400", fdf.format(date2));
195 assertEquals("-0400", fdf.format(cal2));
196 assertEquals("-0400", fdf.format(millis2));
197
198 fdf = getInstance("ZZ");
199 assertEquals("-05:00", fdf.format(date1));
200 assertEquals("-05:00", fdf.format(cal1));
201 assertEquals("-05:00", fdf.format(millis1));
202
203 assertEquals("-04:00", fdf.format(date2));
204 assertEquals("-04:00", fdf.format(cal2));
205 assertEquals("-04:00", fdf.format(millis2));
206
207 final String pattern = "GGGG GGG GG G yyyy yyy yy y MMMM MMM MM M" +
208 " dddd ddd dd d DDDD DDD DD D EEEE EEE EE E aaaa aaa aa a zzzz zzz zz z";
209 fdf = getInstance(pattern);
210 sdf = new SimpleDateFormat(pattern);
211 // SDF bug fix starting with Java 7
212 assertEquals(sdf.format(date1).replace("2003 03 03 03", "2003 2003 03 2003"), fdf.format(date1));
213 assertEquals(sdf.format(date2).replace("2003 03 03 03", "2003 2003 03 2003"), fdf.format(date2));
214 }
215
216 @Test
217 public void testHourFormats() {
218 final Calendar calendar = Calendar.getInstance();
219 calendar.clear();
220 final DatePrinter printer = getInstance("K k H h");
221
222 calendar.set(Calendar.HOUR_OF_DAY, 0);
223 assertEquals("0 24 0 12", printer.format(calendar));
224
225 calendar.set(Calendar.HOUR_OF_DAY, 12);
226 assertEquals("0 12 12 12", printer.format(calendar));
227
228 calendar.set(Calendar.HOUR_OF_DAY, 23);
229 assertEquals("11 23 23 11", printer.format(calendar));
323230 }
324231
325232 @Test
332239 assertEquals("002", getInstance("ddd", SWEDEN).format(cal));
333240 assertEquals("0002", getInstance("dddd", SWEDEN).format(cal));
334241 assertEquals("00002", getInstance("ddddd", SWEDEN).format(cal));
242 }
243
244 @Test
245 public void testLang303() {
246 final Calendar cal = Calendar.getInstance();
247 cal.set(2004, Calendar.DECEMBER, 31);
248
249 DatePrinter format = getInstance(YYYY_MM_DD);
250 final String output = format.format(cal);
251
252 format = SerializationUtils.deserialize(SerializationUtils.serialize((Serializable) format));
253 assertEquals(output, format.format(cal));
254 }
255
256 @Test
257 public void testLang538() {
258 // more commonly constructed with: cal = new GregorianCalendar(2009, 9, 16, 8, 42, 16)
259 // for the unit test to work in any time zone, constructing with GMT-8 rather than default locale time zone
260 final GregorianCalendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT-8"));
261 cal.clear();
262 cal.set(2009, Calendar.OCTOBER, 16, 8, 42, 16);
263
264 final DatePrinter format = getInstance("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", TimeZone.getTimeZone("GMT"));
265 assertEquals("2009-10-16T16:42:16.000Z", format.format(cal.getTime()), "dateTime");
266 assertEquals("2009-10-16T16:42:16.000Z", format.format(cal), "dateTime");
267 }
268
269 @Test
270 public void testLang645() {
271 final Locale locale = new Locale("sv", "SE");
272
273 final Calendar cal = Calendar.getInstance();
274 cal.set(2010, Calendar.JANUARY, 1, 12, 0, 0);
275 final Date d = cal.getTime();
276
277 final DatePrinter fdf = getInstance("EEEE', week 'ww", locale);
278
279 assertEquals("fredag, week 53", fdf.format(d));
335280 }
336281
337282 /**
363308 }
364309
365310 @Test
366 public void testHourFormats() {
367 final Calendar calendar = Calendar.getInstance();
368 calendar.clear();
369 final DatePrinter printer = getInstance("K k H h");
370
371 calendar.set(Calendar.HOUR_OF_DAY, 0);
372 assertEquals("0 24 0 12", printer.format(calendar));
373
374 calendar.set(Calendar.HOUR_OF_DAY, 12);
375 assertEquals("0 12 12 12", printer.format(calendar));
376
377 calendar.set(Calendar.HOUR_OF_DAY, 23);
378 assertEquals("11 23 23 11", printer.format(calendar));
311 public void testLocaleMatches() {
312 final DatePrinter printer= getInstance(YYYY_MM_DD, SWEDEN);
313 assertEquals(SWEDEN, printer.getLocale());
314 }
315
316 /**
317 * Tests that pre-1000AD years get padded with yyyy
318 */
319 @Test
320 public void testLowYearPadding() {
321 final Calendar cal = Calendar.getInstance();
322 final DatePrinter format = getInstance(YYYY_MM_DD);
323
324 cal.set(1, Calendar.JANUARY, 1);
325 assertEquals("0001/01/01", format.format(cal));
326 cal.set(10, Calendar.JANUARY, 1);
327 assertEquals("0010/01/01", format.format(cal));
328 cal.set(100, Calendar.JANUARY, 1);
329 assertEquals("0100/01/01", format.format(cal));
330 cal.set(999, Calendar.JANUARY, 1);
331 assertEquals("0999/01/01", format.format(cal));
332 }
333
334 /**
335 * Show Bug #39410 is solved
336 */
337 @Test
338 public void testMilleniumBug() {
339 final Calendar cal = Calendar.getInstance();
340 final DatePrinter format = getInstance("dd.MM.yyyy");
341
342 cal.set(1000, Calendar.JANUARY, 1);
343 assertEquals("01.01.1000", format.format(cal));
344 }
345
346 @Test
347 public void testPatternMatches() {
348 final DatePrinter printer= getInstance(YYYY_MM_DD);
349 assertEquals(YYYY_MM_DD, printer.getPattern());
350 }
351
352 /**
353 * Test case for {@link FastDateParser#FastDateParser(String, TimeZone, Locale)}.
354 */
355 @Test
356 public void testShortDateStyleWithLocales() {
357 final Locale usLocale = Locale.US;
358 final Locale swedishLocale = new Locale("sv", "SE");
359 final Calendar cal = Calendar.getInstance();
360 cal.set(2004, Calendar.FEBRUARY, 3);
361 DatePrinter fdf = getDateInstance(FastDateFormat.SHORT, usLocale);
362 assertEquals("2/3/04", fdf.format(cal));
363
364 fdf = getDateInstance(FastDateFormat.SHORT, swedishLocale);
365 assertEquals("2004-02-03", fdf.format(cal));
366
367 }
368
369 /**
370 * testLowYearPadding showed that the date was buggy
371 * This test confirms it, getting 366 back as a date
372 */
373 @Test
374 public void testSimpleDate() {
375 final Calendar cal = Calendar.getInstance();
376 final DatePrinter format = getInstance(YYYY_MM_DD);
377
378 cal.set(2004, Calendar.DECEMBER, 31);
379 assertEquals("2004/12/31", format.format(cal));
380 cal.set(999, Calendar.DECEMBER, 31);
381 assertEquals("0999/12/31", format.format(cal));
382 cal.set(1, Calendar.MARCH, 2);
383 assertEquals("0001/03/02", format.format(cal));
379384 }
380385
381386 @SuppressWarnings("deprecation")
401406 assertEquals(expected, format.format(epoch, sb).toString());
402407 }
403408
404 @Test
405 public void testAppendableOptions() {
406 final DatePrinter format = getInstance("yyyy-MM-dd HH:mm:ss.SSS Z", TimeZone.getTimeZone("GMT"));
407 final Calendar calendar = Calendar.getInstance();
408 final StringBuilder sb = new StringBuilder();
409 final String expected = format.format(calendar, sb).toString();
410 sb.setLength(0);
411
412 final Date date = calendar.getTime();
413 assertEquals(expected, format.format(date, sb).toString());
414 sb.setLength(0);
415
416 final long epoch = date.getTime();
417 assertEquals(expected, format.format(epoch, sb).toString());
418 }
419
420 @Test
421 public void testDayNumberOfWeek() {
422 final DatePrinter printer = getInstance("u");
423 final Calendar calendar = Calendar.getInstance();
424
425 calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
426 assertEquals("1", printer.format(calendar.getTime()));
427
428 calendar.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
429 assertEquals("6", printer.format(calendar.getTime()));
430
431 calendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
432 assertEquals("7", printer.format(calendar.getTime()));
409 @DefaultTimeZone("UTC")
410 @Test
411 public void testTimeZoneAsZ() {
412 final Calendar c = Calendar.getInstance(FastTimeZone.getGmtTimeZone());
413 final FastDateFormat noColonFormat = FastDateFormat.getInstance("Z");
414 assertEquals("+0000", noColonFormat.format(c));
415
416 final FastDateFormat isoFormat = FastDateFormat.getInstance("ZZ");
417 assertEquals("Z", isoFormat.format(c));
418
419 final FastDateFormat colonFormat = FastDateFormat.getInstance("ZZZ");
420 assertEquals("+00:00", colonFormat.format(c));
421 }
422
423 @Test
424 public void testTimeZoneMatches() {
425 final DatePrinter printer= getInstance(YYYY_MM_DD, NEW_YORK);
426 assertEquals(NEW_YORK, printer.getTimeZone());
427 }
428
429 @Test
430 public void testToStringContainsName() {
431 final DatePrinter printer= getInstance(YYYY_MM_DD);
432 assertTrue(printer.toString().startsWith("FastDate"));
433 }
434
435 @DefaultLocale(language = "en", country = "US")
436 @DefaultTimeZone("America/New_York")
437 @Test
438 public void testWeekYear() {
439 final GregorianCalendar cal = new GregorianCalendar(2020, 12, 31, 0, 0, 0);
440 final DatePrinter printer4Digits = getInstance("YYYY");
441 final DatePrinter printer4DigitsFallback = getInstance("YYY");
442 final DatePrinter printer2Digits = getInstance("YY");
443 final DatePrinter printer4DigitAnotherFallback = getInstance("Y");
444 assertEquals("2021", printer4Digits.format(cal));
445 assertEquals("2021", printer4DigitsFallback.format(cal));
446 assertEquals("2021", printer4DigitAnotherFallback.format(cal));
447 assertEquals("21", printer2Digits.format(cal));
433448 }
434449 }
1818 import static org.junit.jupiter.api.Assertions.assertEquals;
1919
2020 import java.text.SimpleDateFormat;
21 import java.util.Arrays;
2221 import java.util.Calendar;
2322 import java.util.TimeZone;
2423 import java.util.stream.Stream;
3130 private static final String PATTERN = "h:mma z";
3231
3332 public static Stream<TimeZone> data() {
34 return Arrays.stream(TimeZone.getAvailableIDs()).map(TimeZone::getTimeZone);
33 return Stream.of(TimeZone.getAvailableIDs()).map(TimeZone::getTimeZone);
3534 }
3635
3736 @ParameterizedTest
3232 private static final int MINUTES_5 = 5 * 60 * 1000;
3333
3434 @Test
35 public void testGetGmtTimeZone() {
36 assertEquals(0, FastTimeZone.getGmtTimeZone().getRawOffset());
37 }
38
39 @Test
4035 public void testBareGmt() {
4136 assertEquals(FastTimeZone.getGmtTimeZone(), FastTimeZone.getTimeZone("GMT"));
4237 }
4338
4439 @Test
45 public void testZ() {
46 assertEquals(FastTimeZone.getGmtTimeZone(), FastTimeZone.getTimeZone("Z"));
47 }
48
49 @Test
50 public void testUTC() {
51 assertEquals(FastTimeZone.getGmtTimeZone(), FastTimeZone.getTimeZone("UTC"));
52 }
53
54 @Test
55 public void testZeroOffsetsReturnSingleton() {
56 assertEquals(FastTimeZone.getGmtTimeZone(), FastTimeZone.getTimeZone("+0"));
57 assertEquals(FastTimeZone.getGmtTimeZone(), FastTimeZone.getTimeZone("-0"));
58 }
59
60 @Test
61 public void testOlson() {
62 assertEquals(TimeZone.getTimeZone("America/New_York"), FastTimeZone.getTimeZone("America/New_York"));
40 public void testGetGmtTimeZone() {
41 assertEquals(0, FastTimeZone.getGmtTimeZone().getRawOffset());
6342 }
6443
6544 @Test
6645 public void testGmtPrefix() {
6746 assertEquals(HOURS_23, FastTimeZone.getGmtTimeZone("GMT+23:00").getRawOffset());
6847 assertEquals(-HOURS_23, FastTimeZone.getGmtTimeZone("GMT-23:00").getRawOffset());
69 }
70
71 @Test
72 public void testSign() {
73 assertEquals(HOURS_23, FastTimeZone.getGmtTimeZone("+23:00").getRawOffset());
74 assertEquals(HOURS_2, FastTimeZone.getGmtTimeZone("+2:00").getRawOffset());
75 assertEquals(-HOURS_23, FastTimeZone.getGmtTimeZone("-23:00").getRawOffset());
76 assertEquals(-HOURS_2, FastTimeZone.getGmtTimeZone("-2:00").getRawOffset());
7748 }
7849
7950 @Test
9667 assertEquals(HOURS_2+MINUTES_5, FastTimeZone.getGmtTimeZone("0205").getRawOffset());
9768 }
9869
70 @Test
71 public void testOlson() {
72 assertEquals(TimeZone.getTimeZone("America/New_York"), FastTimeZone.getTimeZone("America/New_York"));
73 }
74
75 @Test
76 public void testSign() {
77 assertEquals(HOURS_23, FastTimeZone.getGmtTimeZone("+23:00").getRawOffset());
78 assertEquals(HOURS_2, FastTimeZone.getGmtTimeZone("+2:00").getRawOffset());
79 assertEquals(-HOURS_23, FastTimeZone.getGmtTimeZone("-23:00").getRawOffset());
80 assertEquals(-HOURS_2, FastTimeZone.getGmtTimeZone("-2:00").getRawOffset());
81 }
82
83 @Test
84 public void testUTC() {
85 assertEquals(FastTimeZone.getGmtTimeZone(), FastTimeZone.getTimeZone("UTC"));
86 }
87
88 @Test
89 public void testZ() {
90 assertEquals(FastTimeZone.getGmtTimeZone(), FastTimeZone.getTimeZone("Z"));
91 }
92
93 @Test
94 public void testZeroOffsetsReturnSingleton() {
95 assertEquals(FastTimeZone.getGmtTimeZone(), FastTimeZone.getTimeZone("+0"));
96 assertEquals(FastTimeZone.getGmtTimeZone(), FastTimeZone.getTimeZone("-0"));
97 }
98
9999 }
2727 public class GmtTimeZoneTest {
2828
2929 @Test
30 public void hoursOutOfRange() {
31 assertThrows(IllegalArgumentException.class, () -> new GmtTimeZone(false, 24, 0));
32 }
33
34 @Test
35 public void hoursInRange() {
36 assertEquals(23 * 60 * 60 * 1000, new GmtTimeZone(false, 23, 0).getRawOffset());
37 }
38
39 @Test
40 public void minutesOutOfRange() {
41 assertThrows(IllegalArgumentException.class, () -> new GmtTimeZone(false, 0, 60));
42 }
43
44 @Test
45 public void minutesInRange() {
46 assertEquals(59 * 60 * 1000, new GmtTimeZone(false, 0, 59).getRawOffset());
47 }
48
49 @Test
50 public void getOffset() {
51 assertEquals(0, new GmtTimeZone(false, 0, 0).getOffset(234304));
52 }
53
54 @Test
55 public void setRawOffset() {
56 assertThrows(UnsupportedOperationException.class, () -> new GmtTimeZone(false, 0, 0).setRawOffset(0));
57 }
58
59 @Test
60 public void getRawOffset() {
61 assertEquals(0, new GmtTimeZone(false, 0, 0).getRawOffset());
62 }
63
64 @Test
6530 public void getID() {
6631 assertEquals("GMT+00:00", new GmtTimeZone(false, 0, 0).getID());
6732 assertEquals("GMT+01:02", new GmtTimeZone(false, 1, 2).getID());
7136 }
7237
7338 @Test
74 public void useDaylightTime() {
75 assertFalse(new GmtTimeZone(false, 0, 0).useDaylightTime());
39 public void getOffset() {
40 assertEquals(0, new GmtTimeZone(false, 0, 0).getOffset(234304));
41 }
42
43 @Test
44 public void getRawOffset() {
45 assertEquals(0, new GmtTimeZone(false, 0, 0).getRawOffset());
46 }
47
48 @Test
49 public void hoursInRange() {
50 assertEquals(23 * 60 * 60 * 1000, new GmtTimeZone(false, 23, 0).getRawOffset());
51 }
52
53 @Test
54 public void hoursOutOfRange() {
55 assertThrows(IllegalArgumentException.class, () -> new GmtTimeZone(false, 24, 0));
7656 }
7757
7858 @Test
7959 public void inDaylightTime() {
8060 assertFalse(new GmtTimeZone(false, 0, 0).useDaylightTime());
61 }
62
63 @Test
64 public void minutesInRange() {
65 assertEquals(59 * 60 * 1000, new GmtTimeZone(false, 0, 59).getRawOffset());
66 }
67
68 @Test
69 public void minutesOutOfRange() {
70 assertThrows(IllegalArgumentException.class, () -> new GmtTimeZone(false, 0, 60));
71 }
72
73 @Test
74 public void setRawOffset() {
75 assertThrows(UnsupportedOperationException.class, () -> new GmtTimeZone(false, 0, 0).setRawOffset(0));
76 }
77
78 @Test
79 public void testGetOffset() {
80 assertEquals(-(6 * 60 + 30) * 60 * 1000,
81 new GmtTimeZone(true, 6, 30).getOffset(1, 1, 1, 1, 1, 1));
8182 }
8283
8384 @Test
8788 }
8889
8990 @Test
90 public void testGetOffset() {
91 assertEquals(-(6 * 60 + 30) * 60 * 1000,
92 new GmtTimeZone(true, 6, 30).getOffset(1, 1, 1, 1, 1, 1));
91 public void useDaylightTime() {
92 assertFalse(new GmtTimeZone(false, 0, 0).useDaylightTime());
9393 }
9494 }
0 /*
1 * Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package org.apache.commons.lang3.time;
18
19 import java.text.ParseException;
20 import java.text.SimpleDateFormat;
21 import java.util.Calendar;
22 import java.util.GregorianCalendar;
23 import java.util.Locale;
24 import java.util.TimeZone;
25
26 import org.apache.commons.lang3.function.TriFunction;
27 import org.junit.jupiter.api.Test;
28 import org.junit.jupiter.params.ParameterizedTest;
29 import org.junit.jupiter.params.provider.MethodSource;
30
31 /**
32 * These tests fail on Java 15 due to a bug which was only fixed for Java 16.
33 * <ul>
34 * <li>https://bugs.openjdk.java.net/browse/JDK-8248434</li>
35 * <li>https://bugs.openjdk.java.net/browse/JDK-8248655</li>
36 * </ul>
37 */
38 public class Java15BugFastDateParserTest {
39
40 /** @see org.apache.commons.lang3.time.FastDateParserTest#dateParserParameters() */
41 private static final String DATE_PARSER_PARAMETERS = "org.apache.commons.lang3.time.FastDateParserTest#dateParserParameters()";
42
43 @Test
44 public void java15BuggyLocaleTest() throws ParseException {
45 final String buggyLocaleName = "ff_LR_#Adlm";
46 Locale buggyLocale = null;
47 for (final Locale locale : Locale.getAvailableLocales()) {
48 if (buggyLocaleName.equals(locale.toString())) {
49 buggyLocale = locale;
50 break;
51 }
52 }
53 if (buggyLocale == null) {
54 return;
55 }
56 testSingleLocale(buggyLocale);
57 }
58
59 @Test
60 public void java15BuggyLocaleTestAll() throws ParseException {
61 for (final Locale locale : Locale.getAvailableLocales()) {
62 testSingleLocale(locale);
63 }
64 }
65
66 private void testLocales(final TriFunction<String, TimeZone, Locale, DateParser> dbProvider, final String format,
67 final boolean eraBC) throws Exception {
68
69 final Calendar cal = Calendar.getInstance(FastDateParserTest.GMT);
70 cal.clear();
71 cal.set(2003, Calendar.FEBRUARY, 10);
72 if (eraBC) {
73 cal.set(Calendar.ERA, GregorianCalendar.BC);
74 }
75
76 for (final Locale locale : Locale.getAvailableLocales()) {
77 // ja_JP_JP cannot handle dates before 1868 properly
78 if (eraBC && locale.equals(FastDateParser.JAPANESE_IMPERIAL)) {
79 continue;
80 }
81 final SimpleDateFormat sdf = new SimpleDateFormat(format, locale);
82 final DateParser fdf = dbProvider.apply(format, TimeZone.getDefault(), locale);
83
84 // If parsing fails, a ParseException will be thrown and the test will fail
85 FastDateParserTest.checkParse(locale, cal, sdf, fdf);
86 }
87 }
88
89 @ParameterizedTest
90 @MethodSource(DATE_PARSER_PARAMETERS)
91 public void testLocales_Long_AD(final TriFunction<String, TimeZone, Locale, DateParser> dpProvider)
92 throws Exception {
93 testLocales(dpProvider, FastDateParserTest.LONG_FORMAT, false);
94 }
95
96 @ParameterizedTest
97 @MethodSource(DATE_PARSER_PARAMETERS)
98 public void testLocales_Long_BC(final TriFunction<String, TimeZone, Locale, DateParser> dpProvider)
99 throws Exception {
100 testLocales(dpProvider, FastDateParserTest.LONG_FORMAT, true);
101 }
102
103 @ParameterizedTest
104 @MethodSource(DATE_PARSER_PARAMETERS)
105 public void testLocales_LongNoEra_AD(final TriFunction<String, TimeZone, Locale, DateParser> dpProvider)
106 throws Exception {
107 testLocales(dpProvider, FastDateParserTest.LONG_FORMAT_NOERA, false);
108 }
109
110 @ParameterizedTest
111 @MethodSource(DATE_PARSER_PARAMETERS)
112 public void testLocales_LongNoEra_BC(final TriFunction<String, TimeZone, Locale, DateParser> dpProvider)
113 throws Exception {
114 testLocales(dpProvider, FastDateParserTest.LONG_FORMAT_NOERA, true);
115 }
116
117 @ParameterizedTest
118 @MethodSource(DATE_PARSER_PARAMETERS)
119 public void testLocales_Short_AD(final TriFunction<String, TimeZone, Locale, DateParser> dpProvider)
120 throws Exception {
121 testLocales(dpProvider, FastDateParserTest.SHORT_FORMAT, false);
122 }
123
124 @ParameterizedTest
125 @MethodSource(DATE_PARSER_PARAMETERS)
126 public void testLocales_Short_BC(final TriFunction<String, TimeZone, Locale, DateParser> dpProvider)
127 throws Exception {
128 testLocales(dpProvider, FastDateParserTest.SHORT_FORMAT, true);
129 }
130
131 @ParameterizedTest
132 @MethodSource(DATE_PARSER_PARAMETERS)
133 public void testLocales_ShortNoEra_AD(final TriFunction<String, TimeZone, Locale, DateParser> dpProvider)
134 throws Exception {
135 testLocales(dpProvider, FastDateParserTest.SHORT_FORMAT_NOERA, false);
136 }
137
138 @ParameterizedTest
139 @MethodSource(DATE_PARSER_PARAMETERS)
140 public void testLocales_ShortNoEra_BC(final TriFunction<String, TimeZone, Locale, DateParser> dpProvider)
141 throws Exception {
142 testLocales(dpProvider, FastDateParserTest.SHORT_FORMAT_NOERA, true);
143 }
144
145 private void testSingleLocale(final Locale locale) throws ParseException {
146 final Calendar cal = Calendar.getInstance(FastDateParserTest.GMT);
147 cal.clear();
148 cal.set(2003, Calendar.FEBRUARY, 10);
149 final SimpleDateFormat sdf = new SimpleDateFormat(FastDateParserTest.LONG_FORMAT, locale);
150 final String formattedDate = sdf.format(cal.getTime());
151 sdf.parse(formattedDate);
152 sdf.parse(formattedDate.toUpperCase(locale));
153 sdf.parse(formattedDate.toLowerCase(locale));
154 }
155
156 }
2222 import static org.junit.jupiter.api.Assertions.assertThrows;
2323 import static org.junit.jupiter.api.Assertions.assertTrue;
2424
25 import java.time.Duration;
2526 import java.util.concurrent.TimeUnit;
2627
28 import org.apache.commons.lang3.ThreadUtils;
2729 import org.apache.commons.lang3.reflect.FieldUtils;
2830 import org.junit.jupiter.api.Test;
2931
3234 */
3335 public class StopWatchTest {
3436
37 private static final Duration MILLIS_200 = Duration.ofMillis(200);
38 private static final Duration MILLIS_550 = Duration.ofMillis(550);
3539 private static final String MESSAGE = "Baking cookies";
3640 private static final int MIN_SLEEP_MILLISECONDS = 20;
3741 private static final String ZERO_HOURS_PREFIX = "00:";
3943
4044 /**
4145 * <p>
42 * Creates a suspended StopWatch object which appears to have elapsed
43 * for the requested amount of time in nanoseconds.
46 * Creates a suspended StopWatch object which appears to have elapsed for the requested amount of time in
47 * nanoseconds.
4448 * <p>
4549 * <p>
50 *
4651 * <pre>
4752 * // Create a mock StopWatch with a time of 2:59:01.999
4853 * final long nanos = TimeUnit.HOURS.toNanos(2)
6065 watch.suspend();
6166 try {
6267 final long currentNanos = System.nanoTime();
63 FieldUtils.writeField(watch, "startTime", currentNanos - nanos, true);
64 FieldUtils.writeField(watch, "stopTime", currentNanos, true);
68 FieldUtils.writeField(watch, "startTimeNanos", currentNanos - nanos, true);
69 FieldUtils.writeField(watch, "stopTimeNanos", currentNanos, true);
6570 } catch (final IllegalAccessException e) {
6671 return null;
6772 }
6873 return watch;
6974 }
7075
76 private void sleepQuietly(final Duration duration) throws InterruptedException {
77 ThreadUtils.sleep(duration);
78 }
79
7180 // test bad states
7281 @Test
7382 public void testBadStates() {
7483 final StopWatch watch = new StopWatch();
75 assertThrows(
76 IllegalStateException.class,
77 watch::stop,
78 "Calling stop on an unstarted StopWatch should throw an exception. ");
79
80 assertThrows(
81 IllegalStateException.class,
82 watch::suspend,
83 "Calling suspend on an unstarted StopWatch should throw an exception. ");
84
85 assertThrows(
86 IllegalStateException.class,
87 watch::split,
88 "Calling split on a non-running StopWatch should throw an exception. ");
89
90 assertThrows(
91 IllegalStateException.class,
92 watch::unsplit,
93 "Calling unsplit on an unsplit StopWatch should throw an exception. ");
94
95 assertThrows(
96 IllegalStateException.class,
97 watch::resume,
98 "Calling resume on an unsuspended StopWatch should throw an exception. ");
99
100 watch.start();
101
102 assertThrows(
103 IllegalStateException.class,
104 watch::start,
105 "Calling start on a started StopWatch should throw an exception. ");
106
107 assertThrows(
108 IllegalStateException.class,
109 watch::unsplit,
110 "Calling unsplit on an unsplit StopWatch should throw an exception. ");
111
112 assertThrows(
113 IllegalStateException.class,
114 watch::getSplitTime,
115 "Calling getSplitTime on an unsplit StopWatch should throw an exception. ");
116
117 assertThrows(
118 IllegalStateException.class,
119 watch::resume,
120 "Calling resume on an unsuspended StopWatch should throw an exception. ");
121
122 watch.stop();
123
124 assertThrows(
125 IllegalStateException.class,
126 watch::start,
127 "Calling start on a stopped StopWatch should throw an exception as it needs to be reset. ");
84 assertThrows(IllegalStateException.class, watch::stop,
85 "Calling stop on an unstarted StopWatch should throw an exception. ");
86
87 assertThrows(IllegalStateException.class, watch::suspend,
88 "Calling suspend on an unstarted StopWatch should throw an exception. ");
89
90 assertThrows(IllegalStateException.class, watch::split,
91 "Calling split on a non-running StopWatch should throw an exception. ");
92
93 assertThrows(IllegalStateException.class, watch::unsplit,
94 "Calling unsplit on an unsplit StopWatch should throw an exception. ");
95
96 assertThrows(IllegalStateException.class, watch::resume,
97 "Calling resume on an unsuspended StopWatch should throw an exception. ");
98
99 watch.start();
100
101 assertThrows(IllegalStateException.class, watch::start,
102 "Calling start on a started StopWatch should throw an exception. ");
103
104 assertThrows(IllegalStateException.class, watch::unsplit,
105 "Calling unsplit on an unsplit StopWatch should throw an exception. ");
106
107 assertThrows(IllegalStateException.class, watch::getSplitTime,
108 "Calling getSplitTime on an unsplit StopWatch should throw an exception. ");
109
110 assertThrows(IllegalStateException.class, watch::resume,
111 "Calling resume on an unsuspended StopWatch should throw an exception. ");
112
113 watch.stop();
114
115 assertThrows(IllegalStateException.class, watch::start,
116 "Calling start on a stopped StopWatch should throw an exception as it needs to be reset. ");
128117 }
129118
130119 @Test
153142 @Test
154143 public void testFormatSplitTime() throws InterruptedException {
155144 final StopWatch watch = StopWatch.createStarted();
156 Thread.sleep(MIN_SLEEP_MILLISECONDS);
145 ThreadUtils.sleepQuietly(MIN_SLEEP_MILLISECONDS);
157146 watch.split();
158147 final String formatSplitTime = watch.formatSplitTime();
159148 assertNotEquals(ZERO_TIME_ELAPSED, formatSplitTime);
164153 public void testFormatSplitTimeWithMessage() throws InterruptedException {
165154 final StopWatch watch = new StopWatch(MESSAGE);
166155 watch.start();
167 Thread.sleep(MIN_SLEEP_MILLISECONDS);
156 ThreadUtils.sleepQuietly(MIN_SLEEP_MILLISECONDS);
168157 watch.split();
169158 final String formatSplitTime = watch.formatSplitTime();
170159 assertFalse(formatSplitTime.startsWith(MESSAGE), formatSplitTime);
188177
189178 @Test
190179 public void testGetStartTime() {
191 final long beforeStopWatch = System.currentTimeMillis();
180 final long beforeStopWatchMillis = System.currentTimeMillis();
192181 final StopWatch watch = new StopWatch();
193 assertThrows(
194 IllegalStateException.class,
195 watch::getStartTime,
196 "Calling getStartTime on an unstarted StopWatch should throw an exception");
182 assertThrows(IllegalStateException.class, watch::getStartTime,
183 "Calling getStartTime on an unstarted StopWatch should throw an exception");
197184 watch.start();
198185
199186 watch.getStartTime();
200 assertTrue(watch.getStartTime() >= beforeStopWatch);
187 assertTrue(watch.getStartTime() >= beforeStopWatchMillis);
201188
202189 watch.reset();
203 assertThrows(
204 IllegalStateException.class,
205 watch::getStartTime,
206 "Calling getStartTime on a reset, but unstarted StopWatch should throw an exception");
207 }
208
209 @Test
210 public void testLang315() {
211 final StopWatch watch = StopWatch.createStarted();
212 try {
213 Thread.sleep(200);
214 } catch (final InterruptedException ex) {
215 // ignore
216 }
190 assertThrows(IllegalStateException.class, watch::getStartTime,
191 "Calling getStartTime on a reset, but unstarted StopWatch should throw an exception");
192 }
193
194 @Test
195 public void testLang315() throws InterruptedException {
196 final StopWatch watch = StopWatch.createStarted();
197 sleepQuietly(MILLIS_200);
217198 watch.suspend();
218199 final long suspendTime = watch.getTime();
219 try {
220 Thread.sleep(200);
221 } catch (final InterruptedException ex) {
222 // ignore
223 }
200 sleepQuietly(MILLIS_200);
224201 watch.stop();
225202 final long totalTime = watch.getTime();
226203 assertEquals(suspendTime, totalTime);
238215 }
239216
240217 @Test
218 public void testStopTimeSimple() throws InterruptedException {
219 final StopWatch watch = StopWatch.createStarted();
220 final long testStartMillis = System.currentTimeMillis();
221 sleepQuietly(MILLIS_550);
222 watch.stop();
223 final long testEndMillis = System.currentTimeMillis();
224 final long stopTime = watch.getStopTime();
225 assertEquals(stopTime, watch.getStopTime());
226
227 assertTrue(stopTime >= testStartMillis);
228 assertTrue(stopTime <= testEndMillis);
229 }
230
231 @Test
241232 public void testStopWatchGetWithTimeUnit() {
242233 // Create a mock StopWatch with a time of 2:59:01.999
234 // @formatter:off
243235 final StopWatch watch = createMockStopWatch(
244 TimeUnit.HOURS.toNanos(2)
245 + TimeUnit.MINUTES.toNanos(59)
246 + TimeUnit.SECONDS.toNanos(1)
247 + TimeUnit.MILLISECONDS.toNanos(999));
236 TimeUnit.HOURS.toNanos(2)
237 + TimeUnit.MINUTES.toNanos(59)
238 + TimeUnit.SECONDS.toNanos(1)
239 + TimeUnit.MILLISECONDS.toNanos(999));
240 // @formatter:on
248241
249242 assertEquals(2L, watch.getTime(TimeUnit.HOURS));
250243 assertEquals(179L, watch.getTime(TimeUnit.MINUTES));
253246 }
254247
255248 @Test
256 public void testStopWatchSimple() {
257 final StopWatch watch = StopWatch.createStarted();
258 try {
259 Thread.sleep(550);
260 } catch (final InterruptedException ex) {
261 // ignore
262 }
249 public void testStopWatchSimple() throws InterruptedException {
250 final StopWatch watch = StopWatch.createStarted();
251 sleepQuietly(MILLIS_550);
263252 watch.stop();
264253 final long time = watch.getTime();
265254 assertEquals(time, watch.getTime());
272261 }
273262
274263 @Test
275 public void testStopWatchSimpleGet() {
264 public void testStopWatchSimpleGet() throws InterruptedException {
276265 final StopWatch watch = new StopWatch();
277266 assertEquals(0, watch.getTime());
278267 assertEquals(ZERO_TIME_ELAPSED, watch.toString());
279268
280269 watch.start();
281 try {
282 Thread.sleep(500);
283 } catch (final InterruptedException ex) {
284 // ignore
285 }
270 sleepQuietly(MILLIS_550);
286271 assertTrue(watch.getTime() < 2000);
287272 }
288273
289274 @Test
290 public void testStopWatchSplit() {
291 final StopWatch watch = StopWatch.createStarted();
292 try {
293 Thread.sleep(550);
294 } catch (final InterruptedException ex) {
295 // ignore
296 }
275 public void testStopWatchSplit() throws InterruptedException {
276 final StopWatch watch = StopWatch.createStarted();
277 sleepQuietly(MILLIS_550);
297278 watch.split();
298279 final long splitTime = watch.getSplitTime();
299280 final String splitStr = watch.toSplitString();
300 try {
301 Thread.sleep(550);
302 } catch (final InterruptedException ex) {
303 // ignore
304 }
281 sleepQuietly(MILLIS_550);
305282 watch.unsplit();
306 try {
307 Thread.sleep(550);
308 } catch (final InterruptedException ex) {
309 // ignore
310 }
283 sleepQuietly(MILLIS_550);
311284 watch.stop();
312285 final long totalTime = watch.getTime();
313286
325298 }
326299
327300 @Test
328 public void testStopWatchSuspend() {
329 final StopWatch watch = StopWatch.createStarted();
330 try {
331 Thread.sleep(550);
332 } catch (final InterruptedException ex) {
333 // ignore
334 }
301 public void testStopWatchSuspend() throws InterruptedException {
302 final StopWatch watch = StopWatch.createStarted();
303 final long testStartMillis = System.currentTimeMillis();
304 sleepQuietly(MILLIS_550);
335305 watch.suspend();
306 final long testSuspendMillis = System.currentTimeMillis();
336307 final long suspendTime = watch.getTime();
337 try {
338 Thread.sleep(550);
339 } catch (final InterruptedException ex) {
340 // ignore
341 }
308 final long stopTime = watch.getStopTime();
309
310 assertTrue(testStartMillis <= stopTime);
311 assertTrue(testSuspendMillis <= stopTime);
312
313 sleepQuietly(MILLIS_550);
342314 watch.resume();
343 try {
344 Thread.sleep(550);
345 } catch (final InterruptedException ex) {
346 // ignore
347 }
315 sleepQuietly(MILLIS_550);
348316 watch.stop();
349317 final long totalTime = watch.getTime();
350318
355323 }
356324
357325 @Test
358 public void testToSplitString() {
359 final StopWatch watch = StopWatch.createStarted();
360 try {
361 Thread.sleep(550);
362 } catch (final InterruptedException ex) {
363 // ignore
364 }
326 public void testToSplitString() throws InterruptedException {
327 final StopWatch watch = StopWatch.createStarted();
328 sleepQuietly(MILLIS_550);
365329 watch.split();
366330 final String splitStr = watch.toSplitString();
367331 assertEquals(splitStr.length(), 12, "Formatted split string not the correct length");
368332 }
369333
370334 @Test
371 public void testToSplitStringWithMessage() {
335 public void testToSplitStringWithMessage() throws InterruptedException {
372336 final StopWatch watch = new StopWatch(MESSAGE);
373337 watch.start();
374 try {
375 Thread.sleep(550);
376 } catch (final InterruptedException ex) {
377 // ignore
378 }
338 sleepQuietly(MILLIS_550);
379339 watch.split();
380340 final String splitStr = watch.toSplitString();
381341 assertEquals(splitStr.length(), 12 + MESSAGE.length() + 1, "Formatted split string not the correct length");
382342 }
383343
384344 @Test
385 public void testToString() {
345 public void testToString() throws InterruptedException {
386346 //
387347 final StopWatch watch = StopWatch.createStarted();
388 try {
389 Thread.sleep(550);
390 } catch (final InterruptedException ex) {
391 // ignore
392 }
348 sleepQuietly(MILLIS_550);
393349 watch.split();
394350 final String splitStr = watch.toString();
395351 assertEquals(splitStr.length(), 12, "Formatted split string not the correct length");
396352 }
397353
398354 @Test
399 public void testToStringWithMessage() {
355 public void testToStringWithMessage() throws InterruptedException {
400356 assertTrue(new StopWatch(MESSAGE).toString().startsWith(MESSAGE));
401357 //
402358 final StopWatch watch = new StopWatch(MESSAGE);
403359 watch.start();
404 try {
405 Thread.sleep(550);
406 } catch (final InterruptedException ex) {
407 // ignore
408 }
360 sleepQuietly(MILLIS_550);
409361 watch.split();
410362 final String splitStr = watch.toString();
411363 assertEquals(splitStr.length(), 12 + MESSAGE.length() + 1, "Formatted split string not the correct length");
2222 import static org.junit.jupiter.api.Assertions.assertSame;
2323 import static org.junit.jupiter.api.Assertions.assertTrue;
2424
25 import java.io.ByteArrayInputStream;
26 import java.io.ByteArrayOutputStream;
27 import java.io.ObjectInputStream;
28 import java.io.ObjectOutputStream;
2925 import java.util.ArrayList;
3026 import java.util.HashMap;
3127 import java.util.Iterator;
3228 import java.util.Map.Entry;
3329 import java.util.TreeMap;
3430
31 import org.apache.commons.lang3.SerializationUtils;
3532 import org.junit.jupiter.api.Test;
3633
3734 /**
3835 * Test the Pair class.
3936 */
4037 public class ImmutablePairTest {
41
42 @Test
43 public void testEmptyArrayLength() {
44 @SuppressWarnings("unchecked")
45 final ImmutablePair<Integer, String>[] empty = (ImmutablePair<Integer, String>[]) ImmutablePair.EMPTY_ARRAY;
46 assertEquals(0, empty.length);
47 }
48
49 @Test
50 public void testEmptyArrayGenerics() {
51 final ImmutablePair<Integer, String>[] empty = ImmutablePair.emptyArray();
52 assertEquals(0, empty.length);
53 }
5438
5539 @Test
5640 public void testBasic() {
7963 }
8064
8165 @Test
66 public void testComparableLeftOnly() {
67 final Pair<String, String> pair1 = ImmutablePair.left("A");
68 final Pair<String, String> pair2 = ImmutablePair.left("B");
69 assertEquals("A", pair1.getLeft());
70 assertEquals("B", pair2.getLeft());
71 assertEquals(0, pair1.compareTo(pair1));
72 assertTrue(pair1.compareTo(pair2) < 0);
73 assertEquals(0, pair2.compareTo(pair2));
74 assertTrue(pair2.compareTo(pair1) > 0);
75 }
76
77 @Test
78 public void testComparableRightOnly() {
79 final Pair<String, String> pair1 = ImmutablePair.right("A");
80 final Pair<String, String> pair2 = ImmutablePair.right("B");
81 assertEquals("A", pair1.getRight());
82 assertEquals("B", pair2.getRight());
83 assertEquals(0, pair1.compareTo(pair1));
84 assertTrue(pair1.compareTo(pair2) < 0);
85 assertEquals(0, pair2.compareTo(pair2));
86 assertTrue(pair2.compareTo(pair1) > 0);
87 }
88
89 @Test
90 public void testEmptyArrayGenerics() {
91 final ImmutablePair<Integer, String>[] empty = ImmutablePair.emptyArray();
92 assertEquals(0, empty.length);
93 }
94
95 @Test
96 public void testEmptyArrayLength() {
97 @SuppressWarnings("unchecked")
98 final ImmutablePair<Integer, String>[] empty = (ImmutablePair<Integer, String>[]) ImmutablePair.EMPTY_ARRAY;
99 assertEquals(0, empty.length);
100 }
101
102 @Test
82103 public void testEquals() {
83104 assertEquals(ImmutablePair.of(null, "foo"), ImmutablePair.of(null, "foo"));
84105 assertNotEquals(ImmutablePair.of("foo", 0), ImmutablePair.of("foo", null));
154175 assertNull(pair2.getLeft());
155176 assertEquals("bar", pair2.right);
156177 assertEquals("bar", pair2.getRight());
157 final ImmutablePair pair3 = ImmutablePair.of(null, null);
178 final ImmutablePair<?, ?> pair3 = ImmutablePair.of(null, null);
158179 assertNull(pair3.left);
159180 assertNull(pair3.right);
160181 }
163184 @SuppressWarnings("unchecked")
164185 public void testSerialization() throws Exception {
165186 final ImmutablePair<Integer, String> origPair = ImmutablePair.of(0, "foo");
166 final ByteArrayOutputStream baos = new ByteArrayOutputStream();
167 final ObjectOutputStream out = new ObjectOutputStream(baos);
168 out.writeObject(origPair);
169 final ImmutablePair<Integer, String> deserializedPair = (ImmutablePair<Integer, String>) new ObjectInputStream(
170 new ByteArrayInputStream(baos.toByteArray())).readObject();
187 final ImmutablePair<Integer, String> deserializedPair = SerializationUtils.roundtrip(origPair);
171188 assertEquals(origPair, deserializedPair);
172189 assertEquals(origPair.hashCode(), deserializedPair.hashCode());
173190 }
178195 assertEquals("(null,two)", ImmutablePair.of(null, "two").toString());
179196 assertEquals("(one,null)", ImmutablePair.of("one", null).toString());
180197 assertEquals("(one,two)", ImmutablePair.of("one", "two").toString());
198 }
199
200 @Test
201 public void testToStringLeft() {
202 final Pair<String, String> pair = ImmutablePair.left("Key");
203 assertEquals("(Key,null)", pair.toString());
204 }
205
206 @Test
207 public void testToStringRight() {
208 final Pair<String, String> pair = ImmutablePair.right("Value");
209 assertEquals("(null,Value)", pair.toString());
181210 }
182211
183212 @Test
209238 assertEquals(item.getLeft() + "" + item.getRight(), entry.getValue());
210239 }
211240 }
212
213 @Test
214 public void testComparableLeftOnly() {
215 final Pair<String, String> pair1 = ImmutablePair.left("A");
216 final Pair<String, String> pair2 = ImmutablePair.left("B");
217 assertEquals("A", pair1.getLeft());
218 assertEquals("B", pair2.getLeft());
219 assertEquals(0, pair1.compareTo(pair1));
220 assertTrue(pair1.compareTo(pair2) < 0);
221 assertEquals(0, pair2.compareTo(pair2));
222 assertTrue(pair2.compareTo(pair1) > 0);
223 }
224
225 @Test
226 public void testComparableRightOnly() {
227 final Pair<String, String> pair1 = ImmutablePair.right("A");
228 final Pair<String, String> pair2 = ImmutablePair.right("B");
229 assertEquals("A", pair1.getRight());
230 assertEquals("B", pair2.getRight());
231 assertEquals(0, pair1.compareTo(pair1));
232 assertTrue(pair1.compareTo(pair2) < 0);
233 assertEquals(0, pair2.compareTo(pair2));
234 assertTrue(pair2.compareTo(pair1) > 0);
235 }
236
237 @Test
238 public void testToStringLeft() {
239 final Pair<String, String> pair = ImmutablePair.left("Key");
240 assertEquals("(Key,null)", pair.toString());
241 }
242
243 @Test
244 public void testToStringRight() {
245 final Pair<String, String> pair = ImmutablePair.right("Value");
246 assertEquals("(null,Value)", pair.toString());
247 }
248241 }
2121 import static org.junit.jupiter.api.Assertions.assertNull;
2222 import static org.junit.jupiter.api.Assertions.assertSame;
2323
24 import java.io.ByteArrayInputStream;
25 import java.io.ByteArrayOutputStream;
26 import java.io.ObjectInputStream;
27 import java.io.ObjectOutputStream;
2824 import java.util.ArrayList;
2925 import java.util.HashMap;
3026 import java.util.Iterator;
3127 import java.util.Map.Entry;
3228 import java.util.TreeMap;
3329
30 import org.apache.commons.lang3.SerializationUtils;
3431 import org.junit.jupiter.api.Test;
3532
3633 /**
3734 * Test the Triple class.
3835 */
3936 public class ImmutableTripleTest {
40
41 @Test
42 public void testEmptyArrayLength() {
43 @SuppressWarnings("unchecked")
44 final ImmutableTriple<Integer, String, Boolean>[] empty = (ImmutableTriple<Integer, String, Boolean>[]) ImmutableTriple.EMPTY_ARRAY;
45 assertEquals(0, empty.length);
46 }
47
48 @Test
49 public void testEmptyArrayGenerics() {
50 final ImmutableTriple<Integer, String, Boolean>[] empty = ImmutableTriple.emptyArray();
51 assertEquals(0, empty.length);
52 }
5337
5438 @Test
5539 public void testBasic() {
6549 assertNull(triple2.getLeft());
6650 assertEquals("bar", triple2.middle);
6751 assertEquals("bar", triple2.getMiddle());
68 assertEquals(new Integer(42), triple2.right);
69 assertEquals(new Integer(42), triple2.getRight());
52 assertEquals(Integer.valueOf(42), triple2.right);
53 assertEquals(Integer.valueOf(42), triple2.getRight());
54 }
55
56 @Test
57 public void testEmptyArrayGenerics() {
58 final ImmutableTriple<Integer, String, Boolean>[] empty = ImmutableTriple.emptyArray();
59 assertEquals(0, empty.length);
60 }
61
62 @Test
63 public void testEmptyArrayLength() {
64 @SuppressWarnings("unchecked")
65 final ImmutableTriple<Integer, String, Boolean>[] empty = (ImmutableTriple<Integer, String, Boolean>[]) ImmutableTriple.EMPTY_ARRAY;
66 assertEquals(0, empty.length);
7067 }
7168
7269 @Test
122119 @SuppressWarnings("unchecked")
123120 public void testSerialization() throws Exception {
124121 final ImmutableTriple<Integer, String, Boolean> origTriple = ImmutableTriple.of(0, "foo", Boolean.TRUE);
125 final ByteArrayOutputStream baos = new ByteArrayOutputStream();
126 final ObjectOutputStream out = new ObjectOutputStream(baos);
127 out.writeObject(origTriple);
128 final ImmutableTriple<Integer, String, Boolean> deserializedTriple = (ImmutableTriple<Integer, String, Boolean>) new ObjectInputStream(
129 new ByteArrayInputStream(baos.toByteArray())).readObject();
122 final ImmutableTriple<Integer, String, Boolean> deserializedTriple = SerializationUtils.roundtrip(origTriple);
130123 assertEquals(origTriple, deserializedTriple);
131124 assertEquals(origTriple.hashCode(), deserializedTriple.hashCode());
132125 }
1919 import static org.junit.jupiter.api.Assertions.assertNotEquals;
2020 import static org.junit.jupiter.api.Assertions.assertNull;
2121
22 import java.io.ByteArrayInputStream;
23 import java.io.ByteArrayOutputStream;
24 import java.io.ObjectInputStream;
25 import java.io.ObjectOutputStream;
2622 import java.util.HashMap;
2723 import java.util.Map.Entry;
2824
25 import org.apache.commons.lang3.SerializationUtils;
2926 import org.junit.jupiter.api.Test;
3027
3128 /**
3229 * Test the MutablePair class.
3330 */
3431 public class MutablePairTest {
35
36 @Test
37 public void testEmptyArrayLength() {
38 @SuppressWarnings("unchecked")
39 final MutablePair<Integer, String>[] empty = (MutablePair<Integer, String>[]) MutablePair.EMPTY_ARRAY;
40 assertEquals(0, empty.length);
41 }
42
43 @Test
44 public void testEmptyArrayGenerics() {
45 final MutablePair<Integer, String>[] empty = MutablePair.emptyArray();
46 assertEquals(0, empty.length);
47 }
4832
4933 @Test
5034 public void testBasic() {
7761 final MutablePair<Integer, String> pair = new MutablePair<>();
7862 assertNull(pair.getLeft());
7963 assertNull(pair.getRight());
64 }
65
66 @Test
67 public void testEmptyArrayGenerics() {
68 final MutablePair<Integer, String>[] empty = MutablePair.emptyArray();
69 assertEquals(0, empty.length);
70 }
71
72 @Test
73 public void testEmptyArrayLength() {
74 @SuppressWarnings("unchecked")
75 final MutablePair<Integer, String>[] empty = (MutablePair<Integer, String>[]) MutablePair.EMPTY_ARRAY;
76 assertEquals(0, empty.length);
8077 }
8178
8279 @Test
122119 final MutablePair<Object, String> pair2 = MutablePair.of(null, "bar");
123120 assertNull(pair2.getLeft());
124121 assertEquals("bar", pair2.getRight());
125 final MutablePair pair3 = MutablePair.of(null, null);
122 final MutablePair<?, ?> pair3 = MutablePair.of(null, null);
126123 assertNull(pair3.left);
127124 assertNull(pair3.right);
128125 }
129126
130127 @Test
131 @SuppressWarnings("unchecked")
132128 public void testSerialization() throws Exception {
133129 final MutablePair<Integer, String> origPair = MutablePair.of(0, "foo");
134 final ByteArrayOutputStream baos = new ByteArrayOutputStream();
135 final ObjectOutputStream out = new ObjectOutputStream(baos);
136 out.writeObject(origPair);
137 final MutablePair<Integer, String> deserializedPair = (MutablePair<Integer, String>) new ObjectInputStream(
138 new ByteArrayInputStream(baos.toByteArray())).readObject();
130 final MutablePair<Integer, String> deserializedPair = SerializationUtils.roundtrip(origPair);
139131 assertEquals(origPair, deserializedPair);
140132 assertEquals(origPair.hashCode(), deserializedPair.hashCode());
141133 }
1919 import static org.junit.jupiter.api.Assertions.assertNotEquals;
2020 import static org.junit.jupiter.api.Assertions.assertNull;
2121
22 import java.io.ByteArrayInputStream;
23 import java.io.ByteArrayOutputStream;
24 import java.io.ObjectInputStream;
25 import java.io.ObjectOutputStream;
26
22 import org.apache.commons.lang3.SerializationUtils;
2723 import org.junit.jupiter.api.Test;
2824
2925 /**
3026 * Test the MutableTriple class.
3127 */
3228 public class MutableTripleTest {
33
34 @Test
35 public void testEmptyArrayLength() {
36 @SuppressWarnings("unchecked")
37 final MutableTriple<Integer, String, Boolean>[] empty = (MutableTriple<Integer, String, Boolean>[]) MutableTriple.EMPTY_ARRAY;
38 assertEquals(0, empty.length);
39 }
40
41 @Test
42 public void testEmptyArrayGenerics() {
43 final MutableTriple<Integer, String, Boolean>[] empty = MutableTriple.emptyArray();
44 assertEquals(0, empty.length);
45 }
4629
4730 @Test
4831 public void testBasic() {
6245 assertNull(triple.getLeft());
6346 assertNull(triple.getMiddle());
6447 assertNull(triple.getRight());
48 }
49
50 @Test
51 public void testEmptyArrayGenerics() {
52 final MutableTriple<Integer, String, Boolean>[] empty = MutableTriple.emptyArray();
53 assertEquals(0, empty.length);
54 }
55
56 @Test
57 public void testEmptyArrayLength() {
58 @SuppressWarnings("unchecked")
59 final MutableTriple<Integer, String, Boolean>[] empty = (MutableTriple<Integer, String, Boolean>[]) MutableTriple.EMPTY_ARRAY;
60 assertEquals(0, empty.length);
6561 }
6662
6763 @Test
9692 @SuppressWarnings("unchecked")
9793 public void testSerialization() throws Exception {
9894 final MutableTriple<Integer, String, Boolean> origTriple = MutableTriple.of(0, "foo", Boolean.TRUE);
99 final ByteArrayOutputStream baos = new ByteArrayOutputStream();
100 final ObjectOutputStream out = new ObjectOutputStream(baos);
101 out.writeObject(origTriple);
102 final MutableTriple<Integer, String, Boolean> deserializedTriple = (MutableTriple<Integer, String, Boolean>) new ObjectInputStream(
103 new ByteArrayInputStream(baos.toByteArray())).readObject();
95 final MutableTriple<Integer, String, Boolean> deserializedTriple = SerializationUtils.roundtrip(origTriple);
10496 assertEquals(origTriple, deserializedTriple);
10597 assertEquals(origTriple.hashCode(), deserializedTriple.hashCode());
10698 }
3333 public class PairTest {
3434
3535 @Test
36 public void testEmptyArrayLength() {
37 @SuppressWarnings("unchecked")
38 final Pair<Integer, String>[] empty = (Pair<Integer, String>[]) Pair.EMPTY_ARRAY;
39 assertEquals(0, empty.length);
40 }
41
42 @Test
43 public void testEmptyArrayGenerics() {
44 final Pair<Integer, String>[] empty = Pair.emptyArray();
45 assertEquals(0, empty.length);
46 }
47
48 @Test
4936 public void testComparable1() {
5037 final Pair<String, String> pair1 = Pair.of("A", "D");
5138 final Pair<String, String> pair2 = Pair.of("B", "C");
7865 pair2.setValue("bar");
7966 assertNotEquals(pair, pair2);
8067 assertNotEquals(pair.hashCode(), pair2.hashCode());
68 }
69
70 @Test
71 public void testEmptyArrayGenerics() {
72 final Pair<Integer, String>[] empty = Pair.emptyArray();
73 assertEquals(0, empty.length);
74 }
75
76 @Test
77 public void testEmptyArrayLength() {
78 @SuppressWarnings("unchecked")
79 final Pair<Integer, String>[] empty = (Pair<Integer, String>[]) Pair.EMPTY_ARRAY;
80 assertEquals(0, empty.length);
8181 }
8282
8383 @Test
2828 * Test the Triple class.
2929 */
3030 public class TripleTest {
31
32 @Test
33 public void testEmptyArrayLength() {
34 @SuppressWarnings("unchecked")
35 final Triple<Integer, String, Boolean>[] empty = (Triple<Integer, String, Boolean>[]) Triple.EMPTY_ARRAY;
36 assertEquals(0, empty.length);
37 }
38
39 @Test
40 public void testEmptyArrayGenerics() {
41 final Triple<Integer, String, Boolean>[] empty = Triple.emptyArray();
42 assertEquals(0, empty.length);
43 }
4431
4532 @Test
4633 public void testComparable1() {
9481 }
9582
9683 @Test
84 public void testEmptyArrayGenerics() {
85 final Triple<Integer, String, Boolean>[] empty = Triple.emptyArray();
86 assertEquals(0, empty.length);
87 }
88
89 @Test
90 public void testEmptyArrayLength() {
91 @SuppressWarnings("unchecked")
92 final Triple<Integer, String, Boolean>[] empty = (Triple<Integer, String, Boolean>[]) Triple.EMPTY_ARRAY;
93 assertEquals(0, empty.length);
94 }
95
96 @Test
9797 public void testFormattable_padded() {
9898 final Triple<String, String, String> triple = Triple.of("Key", "Something", "Value");
9999 assertEquals(" (Key,Something,Value)", String.format("%1$30s", triple));
130130 assertTrue(triple2 instanceof ImmutableTriple<?, ?, ?>);
131131 assertNull(((ImmutableTriple<Object, String, Long>) triple2).left);
132132 assertEquals("bar", ((ImmutableTriple<Object, String, Long>) triple2).middle);
133 assertEquals(new Long(200L), ((ImmutableTriple<Object, String, Long>) triple2).right);
133 assertEquals(Long.valueOf(200L), ((ImmutableTriple<Object, String, Long>) triple2).right);
134134 }
135135
136136 }