You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@commons.apache.org by gg...@apache.org on 2023/11/03 15:26:25 UTC
(commons-lang) branch master updated (083822532 -> 629a83c6c)
This is an automated email from the ASF dual-hosted git repository.
ggregory pushed a change to branch master
in repository https://gitbox.apache.org/repos/asf/commons-lang.git
from 083822532 Clarifies Java platform requirement
new 972b3f218 Normalize test method names
new dc83c2820 Sort main members
new 629a83c6c Sort test members
The 3 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
Summary of changes:
.../org/apache/commons/lang3/AnnotationUtils.java | 262 +-
.../java/org/apache/commons/lang3/ArchUtils.java | 76 +-
.../java/org/apache/commons/lang3/BitField.java | 212 +-
.../java/org/apache/commons/lang3/CharRange.java | 350 +-
.../java/org/apache/commons/lang3/CharSet.java | 30 +-
.../java/org/apache/commons/lang3/CharUtils.java | 378 +-
.../java/org/apache/commons/lang3/ClassUtils.java | 20 +-
.../java/org/apache/commons/lang3/Conversion.java | 1602 ++++-----
.../java/org/apache/commons/lang3/JavaVersion.java | 138 +-
.../java/org/apache/commons/lang3/LocaleUtils.java | 8 +-
.../commons/lang3/NotImplementedException.java | 24 +-
.../java/org/apache/commons/lang3/ObjectUtils.java | 42 +-
.../commons/lang3/SerializationException.java | 14 +-
.../java/org/apache/commons/lang3/Streams.java | 332 +-
.../apache/commons/lang3/StringEscapeUtils.java | 468 +--
.../java/org/apache/commons/lang3/Validate.java | 1494 ++++----
.../org/apache/commons/lang3/builder/Diff.java | 32 +-
.../apache/commons/lang3/builder/DiffBuilder.java | 260 +-
.../apache/commons/lang3/builder/DiffResult.java | 56 +-
.../commons/lang3/builder/EqualsBuilder.java | 1070 +++---
.../org/apache/commons/lang3/builder/IDKey.java | 18 +-
.../builder/MultilineRecursiveToStringStyle.java | 108 +-
.../lang3/builder/RecursiveToStringStyle.java | 36 +-
.../lang3/builder/ReflectionDiffBuilder.java | 86 +-
.../lang3/builder/StandardToStringStyle.java | 390 +-
.../commons/lang3/builder/ToStringBuilder.java | 68 +-
.../commons/lang3/builder/ToStringStyle.java | 3358 +++++++++---------
.../lang3/concurrent/AbstractCircuitBreaker.java | 154 +-
.../concurrent/AbstractConcurrentInitializer.java | 16 +-
.../lang3/concurrent/AtomicInitializer.java | 22 +-
.../lang3/concurrent/AtomicSafeInitializer.java | 28 +-
.../lang3/concurrent/BackgroundInitializer.java | 304 +-
.../lang3/concurrent/BasicThreadFactory.java | 334 +-
.../concurrent/CallableBackgroundInitializer.java | 26 +-
.../commons/lang3/concurrent/CircuitBreaker.java | 50 +-
.../lang3/concurrent/CircuitBreakingException.java | 14 +-
.../lang3/concurrent/ConcurrentException.java | 14 +-
.../concurrent/ConcurrentRuntimeException.java | 14 +-
.../commons/lang3/concurrent/ConcurrentUtils.java | 304 +-
.../lang3/concurrent/ConstantInitializer.java | 58 +-
.../lang3/concurrent/EventCountCircuitBreaker.java | 560 +--
.../commons/lang3/concurrent/FutureTasks.java | 8 +-
.../commons/lang3/concurrent/LazyInitializer.java | 16 +-
.../concurrent/MultiBackgroundInitializer.java | 338 +-
.../lang3/concurrent/ThresholdCircuitBreaker.java | 18 +-
.../commons/lang3/concurrent/TimedSemaphore.java | 232 +-
.../commons/lang3/event/EventListenerSupport.java | 228 +-
.../org/apache/commons/lang3/event/EventUtils.java | 98 +-
.../lang3/exception/CloneFailedException.java | 10 +-
.../lang3/exception/ContextedException.java | 74 +-
.../lang3/exception/ContextedRuntimeException.java | 74 +-
.../apache/commons/lang3/function/Consumers.java | 8 +-
.../apache/commons/lang3/function/Suppliers.java | 22 +-
.../apache/commons/lang3/function/TriFunction.java | 20 +-
.../org/apache/commons/lang3/math/Fraction.java | 808 ++---
.../apache/commons/lang3/math/IEEE754rUtils.java | 208 +-
.../org/apache/commons/lang3/math/NumberUtils.java | 2302 ++++++------
.../commons/lang3/mutable/MutableBoolean.java | 122 +-
.../apache/commons/lang3/mutable/MutableByte.java | 276 +-
.../commons/lang3/mutable/MutableDouble.java | 348 +-
.../apache/commons/lang3/mutable/MutableFloat.java | 350 +-
.../apache/commons/lang3/mutable/MutableInt.java | 274 +-
.../apache/commons/lang3/mutable/MutableLong.java | 276 +-
.../commons/lang3/mutable/MutableObject.java | 40 +-
.../apache/commons/lang3/mutable/MutableShort.java | 292 +-
.../commons/lang3/reflect/ConstructorUtils.java | 204 +-
.../apache/commons/lang3/reflect/FieldUtils.java | 608 ++--
.../commons/lang3/reflect/InheritanceUtils.java | 22 +-
.../apache/commons/lang3/reflect/MemberUtils.java | 278 +-
.../apache/commons/lang3/reflect/MethodUtils.java | 1490 ++++----
.../apache/commons/lang3/reflect/TypeLiteral.java | 10 +-
.../apache/commons/lang3/text/CompositeFormat.java | 28 +-
.../commons/lang3/text/ExtendedMessageFormat.java | 360 +-
.../commons/lang3/text/FormattableUtils.java | 80 +-
.../org/apache/commons/lang3/text/StrBuilder.java | 3738 ++++++++++----------
.../org/apache/commons/lang3/text/StrLookup.java | 132 +-
.../org/apache/commons/lang3/text/StrMatcher.java | 488 +--
.../apache/commons/lang3/text/StrSubstitutor.java | 994 +++---
.../apache/commons/lang3/text/StrTokenizer.java | 846 ++---
.../org/apache/commons/lang3/text/WordUtils.java | 1022 +++---
.../text/translate/CharSequenceTranslator.java | 42 +-
.../commons/lang3/text/translate/EntityArrays.java | 146 +-
.../lang3/text/translate/NumericEntityEscaper.java | 68 +-
.../lang3/text/translate/OctalUnescaper.java | 36 +-
.../lang3/text/translate/UnicodeEscaper.java | 94 +-
.../commons/lang3/time/AbstractFormatCache.java | 234 +-
.../apache/commons/lang3/time/DateFormatUtils.java | 18 +-
.../org/apache/commons/lang3/time/DateParser.java | 54 +-
.../org/apache/commons/lang3/time/DatePrinter.java | 124 +-
.../org/apache/commons/lang3/time/DateUtils.java | 2312 ++++++------
.../commons/lang3/time/DurationFormatUtils.java | 712 ++--
.../apache/commons/lang3/time/DurationUtils.java | 12 +-
.../apache/commons/lang3/time/FastDateFormat.java | 528 +--
.../apache/commons/lang3/time/FastDateParser.java | 1592 ++++-----
.../apache/commons/lang3/time/FastDatePrinter.java | 2370 ++++++-------
.../org/apache/commons/lang3/time/TimeZones.java | 8 +-
.../apache/commons/lang3/AnnotationUtilsTest.java | 216 +-
.../org/apache/commons/lang3/ArchUtilsTest.java | 16 +-
.../org/apache/commons/lang3/ArrayUtilsTest.java | 26 +-
.../org/apache/commons/lang3/BitFieldTest.java | 254 +-
.../org/apache/commons/lang3/BooleanUtilsTest.java | 14 +-
.../org/apache/commons/lang3/CharEncodingTest.java | 14 +-
.../org/apache/commons/lang3/CharRangeTest.java | 136 +-
.../commons/lang3/CharSequenceUtilsTest.java | 258 +-
.../java/org/apache/commons/lang3/CharSetTest.java | 288 +-
.../org/apache/commons/lang3/CharSetUtilsTest.java | 142 +-
.../org/apache/commons/lang3/CharUtilsPerfRun.java | 10 +-
.../apache/commons/lang3/ClassPathUtilsTest.java | 44 +-
.../org/apache/commons/lang3/ClassUtilsTest.java | 4 +-
.../org/apache/commons/lang3/ConversionTest.java | 2228 ++++++------
.../apache/commons/lang3/HashSetvBitSetTest.java | 52 +-
.../org/apache/commons/lang3/JavaVersionTest.java | 20 +-
.../org/apache/commons/lang3/LocaleUtilsTest.java | 604 ++--
.../commons/lang3/NotImplementedExceptionTest.java | 14 +-
.../org/apache/commons/lang3/ObjectUtilsTest.java | 4 +-
.../commons/lang3/RandomStringUtilsTest.java | 500 +--
.../org/apache/commons/lang3/RandomUtilsTest.java | 242 +-
.../java/org/apache/commons/lang3/RangeTest.java | 66 +-
.../commons/lang3/SerializationUtilsTest.java | 310 +-
.../java/org/apache/commons/lang3/StreamsTest.java | 182 +-
.../commons/lang3/StringEscapeUtilsTest.java | 558 +--
.../commons/lang3/StringUtilsContainsTest.java | 42 +-
.../commons/lang3/StringUtilsEmptyBlankTest.java | 164 +-
.../lang3/StringUtilsEqualsIndexOfTest.java | 264 +-
.../commons/lang3/StringUtilsIsMixedCaseTest.java | 66 +-
.../lang3/StringUtilsStartsEndsWithTest.java | 180 +-
.../commons/lang3/StringUtilsSubstringTest.java | 436 +--
.../org/apache/commons/lang3/StringUtilsTest.java | 366 +-
.../commons/lang3/StringUtilsTrimStripTest.java | 244 +-
.../apache/commons/lang3/SystemPropertiesTest.java | 84 +-
.../org/apache/commons/lang3/SystemUtilsTest.java | 44 +-
.../org/apache/commons/lang3/ValidateTest.java | 1836 +++++-----
.../lang3/builder/CompareToBuilderTest.java | 1234 +++----
.../lang3/builder/DefaultToStringStyleTest.java | 104 +-
.../commons/lang3/builder/DiffBuilderTest.java | 8 +-
.../commons/lang3/builder/DiffResultTest.java | 116 +-
.../org/apache/commons/lang3/builder/DiffTest.java | 6 +-
.../commons/lang3/builder/EqualsBuilderTest.java | 1744 ++++-----
.../HashCodeBuilderAndEqualsBuilderTest.java | 136 +-
.../lang3/builder/JsonToStringStyleTest.java | 728 ++--
.../lang3/builder/MultiLineToStringStyleTest.java | 104 +-
.../MultilineRecursiveToStringStyleTest.java | 302 +-
.../builder/NoClassNameToStringStyleTest.java | 102 +-
.../builder/NoFieldNamesToStringStyleTest.java | 104 +-
.../lang3/builder/RecursiveToStringStyleTest.java | 140 +-
.../lang3/builder/ReflectionDiffBuilderTest.java | 80 +-
.../ReflectionToStringBuilderConcurrencyTest.java | 24 +-
...ectionToStringBuilderExcludeNullValuesTest.java | 120 +-
.../ReflectionToStringBuilderIncludeTest.java | 60 +-
...oStringBuilderMutateInspectConcurrencyTest.java | 46 +-
.../builder/ShortPrefixToStringStyleTest.java | 104 +-
.../lang3/builder/SimpleToStringStyleTest.java | 102 +-
.../lang3/builder/StandardToStringStyleTest.java | 176 +-
.../commons/lang3/builder/ToStringBuilderTest.java | 1760 ++++-----
.../builder/ToStringStyleConcurrencyTest.java | 20 +-
.../commons/lang3/builder/ToStringStyleTest.java | 78 +-
.../commons/lang3/compare/ComparableUtilsTest.java | 42 +-
...oncurrentInitializerCloseAndExceptionsTest.java | 160 +-
.../AbstractConcurrentInitializerTest.java | 64 +-
.../AtomicSafeInitializerSupplierTest.java | 52 +-
.../concurrent/AtomicSafeInitializerTest.java | 56 +-
.../BackgroundInitializerSupplierTest.java | 92 +-
.../concurrent/BackgroundInitializerTest.java | 374 +-
.../lang3/concurrent/BasicThreadFactoryTest.java | 216 +-
.../CallableBackgroundInitializerTest.java | 44 +-
.../concurrent/CircuitBreakingExceptionTest.java | 16 +-
.../lang3/concurrent/ConcurrentUtilsTest.java | 408 +--
.../lang3/concurrent/ConstantInitializerTest.java | 76 +-
.../concurrent/EventCountCircuitBreakerTest.java | 402 +--
.../LazyInitializerSingleInstanceTest.java | 10 +-
.../MultiBackgroundInitializerSupplierTest.java | 70 +-
.../concurrent/MultiBackgroundInitializerTest.java | 524 +--
.../concurrent/ThresholdCircuitBreakerTest.java | 40 +-
.../lang3/concurrent/TimedSemaphoreTest.java | 658 ++--
.../lang3/event/EventListenerSupportTest.java | 84 +-
.../apache/commons/lang3/event/EventUtilsTest.java | 216 +-
.../exception/AbstractExceptionContextTest.java | 120 +-
.../lang3/exception/CloneFailedExceptionTest.java | 8 +-
.../lang3/exception/ContextedExceptionTest.java | 28 +-
.../exception/ContextedRuntimeExceptionTest.java | 20 +-
.../MethodInvokersFailableFunctionTest.java | 8 +-
.../apache/commons/lang3/math/NumberUtilsTest.java | 12 +-
.../lang3/reflect/ConstructorUtilsTest.java | 232 +-
.../commons/lang3/reflect/FieldUtilsTest.java | 974 ++---
.../lang3/reflect/InheritanceUtilsTest.java | 20 +-
.../commons/lang3/reflect/MethodUtilsTest.java | 1452 ++++----
.../commons/lang3/reflect/TypeLiteralTest.java | 16 +-
.../lang3/reflect/testbed/GenericParent.java | 6 +-
.../commons/lang3/reflect/testbed/Parent.java | 6 +-
.../commons/lang3/reflect/testbed/PublicChild.java | 4 +-
.../lang3/reflect/testbed/StaticContainer.java | 22 +-
.../reflect/testbed/StringParameterizedChild.java | 4 +-
.../lang3/test/NotVisibleExceptionFactory.java | 24 +-
.../lang3/text/ExtendedMessageFormatTest.java | 458 +--
.../commons/lang3/text/FormattableUtilsTest.java | 78 +-
.../lang3/text/StrBuilderAppendInsertTest.java | 1068 +++---
.../apache/commons/lang3/text/StrBuilderTest.java | 2382 ++++++-------
.../apache/commons/lang3/text/StrLookupTest.java | 40 +-
.../apache/commons/lang3/text/StrMatcherTest.java | 194 +-
.../commons/lang3/text/StrSubstitutorTest.java | 760 ++--
.../commons/lang3/text/StrTokenizerTest.java | 394 +--
.../apache/commons/lang3/text/WordUtilsTest.java | 414 +--
.../text/translate/NumericEntityEscaperTest.java | 18 +-
.../text/translate/NumericEntityUnescaperTest.java | 20 +-
.../lang3/text/translate/UnicodeEscaperTest.java | 18 +-
.../lang3/text/translate/UnicodeUnescaperTest.java | 22 +-
.../UnicodeUnpairedSurrogateRemoverTest.java | 12 +-
.../lang3/time/DurationFormatUtilsTest.java | 176 +-
.../commons/lang3/time/DurationUtilsTest.java | 36 +-
.../commons/lang3/time/FastDateFormatTest.java | 56 +-
.../apache/commons/lang3/time/GmtTimeZoneTest.java | 28 +-
.../lang3/time/Java15BugFastDateParserTest.java | 4 +-
.../commons/lang3/tuple/ImmutablePairTest.java | 14 +-
.../commons/lang3/tuple/MutableTripleTest.java | 28 +-
.../org/apache/commons/lang3/tuple/TripleTest.java | 26 +-
215 files changed, 34025 insertions(+), 34029 deletions(-)
(commons-lang) 01/03: Normalize test method names
Posted by gg...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
ggregory pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/commons-lang.git
commit 972b3f218eb8edcb31580a3e68ddcd0e0bcc3f18
Author: Gary Gregory <ga...@gmail.com>
AuthorDate: Fri Nov 3 11:25:33 2023 -0400
Normalize test method names
---
.../apache/commons/lang3/time/GmtTimeZoneTest.java | 28 ++++++++++------------
.../lang3/time/Java15BugFastDateParserTest.java | 4 ++--
2 files changed, 14 insertions(+), 18 deletions(-)
diff --git a/src/test/java/org/apache/commons/lang3/time/GmtTimeZoneTest.java b/src/test/java/org/apache/commons/lang3/time/GmtTimeZoneTest.java
index ede51b8f3..336b06fca 100644
--- a/src/test/java/org/apache/commons/lang3/time/GmtTimeZoneTest.java
+++ b/src/test/java/org/apache/commons/lang3/time/GmtTimeZoneTest.java
@@ -29,7 +29,7 @@ import org.junit.jupiter.api.Test;
public class GmtTimeZoneTest extends AbstractLangTest {
@Test
- public void getID() {
+ public void testGetID() {
assertEquals("GMT+00:00", new GmtTimeZone(false, 0, 0).getID());
assertEquals("GMT+01:02", new GmtTimeZone(false, 1, 2).getID());
assertEquals("GMT+11:22", new GmtTimeZone(false, 11, 22).getID());
@@ -38,51 +38,47 @@ public class GmtTimeZoneTest extends AbstractLangTest {
}
@Test
- public void getOffset() {
+ public void testGetOffset() {
assertEquals(0, new GmtTimeZone(false, 0, 0).getOffset(234304));
+ assertEquals(-(6 * 60 + 30) * 60 * 1000,
+ new GmtTimeZone(true, 6, 30).getOffset(1, 1, 1, 1, 1, 1));
}
@Test
- public void getRawOffset() {
+ public void testGetRawOffset() {
assertEquals(0, new GmtTimeZone(false, 0, 0).getRawOffset());
}
@Test
- public void hoursInRange() {
+ public void testHoursInRange() {
assertEquals(23 * 60 * 60 * 1000, new GmtTimeZone(false, 23, 0).getRawOffset());
}
@Test
- public void hoursOutOfRange() {
+ public void testHoursOutOfRange() {
assertThrows(IllegalArgumentException.class, () -> new GmtTimeZone(false, 24, 0));
}
@Test
- public void inDaylightTime() {
+ public void testInDaylightTime() {
assertFalse(new GmtTimeZone(false, 0, 0).useDaylightTime());
}
@Test
- public void minutesInRange() {
+ public void testMinutesInRange() {
assertEquals(59 * 60 * 1000, new GmtTimeZone(false, 0, 59).getRawOffset());
}
@Test
- public void minutesOutOfRange() {
+ public void testMinutesOutOfRange() {
assertThrows(IllegalArgumentException.class, () -> new GmtTimeZone(false, 0, 60));
}
@Test
- public void setRawOffset() {
+ public void testSetRawOffset() {
assertThrows(UnsupportedOperationException.class, () -> new GmtTimeZone(false, 0, 0).setRawOffset(0));
}
- @Test
- public void testGetOffset() {
- assertEquals(-(6 * 60 + 30) * 60 * 1000,
- new GmtTimeZone(true, 6, 30).getOffset(1, 1, 1, 1, 1, 1));
- }
-
@Test
public void testToString() {
assertEquals("[GmtTimeZone id=\"GMT-12:00\",offset=-43200000]",
@@ -90,7 +86,7 @@ public class GmtTimeZoneTest extends AbstractLangTest {
}
@Test
- public void useDaylightTime() {
+ public void testUseDaylightTime() {
assertFalse(new GmtTimeZone(false, 0, 0).useDaylightTime());
}
}
diff --git a/src/test/java/org/apache/commons/lang3/time/Java15BugFastDateParserTest.java b/src/test/java/org/apache/commons/lang3/time/Java15BugFastDateParserTest.java
index 7259f6499..a159a35a4 100644
--- a/src/test/java/org/apache/commons/lang3/time/Java15BugFastDateParserTest.java
+++ b/src/test/java/org/apache/commons/lang3/time/Java15BugFastDateParserTest.java
@@ -43,7 +43,7 @@ public class Java15BugFastDateParserTest extends AbstractLangTest {
private static final String DATE_PARSER_PARAMETERS = "org.apache.commons.lang3.time.FastDateParserTest#dateParserParameters()";
@Test
- public void java15BuggyLocaleTest() throws ParseException {
+ public void testJava15BuggyLocaleTest() throws ParseException {
final String buggyLocaleName = "ff_LR_#Adlm";
Locale buggyLocale = null;
for (final Locale locale : Locale.getAvailableLocales()) {
@@ -59,7 +59,7 @@ public class Java15BugFastDateParserTest extends AbstractLangTest {
}
@Test
- public void java15BuggyLocaleTestAll() throws ParseException {
+ public void testJava15BuggyLocaleTestAll() throws ParseException {
for (final Locale locale : Locale.getAvailableLocales()) {
testSingleLocale(locale);
}
(commons-lang) 03/03: Sort test members
Posted by gg...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
ggregory pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/commons-lang.git
commit 629a83c6c477cdddc58f395786d607ec46fe1d31
Author: Gary Gregory <ga...@gmail.com>
AuthorDate: Fri Nov 3 11:26:15 2023 -0400
Sort test members
---
.../apache/commons/lang3/AnnotationUtilsTest.java | 216 +-
.../org/apache/commons/lang3/ArchUtilsTest.java | 16 +-
.../org/apache/commons/lang3/ArrayUtilsTest.java | 26 +-
.../org/apache/commons/lang3/BitFieldTest.java | 254 +--
.../org/apache/commons/lang3/BooleanUtilsTest.java | 14 +-
.../org/apache/commons/lang3/CharEncodingTest.java | 14 +-
.../org/apache/commons/lang3/CharRangeTest.java | 136 +-
.../commons/lang3/CharSequenceUtilsTest.java | 258 +--
.../java/org/apache/commons/lang3/CharSetTest.java | 288 +--
.../org/apache/commons/lang3/CharSetUtilsTest.java | 142 +-
.../org/apache/commons/lang3/CharUtilsPerfRun.java | 10 +-
.../apache/commons/lang3/ClassPathUtilsTest.java | 44 +-
.../org/apache/commons/lang3/ClassUtilsTest.java | 4 +-
.../org/apache/commons/lang3/ConversionTest.java | 2228 +++++++++---------
.../apache/commons/lang3/HashSetvBitSetTest.java | 52 +-
.../org/apache/commons/lang3/JavaVersionTest.java | 20 +-
.../org/apache/commons/lang3/LocaleUtilsTest.java | 604 ++---
.../commons/lang3/NotImplementedExceptionTest.java | 14 +-
.../org/apache/commons/lang3/ObjectUtilsTest.java | 4 +-
.../commons/lang3/RandomStringUtilsTest.java | 500 ++--
.../org/apache/commons/lang3/RandomUtilsTest.java | 242 +-
.../java/org/apache/commons/lang3/RangeTest.java | 66 +-
.../commons/lang3/SerializationUtilsTest.java | 310 +--
.../java/org/apache/commons/lang3/StreamsTest.java | 182 +-
.../commons/lang3/StringEscapeUtilsTest.java | 558 ++---
.../commons/lang3/StringUtilsContainsTest.java | 42 +-
.../commons/lang3/StringUtilsEmptyBlankTest.java | 164 +-
.../lang3/StringUtilsEqualsIndexOfTest.java | 264 +--
.../commons/lang3/StringUtilsIsMixedCaseTest.java | 66 +-
.../lang3/StringUtilsStartsEndsWithTest.java | 180 +-
.../commons/lang3/StringUtilsSubstringTest.java | 436 ++--
.../org/apache/commons/lang3/StringUtilsTest.java | 366 +--
.../commons/lang3/StringUtilsTrimStripTest.java | 244 +-
.../apache/commons/lang3/SystemPropertiesTest.java | 84 +-
.../org/apache/commons/lang3/SystemUtilsTest.java | 44 +-
.../org/apache/commons/lang3/ValidateTest.java | 1836 +++++++--------
.../lang3/builder/CompareToBuilderTest.java | 1234 +++++-----
.../lang3/builder/DefaultToStringStyleTest.java | 104 +-
.../commons/lang3/builder/DiffBuilderTest.java | 8 +-
.../commons/lang3/builder/DiffResultTest.java | 116 +-
.../org/apache/commons/lang3/builder/DiffTest.java | 6 +-
.../commons/lang3/builder/EqualsBuilderTest.java | 1744 +++++++-------
.../HashCodeBuilderAndEqualsBuilderTest.java | 136 +-
.../lang3/builder/JsonToStringStyleTest.java | 728 +++---
.../lang3/builder/MultiLineToStringStyleTest.java | 104 +-
.../MultilineRecursiveToStringStyleTest.java | 302 +--
.../builder/NoClassNameToStringStyleTest.java | 102 +-
.../builder/NoFieldNamesToStringStyleTest.java | 104 +-
.../lang3/builder/RecursiveToStringStyleTest.java | 140 +-
.../lang3/builder/ReflectionDiffBuilderTest.java | 80 +-
.../ReflectionToStringBuilderConcurrencyTest.java | 24 +-
...ectionToStringBuilderExcludeNullValuesTest.java | 120 +-
.../ReflectionToStringBuilderIncludeTest.java | 60 +-
...oStringBuilderMutateInspectConcurrencyTest.java | 46 +-
.../builder/ShortPrefixToStringStyleTest.java | 104 +-
.../lang3/builder/SimpleToStringStyleTest.java | 102 +-
.../lang3/builder/StandardToStringStyleTest.java | 176 +-
.../commons/lang3/builder/ToStringBuilderTest.java | 1760 +++++++--------
.../builder/ToStringStyleConcurrencyTest.java | 20 +-
.../commons/lang3/builder/ToStringStyleTest.java | 78 +-
.../commons/lang3/compare/ComparableUtilsTest.java | 42 +-
...oncurrentInitializerCloseAndExceptionsTest.java | 160 +-
.../AbstractConcurrentInitializerTest.java | 64 +-
.../AtomicSafeInitializerSupplierTest.java | 52 +-
.../concurrent/AtomicSafeInitializerTest.java | 56 +-
.../BackgroundInitializerSupplierTest.java | 92 +-
.../concurrent/BackgroundInitializerTest.java | 374 +--
.../lang3/concurrent/BasicThreadFactoryTest.java | 216 +-
.../CallableBackgroundInitializerTest.java | 44 +-
.../concurrent/CircuitBreakingExceptionTest.java | 16 +-
.../lang3/concurrent/ConcurrentUtilsTest.java | 408 ++--
.../lang3/concurrent/ConstantInitializerTest.java | 76 +-
.../concurrent/EventCountCircuitBreakerTest.java | 402 ++--
.../LazyInitializerSingleInstanceTest.java | 10 +-
.../MultiBackgroundInitializerSupplierTest.java | 70 +-
.../concurrent/MultiBackgroundInitializerTest.java | 524 ++---
.../concurrent/ThresholdCircuitBreakerTest.java | 40 +-
.../lang3/concurrent/TimedSemaphoreTest.java | 658 +++---
.../lang3/event/EventListenerSupportTest.java | 84 +-
.../apache/commons/lang3/event/EventUtilsTest.java | 216 +-
.../exception/AbstractExceptionContextTest.java | 120 +-
.../lang3/exception/CloneFailedExceptionTest.java | 8 +-
.../lang3/exception/ContextedExceptionTest.java | 28 +-
.../exception/ContextedRuntimeExceptionTest.java | 20 +-
.../MethodInvokersFailableFunctionTest.java | 8 +-
.../apache/commons/lang3/math/NumberUtilsTest.java | 12 +-
.../lang3/reflect/ConstructorUtilsTest.java | 232 +-
.../commons/lang3/reflect/FieldUtilsTest.java | 974 ++++----
.../lang3/reflect/InheritanceUtilsTest.java | 20 +-
.../commons/lang3/reflect/MethodUtilsTest.java | 1452 ++++++------
.../commons/lang3/reflect/TypeLiteralTest.java | 16 +-
.../lang3/reflect/testbed/GenericParent.java | 6 +-
.../commons/lang3/reflect/testbed/Parent.java | 6 +-
.../commons/lang3/reflect/testbed/PublicChild.java | 4 +-
.../lang3/reflect/testbed/StaticContainer.java | 22 +-
.../reflect/testbed/StringParameterizedChild.java | 4 +-
.../lang3/test/NotVisibleExceptionFactory.java | 24 +-
.../lang3/text/ExtendedMessageFormatTest.java | 458 ++--
.../commons/lang3/text/FormattableUtilsTest.java | 78 +-
.../lang3/text/StrBuilderAppendInsertTest.java | 1068 ++++-----
.../apache/commons/lang3/text/StrBuilderTest.java | 2382 ++++++++++----------
.../apache/commons/lang3/text/StrLookupTest.java | 40 +-
.../apache/commons/lang3/text/StrMatcherTest.java | 194 +-
.../commons/lang3/text/StrSubstitutorTest.java | 760 +++----
.../commons/lang3/text/StrTokenizerTest.java | 394 ++--
.../apache/commons/lang3/text/WordUtilsTest.java | 414 ++--
.../text/translate/NumericEntityEscaperTest.java | 18 +-
.../text/translate/NumericEntityUnescaperTest.java | 20 +-
.../lang3/text/translate/UnicodeEscaperTest.java | 18 +-
.../lang3/text/translate/UnicodeUnescaperTest.java | 22 +-
.../UnicodeUnpairedSurrogateRemoverTest.java | 12 +-
.../lang3/time/DurationFormatUtilsTest.java | 176 +-
.../commons/lang3/time/DurationUtilsTest.java | 36 +-
.../commons/lang3/time/FastDateFormatTest.java | 56 +-
.../commons/lang3/tuple/ImmutablePairTest.java | 14 +-
.../commons/lang3/tuple/MutableTripleTest.java | 28 +-
.../org/apache/commons/lang3/tuple/TripleTest.java | 26 +-
117 files changed, 15050 insertions(+), 15050 deletions(-)
diff --git a/src/test/java/org/apache/commons/lang3/AnnotationUtilsTest.java b/src/test/java/org/apache/commons/lang3/AnnotationUtilsTest.java
index 9dc3bb3ad..9dd61358f 100644
--- a/src/test/java/org/apache/commons/lang3/AnnotationUtilsTest.java
+++ b/src/test/java/org/apache/commons/lang3/AnnotationUtilsTest.java
@@ -40,6 +40,78 @@ import org.junit.jupiter.api.Test;
/**
*/
public class AnnotationUtilsTest extends AbstractLangTest {
+ @Retention(RetentionPolicy.RUNTIME)
+ public @interface NestAnnotation {
+ boolean booleanValue();
+ boolean[] booleanValues();
+ byte byteValue();
+ byte[] byteValues();
+ char charValue();
+ char[] charValues();
+ double doubleValue();
+ double[] doubleValues();
+ float floatValue();
+ float[] floatValues();
+ int intValue();
+ int[] intValues();
+ long longValue();
+ long[] longValues();
+ short shortValue();
+ short[] shortValues();
+ Stooge stooge();
+ Stooge[] stooges();
+ String string();
+ String[] strings();
+ Class<?> type();
+ Class<?>[] types();
+ }
+
+ public enum Stooge {
+ MOE, LARRY, CURLY, JOE, SHEMP
+ }
+
+ @Target(ElementType.FIELD)
+ @Retention(RetentionPolicy.RUNTIME)
+ public @interface TestAnnotation {
+ boolean booleanValue();
+ boolean[] booleanValues();
+ byte byteValue();
+ byte[] byteValues();
+ char charValue();
+ char[] charValues();
+ double doubleValue();
+ double[] doubleValues();
+ float floatValue();
+ float[] floatValues();
+ int intValue();
+ int[] intValues();
+ long longValue();
+ long[] longValues();
+ NestAnnotation nest();
+ NestAnnotation[] nests();
+ short shortValue();
+ short[] shortValues();
+ Stooge stooge();
+ Stooge[] stooges();
+ String string();
+ String[] strings();
+ Class<?> type();
+ Class<?>[] types();
+ }
+
+ @Retention(RetentionPolicy.RUNTIME)
+ @Target({ElementType.METHOD})
+ public @interface TestMethodAnnotation {
+ class None extends Throwable {
+
+ private static final long serialVersionUID = 1L;
+ }
+
+ Class<? extends Throwable> expected() default None.class;
+
+ long timeout() default 0L;
+ }
+
@TestAnnotation(
booleanValue = false,
booleanValues = { false },
@@ -319,78 +391,6 @@ public class AnnotationUtilsTest extends AbstractLangTest {
)
public Object dummy4;
- @Target(ElementType.FIELD)
- @Retention(RetentionPolicy.RUNTIME)
- public @interface TestAnnotation {
- String string();
- String[] strings();
- Class<?> type();
- Class<?>[] types();
- byte byteValue();
- byte[] byteValues();
- short shortValue();
- short[] shortValues();
- int intValue();
- int[] intValues();
- char charValue();
- char[] charValues();
- long longValue();
- long[] longValues();
- float floatValue();
- float[] floatValues();
- double doubleValue();
- double[] doubleValues();
- boolean booleanValue();
- boolean[] booleanValues();
- Stooge stooge();
- Stooge[] stooges();
- NestAnnotation nest();
- NestAnnotation[] nests();
- }
-
- @Retention(RetentionPolicy.RUNTIME)
- public @interface NestAnnotation {
- String string();
- String[] strings();
- Class<?> type();
- Class<?>[] types();
- byte byteValue();
- byte[] byteValues();
- short shortValue();
- short[] shortValues();
- int intValue();
- int[] intValues();
- char charValue();
- char[] charValues();
- long longValue();
- long[] longValues();
- float floatValue();
- float[] floatValues();
- double doubleValue();
- double[] doubleValues();
- boolean booleanValue();
- boolean[] booleanValues();
- Stooge stooge();
- Stooge[] stooges();
- }
-
- @Retention(RetentionPolicy.RUNTIME)
- @Target({ElementType.METHOD})
- public @interface TestMethodAnnotation {
- Class<? extends Throwable> expected() default None.class;
-
- long timeout() default 0L;
-
- class None extends Throwable {
-
- private static final long serialVersionUID = 1L;
- }
- }
-
- public enum Stooge {
- MOE, LARRY, CURLY, JOE, SHEMP
- }
-
private Field field1;
private Field field2;
private Field field3;
@@ -404,54 +404,21 @@ public class AnnotationUtilsTest extends AbstractLangTest {
field4 = getClass().getDeclaredField("dummy4");
}
- @Test
- public void testEquivalence() {
- assertTrue(AnnotationUtils.equals(field1.getAnnotation(TestAnnotation.class), field2.getAnnotation(TestAnnotation.class)));
- assertTrue(AnnotationUtils.equals(field2.getAnnotation(TestAnnotation.class), field1.getAnnotation(TestAnnotation.class)));
- }
-
- @Test
- public void testSameInstance() {
- assertTrue(AnnotationUtils.equals(field1.getAnnotation(TestAnnotation.class), field1.getAnnotation(TestAnnotation.class)));
- }
-
- @Test
- public void testNonEquivalentAnnotationsOfSameType() {
- assertFalse(AnnotationUtils.equals(field1.getAnnotation(TestAnnotation.class), field3.getAnnotation(TestAnnotation.class)));
- assertFalse(AnnotationUtils.equals(field3.getAnnotation(TestAnnotation.class), field1.getAnnotation(TestAnnotation.class)));
- }
-
@Test
public void testAnnotationsOfDifferingTypes() {
assertFalse(AnnotationUtils.equals(field1.getAnnotation(TestAnnotation.class), field4.getAnnotation(NestAnnotation.class)));
assertFalse(AnnotationUtils.equals(field4.getAnnotation(NestAnnotation.class), field1.getAnnotation(TestAnnotation.class)));
}
- @Test
- public void testOneArgNull() {
- assertFalse(AnnotationUtils.equals(field1.getAnnotation(TestAnnotation.class), null));
- assertFalse(AnnotationUtils.equals(null, field1.getAnnotation(TestAnnotation.class)));
- }
-
@Test
public void testBothArgsNull() {
assertTrue(AnnotationUtils.equals(null, null));
}
@Test
- public void testIsValidAnnotationMemberType() {
- for (final Class<?> type : new Class[] { byte.class, short.class, int.class, char.class,
- long.class, float.class, double.class, boolean.class, String.class, Class.class,
- NestAnnotation.class, TestAnnotation.class, Stooge.class, ElementType.class }) {
- assertTrue(AnnotationUtils.isValidAnnotationMemberType(type));
- assertTrue(AnnotationUtils.isValidAnnotationMemberType(Array.newInstance(type, 0)
- .getClass()));
- }
- for (final Class<?> type : new Class[] { Object.class, Map.class, Collection.class }) {
- assertFalse(AnnotationUtils.isValidAnnotationMemberType(type));
- assertFalse(AnnotationUtils.isValidAnnotationMemberType(Array.newInstance(type, 0)
- .getClass()));
- }
+ public void testEquivalence() {
+ assertTrue(AnnotationUtils.equals(field1.getAnnotation(TestAnnotation.class), field2.getAnnotation(TestAnnotation.class)));
+ assertTrue(AnnotationUtils.equals(field2.getAnnotation(TestAnnotation.class), field1.getAnnotation(TestAnnotation.class)));
}
@Test
@@ -503,6 +470,39 @@ public class AnnotationUtilsTest extends AbstractLangTest {
});
}
+ @Test
+ public void testIsValidAnnotationMemberType() {
+ for (final Class<?> type : new Class[] { byte.class, short.class, int.class, char.class,
+ long.class, float.class, double.class, boolean.class, String.class, Class.class,
+ NestAnnotation.class, TestAnnotation.class, Stooge.class, ElementType.class }) {
+ assertTrue(AnnotationUtils.isValidAnnotationMemberType(type));
+ assertTrue(AnnotationUtils.isValidAnnotationMemberType(Array.newInstance(type, 0)
+ .getClass()));
+ }
+ for (final Class<?> type : new Class[] { Object.class, Map.class, Collection.class }) {
+ assertFalse(AnnotationUtils.isValidAnnotationMemberType(type));
+ assertFalse(AnnotationUtils.isValidAnnotationMemberType(Array.newInstance(type, 0)
+ .getClass()));
+ }
+ }
+
+ @Test
+ public void testNonEquivalentAnnotationsOfSameType() {
+ assertFalse(AnnotationUtils.equals(field1.getAnnotation(TestAnnotation.class), field3.getAnnotation(TestAnnotation.class)));
+ assertFalse(AnnotationUtils.equals(field3.getAnnotation(TestAnnotation.class), field1.getAnnotation(TestAnnotation.class)));
+ }
+
+ @Test
+ public void testOneArgNull() {
+ assertFalse(AnnotationUtils.equals(field1.getAnnotation(TestAnnotation.class), null));
+ assertFalse(AnnotationUtils.equals(null, field1.getAnnotation(TestAnnotation.class)));
+ }
+
+ @Test
+ public void testSameInstance() {
+ assertTrue(AnnotationUtils.equals(field1.getAnnotation(TestAnnotation.class), field1.getAnnotation(TestAnnotation.class)));
+ }
+
@Test
@TestMethodAnnotation(timeout = 666000)
public void testToString() {
diff --git a/src/test/java/org/apache/commons/lang3/ArchUtilsTest.java b/src/test/java/org/apache/commons/lang3/ArchUtilsTest.java
index c88742391..fb23cfa08 100644
--- a/src/test/java/org/apache/commons/lang3/ArchUtilsTest.java
+++ b/src/test/java/org/apache/commons/lang3/ArchUtilsTest.java
@@ -110,14 +110,6 @@ public class ArchUtilsTest extends AbstractLangTest {
}
}
- @Test
- public void testTypeLabels() {
- for (final Type type : Type.values()) {
- // Only test label presence.
- assertFalse(type.getLabel().isEmpty());
- }
- }
-
@Test
public void testGetProcessor() {
assertNotNull(ArchUtils.getProcessor(X86));
@@ -188,4 +180,12 @@ public class ArchUtilsTest extends AbstractLangTest {
assertFalse(processor.is32Bit());
}
+ @Test
+ public void testTypeLabels() {
+ for (final Type type : Type.values()) {
+ // Only test label presence.
+ assertFalse(type.getLabel().isEmpty());
+ }
+ }
+
}
diff --git a/src/test/java/org/apache/commons/lang3/ArrayUtilsTest.java b/src/test/java/org/apache/commons/lang3/ArrayUtilsTest.java
index 7f496cd3f..91b86c3d6 100644
--- a/src/test/java/org/apache/commons/lang3/ArrayUtilsTest.java
+++ b/src/test/java/org/apache/commons/lang3/ArrayUtilsTest.java
@@ -212,19 +212,6 @@ public class ArrayUtilsTest extends AbstractLangTest {
assertTrue(ArrayUtils.contains(array, null));
}
- @Test
- public void testContainsAny() {
- final Object[] array = {"0", "1", "2", "3", null, "0"};
- assertFalse(ArrayUtils.containsAny(null, null));
- assertFalse(ArrayUtils.containsAny(null, "1"));
- assertTrue(ArrayUtils.containsAny(array, "0"));
- assertTrue(ArrayUtils.containsAny(array, "1"));
- assertTrue(ArrayUtils.containsAny(array, "2"));
- assertTrue(ArrayUtils.containsAny(array, "3"));
- assertFalse(ArrayUtils.containsAny(array, "notInArray"));
- assertTrue(ArrayUtils.containsAny(array, new String[] {null}));
- }
-
@Test
public void testContains_LANG_1261() {
@@ -244,6 +231,19 @@ public class ArrayUtilsTest extends AbstractLangTest {
assertTrue(ArrayUtils.contains(array, new LANG1261ParentObject()));
}
+ @Test
+ public void testContainsAny() {
+ final Object[] array = {"0", "1", "2", "3", null, "0"};
+ assertFalse(ArrayUtils.containsAny(null, null));
+ assertFalse(ArrayUtils.containsAny(null, "1"));
+ assertTrue(ArrayUtils.containsAny(array, "0"));
+ assertTrue(ArrayUtils.containsAny(array, "1"));
+ assertTrue(ArrayUtils.containsAny(array, "2"));
+ assertTrue(ArrayUtils.containsAny(array, "3"));
+ assertFalse(ArrayUtils.containsAny(array, "notInArray"));
+ assertTrue(ArrayUtils.containsAny(array, new String[] {null}));
+ }
+
@Test
public void testContainsBoolean() {
boolean[] array = null;
diff --git a/src/test/java/org/apache/commons/lang3/BitFieldTest.java b/src/test/java/org/apache/commons/lang3/BitFieldTest.java
index a3924f150..1992b82f4 100644
--- a/src/test/java/org/apache/commons/lang3/BitFieldTest.java
+++ b/src/test/java/org/apache/commons/lang3/BitFieldTest.java
@@ -31,30 +31,50 @@ public class BitFieldTest extends AbstractLangTest {
private static final BitField bf_single = new BitField(0x4000);
private static final BitField bf_zero = new BitField(0);
+ @Test
+ public void testByte() {
+ assertEquals(0, new BitField(0).setByteBoolean((byte) 0, true));
+ assertEquals(1, new BitField(1).setByteBoolean((byte) 0, true));
+ assertEquals(2, new BitField(2).setByteBoolean((byte) 0, true));
+ assertEquals(4, new BitField(4).setByteBoolean((byte) 0, true));
+ assertEquals(8, new BitField(8).setByteBoolean((byte) 0, true));
+ assertEquals(16, new BitField(16).setByteBoolean((byte) 0, true));
+ assertEquals(32, new BitField(32).setByteBoolean((byte) 0, true));
+ assertEquals(64, new BitField(64).setByteBoolean((byte) 0, true));
+ assertEquals(-128, new BitField(128).setByteBoolean((byte) 0, true));
+ assertEquals(1, new BitField(0).setByteBoolean((byte) 1, false));
+ assertEquals(0, new BitField(1).setByteBoolean((byte) 1, false));
+ assertEquals(0, new BitField(2).setByteBoolean((byte) 2, false));
+ assertEquals(0, new BitField(4).setByteBoolean((byte) 4, false));
+ assertEquals(0, new BitField(8).setByteBoolean((byte) 8, false));
+ assertEquals(0, new BitField(16).setByteBoolean((byte) 16, false));
+ assertEquals(0, new BitField(32).setByteBoolean((byte) 32, false));
+ assertEquals(0, new BitField(64).setByteBoolean((byte) 64, false));
+ assertEquals(0, new BitField(128).setByteBoolean((byte) 128, false));
+ assertEquals(-2, new BitField(1).setByteBoolean((byte) 255, false));
+ final byte clearedBit = new BitField(0x40).setByteBoolean((byte) - 63, false);
+
+ assertFalse(new BitField(0x40).isSet(clearedBit));
+ }
+
/**
- * test the getValue() method
+ * test the clear() method
*/
@Test
- public void testGetValue() {
- assertEquals(bf_multi.getValue(-1), 127);
- assertEquals(bf_multi.getValue(0), 0);
- assertEquals(bf_single.getValue(-1), 1);
- assertEquals(bf_single.getValue(0), 0);
- assertEquals(bf_zero.getValue(-1), 0);
- assertEquals(bf_zero.getValue(0), 0);
+ public void testClear() {
+ assertEquals(bf_multi.clear(-1), 0xFFFFC07F);
+ assertEquals(bf_single.clear(-1), 0xFFFFBFFF);
+ assertEquals(bf_zero.clear(-1), 0xFFFFFFFF);
}
/**
- * test the getShortValue() method
+ * test the clearShort() method
*/
@Test
- public void testGetShortValue() {
- assertEquals(bf_multi.getShortValue((short) - 1), (short) 127);
- assertEquals(bf_multi.getShortValue((short) 0), (short) 0);
- assertEquals(bf_single.getShortValue((short) - 1), (short) 1);
- assertEquals(bf_single.getShortValue((short) 0), (short) 0);
- assertEquals(bf_zero.getShortValue((short) -1), (short) 0);
- assertEquals(bf_zero.getShortValue((short) 0), (short) 0);
+ public void testClearShort() {
+ assertEquals(bf_multi.clearShort((short) - 1), (short) 0xC07F);
+ assertEquals(bf_single.clearShort((short) - 1), (short) 0xBFFF);
+ assertEquals(bf_zero.clearShort((short) -1), (short) 0xFFFF);
}
/**
@@ -84,20 +104,29 @@ public class BitFieldTest extends AbstractLangTest {
}
/**
- * test the isSet() method
+ * test the getShortValue() method
*/
@Test
- public void testIsSet() {
- assertFalse(bf_multi.isSet(0));
- assertFalse(bf_zero.isSet(0));
- for (int j = 0x80; j <= 0x3F80; j += 0x80) {
- assertTrue(bf_multi.isSet(j));
- }
- for (int j = 0x80; j <= 0x3F80; j += 0x80) {
- assertFalse(bf_zero.isSet(j));
- }
- assertFalse(bf_single.isSet(0));
- assertTrue(bf_single.isSet(0x4000));
+ public void testGetShortValue() {
+ assertEquals(bf_multi.getShortValue((short) - 1), (short) 127);
+ assertEquals(bf_multi.getShortValue((short) 0), (short) 0);
+ assertEquals(bf_single.getShortValue((short) - 1), (short) 1);
+ assertEquals(bf_single.getShortValue((short) 0), (short) 0);
+ assertEquals(bf_zero.getShortValue((short) -1), (short) 0);
+ assertEquals(bf_zero.getShortValue((short) 0), (short) 0);
+ }
+
+ /**
+ * test the getValue() method
+ */
+ @Test
+ public void testGetValue() {
+ assertEquals(bf_multi.getValue(-1), 127);
+ assertEquals(bf_multi.getValue(0), 0);
+ assertEquals(bf_single.getValue(-1), 1);
+ assertEquals(bf_single.getValue(0), 0);
+ assertEquals(bf_zero.getValue(-1), 0);
+ assertEquals(bf_zero.getValue(0), 0);
}
/**
@@ -115,99 +144,20 @@ public class BitFieldTest extends AbstractLangTest {
}
/**
- * test the setValue() method
- */
- @Test
- public void testSetValue() {
- for (int j = 0; j < 128; j++) {
- assertEquals(bf_multi.getValue(bf_multi.setValue(0, j)), j);
- assertEquals(bf_multi.setValue(0, j), j << 7);
- }
- for (int j = 0; j < 128; j++) {
- assertEquals(bf_zero.getValue(bf_zero.setValue(0, j)), 0);
- assertEquals(bf_zero.setValue(0, j), 0);
- }
-
- // verify that excess bits are stripped off
- assertEquals(bf_multi.setValue(0x3f80, 128), 0);
- for (int j = 0; j < 2; j++) {
- assertEquals(bf_single.getValue(bf_single.setValue(0, j)), j);
- assertEquals(bf_single.setValue(0, j), j << 14);
- }
-
- // verify that excess bits are stripped off
- assertEquals(bf_single.setValue(0x4000, 2), 0);
- }
-
- /**
- * test the setShortValue() method
+ * test the isSet() method
*/
@Test
- public void testSetShortValue() {
- for (int j = 0; j < 128; j++) {
- assertEquals(bf_multi.getShortValue(bf_multi.setShortValue((short) 0, (short) j)), (short) j);
- assertEquals(bf_multi.setShortValue((short) 0, (short) j), (short) (j << 7));
- }
- for (int j = 0; j < 128; j++) {
- assertEquals(bf_zero.getShortValue(bf_zero.setShortValue((short) 0, (short) j)), (short) 0);
- assertEquals(bf_zero.setShortValue((short) 0, (short) j), (short) 0);
+ public void testIsSet() {
+ assertFalse(bf_multi.isSet(0));
+ assertFalse(bf_zero.isSet(0));
+ for (int j = 0x80; j <= 0x3F80; j += 0x80) {
+ assertTrue(bf_multi.isSet(j));
}
-
- // verify that excess bits are stripped off
- assertEquals(bf_multi.setShortValue((short) 0x3f80, (short) 128), (short) 0);
- for (int j = 0; j < 2; j++) {
- assertEquals(bf_single.getShortValue(bf_single.setShortValue((short) 0, (short) j)), (short) j);
- assertEquals(bf_single.setShortValue((short) 0, (short) j), (short) (j << 14));
+ for (int j = 0x80; j <= 0x3F80; j += 0x80) {
+ assertFalse(bf_zero.isSet(j));
}
-
- // verify that excess bits are stripped off
- assertEquals(bf_single.setShortValue((short) 0x4000, (short) 2), (short) 0);
- }
-
- @Test
- public void testByte() {
- assertEquals(0, new BitField(0).setByteBoolean((byte) 0, true));
- assertEquals(1, new BitField(1).setByteBoolean((byte) 0, true));
- assertEquals(2, new BitField(2).setByteBoolean((byte) 0, true));
- assertEquals(4, new BitField(4).setByteBoolean((byte) 0, true));
- assertEquals(8, new BitField(8).setByteBoolean((byte) 0, true));
- assertEquals(16, new BitField(16).setByteBoolean((byte) 0, true));
- assertEquals(32, new BitField(32).setByteBoolean((byte) 0, true));
- assertEquals(64, new BitField(64).setByteBoolean((byte) 0, true));
- assertEquals(-128, new BitField(128).setByteBoolean((byte) 0, true));
- assertEquals(1, new BitField(0).setByteBoolean((byte) 1, false));
- assertEquals(0, new BitField(1).setByteBoolean((byte) 1, false));
- assertEquals(0, new BitField(2).setByteBoolean((byte) 2, false));
- assertEquals(0, new BitField(4).setByteBoolean((byte) 4, false));
- assertEquals(0, new BitField(8).setByteBoolean((byte) 8, false));
- assertEquals(0, new BitField(16).setByteBoolean((byte) 16, false));
- assertEquals(0, new BitField(32).setByteBoolean((byte) 32, false));
- assertEquals(0, new BitField(64).setByteBoolean((byte) 64, false));
- assertEquals(0, new BitField(128).setByteBoolean((byte) 128, false));
- assertEquals(-2, new BitField(1).setByteBoolean((byte) 255, false));
- final byte clearedBit = new BitField(0x40).setByteBoolean((byte) - 63, false);
-
- assertFalse(new BitField(0x40).isSet(clearedBit));
- }
-
- /**
- * test the clear() method
- */
- @Test
- public void testClear() {
- assertEquals(bf_multi.clear(-1), 0xFFFFC07F);
- assertEquals(bf_single.clear(-1), 0xFFFFBFFF);
- assertEquals(bf_zero.clear(-1), 0xFFFFFFFF);
- }
-
- /**
- * test the clearShort() method
- */
- @Test
- public void testClearShort() {
- assertEquals(bf_multi.clearShort((short) - 1), (short) 0xC07F);
- assertEquals(bf_single.clearShort((short) - 1), (short) 0xBFFF);
- assertEquals(bf_zero.clearShort((short) -1), (short) 0xFFFF);
+ assertFalse(bf_single.isSet(0));
+ assertTrue(bf_single.isSet(0x4000));
}
/**
@@ -220,16 +170,6 @@ public class BitFieldTest extends AbstractLangTest {
assertEquals(bf_zero.set(0), 0);
}
- /**
- * test the setShort() method
- */
- @Test
- public void testSetShort() {
- assertEquals(bf_multi.setShort((short) 0), (short) 0x3F80);
- assertEquals(bf_single.setShort((short) 0), (short) 0x4000);
- assertEquals(bf_zero.setShort((short) 0), (short) 0);
- }
-
/**
* test the setBoolean() method
*/
@@ -243,6 +183,16 @@ public class BitFieldTest extends AbstractLangTest {
assertEquals(bf_zero.clear(-1), bf_zero.setBoolean(-1, false));
}
+ /**
+ * test the setShort() method
+ */
+ @Test
+ public void testSetShort() {
+ assertEquals(bf_multi.setShort((short) 0), (short) 0x3F80);
+ assertEquals(bf_single.setShort((short) 0), (short) 0x4000);
+ assertEquals(bf_zero.setShort((short) 0), (short) 0);
+ }
+
/**
* test the setShortBoolean() method
*/
@@ -256,4 +206,54 @@ public class BitFieldTest extends AbstractLangTest {
assertEquals(bf_zero.clearShort((short) -1), bf_zero.setShortBoolean((short) -1, false));
}
+ /**
+ * test the setShortValue() method
+ */
+ @Test
+ public void testSetShortValue() {
+ for (int j = 0; j < 128; j++) {
+ assertEquals(bf_multi.getShortValue(bf_multi.setShortValue((short) 0, (short) j)), (short) j);
+ assertEquals(bf_multi.setShortValue((short) 0, (short) j), (short) (j << 7));
+ }
+ for (int j = 0; j < 128; j++) {
+ assertEquals(bf_zero.getShortValue(bf_zero.setShortValue((short) 0, (short) j)), (short) 0);
+ assertEquals(bf_zero.setShortValue((short) 0, (short) j), (short) 0);
+ }
+
+ // verify that excess bits are stripped off
+ assertEquals(bf_multi.setShortValue((short) 0x3f80, (short) 128), (short) 0);
+ for (int j = 0; j < 2; j++) {
+ assertEquals(bf_single.getShortValue(bf_single.setShortValue((short) 0, (short) j)), (short) j);
+ assertEquals(bf_single.setShortValue((short) 0, (short) j), (short) (j << 14));
+ }
+
+ // verify that excess bits are stripped off
+ assertEquals(bf_single.setShortValue((short) 0x4000, (short) 2), (short) 0);
+ }
+
+ /**
+ * test the setValue() method
+ */
+ @Test
+ public void testSetValue() {
+ for (int j = 0; j < 128; j++) {
+ assertEquals(bf_multi.getValue(bf_multi.setValue(0, j)), j);
+ assertEquals(bf_multi.setValue(0, j), j << 7);
+ }
+ for (int j = 0; j < 128; j++) {
+ assertEquals(bf_zero.getValue(bf_zero.setValue(0, j)), 0);
+ assertEquals(bf_zero.setValue(0, j), 0);
+ }
+
+ // verify that excess bits are stripped off
+ assertEquals(bf_multi.setValue(0x3f80, 128), 0);
+ for (int j = 0; j < 2; j++) {
+ assertEquals(bf_single.getValue(bf_single.setValue(0, j)), j);
+ assertEquals(bf_single.setValue(0, j), j << 14);
+ }
+
+ // verify that excess bits are stripped off
+ assertEquals(bf_single.setValue(0x4000, 2), 0);
+ }
+
}
diff --git a/src/test/java/org/apache/commons/lang3/BooleanUtilsTest.java b/src/test/java/org/apache/commons/lang3/BooleanUtilsTest.java
index 5b6197e1c..0440cfacb 100644
--- a/src/test/java/org/apache/commons/lang3/BooleanUtilsTest.java
+++ b/src/test/java/org/apache/commons/lang3/BooleanUtilsTest.java
@@ -46,13 +46,6 @@ public class BooleanUtilsTest extends AbstractLangTest {
assertArrayEquals(sort(expected), BooleanUtils.booleanValues());
}
- @Test
- public void test_values() {
- final List<Boolean> expected = Arrays.asList(Boolean.FALSE, Boolean.TRUE);
- Collections.sort(expected);
- assertEquals(expected, BooleanUtils.values());
- }
-
@Test
public void test_forEach() {
final List<Boolean> list = new ArrayList<>();
@@ -447,6 +440,13 @@ public class BooleanUtilsTest extends AbstractLangTest {
assertEquals("no", BooleanUtils.toStringYesNo(Boolean.FALSE));
}
+ @Test
+ public void test_values() {
+ final List<Boolean> expected = Arrays.asList(Boolean.FALSE, Boolean.TRUE);
+ Collections.sort(expected);
+ assertEquals(expected, BooleanUtils.values());
+ }
+
@Test
public void testAnd_object_emptyInput() {
assertThrows(IllegalArgumentException.class, () -> BooleanUtils.and(new Boolean[] {}));
diff --git a/src/test/java/org/apache/commons/lang3/CharEncodingTest.java b/src/test/java/org/apache/commons/lang3/CharEncodingTest.java
index 2035605c7..c2e379800 100644
--- a/src/test/java/org/apache/commons/lang3/CharEncodingTest.java
+++ b/src/test/java/org/apache/commons/lang3/CharEncodingTest.java
@@ -55,13 +55,6 @@ public class CharEncodingTest extends AbstractLangTest {
this.assertSupportedEncoding(CharEncoding.UTF_8);
}
- @Test
- public void testSupported() {
- assertTrue(CharEncoding.isSupported("UTF8"));
- assertTrue(CharEncoding.isSupported("UTF-8"));
- assertTrue(CharEncoding.isSupported("ASCII"));
- }
-
@Test
public void testNotSupported() {
assertFalse(CharEncoding.isSupported(null));
@@ -81,4 +74,11 @@ public class CharEncodingTest extends AbstractLangTest {
assertEquals(StandardCharsets.UTF_16BE.name(), CharEncoding.UTF_16BE);
assertEquals(StandardCharsets.UTF_16LE.name(), CharEncoding.UTF_16LE);
}
+
+ @Test
+ public void testSupported() {
+ assertTrue(CharEncoding.isSupported("UTF8"));
+ assertTrue(CharEncoding.isSupported("UTF-8"));
+ assertTrue(CharEncoding.isSupported("ASCII"));
+ }
}
diff --git a/src/test/java/org/apache/commons/lang3/CharRangeTest.java b/src/test/java/org/apache/commons/lang3/CharRangeTest.java
index e5485eec6..da207d83f 100644
--- a/src/test/java/org/apache/commons/lang3/CharRangeTest.java
+++ b/src/test/java/org/apache/commons/lang3/CharRangeTest.java
@@ -52,24 +52,6 @@ public class CharRangeTest extends AbstractLangTest {
assertEquals("a", rangea.toString());
}
- @Test
- public void testConstructorAccessors_isNot() {
- final CharRange rangea = CharRange.isNot('a');
- assertEquals('a', rangea.getStart());
- assertEquals('a', rangea.getEnd());
- assertTrue(rangea.isNegated());
- assertEquals("^a", rangea.toString());
- }
-
- @Test
- public void testConstructorAccessors_isIn_Same() {
- final CharRange rangea = CharRange.isIn('a', 'a');
- assertEquals('a', rangea.getStart());
- assertEquals('a', rangea.getEnd());
- assertFalse(rangea.isNegated());
- assertEquals("a", rangea.toString());
- }
-
@Test
public void testConstructorAccessors_isIn_Normal() {
final CharRange rangea = CharRange.isIn('a', 'e');
@@ -89,8 +71,17 @@ public class CharRangeTest extends AbstractLangTest {
}
@Test
- public void testConstructorAccessors_isNotIn_Same() {
- final CharRange rangea = CharRange.isNotIn('a', 'a');
+ public void testConstructorAccessors_isIn_Same() {
+ final CharRange rangea = CharRange.isIn('a', 'a');
+ assertEquals('a', rangea.getStart());
+ assertEquals('a', rangea.getEnd());
+ assertFalse(rangea.isNegated());
+ assertEquals("a", rangea.toString());
+ }
+
+ @Test
+ public void testConstructorAccessors_isNot() {
+ final CharRange rangea = CharRange.isNot('a');
assertEquals('a', rangea.getStart());
assertEquals('a', rangea.getEnd());
assertTrue(rangea.isNegated());
@@ -116,47 +107,12 @@ public class CharRangeTest extends AbstractLangTest {
}
@Test
- public void testEquals_Object() {
- final CharRange rangea = CharRange.is('a');
- final CharRange rangeae = CharRange.isIn('a', 'e');
- final CharRange rangenotbf = CharRange.isIn('b', 'f');
-
- assertNotEquals(null, rangea);
-
- assertEquals(rangea, rangea);
- assertEquals(rangea, CharRange.is('a'));
- assertEquals(rangeae, rangeae);
- assertEquals(rangeae, CharRange.isIn('a', 'e'));
- assertEquals(rangenotbf, rangenotbf);
- assertEquals(rangenotbf, CharRange.isIn('b', 'f'));
-
- assertNotEquals(rangea, rangeae);
- assertNotEquals(rangea, rangenotbf);
- assertNotEquals(rangeae, rangea);
- assertNotEquals(rangeae, rangenotbf);
- assertNotEquals(rangenotbf, rangea);
- assertNotEquals(rangenotbf, rangeae);
- }
-
- @Test
- public void testHashCode() {
- final CharRange rangea = CharRange.is('a');
- final CharRange rangeae = CharRange.isIn('a', 'e');
- final CharRange rangenotbf = CharRange.isIn('b', 'f');
-
- assertEquals(rangea.hashCode(), rangea.hashCode());
- assertEquals(rangea.hashCode(), CharRange.is('a').hashCode());
- assertEquals(rangeae.hashCode(), rangeae.hashCode());
- assertEquals(rangeae.hashCode(), CharRange.isIn('a', 'e').hashCode());
- assertEquals(rangenotbf.hashCode(), rangenotbf.hashCode());
- assertEquals(rangenotbf.hashCode(), CharRange.isIn('b', 'f').hashCode());
-
- assertNotEquals(rangea.hashCode(), rangeae.hashCode());
- assertNotEquals(rangea.hashCode(), rangenotbf.hashCode());
- assertNotEquals(rangeae.hashCode(), rangea.hashCode());
- assertNotEquals(rangeae.hashCode(), rangenotbf.hashCode());
- assertNotEquals(rangenotbf.hashCode(), rangea.hashCode());
- assertNotEquals(rangenotbf.hashCode(), rangeae.hashCode());
+ public void testConstructorAccessors_isNotIn_Same() {
+ final CharRange rangea = CharRange.isNotIn('a', 'a');
+ assertEquals('a', rangea.getStart());
+ assertEquals('a', rangea.getEnd());
+ assertTrue(rangea.isNegated());
+ assertEquals("^a", rangea.toString());
}
@Test
@@ -310,6 +266,50 @@ public class CharRangeTest extends AbstractLangTest {
assertEquals("range", e.getMessage());
}
+ @Test
+ public void testEquals_Object() {
+ final CharRange rangea = CharRange.is('a');
+ final CharRange rangeae = CharRange.isIn('a', 'e');
+ final CharRange rangenotbf = CharRange.isIn('b', 'f');
+
+ assertNotEquals(null, rangea);
+
+ assertEquals(rangea, rangea);
+ assertEquals(rangea, CharRange.is('a'));
+ assertEquals(rangeae, rangeae);
+ assertEquals(rangeae, CharRange.isIn('a', 'e'));
+ assertEquals(rangenotbf, rangenotbf);
+ assertEquals(rangenotbf, CharRange.isIn('b', 'f'));
+
+ assertNotEquals(rangea, rangeae);
+ assertNotEquals(rangea, rangenotbf);
+ assertNotEquals(rangeae, rangea);
+ assertNotEquals(rangeae, rangenotbf);
+ assertNotEquals(rangenotbf, rangea);
+ assertNotEquals(rangenotbf, rangeae);
+ }
+
+ @Test
+ public void testHashCode() {
+ final CharRange rangea = CharRange.is('a');
+ final CharRange rangeae = CharRange.isIn('a', 'e');
+ final CharRange rangenotbf = CharRange.isIn('b', 'f');
+
+ assertEquals(rangea.hashCode(), rangea.hashCode());
+ assertEquals(rangea.hashCode(), CharRange.is('a').hashCode());
+ assertEquals(rangeae.hashCode(), rangeae.hashCode());
+ assertEquals(rangeae.hashCode(), CharRange.isIn('a', 'e').hashCode());
+ assertEquals(rangenotbf.hashCode(), rangenotbf.hashCode());
+ assertEquals(rangenotbf.hashCode(), CharRange.isIn('b', 'f').hashCode());
+
+ assertNotEquals(rangea.hashCode(), rangeae.hashCode());
+ assertNotEquals(rangea.hashCode(), rangenotbf.hashCode());
+ assertNotEquals(rangeae.hashCode(), rangea.hashCode());
+ assertNotEquals(rangeae.hashCode(), rangenotbf.hashCode());
+ assertNotEquals(rangenotbf.hashCode(), rangea.hashCode());
+ assertNotEquals(rangenotbf.hashCode(), rangeae.hashCode());
+ }
+
@Test
public void testIterator() {
final CharRange a = CharRange.is('a');
@@ -362,6 +362,13 @@ public class CharRangeTest extends AbstractLangTest {
assertThrows(NoSuchElementException.class, notLastIt::next);
}
+ @Test
+ public void testIteratorRemove() {
+ final CharRange a = CharRange.is('a');
+ final Iterator<Character> aIt = a.iterator();
+ assertThrows(UnsupportedOperationException.class, aIt::remove);
+ }
+
@Test
public void testSerialization() {
CharRange range = CharRange.is('a');
@@ -371,11 +378,4 @@ public class CharRangeTest extends AbstractLangTest {
range = CharRange.isNotIn('a', 'e');
assertEquals(range, SerializationUtils.clone(range));
}
-
- @Test
- public void testIteratorRemove() {
- final CharRange a = CharRange.is('a');
- final Iterator<Character> aIt = a.iterator();
- assertThrows(UnsupportedOperationException.class, aIt::remove);
- }
}
diff --git a/src/test/java/org/apache/commons/lang3/CharSequenceUtilsTest.java b/src/test/java/org/apache/commons/lang3/CharSequenceUtilsTest.java
index 7d095d3dd..0574685f1 100644
--- a/src/test/java/org/apache/commons/lang3/CharSequenceUtilsTest.java
+++ b/src/test/java/org/apache/commons/lang3/CharSequenceUtilsTest.java
@@ -41,42 +41,19 @@ import org.junit.jupiter.params.provider.MethodSource;
*/
public class CharSequenceUtilsTest extends AbstractLangTest {
- @Test
- public void testConstructor() {
- assertNotNull(new CharSequenceUtils());
- final Constructor<?>[] cons = CharSequenceUtils.class.getDeclaredConstructors();
- assertEquals(1, cons.length);
- assertTrue(Modifier.isPublic(cons[0].getModifiers()));
- assertTrue(Modifier.isPublic(CharSequenceUtils.class.getModifiers()));
- assertFalse(Modifier.isFinal(CharSequenceUtils.class.getModifiers()));
- }
+ private abstract static class RunTest {
- @Test
- public void testSubSequence() {
- //
- // null input
- //
- assertNull(CharSequenceUtils.subSequence(null, -1));
- assertNull(CharSequenceUtils.subSequence(null, 0));
- assertNull(CharSequenceUtils.subSequence(null, 1));
- //
- // non-null input
- //
- assertEquals(StringUtils.EMPTY, CharSequenceUtils.subSequence(StringUtils.EMPTY, 0));
- assertEquals("012", CharSequenceUtils.subSequence("012", 0));
- assertEquals("12", CharSequenceUtils.subSequence("012", 1));
- assertEquals("2", CharSequenceUtils.subSequence("012", 2));
- assertEquals(StringUtils.EMPTY, CharSequenceUtils.subSequence("012", 3));
- }
+ abstract boolean invoke();
- @Test
- public void testSubSequenceNegativeStart() {
- assertThrows(IndexOutOfBoundsException.class, () -> CharSequenceUtils.subSequence(StringUtils.EMPTY, -1));
- }
+ void run(final TestData data, final String id) {
+ if (data.throwable != null) {
+ assertThrows(data.throwable, this::invoke, id + " Expected " + data.throwable);
+ } else {
+ final boolean stringCheck = invoke();
+ assertEquals(data.expected, stringCheck, id + " Failed test " + data);
+ }
+ }
- @Test
- public void testSubSequenceTooLong() {
- assertThrows(IndexOutOfBoundsException.class, () -> CharSequenceUtils.subSequence(StringUtils.EMPTY, 1));
}
static class TestData{
@@ -126,72 +103,6 @@ public class CharSequenceUtilsTest extends AbstractLangTest {
}
}
- private static final TestData[] TEST_DATA = {
- // Source IgnoreCase Offset Other Offset Length Result
- new TestData("", true, -1, "", -1, -1, false),
- new TestData("", true, 0, "", 0, 1, false),
- new TestData("a", true, 0, "abc", 0, 0, true),
- new TestData("a", true, 0, "abc", 0, 1, true),
- new TestData("a", true, 0, null, 0, 0, NullPointerException.class),
- new TestData(null, true, 0, null, 0, 0, NullPointerException.class),
- new TestData(null, true, 0, "", 0, 0, NullPointerException.class),
- new TestData("Abc", true, 0, "abc", 0, 3, true),
- new TestData("Abc", false, 0, "abc", 0, 3, false),
- new TestData("Abc", true, 1, "abc", 1, 2, true),
- new TestData("Abc", false, 1, "abc", 1, 2, true),
- new TestData("Abcd", true, 1, "abcD", 1, 2, true),
- new TestData("Abcd", false, 1, "abcD", 1, 2, true),
- };
-
- private abstract static class RunTest {
-
- abstract boolean invoke();
-
- void run(final TestData data, final String id) {
- if (data.throwable != null) {
- assertThrows(data.throwable, this::invoke, id + " Expected " + data.throwable);
- } else {
- final boolean stringCheck = invoke();
- assertEquals(data.expected, stringCheck, id + " Failed test " + data);
- }
- }
-
- }
-
- @Test
- public void testRegionMatches() {
- for (final TestData data : TEST_DATA) {
- new RunTest() {
- @Override
- boolean invoke() {
- return data.source.regionMatches(data.ignoreCase, data.toffset, data.other, data.ooffset, data.len);
- }
- }.run(data, "String");
- new RunTest() {
- @Override
- boolean invoke() {
- return CharSequenceUtils.regionMatches(data.source, data.ignoreCase, data.toffset, data.other, data.ooffset, data.len);
- }
- }.run(data, "CSString");
- new RunTest() {
- @Override
- boolean invoke() {
- return CharSequenceUtils.regionMatches(new StringBuilder(data.source), data.ignoreCase, data.toffset, data.other, data.ooffset, data.len);
- }
- }.run(data, "CSNonString");
- }
- }
-
-
- @Test
- public void testToCharArray() {
- final StringBuilder builder = new StringBuilder("abcdefg");
- final char[] expected = builder.toString().toCharArray();
- assertArrayEquals(expected, CharSequenceUtils.toCharArray(builder));
- assertArrayEquals(expected, CharSequenceUtils.toCharArray(builder.toString()));
- assertArrayEquals(ArrayUtils.EMPTY_CHAR_ARRAY, CharSequenceUtils.toCharArray(null));
- }
-
static class WrapperString implements CharSequence {
private final CharSequence inner;
@@ -200,36 +111,82 @@ public class CharSequenceUtilsTest extends AbstractLangTest {
}
@Override
- public int length() {
- return inner.length();
+ public char charAt(final int index) {
+ return inner.charAt(index);
}
@Override
- public char charAt(final int index) {
- return inner.charAt(index);
+ public IntStream chars() {
+ return inner.chars();
}
@Override
- public CharSequence subSequence(final int start, final int end) {
- return inner.subSequence(start, end);
+ public IntStream codePoints() {
+ return inner.codePoints();
}
@Override
- public String toString() {
- return inner.toString();
+ public int length() {
+ return inner.length();
}
@Override
- public IntStream chars() {
- return inner.chars();
+ public CharSequence subSequence(final int start, final int end) {
+ return inner.subSequence(start, end);
}
@Override
- public IntStream codePoints() {
- return inner.codePoints();
+ public String toString() {
+ return inner.toString();
}
}
+ private static final TestData[] TEST_DATA = {
+ // Source IgnoreCase Offset Other Offset Length Result
+ new TestData("", true, -1, "", -1, -1, false),
+ new TestData("", true, 0, "", 0, 1, false),
+ new TestData("a", true, 0, "abc", 0, 0, true),
+ new TestData("a", true, 0, "abc", 0, 1, true),
+ new TestData("a", true, 0, null, 0, 0, NullPointerException.class),
+ new TestData(null, true, 0, null, 0, 0, NullPointerException.class),
+ new TestData(null, true, 0, "", 0, 0, NullPointerException.class),
+ new TestData("Abc", true, 0, "abc", 0, 3, true),
+ new TestData("Abc", false, 0, "abc", 0, 3, false),
+ new TestData("Abc", true, 1, "abc", 1, 2, true),
+ new TestData("Abc", false, 1, "abc", 1, 2, true),
+ new TestData("Abcd", true, 1, "abcD", 1, 2, true),
+ new TestData("Abcd", false, 1, "abcD", 1, 2, true),
+ };
+
+ static Stream<Arguments> lastIndexWithStandardCharSequence() {
+ return Stream.of(
+ arguments("abc", "b", 2, 1),
+ arguments(new StringBuilder("abc"), "b", 2, 1),
+ arguments(new StringBuffer("abc"), "b", 2, 1),
+ arguments("abc", new StringBuilder("b"), 2, 1),
+ arguments(new StringBuilder("abc"), new StringBuilder("b"), 2, 1),
+ arguments(new StringBuffer("abc"), new StringBuffer("b"), 2, 1),
+ arguments(new StringBuilder("abc"), new StringBuffer("b"), 2, 1)
+ );
+ }
+
+ @Test
+ public void testConstructor() {
+ assertNotNull(new CharSequenceUtils());
+ final Constructor<?>[] cons = CharSequenceUtils.class.getDeclaredConstructors();
+ assertEquals(1, cons.length);
+ assertTrue(Modifier.isPublic(cons[0].getModifiers()));
+ assertTrue(Modifier.isPublic(CharSequenceUtils.class.getModifiers()));
+ assertFalse(Modifier.isFinal(CharSequenceUtils.class.getModifiers()));
+ }
+
+ @ParameterizedTest
+ @MethodSource("lastIndexWithStandardCharSequence")
+ public void testLastIndexOfWithDifferentCharSequences(final CharSequence cs, final CharSequence search, final int start,
+ final int expected) {
+ assertEquals(expected, CharSequenceUtils.lastIndexOf(cs, search, start));
+ }
+
@Test
public void testNewLastIndexOf() {
testNewLastIndexOfSingle("808087847-1321060740-635567660180086727-925755305", "-1321060740-635567660", 21);
@@ -268,24 +225,6 @@ public class CharSequenceUtilsTest extends AbstractLangTest {
}
}
- @ParameterizedTest
- @MethodSource("lastIndexWithStandardCharSequence")
- public void testLastIndexOfWithDifferentCharSequences(final CharSequence cs, final CharSequence search, final int start,
- final int expected) {
- assertEquals(expected, CharSequenceUtils.lastIndexOf(cs, search, start));
- }
-
- static Stream<Arguments> lastIndexWithStandardCharSequence() {
- return Stream.of(
- arguments("abc", "b", 2, 1),
- arguments(new StringBuilder("abc"), "b", 2, 1),
- arguments(new StringBuffer("abc"), "b", 2, 1),
- arguments("abc", new StringBuilder("b"), 2, 1),
- arguments(new StringBuilder("abc"), new StringBuilder("b"), 2, 1),
- arguments(new StringBuffer("abc"), new StringBuffer("b"), 2, 1),
- arguments(new StringBuilder("abc"), new StringBuffer("b"), 2, 1)
- );
- }
private void testNewLastIndexOfSingle(final CharSequence a, final CharSequence b) {
final int maxa = Math.max(a.length(), b.length());
@@ -308,4 +247,65 @@ public class CharSequenceUtilsTest extends AbstractLangTest {
"testNewLastIndexOf fails! original : " + a + " seg : " + b + " start : " + start
);
}
+
+ @Test
+ public void testRegionMatches() {
+ for (final TestData data : TEST_DATA) {
+ new RunTest() {
+ @Override
+ boolean invoke() {
+ return data.source.regionMatches(data.ignoreCase, data.toffset, data.other, data.ooffset, data.len);
+ }
+ }.run(data, "String");
+ new RunTest() {
+ @Override
+ boolean invoke() {
+ return CharSequenceUtils.regionMatches(data.source, data.ignoreCase, data.toffset, data.other, data.ooffset, data.len);
+ }
+ }.run(data, "CSString");
+ new RunTest() {
+ @Override
+ boolean invoke() {
+ return CharSequenceUtils.regionMatches(new StringBuilder(data.source), data.ignoreCase, data.toffset, data.other, data.ooffset, data.len);
+ }
+ }.run(data, "CSNonString");
+ }
+ }
+
+ @Test
+ public void testSubSequence() {
+ //
+ // null input
+ //
+ assertNull(CharSequenceUtils.subSequence(null, -1));
+ assertNull(CharSequenceUtils.subSequence(null, 0));
+ assertNull(CharSequenceUtils.subSequence(null, 1));
+ //
+ // non-null input
+ //
+ assertEquals(StringUtils.EMPTY, CharSequenceUtils.subSequence(StringUtils.EMPTY, 0));
+ assertEquals("012", CharSequenceUtils.subSequence("012", 0));
+ assertEquals("12", CharSequenceUtils.subSequence("012", 1));
+ assertEquals("2", CharSequenceUtils.subSequence("012", 2));
+ assertEquals(StringUtils.EMPTY, CharSequenceUtils.subSequence("012", 3));
+ }
+
+ @Test
+ public void testSubSequenceNegativeStart() {
+ assertThrows(IndexOutOfBoundsException.class, () -> CharSequenceUtils.subSequence(StringUtils.EMPTY, -1));
+ }
+
+ @Test
+ public void testSubSequenceTooLong() {
+ assertThrows(IndexOutOfBoundsException.class, () -> CharSequenceUtils.subSequence(StringUtils.EMPTY, 1));
+ }
+
+ @Test
+ public void testToCharArray() {
+ final StringBuilder builder = new StringBuilder("abcdefg");
+ final char[] expected = builder.toString().toCharArray();
+ assertArrayEquals(expected, CharSequenceUtils.toCharArray(builder));
+ assertArrayEquals(expected, CharSequenceUtils.toCharArray(builder.toString()));
+ assertArrayEquals(ArrayUtils.EMPTY_CHAR_ARRAY, CharSequenceUtils.toCharArray(null));
+ }
}
diff --git a/src/test/java/org/apache/commons/lang3/CharSetTest.java b/src/test/java/org/apache/commons/lang3/CharSetTest.java
index 21f394a52..10427dba0 100644
--- a/src/test/java/org/apache/commons/lang3/CharSetTest.java
+++ b/src/test/java/org/apache/commons/lang3/CharSetTest.java
@@ -40,65 +40,6 @@ public class CharSetTest extends AbstractLangTest {
assertFalse(Modifier.isFinal(CharSet.class.getModifiers()));
}
- @Test
- public void testGetInstance() {
- assertSame(CharSet.EMPTY, CharSet.getInstance( (String) null));
- assertSame(CharSet.EMPTY, CharSet.getInstance(""));
- assertSame(CharSet.ASCII_ALPHA, CharSet.getInstance("a-zA-Z"));
- assertSame(CharSet.ASCII_ALPHA, CharSet.getInstance("A-Za-z"));
- assertSame(CharSet.ASCII_ALPHA_LOWER, CharSet.getInstance("a-z"));
- assertSame(CharSet.ASCII_ALPHA_UPPER, CharSet.getInstance("A-Z"));
- assertSame(CharSet.ASCII_NUMERIC, CharSet.getInstance("0-9"));
- }
-
- @Test
- public void testGetInstance_Stringarray() {
- assertNull(CharSet.getInstance((String[]) null));
- assertEquals("[]", CharSet.getInstance(new String[0]).toString());
- assertEquals("[]", CharSet.getInstance(new String[] {null}).toString());
- assertEquals("[a-e]", CharSet.getInstance(new String[] {"a-e"}).toString());
- }
-
- @Test
- public void testConstructor_String_simple() {
- CharSet set;
- CharRange[] array;
-
- set = CharSet.getInstance((String) null);
- array = set.getCharRanges();
- assertEquals("[]", set.toString());
- assertEquals(0, array.length);
-
- set = CharSet.getInstance("");
- array = set.getCharRanges();
- assertEquals("[]", set.toString());
- assertEquals(0, array.length);
-
- set = CharSet.getInstance("a");
- array = set.getCharRanges();
- assertEquals("[a]", set.toString());
- assertEquals(1, array.length);
- assertEquals("a", array[0].toString());
-
- set = CharSet.getInstance("^a");
- array = set.getCharRanges();
- assertEquals("[^a]", set.toString());
- assertEquals(1, array.length);
- assertEquals("^a", array[0].toString());
-
- set = CharSet.getInstance("a-e");
- array = set.getCharRanges();
- assertEquals("[a-e]", set.toString());
- assertEquals(1, array.length);
- assertEquals("a-e", array[0].toString());
-
- set = CharSet.getInstance("^a-e");
- array = set.getCharRanges();
- assertEquals("[^a-e]", set.toString());
- assertEquals(1, array.length);
- assertEquals("^a-e", array[0].toString());
- }
-
@Test
public void testConstructor_String_combo() {
CharSet set;
@@ -179,6 +120,55 @@ public class CharSetTest extends AbstractLangTest {
assertTrue(ArrayUtils.contains(array, CharRange.is('b')));
}
+ @Test
+ public void testConstructor_String_oddCombinations() {
+ CharSet set;
+ CharRange[] array;
+
+ set = CharSet.getInstance("a-^c");
+ array = set.getCharRanges();
+ assertTrue(ArrayUtils.contains(array, CharRange.isIn('a', '^'))); // "a-^"
+ assertTrue(ArrayUtils.contains(array, CharRange.is('c'))); // "c"
+ assertFalse(set.contains('b'));
+ assertTrue(set.contains('^'));
+ assertTrue(set.contains('_')); // between ^ and a
+ assertTrue(set.contains('c'));
+
+ set = CharSet.getInstance("^a-^c");
+ array = set.getCharRanges();
+ assertTrue(ArrayUtils.contains(array, CharRange.isNotIn('a', '^'))); // "^a-^"
+ assertTrue(ArrayUtils.contains(array, CharRange.is('c'))); // "c"
+ assertTrue(set.contains('b'));
+ assertFalse(set.contains('^'));
+ assertFalse(set.contains('_')); // between ^ and a
+
+ set = CharSet.getInstance("a- ^-- "); //contains everything
+ array = set.getCharRanges();
+ assertTrue(ArrayUtils.contains(array, CharRange.isIn('a', ' '))); // "a- "
+ assertTrue(ArrayUtils.contains(array, CharRange.isNotIn('-', ' '))); // "^-- "
+ assertTrue(set.contains('#'));
+ assertTrue(set.contains('^'));
+ assertTrue(set.contains('a'));
+ assertTrue(set.contains('*'));
+ assertTrue(set.contains('A'));
+
+ set = CharSet.getInstance("^-b");
+ array = set.getCharRanges();
+ assertTrue(ArrayUtils.contains(array, CharRange.isIn('^', 'b'))); // "^-b"
+ assertTrue(set.contains('b'));
+ assertTrue(set.contains('_')); // between ^ and a
+ assertFalse(set.contains('A'));
+ assertTrue(set.contains('^'));
+
+ set = CharSet.getInstance("b-^");
+ array = set.getCharRanges();
+ assertTrue(ArrayUtils.contains(array, CharRange.isIn('^', 'b'))); // "b-^"
+ assertTrue(set.contains('b'));
+ assertTrue(set.contains('^'));
+ assertTrue(set.contains('a')); // between ^ and b
+ assertFalse(set.contains('c'));
+ }
+
@Test
public void testConstructor_String_oddDash() {
CharSet set;
@@ -288,52 +278,86 @@ public class CharSetTest extends AbstractLangTest {
}
@Test
- public void testConstructor_String_oddCombinations() {
+ public void testConstructor_String_simple() {
CharSet set;
CharRange[] array;
- set = CharSet.getInstance("a-^c");
+ set = CharSet.getInstance((String) null);
array = set.getCharRanges();
- assertTrue(ArrayUtils.contains(array, CharRange.isIn('a', '^'))); // "a-^"
- assertTrue(ArrayUtils.contains(array, CharRange.is('c'))); // "c"
- assertFalse(set.contains('b'));
- assertTrue(set.contains('^'));
- assertTrue(set.contains('_')); // between ^ and a
- assertTrue(set.contains('c'));
+ assertEquals("[]", set.toString());
+ assertEquals(0, array.length);
- set = CharSet.getInstance("^a-^c");
+ set = CharSet.getInstance("");
array = set.getCharRanges();
- assertTrue(ArrayUtils.contains(array, CharRange.isNotIn('a', '^'))); // "^a-^"
- assertTrue(ArrayUtils.contains(array, CharRange.is('c'))); // "c"
- assertTrue(set.contains('b'));
- assertFalse(set.contains('^'));
- assertFalse(set.contains('_')); // between ^ and a
+ assertEquals("[]", set.toString());
+ assertEquals(0, array.length);
- set = CharSet.getInstance("a- ^-- "); //contains everything
+ set = CharSet.getInstance("a");
array = set.getCharRanges();
- assertTrue(ArrayUtils.contains(array, CharRange.isIn('a', ' '))); // "a- "
- assertTrue(ArrayUtils.contains(array, CharRange.isNotIn('-', ' '))); // "^-- "
- assertTrue(set.contains('#'));
- assertTrue(set.contains('^'));
- assertTrue(set.contains('a'));
- assertTrue(set.contains('*'));
- assertTrue(set.contains('A'));
+ assertEquals("[a]", set.toString());
+ assertEquals(1, array.length);
+ assertEquals("a", array[0].toString());
- set = CharSet.getInstance("^-b");
+ set = CharSet.getInstance("^a");
array = set.getCharRanges();
- assertTrue(ArrayUtils.contains(array, CharRange.isIn('^', 'b'))); // "^-b"
- assertTrue(set.contains('b'));
- assertTrue(set.contains('_')); // between ^ and a
- assertFalse(set.contains('A'));
- assertTrue(set.contains('^'));
+ assertEquals("[^a]", set.toString());
+ assertEquals(1, array.length);
+ assertEquals("^a", array[0].toString());
- set = CharSet.getInstance("b-^");
+ set = CharSet.getInstance("a-e");
array = set.getCharRanges();
- assertTrue(ArrayUtils.contains(array, CharRange.isIn('^', 'b'))); // "b-^"
- assertTrue(set.contains('b'));
- assertTrue(set.contains('^'));
- assertTrue(set.contains('a')); // between ^ and b
- assertFalse(set.contains('c'));
+ assertEquals("[a-e]", set.toString());
+ assertEquals(1, array.length);
+ assertEquals("a-e", array[0].toString());
+
+ set = CharSet.getInstance("^a-e");
+ array = set.getCharRanges();
+ assertEquals("[^a-e]", set.toString());
+ assertEquals(1, array.length);
+ assertEquals("^a-e", array[0].toString());
+ }
+
+ @Test
+ public void testContains_Char() {
+ final CharSet btod = CharSet.getInstance("b-d");
+ final CharSet dtob = CharSet.getInstance("d-b");
+ final CharSet bcd = CharSet.getInstance("bcd");
+ final CharSet bd = CharSet.getInstance("bd");
+ final CharSet notbtod = CharSet.getInstance("^b-d");
+
+ assertFalse(btod.contains('a'));
+ assertTrue(btod.contains('b'));
+ assertTrue(btod.contains('c'));
+ assertTrue(btod.contains('d'));
+ assertFalse(btod.contains('e'));
+
+ assertFalse(bcd.contains('a'));
+ assertTrue(bcd.contains('b'));
+ assertTrue(bcd.contains('c'));
+ assertTrue(bcd.contains('d'));
+ assertFalse(bcd.contains('e'));
+
+ assertFalse(bd.contains('a'));
+ assertTrue(bd.contains('b'));
+ assertFalse(bd.contains('c'));
+ assertTrue(bd.contains('d'));
+ assertFalse(bd.contains('e'));
+
+ assertTrue(notbtod.contains('a'));
+ assertFalse(notbtod.contains('b'));
+ assertFalse(notbtod.contains('c'));
+ assertFalse(notbtod.contains('d'));
+ assertTrue(notbtod.contains('e'));
+
+ assertFalse(dtob.contains('a'));
+ assertTrue(dtob.contains('b'));
+ assertTrue(dtob.contains('c'));
+ assertTrue(dtob.contains('d'));
+ assertFalse(dtob.contains('e'));
+
+ final CharRange[] array = dtob.getCharRanges();
+ assertEquals("[b-d]", dtob.toString());
+ assertEquals(1, array.length);
}
@Test
@@ -363,6 +387,25 @@ public class CharSetTest extends AbstractLangTest {
assertEquals(notatoc, notatoc2);
}
+ @Test
+ public void testGetInstance() {
+ assertSame(CharSet.EMPTY, CharSet.getInstance( (String) null));
+ assertSame(CharSet.EMPTY, CharSet.getInstance(""));
+ assertSame(CharSet.ASCII_ALPHA, CharSet.getInstance("a-zA-Z"));
+ assertSame(CharSet.ASCII_ALPHA, CharSet.getInstance("A-Za-z"));
+ assertSame(CharSet.ASCII_ALPHA_LOWER, CharSet.getInstance("a-z"));
+ assertSame(CharSet.ASCII_ALPHA_UPPER, CharSet.getInstance("A-Z"));
+ assertSame(CharSet.ASCII_NUMERIC, CharSet.getInstance("0-9"));
+ }
+
+ @Test
+ public void testGetInstance_Stringarray() {
+ assertNull(CharSet.getInstance((String[]) null));
+ assertEquals("[]", CharSet.getInstance(new String[0]).toString());
+ assertEquals("[]", CharSet.getInstance(new String[] {null}).toString());
+ assertEquals("[a-e]", CharSet.getInstance(new String[] {"a-e"}).toString());
+ }
+
@Test
public void testHashCode() {
final CharSet abc = CharSet.getInstance("abc");
@@ -381,46 +424,14 @@ public class CharSetTest extends AbstractLangTest {
}
@Test
- public void testContains_Char() {
- final CharSet btod = CharSet.getInstance("b-d");
- final CharSet dtob = CharSet.getInstance("d-b");
- final CharSet bcd = CharSet.getInstance("bcd");
- final CharSet bd = CharSet.getInstance("bd");
- final CharSet notbtod = CharSet.getInstance("^b-d");
-
- assertFalse(btod.contains('a'));
- assertTrue(btod.contains('b'));
- assertTrue(btod.contains('c'));
- assertTrue(btod.contains('d'));
- assertFalse(btod.contains('e'));
-
- assertFalse(bcd.contains('a'));
- assertTrue(bcd.contains('b'));
- assertTrue(bcd.contains('c'));
- assertTrue(bcd.contains('d'));
- assertFalse(bcd.contains('e'));
-
- assertFalse(bd.contains('a'));
- assertTrue(bd.contains('b'));
- assertFalse(bd.contains('c'));
- assertTrue(bd.contains('d'));
- assertFalse(bd.contains('e'));
-
- assertTrue(notbtod.contains('a'));
- assertFalse(notbtod.contains('b'));
- assertFalse(notbtod.contains('c'));
- assertFalse(notbtod.contains('d'));
- assertTrue(notbtod.contains('e'));
-
- assertFalse(dtob.contains('a'));
- assertTrue(dtob.contains('b'));
- assertTrue(dtob.contains('c'));
- assertTrue(dtob.contains('d'));
- assertFalse(dtob.contains('e'));
-
- final CharRange[] array = dtob.getCharRanges();
- assertEquals("[b-d]", dtob.toString());
- assertEquals(1, array.length);
+ public void testJavadocExamples() {
+ assertFalse(CharSet.getInstance("^a-c").contains('a'));
+ assertTrue(CharSet.getInstance("^a-c").contains('d'));
+ assertTrue(CharSet.getInstance("^^a-c").contains('a'));
+ assertFalse(CharSet.getInstance("^^a-c").contains('^'));
+ assertTrue(CharSet.getInstance("^a-cd-f").contains('d'));
+ assertTrue(CharSet.getInstance("a-c^").contains('^'));
+ assertTrue(CharSet.getInstance("^", "a-c").contains('^'));
}
@Test
@@ -457,15 +468,4 @@ public class CharSetTest extends AbstractLangTest {
assertEquals(1, array.length);
assertTrue(ArrayUtils.contains(array, CharRange.isIn('0', '9')));
}
-
- @Test
- public void testJavadocExamples() {
- assertFalse(CharSet.getInstance("^a-c").contains('a'));
- assertTrue(CharSet.getInstance("^a-c").contains('d'));
- assertTrue(CharSet.getInstance("^^a-c").contains('a'));
- assertFalse(CharSet.getInstance("^^a-c").contains('^'));
- assertTrue(CharSet.getInstance("^a-cd-f").contains('d'));
- assertTrue(CharSet.getInstance("a-c^").contains('^'));
- assertTrue(CharSet.getInstance("^", "a-c").contains('^'));
- }
}
diff --git a/src/test/java/org/apache/commons/lang3/CharSetUtilsTest.java b/src/test/java/org/apache/commons/lang3/CharSetUtilsTest.java
index b6b5e7925..5881952a2 100644
--- a/src/test/java/org/apache/commons/lang3/CharSetUtilsTest.java
+++ b/src/test/java/org/apache/commons/lang3/CharSetUtilsTest.java
@@ -42,46 +42,6 @@ public class CharSetUtilsTest extends AbstractLangTest {
assertFalse(Modifier.isFinal(CharSetUtils.class.getModifiers()));
}
- @Test
- public void testSqueeze_StringString() {
- assertNull(CharSetUtils.squeeze(null, (String) null));
- assertNull(CharSetUtils.squeeze(null, ""));
-
- assertEquals("", CharSetUtils.squeeze("", (String) null));
- assertEquals("", CharSetUtils.squeeze("", ""));
- assertEquals("", CharSetUtils.squeeze("", "a-e"));
-
- assertEquals("hello", CharSetUtils.squeeze("hello", (String) null));
- assertEquals("hello", CharSetUtils.squeeze("hello", ""));
- assertEquals("hello", CharSetUtils.squeeze("hello", "a-e"));
- assertEquals("helo", CharSetUtils.squeeze("hello", "l-p"));
- assertEquals("heloo", CharSetUtils.squeeze("helloo", "l"));
- assertEquals("hello", CharSetUtils.squeeze("helloo", "^l"));
- }
-
- @Test
- public void testSqueeze_StringStringarray() {
- assertNull(CharSetUtils.squeeze(null, (String[]) null));
- assertNull(CharSetUtils.squeeze(null));
- assertNull(CharSetUtils.squeeze(null, null));
- assertNull(CharSetUtils.squeeze(null, "el"));
-
- assertEquals("", CharSetUtils.squeeze("", (String[]) null));
- assertEquals("", CharSetUtils.squeeze(""));
- assertEquals("", CharSetUtils.squeeze("", null));
- assertEquals("", CharSetUtils.squeeze("", "a-e"));
-
- assertEquals("hello", CharSetUtils.squeeze("hello", (String[]) null));
- assertEquals("hello", CharSetUtils.squeeze("hello"));
- assertEquals("hello", CharSetUtils.squeeze("hello", null));
- assertEquals("hello", CharSetUtils.squeeze("hello", "a-e"));
-
- assertEquals("helo", CharSetUtils.squeeze("hello", "el"));
- assertEquals("hello", CharSetUtils.squeeze("hello", "e"));
- assertEquals("fofof", CharSetUtils.squeeze("fooffooff", "of"));
- assertEquals("fof", CharSetUtils.squeeze("fooooff", "fo"));
- }
-
@Test
public void testContainsAny_StringString() {
assertFalse(CharSetUtils.containsAny(null, (String) null));
@@ -160,6 +120,48 @@ public class CharSetUtilsTest extends AbstractLangTest {
assertEquals(0, CharSetUtils.count("hello", ""));
}
+ @Test
+ public void testDelete_StringString() {
+ assertNull(CharSetUtils.delete(null, (String) null));
+ assertNull(CharSetUtils.delete(null, ""));
+
+ assertEquals("", CharSetUtils.delete("", (String) null));
+ assertEquals("", CharSetUtils.delete("", ""));
+ assertEquals("", CharSetUtils.delete("", "a-e"));
+
+ assertEquals("hello", CharSetUtils.delete("hello", (String) null));
+ assertEquals("hello", CharSetUtils.delete("hello", ""));
+ assertEquals("hllo", CharSetUtils.delete("hello", "a-e"));
+ assertEquals("he", CharSetUtils.delete("hello", "l-p"));
+ assertEquals("hello", CharSetUtils.delete("hello", "z"));
+ }
+
+ @Test
+ public void testDelete_StringStringarray() {
+ assertNull(CharSetUtils.delete(null, (String[]) null));
+ assertNull(CharSetUtils.delete(null));
+ assertNull(CharSetUtils.delete(null, null));
+ assertNull(CharSetUtils.delete(null, "el"));
+
+ assertEquals("", CharSetUtils.delete("", (String[]) null));
+ assertEquals("", CharSetUtils.delete(""));
+ assertEquals("", CharSetUtils.delete("", null));
+ assertEquals("", CharSetUtils.delete("", "a-e"));
+
+ assertEquals("hello", CharSetUtils.delete("hello", (String[]) null));
+ assertEquals("hello", CharSetUtils.delete("hello"));
+ assertEquals("hello", CharSetUtils.delete("hello", null));
+ assertEquals("hello", CharSetUtils.delete("hello", "xyz"));
+
+ assertEquals("ho", CharSetUtils.delete("hello", "el"));
+ assertEquals("", CharSetUtils.delete("hello", "elho"));
+ assertEquals("hello", CharSetUtils.delete("hello", ""));
+ assertEquals("hello", CharSetUtils.delete("hello", ""));
+ assertEquals("", CharSetUtils.delete("hello", "a-z"));
+ assertEquals("", CharSetUtils.delete("----", "-"));
+ assertEquals("heo", CharSetUtils.delete("hello", "l"));
+ }
+
@Test
public void testKeep_StringString() {
assertNull(CharSetUtils.keep(null, (String) null));
@@ -203,45 +205,43 @@ public class CharSetUtilsTest extends AbstractLangTest {
}
@Test
- public void testDelete_StringString() {
- assertNull(CharSetUtils.delete(null, (String) null));
- assertNull(CharSetUtils.delete(null, ""));
+ public void testSqueeze_StringString() {
+ assertNull(CharSetUtils.squeeze(null, (String) null));
+ assertNull(CharSetUtils.squeeze(null, ""));
- assertEquals("", CharSetUtils.delete("", (String) null));
- assertEquals("", CharSetUtils.delete("", ""));
- assertEquals("", CharSetUtils.delete("", "a-e"));
+ assertEquals("", CharSetUtils.squeeze("", (String) null));
+ assertEquals("", CharSetUtils.squeeze("", ""));
+ assertEquals("", CharSetUtils.squeeze("", "a-e"));
- assertEquals("hello", CharSetUtils.delete("hello", (String) null));
- assertEquals("hello", CharSetUtils.delete("hello", ""));
- assertEquals("hllo", CharSetUtils.delete("hello", "a-e"));
- assertEquals("he", CharSetUtils.delete("hello", "l-p"));
- assertEquals("hello", CharSetUtils.delete("hello", "z"));
+ assertEquals("hello", CharSetUtils.squeeze("hello", (String) null));
+ assertEquals("hello", CharSetUtils.squeeze("hello", ""));
+ assertEquals("hello", CharSetUtils.squeeze("hello", "a-e"));
+ assertEquals("helo", CharSetUtils.squeeze("hello", "l-p"));
+ assertEquals("heloo", CharSetUtils.squeeze("helloo", "l"));
+ assertEquals("hello", CharSetUtils.squeeze("helloo", "^l"));
}
@Test
- public void testDelete_StringStringarray() {
- assertNull(CharSetUtils.delete(null, (String[]) null));
- assertNull(CharSetUtils.delete(null));
- assertNull(CharSetUtils.delete(null, null));
- assertNull(CharSetUtils.delete(null, "el"));
+ public void testSqueeze_StringStringarray() {
+ assertNull(CharSetUtils.squeeze(null, (String[]) null));
+ assertNull(CharSetUtils.squeeze(null));
+ assertNull(CharSetUtils.squeeze(null, null));
+ assertNull(CharSetUtils.squeeze(null, "el"));
- assertEquals("", CharSetUtils.delete("", (String[]) null));
- assertEquals("", CharSetUtils.delete(""));
- assertEquals("", CharSetUtils.delete("", null));
- assertEquals("", CharSetUtils.delete("", "a-e"));
+ assertEquals("", CharSetUtils.squeeze("", (String[]) null));
+ assertEquals("", CharSetUtils.squeeze(""));
+ assertEquals("", CharSetUtils.squeeze("", null));
+ assertEquals("", CharSetUtils.squeeze("", "a-e"));
- assertEquals("hello", CharSetUtils.delete("hello", (String[]) null));
- assertEquals("hello", CharSetUtils.delete("hello"));
- assertEquals("hello", CharSetUtils.delete("hello", null));
- assertEquals("hello", CharSetUtils.delete("hello", "xyz"));
+ assertEquals("hello", CharSetUtils.squeeze("hello", (String[]) null));
+ assertEquals("hello", CharSetUtils.squeeze("hello"));
+ assertEquals("hello", CharSetUtils.squeeze("hello", null));
+ assertEquals("hello", CharSetUtils.squeeze("hello", "a-e"));
- assertEquals("ho", CharSetUtils.delete("hello", "el"));
- assertEquals("", CharSetUtils.delete("hello", "elho"));
- assertEquals("hello", CharSetUtils.delete("hello", ""));
- assertEquals("hello", CharSetUtils.delete("hello", ""));
- assertEquals("", CharSetUtils.delete("hello", "a-z"));
- assertEquals("", CharSetUtils.delete("----", "-"));
- assertEquals("heo", CharSetUtils.delete("hello", "l"));
+ assertEquals("helo", CharSetUtils.squeeze("hello", "el"));
+ assertEquals("hello", CharSetUtils.squeeze("hello", "e"));
+ assertEquals("fofof", CharSetUtils.squeeze("fooffooff", "of"));
+ assertEquals("fof", CharSetUtils.squeeze("fooooff", "fo"));
}
}
diff --git a/src/test/java/org/apache/commons/lang3/CharUtilsPerfRun.java b/src/test/java/org/apache/commons/lang3/CharUtilsPerfRun.java
index f9e37ddbb..108168120 100644
--- a/src/test/java/org/apache/commons/lang3/CharUtilsPerfRun.java
+++ b/src/test/java/org/apache/commons/lang3/CharUtilsPerfRun.java
@@ -74,6 +74,11 @@ public class CharUtilsPerfRun {
new CharUtilsPerfRun().run();
}
+ private void printlnTotal(final String prefix, final long startMillis) {
+ final long totalMillis = System.currentTimeMillis() - startMillis;
+ System.out.println(prefix + ": " + NumberFormat.getInstance().format(totalMillis) + " milliseconds.");
+ }
+
private void printSysInfo() {
System.out.println("Now: " + Calendar.getInstance().getTime());
System.out.println(SystemProperties.getJavaVendor()
@@ -146,9 +151,4 @@ public class CharUtilsPerfRun {
}
return t;
}
-
- private void printlnTotal(final String prefix, final long startMillis) {
- final long totalMillis = System.currentTimeMillis() - startMillis;
- System.out.println(prefix + ": " + NumberFormat.getInstance().format(totalMillis) + " milliseconds.");
- }
}
diff --git a/src/test/java/org/apache/commons/lang3/ClassPathUtilsTest.java b/src/test/java/org/apache/commons/lang3/ClassPathUtilsTest.java
index d69fe3e5c..b8b122163 100644
--- a/src/test/java/org/apache/commons/lang3/ClassPathUtilsTest.java
+++ b/src/test/java/org/apache/commons/lang3/ClassPathUtilsTest.java
@@ -55,12 +55,6 @@ public class ClassPathUtilsTest extends AbstractLangTest {
assertEquals("a.b.c", ClassPathUtils.pathToPackage("a/b/c"));
}
- @Test
- public void testToFullyQualifiedNameNullClassString() {
- assertThrows(NullPointerException.class,
- () -> ClassPathUtils.toFullyQualifiedName((Class<?>) null, "Test.properties"));
- }
-
@Test
public void testToFullyQualifiedNameClassNull() {
assertThrows(NullPointerException.class, () -> ClassPathUtils.toFullyQualifiedName(ClassPathUtils.class, null));
@@ -74,6 +68,12 @@ public class ClassPathUtilsTest extends AbstractLangTest {
assertEquals(expected, actual);
}
+ @Test
+ public void testToFullyQualifiedNameNullClassString() {
+ assertThrows(NullPointerException.class,
+ () -> ClassPathUtils.toFullyQualifiedName((Class<?>) null, "Test.properties"));
+ }
+
@Test
public void testToFullyQualifiedNameNullPackageString() {
assertThrows(NullPointerException.class,
@@ -94,17 +94,6 @@ public class ClassPathUtilsTest extends AbstractLangTest {
assertEquals(expected, actual);
}
- @Test
- public void testToFullyQualifiedPathClassNullString() {
- assertThrows(NullPointerException.class,
- () -> ClassPathUtils.toFullyQualifiedPath((Class<?>) null, "Test.properties"));
- }
-
- @Test
- public void testToFullyQualifiedPathClassNull() {
- assertThrows(NullPointerException.class, () -> ClassPathUtils.toFullyQualifiedPath(ClassPathUtils.class, null));
- }
-
@Test
public void testToFullyQualifiedPathClass() {
final String expected = "org/apache/commons/lang3/Test.properties";
@@ -114,15 +103,14 @@ public class ClassPathUtilsTest extends AbstractLangTest {
}
@Test
- public void testToFullyQualifiedPathPackageNullString() {
- assertThrows(NullPointerException.class,
- () -> ClassPathUtils.toFullyQualifiedPath((Package) null, "Test.properties"));
+ public void testToFullyQualifiedPathClassNull() {
+ assertThrows(NullPointerException.class, () -> ClassPathUtils.toFullyQualifiedPath(ClassPathUtils.class, null));
}
@Test
- public void testToFullyQualifiedPathPackageNull() {
+ public void testToFullyQualifiedPathClassNullString() {
assertThrows(NullPointerException.class,
- () -> ClassPathUtils.toFullyQualifiedPath(ClassPathUtils.class.getPackage(), null));
+ () -> ClassPathUtils.toFullyQualifiedPath((Class<?>) null, "Test.properties"));
}
@Test
@@ -132,4 +120,16 @@ public class ClassPathUtilsTest extends AbstractLangTest {
assertEquals(expected, actual);
}
+
+ @Test
+ public void testToFullyQualifiedPathPackageNull() {
+ assertThrows(NullPointerException.class,
+ () -> ClassPathUtils.toFullyQualifiedPath(ClassPathUtils.class.getPackage(), null));
+ }
+
+ @Test
+ public void testToFullyQualifiedPathPackageNullString() {
+ assertThrows(NullPointerException.class,
+ () -> ClassPathUtils.toFullyQualifiedPath((Package) null, "Test.properties"));
+ }
}
diff --git a/src/test/java/org/apache/commons/lang3/ClassUtilsTest.java b/src/test/java/org/apache/commons/lang3/ClassUtilsTest.java
index 181975dc2..164097396 100644
--- a/src/test/java/org/apache/commons/lang3/ClassUtilsTest.java
+++ b/src/test/java/org/apache/commons/lang3/ClassUtilsTest.java
@@ -52,8 +52,6 @@ import org.junit.jupiter.api.Test;
@SuppressWarnings("boxing") // JUnit4 does not support primitive equality testing apart from long
public class ClassUtilsTest extends AbstractLangTest {
- private static final String OBJECT_CANONICAL_NAME = "java.lang.Object";
-
private static class CX implements IB, IA, IE {
// empty
}
@@ -93,6 +91,8 @@ public class ClassUtilsTest extends AbstractLangTest {
}
}
+ private static final String OBJECT_CANONICAL_NAME = "java.lang.Object";
+
private void assertGetClassReturnsClass(final Class<?> c) throws Exception {
assertEquals(c, ClassUtils.getClass(c.getName()));
}
diff --git a/src/test/java/org/apache/commons/lang3/ConversionTest.java b/src/test/java/org/apache/commons/lang3/ConversionTest.java
index c10573918..1dabbe1be 100644
--- a/src/test/java/org/apache/commons/lang3/ConversionTest.java
+++ b/src/test/java/org/apache/commons/lang3/ConversionTest.java
@@ -34,168 +34,137 @@ import org.junit.jupiter.params.provider.ValueSource;
*/
public class ConversionTest extends AbstractLangTest {
- /**
- * Tests {@link Conversion#hexDigitToInt(char)}.
- */
- @Test
- public void testHexDigitToInt() {
- assertEquals(0, Conversion.hexDigitToInt('0'));
- assertEquals(1, Conversion.hexDigitToInt('1'));
- assertEquals(2, Conversion.hexDigitToInt('2'));
- assertEquals(3, Conversion.hexDigitToInt('3'));
- assertEquals(4, Conversion.hexDigitToInt('4'));
- assertEquals(5, Conversion.hexDigitToInt('5'));
- assertEquals(6, Conversion.hexDigitToInt('6'));
- assertEquals(7, Conversion.hexDigitToInt('7'));
- assertEquals(8, Conversion.hexDigitToInt('8'));
- assertEquals(9, Conversion.hexDigitToInt('9'));
- assertEquals(10, Conversion.hexDigitToInt('A'));
- assertEquals(10, Conversion.hexDigitToInt('a'));
- assertEquals(11, Conversion.hexDigitToInt('B'));
- assertEquals(11, Conversion.hexDigitToInt('b'));
- assertEquals(12, Conversion.hexDigitToInt('C'));
- assertEquals(12, Conversion.hexDigitToInt('c'));
- assertEquals(13, Conversion.hexDigitToInt('D'));
- assertEquals(13, Conversion.hexDigitToInt('d'));
- assertEquals(14, Conversion.hexDigitToInt('E'));
- assertEquals(14, Conversion.hexDigitToInt('e'));
- assertEquals(15, Conversion.hexDigitToInt('F'));
- assertEquals(15, Conversion.hexDigitToInt('f'));
- assertThrows(IllegalArgumentException.class, () -> Conversion.hexDigitToInt('G'));
+ static String dbgPrint(final boolean[] src) {
+ final StringBuilder sb = new StringBuilder();
+ for (final boolean e : src) {
+ if (e) {
+ sb.append("1, ");
+ } else {
+ sb.append("0, ");
+ }
+ }
+ final String out = sb.toString();
+ return out.substring(0, out.length() - 1);
+ }
+
+ @ParameterizedTest
+ @ValueSource(ints = {-1, 8, 99})
+ public void binaryBeMsb0ToHexDigitPosOutsideArray(final int index) {
+ assertThrows(IndexOutOfBoundsException.class,
+ () -> Conversion.binaryBeMsb0ToHexDigit(new boolean[8], index));
}
/**
- * Tests {@link Conversion#hexDigitMsb0ToInt(char)}.
+ * Tests {@link Conversion#binaryToHexDigit(boolean[])}.
*/
@Test
- public void testHexDigitMsb0ToInt() {
- assertEquals(0x0, Conversion.hexDigitMsb0ToInt('0'));
- assertEquals(0x8, Conversion.hexDigitMsb0ToInt('1'));
- assertEquals(0x4, Conversion.hexDigitMsb0ToInt('2'));
- assertEquals(0xC, Conversion.hexDigitMsb0ToInt('3'));
- assertEquals(0x2, Conversion.hexDigitMsb0ToInt('4'));
- assertEquals(0xA, Conversion.hexDigitMsb0ToInt('5'));
- assertEquals(0x6, Conversion.hexDigitMsb0ToInt('6'));
- assertEquals(0xE, Conversion.hexDigitMsb0ToInt('7'));
- assertEquals(0x1, Conversion.hexDigitMsb0ToInt('8'));
- assertEquals(0x9, Conversion.hexDigitMsb0ToInt('9'));
- assertEquals(0x5, Conversion.hexDigitMsb0ToInt('A'));
- assertEquals(0x5, Conversion.hexDigitMsb0ToInt('a'));
- assertEquals(0xD, Conversion.hexDigitMsb0ToInt('B'));
- assertEquals(0xD, Conversion.hexDigitMsb0ToInt('b'));
- assertEquals(0x3, Conversion.hexDigitMsb0ToInt('C'));
- assertEquals(0x3, Conversion.hexDigitMsb0ToInt('c'));
- assertEquals(0xB, Conversion.hexDigitMsb0ToInt('D'));
- assertEquals(0xB, Conversion.hexDigitMsb0ToInt('d'));
- assertEquals(0x7, Conversion.hexDigitMsb0ToInt('E'));
- assertEquals(0x7, Conversion.hexDigitMsb0ToInt('e'));
- assertEquals(0xF, Conversion.hexDigitMsb0ToInt('F'));
- assertEquals(0xF, Conversion.hexDigitMsb0ToInt('f'));
- assertThrows(IllegalArgumentException.class, () -> Conversion.hexDigitMsb0ToInt('G'));
+ public void testBinaryBeMsb0ToHexDigit() {
+ assertEquals(
+ '0', Conversion.binaryBeMsb0ToHexDigit(new boolean[]{false, false, false, false}));
+ assertEquals(
+ '1', Conversion.binaryBeMsb0ToHexDigit(new boolean[]{false, false, false, true}));
+ assertEquals(
+ '2', Conversion.binaryBeMsb0ToHexDigit(new boolean[]{false, false, true, false}));
+ assertEquals(
+ '3', Conversion.binaryBeMsb0ToHexDigit(new boolean[]{false, false, true, true}));
+ assertEquals(
+ '4', Conversion.binaryBeMsb0ToHexDigit(new boolean[]{false, true, false, false}));
+ assertEquals(
+ '5', Conversion.binaryBeMsb0ToHexDigit(new boolean[]{false, true, false, true}));
+ assertEquals(
+ '6', Conversion.binaryBeMsb0ToHexDigit(new boolean[]{false, true, true, false}));
+ assertEquals(
+ '7', Conversion.binaryBeMsb0ToHexDigit(new boolean[]{false, true, true, true}));
+ assertEquals(
+ '8', Conversion.binaryBeMsb0ToHexDigit(new boolean[]{true, false, false, false}));
+ assertEquals(
+ '9', Conversion.binaryBeMsb0ToHexDigit(new boolean[]{true, false, false, true}));
+ assertEquals(
+ 'a', Conversion.binaryBeMsb0ToHexDigit(new boolean[]{true, false, true, false}));
+ assertEquals(
+ 'b', Conversion.binaryBeMsb0ToHexDigit(new boolean[]{true, false, true, true}));
+ assertEquals(
+ 'c', Conversion.binaryBeMsb0ToHexDigit(new boolean[]{true, true, false, false}));
+ assertEquals(
+ 'd', Conversion.binaryBeMsb0ToHexDigit(new boolean[]{true, true, false, true}));
+ assertEquals(
+ 'e', Conversion.binaryBeMsb0ToHexDigit(new boolean[]{true, true, true, false}));
+ assertEquals(
+ 'f', Conversion.binaryBeMsb0ToHexDigit(new boolean[]{true, true, true, true}));
+ assertEquals(
+ '4',
+ Conversion.binaryBeMsb0ToHexDigit(new boolean[]{
+ true, false, false, false, false, false, false, false, false, false, false,
+ false, false, true, false, false}));
+ assertThrows(IllegalArgumentException.class, () -> Conversion.binaryBeMsb0ToHexDigit(new boolean[]{}));
}
/**
- * Tests {@link Conversion#hexDigitToBinary(char)}.
+ * Tests {@link Conversion#binaryToHexDigit(boolean[], int)}.
*/
@Test
- public void testHexDigitToBinary() {
- assertArrayEquals(
- new boolean[]{false, false, false, false}, Conversion.hexDigitToBinary('0'));
- assertArrayEquals(
- new boolean[]{true, false, false, false}, Conversion.hexDigitToBinary('1'));
- assertArrayEquals(
- new boolean[]{false, true, false, false}, Conversion.hexDigitToBinary('2'));
- assertArrayEquals(
- new boolean[]{true, true, false, false}, Conversion.hexDigitToBinary('3'));
- assertArrayEquals(
- new boolean[]{false, false, true, false}, Conversion.hexDigitToBinary('4'));
- assertArrayEquals(
- new boolean[]{true, false, true, false}, Conversion.hexDigitToBinary('5'));
- assertArrayEquals(
- new boolean[]{false, true, true, false}, Conversion.hexDigitToBinary('6'));
- assertArrayEquals(
- new boolean[]{true, true, true, false}, Conversion.hexDigitToBinary('7'));
- assertArrayEquals(
- new boolean[]{false, false, false, true}, Conversion.hexDigitToBinary('8'));
- assertArrayEquals(
- new boolean[]{true, false, false, true}, Conversion.hexDigitToBinary('9'));
- assertArrayEquals(
- new boolean[]{false, true, false, true}, Conversion.hexDigitToBinary('A'));
- assertArrayEquals(
- new boolean[]{false, true, false, true}, Conversion.hexDigitToBinary('a'));
- assertArrayEquals(
- new boolean[]{true, true, false, true}, Conversion.hexDigitToBinary('B'));
- assertArrayEquals(
- new boolean[]{true, true, false, true}, Conversion.hexDigitToBinary('b'));
- assertArrayEquals(
- new boolean[]{false, false, true, true}, Conversion.hexDigitToBinary('C'));
- assertArrayEquals(
- new boolean[]{false, false, true, true}, Conversion.hexDigitToBinary('c'));
- assertArrayEquals(
- new boolean[]{true, false, true, true}, Conversion.hexDigitToBinary('D'));
- assertArrayEquals(
- new boolean[]{true, false, true, true}, Conversion.hexDigitToBinary('d'));
- assertArrayEquals(
- new boolean[]{false, true, true, true}, Conversion.hexDigitToBinary('E'));
- assertArrayEquals(
- new boolean[]{false, true, true, true}, Conversion.hexDigitToBinary('e'));
- assertArrayEquals(
- new boolean[]{true, true, true, true}, Conversion.hexDigitToBinary('F'));
- assertArrayEquals(
- new boolean[]{true, true, true, true}, Conversion.hexDigitToBinary('f'));
- assertThrows(IllegalArgumentException.class, () -> Conversion.hexDigitToBinary('G'));
+ public void testBinaryBeMsb0ToHexDigit_2args() {
+ assertEquals(
+ '5',
+ Conversion.binaryBeMsb0ToHexDigit(new boolean[]{
+ true, false, false, false, false, false, false, false, false, false, false,
+ true, false, true, false, false}, 2));
+
+ final boolean[] shortArray = {true, true, false};
+ assertEquals('6', Conversion.binaryBeMsb0ToHexDigit(shortArray, 0));
+ assertEquals('3', Conversion.binaryBeMsb0ToHexDigit(shortArray, 1));
+ assertEquals('1', Conversion.binaryBeMsb0ToHexDigit(shortArray, 2));
+ final boolean[] shortArray2 = {true, true, true, false, false, true, false, true};
+ assertEquals('5', Conversion.binaryBeMsb0ToHexDigit(shortArray2, 0));
+ assertEquals('2', Conversion.binaryBeMsb0ToHexDigit(shortArray2, 1));
+ assertEquals('9', Conversion.binaryBeMsb0ToHexDigit(shortArray2, 2));
+ assertEquals('c', Conversion.binaryBeMsb0ToHexDigit(shortArray2, 3));
+ assertEquals('e', Conversion.binaryBeMsb0ToHexDigit(shortArray2, 4));
+ assertEquals('7', Conversion.binaryBeMsb0ToHexDigit(shortArray2, 5));
+ assertEquals('3', Conversion.binaryBeMsb0ToHexDigit(shortArray2, 6));
+ assertEquals('1', Conversion.binaryBeMsb0ToHexDigit(shortArray2, 7));
+ final boolean[] multiBytesArray = {
+ true, true, false, false, true, false, true, false, true, true, true, false, false,
+ true, false, true};
+ assertEquals('5', Conversion.binaryBeMsb0ToHexDigit(multiBytesArray, 0));
+ assertEquals('2', Conversion.binaryBeMsb0ToHexDigit(multiBytesArray, 1));
+ assertEquals('9', Conversion.binaryBeMsb0ToHexDigit(multiBytesArray, 2));
+ assertEquals('c', Conversion.binaryBeMsb0ToHexDigit(multiBytesArray, 3));
+ assertEquals('e', Conversion.binaryBeMsb0ToHexDigit(multiBytesArray, 4));
+ assertEquals('7', Conversion.binaryBeMsb0ToHexDigit(multiBytesArray, 5));
+ assertEquals('b', Conversion.binaryBeMsb0ToHexDigit(multiBytesArray, 6));
+ assertEquals('5', Conversion.binaryBeMsb0ToHexDigit(multiBytesArray, 7));
+
+ assertEquals('a', Conversion.binaryBeMsb0ToHexDigit(multiBytesArray, 8));
+ assertEquals('5', Conversion.binaryBeMsb0ToHexDigit(multiBytesArray, 9));
+ assertEquals('2', Conversion.binaryBeMsb0ToHexDigit(multiBytesArray, 10));
+ assertEquals('9', Conversion.binaryBeMsb0ToHexDigit(multiBytesArray, 11));
+ assertEquals('c', Conversion.binaryBeMsb0ToHexDigit(multiBytesArray, 12));
+ assertEquals('6', Conversion.binaryBeMsb0ToHexDigit(multiBytesArray, 13));
+ assertEquals('3', Conversion.binaryBeMsb0ToHexDigit(multiBytesArray, 14));
+ assertEquals('1', Conversion.binaryBeMsb0ToHexDigit(multiBytesArray, 15));
+
}
/**
- * Tests {@link Conversion#hexDigitMsb0ToBinary(char)}.
+ * Tests {@link Conversion#binaryToByte(boolean[], int, byte, int, int)}.
*/
@Test
- public void testHexDigitMsb0ToBinary() {
- assertArrayEquals(
- new boolean[]{false, false, false, false}, Conversion.hexDigitMsb0ToBinary('0'));
- assertArrayEquals(
- new boolean[]{false, false, false, true}, Conversion.hexDigitMsb0ToBinary('1'));
- assertArrayEquals(
- new boolean[]{false, false, true, false}, Conversion.hexDigitMsb0ToBinary('2'));
- assertArrayEquals(
- new boolean[]{false, false, true, true}, Conversion.hexDigitMsb0ToBinary('3'));
- assertArrayEquals(
- new boolean[]{false, true, false, false}, Conversion.hexDigitMsb0ToBinary('4'));
- assertArrayEquals(
- new boolean[]{false, true, false, true}, Conversion.hexDigitMsb0ToBinary('5'));
- assertArrayEquals(
- new boolean[]{false, true, true, false}, Conversion.hexDigitMsb0ToBinary('6'));
- assertArrayEquals(
- new boolean[]{false, true, true, true}, Conversion.hexDigitMsb0ToBinary('7'));
- assertArrayEquals(
- new boolean[]{true, false, false, false}, Conversion.hexDigitMsb0ToBinary('8'));
- assertArrayEquals(
- new boolean[]{true, false, false, true}, Conversion.hexDigitMsb0ToBinary('9'));
- assertArrayEquals(
- new boolean[]{true, false, true, false}, Conversion.hexDigitMsb0ToBinary('A'));
- assertArrayEquals(
- new boolean[]{true, false, true, false}, Conversion.hexDigitMsb0ToBinary('a'));
- assertArrayEquals(
- new boolean[]{true, false, true, true}, Conversion.hexDigitMsb0ToBinary('B'));
- assertArrayEquals(
- new boolean[]{true, false, true, true}, Conversion.hexDigitMsb0ToBinary('b'));
- assertArrayEquals(
- new boolean[]{true, true, false, false}, Conversion.hexDigitMsb0ToBinary('C'));
- assertArrayEquals(
- new boolean[]{true, true, false, false}, Conversion.hexDigitMsb0ToBinary('c'));
- assertArrayEquals(
- new boolean[]{true, true, false, true}, Conversion.hexDigitMsb0ToBinary('D'));
- assertArrayEquals(
- new boolean[]{true, true, false, true}, Conversion.hexDigitMsb0ToBinary('d'));
- assertArrayEquals(
- new boolean[]{true, true, true, false}, Conversion.hexDigitMsb0ToBinary('E'));
- assertArrayEquals(
- new boolean[]{true, true, true, false}, Conversion.hexDigitMsb0ToBinary('e'));
- assertArrayEquals(
- new boolean[]{true, true, true, true}, Conversion.hexDigitMsb0ToBinary('F'));
- assertArrayEquals(
- new boolean[]{true, true, true, true}, Conversion.hexDigitMsb0ToBinary('f'));
- assertThrows(IllegalArgumentException.class, () -> Conversion.hexDigitMsb0ToBinary('G'));
+ public void testBinaryToByte() {
+ final boolean[] src = {
+ false, false, true, true, true, false, true, true, true, true, true, true, true,
+ false, false, false, true, true, true, true, false, false, false, false, false,
+ false, true, true, true, false, false, false, false, false, false, false, true,
+ true, true, true, true, false, false, false, false, true, false, false, true, true,
+ false, false, false, false, true, false, true, false, true, false, false, true,
+ true, false, true, true, true, false, false, false, false, true};
+ // conversion of "CDF1F0C10F12345678" by HexToBinary
+ assertEquals((byte) 0x00, Conversion.binaryToByte(src, 0 * 4, (byte) 0, 0, 0 * 4));
+ assertEquals((byte) 0x0C, Conversion.binaryToByte(src, 0 * 4, (byte) 0, 0, 1 * 4));
+ assertEquals((byte) 0xDC, Conversion.binaryToByte(src, 0 * 4, (byte) 0, 0, 2 * 4));
+ assertEquals((byte) 0xFD, Conversion.binaryToByte(src, 1 * 4, (byte) 0, 0, 2 * 4));
+ assertEquals((byte) 0x34, Conversion.binaryToByte(src, 0 * 4, (byte) 0x34, 0, 0 * 4));
+ assertEquals((byte) 0x84, Conversion.binaryToByte(src, 17 * 4, (byte) 0x34, 4, 1 * 4));
}
/**
@@ -245,51 +214,6 @@ public class ConversionTest extends AbstractLangTest {
assertEquals('1', Conversion.binaryToHexDigit(longArray, 6));
}
- /**
- * Tests {@link Conversion#binaryToHexDigitMsb0_4bits(boolean[])}.
- */
- @Test
- public void testBinaryToHexDigitMsb0_bits() {
- assertEquals(
- '0',
- Conversion.binaryToHexDigitMsb0_4bits(new boolean[]{false, false, false, false}));
- assertEquals(
- '1',
- Conversion.binaryToHexDigitMsb0_4bits(new boolean[]{false, false, false, true}));
- assertEquals(
- '2',
- Conversion.binaryToHexDigitMsb0_4bits(new boolean[]{false, false, true, false}));
- assertEquals(
- '3', Conversion.binaryToHexDigitMsb0_4bits(new boolean[]{false, false, true, true}));
- assertEquals(
- '4',
- Conversion.binaryToHexDigitMsb0_4bits(new boolean[]{false, true, false, false}));
- assertEquals(
- '5', Conversion.binaryToHexDigitMsb0_4bits(new boolean[]{false, true, false, true}));
- assertEquals(
- '6', Conversion.binaryToHexDigitMsb0_4bits(new boolean[]{false, true, true, false}));
- assertEquals(
- '7', Conversion.binaryToHexDigitMsb0_4bits(new boolean[]{false, true, true, true}));
- assertEquals(
- '8',
- Conversion.binaryToHexDigitMsb0_4bits(new boolean[]{true, false, false, false}));
- assertEquals(
- '9', Conversion.binaryToHexDigitMsb0_4bits(new boolean[]{true, false, false, true}));
- assertEquals(
- 'a', Conversion.binaryToHexDigitMsb0_4bits(new boolean[]{true, false, true, false}));
- assertEquals(
- 'b', Conversion.binaryToHexDigitMsb0_4bits(new boolean[]{true, false, true, true}));
- assertEquals(
- 'c', Conversion.binaryToHexDigitMsb0_4bits(new boolean[]{true, true, false, false}));
- assertEquals(
- 'd', Conversion.binaryToHexDigitMsb0_4bits(new boolean[]{true, true, false, true}));
- assertEquals(
- 'e', Conversion.binaryToHexDigitMsb0_4bits(new boolean[]{true, true, true, false}));
- assertEquals(
- 'f', Conversion.binaryToHexDigitMsb0_4bits(new boolean[]{true, true, true, true}));
- assertThrows(IllegalArgumentException.class, () -> Conversion.binaryToHexDigitMsb0_4bits(new boolean[]{}));
- }
-
/**
* Tests {@link Conversion#binaryToHexDigitMsb0_4bits(boolean[], int)}.
*/
@@ -326,95 +250,48 @@ public class ConversionTest extends AbstractLangTest {
}
/**
- * Tests {@link Conversion#binaryToHexDigit(boolean[])}.
+ * Tests {@link Conversion#binaryToHexDigitMsb0_4bits(boolean[])}.
*/
@Test
- public void testBinaryBeMsb0ToHexDigit() {
- assertEquals(
- '0', Conversion.binaryBeMsb0ToHexDigit(new boolean[]{false, false, false, false}));
- assertEquals(
- '1', Conversion.binaryBeMsb0ToHexDigit(new boolean[]{false, false, false, true}));
+ public void testBinaryToHexDigitMsb0_bits() {
assertEquals(
- '2', Conversion.binaryBeMsb0ToHexDigit(new boolean[]{false, false, true, false}));
+ '0',
+ Conversion.binaryToHexDigitMsb0_4bits(new boolean[]{false, false, false, false}));
assertEquals(
- '3', Conversion.binaryBeMsb0ToHexDigit(new boolean[]{false, false, true, true}));
+ '1',
+ Conversion.binaryToHexDigitMsb0_4bits(new boolean[]{false, false, false, true}));
assertEquals(
- '4', Conversion.binaryBeMsb0ToHexDigit(new boolean[]{false, true, false, false}));
+ '2',
+ Conversion.binaryToHexDigitMsb0_4bits(new boolean[]{false, false, true, false}));
assertEquals(
- '5', Conversion.binaryBeMsb0ToHexDigit(new boolean[]{false, true, false, true}));
+ '3', Conversion.binaryToHexDigitMsb0_4bits(new boolean[]{false, false, true, true}));
assertEquals(
- '6', Conversion.binaryBeMsb0ToHexDigit(new boolean[]{false, true, true, false}));
+ '4',
+ Conversion.binaryToHexDigitMsb0_4bits(new boolean[]{false, true, false, false}));
assertEquals(
- '7', Conversion.binaryBeMsb0ToHexDigit(new boolean[]{false, true, true, true}));
+ '5', Conversion.binaryToHexDigitMsb0_4bits(new boolean[]{false, true, false, true}));
assertEquals(
- '8', Conversion.binaryBeMsb0ToHexDigit(new boolean[]{true, false, false, false}));
+ '6', Conversion.binaryToHexDigitMsb0_4bits(new boolean[]{false, true, true, false}));
assertEquals(
- '9', Conversion.binaryBeMsb0ToHexDigit(new boolean[]{true, false, false, true}));
+ '7', Conversion.binaryToHexDigitMsb0_4bits(new boolean[]{false, true, true, true}));
assertEquals(
- 'a', Conversion.binaryBeMsb0ToHexDigit(new boolean[]{true, false, true, false}));
+ '8',
+ Conversion.binaryToHexDigitMsb0_4bits(new boolean[]{true, false, false, false}));
assertEquals(
- 'b', Conversion.binaryBeMsb0ToHexDigit(new boolean[]{true, false, true, true}));
+ '9', Conversion.binaryToHexDigitMsb0_4bits(new boolean[]{true, false, false, true}));
assertEquals(
- 'c', Conversion.binaryBeMsb0ToHexDigit(new boolean[]{true, true, false, false}));
+ 'a', Conversion.binaryToHexDigitMsb0_4bits(new boolean[]{true, false, true, false}));
assertEquals(
- 'd', Conversion.binaryBeMsb0ToHexDigit(new boolean[]{true, true, false, true}));
+ 'b', Conversion.binaryToHexDigitMsb0_4bits(new boolean[]{true, false, true, true}));
assertEquals(
- 'e', Conversion.binaryBeMsb0ToHexDigit(new boolean[]{true, true, true, false}));
+ 'c', Conversion.binaryToHexDigitMsb0_4bits(new boolean[]{true, true, false, false}));
assertEquals(
- 'f', Conversion.binaryBeMsb0ToHexDigit(new boolean[]{true, true, true, true}));
+ 'd', Conversion.binaryToHexDigitMsb0_4bits(new boolean[]{true, true, false, true}));
assertEquals(
- '4',
- Conversion.binaryBeMsb0ToHexDigit(new boolean[]{
- true, false, false, false, false, false, false, false, false, false, false,
- false, false, true, false, false}));
- assertThrows(IllegalArgumentException.class, () -> Conversion.binaryBeMsb0ToHexDigit(new boolean[]{}));
- }
-
- /**
- * Tests {@link Conversion#binaryToHexDigit(boolean[], int)}.
- */
- @Test
- public void testBinaryBeMsb0ToHexDigit_2args() {
+ 'e', Conversion.binaryToHexDigitMsb0_4bits(new boolean[]{true, true, true, false}));
assertEquals(
- '5',
- Conversion.binaryBeMsb0ToHexDigit(new boolean[]{
- true, false, false, false, false, false, false, false, false, false, false,
- true, false, true, false, false}, 2));
-
- final boolean[] shortArray = {true, true, false};
- assertEquals('6', Conversion.binaryBeMsb0ToHexDigit(shortArray, 0));
- assertEquals('3', Conversion.binaryBeMsb0ToHexDigit(shortArray, 1));
- assertEquals('1', Conversion.binaryBeMsb0ToHexDigit(shortArray, 2));
- final boolean[] shortArray2 = {true, true, true, false, false, true, false, true};
- assertEquals('5', Conversion.binaryBeMsb0ToHexDigit(shortArray2, 0));
- assertEquals('2', Conversion.binaryBeMsb0ToHexDigit(shortArray2, 1));
- assertEquals('9', Conversion.binaryBeMsb0ToHexDigit(shortArray2, 2));
- assertEquals('c', Conversion.binaryBeMsb0ToHexDigit(shortArray2, 3));
- assertEquals('e', Conversion.binaryBeMsb0ToHexDigit(shortArray2, 4));
- assertEquals('7', Conversion.binaryBeMsb0ToHexDigit(shortArray2, 5));
- assertEquals('3', Conversion.binaryBeMsb0ToHexDigit(shortArray2, 6));
- assertEquals('1', Conversion.binaryBeMsb0ToHexDigit(shortArray2, 7));
- final boolean[] multiBytesArray = {
- true, true, false, false, true, false, true, false, true, true, true, false, false,
- true, false, true};
- assertEquals('5', Conversion.binaryBeMsb0ToHexDigit(multiBytesArray, 0));
- assertEquals('2', Conversion.binaryBeMsb0ToHexDigit(multiBytesArray, 1));
- assertEquals('9', Conversion.binaryBeMsb0ToHexDigit(multiBytesArray, 2));
- assertEquals('c', Conversion.binaryBeMsb0ToHexDigit(multiBytesArray, 3));
- assertEquals('e', Conversion.binaryBeMsb0ToHexDigit(multiBytesArray, 4));
- assertEquals('7', Conversion.binaryBeMsb0ToHexDigit(multiBytesArray, 5));
- assertEquals('b', Conversion.binaryBeMsb0ToHexDigit(multiBytesArray, 6));
- assertEquals('5', Conversion.binaryBeMsb0ToHexDigit(multiBytesArray, 7));
-
- assertEquals('a', Conversion.binaryBeMsb0ToHexDigit(multiBytesArray, 8));
- assertEquals('5', Conversion.binaryBeMsb0ToHexDigit(multiBytesArray, 9));
- assertEquals('2', Conversion.binaryBeMsb0ToHexDigit(multiBytesArray, 10));
- assertEquals('9', Conversion.binaryBeMsb0ToHexDigit(multiBytesArray, 11));
- assertEquals('c', Conversion.binaryBeMsb0ToHexDigit(multiBytesArray, 12));
- assertEquals('6', Conversion.binaryBeMsb0ToHexDigit(multiBytesArray, 13));
- assertEquals('3', Conversion.binaryBeMsb0ToHexDigit(multiBytesArray, 14));
- assertEquals('1', Conversion.binaryBeMsb0ToHexDigit(multiBytesArray, 15));
-
+ 'f', Conversion.binaryToHexDigitMsb0_4bits(new boolean[]{true, true, true, true}));
+ assertThrows(IllegalArgumentException.class, () -> Conversion.binaryToHexDigitMsb0_4bits(new boolean[]{}));
}
@Test
@@ -431,115 +308,93 @@ public class ConversionTest extends AbstractLangTest {
assertEquals(Conversion.binaryToHexDigit(a, k),
Conversion.binaryBeMsb0ToHexDigit(b, k));
}
- }
- }
- }
-
- @ParameterizedTest
- @ValueSource(ints = {-1, 8, 99})
- public void binaryBeMsb0ToHexDigitPosOutsideArray(final int index) {
- assertThrows(IndexOutOfBoundsException.class,
- () -> Conversion.binaryBeMsb0ToHexDigit(new boolean[8], index));
- }
-
- /**
- * Tests {@link Conversion#intToHexDigit(int)}.
- */
- @Test
- public void testIntToHexDigit() {
- assertEquals('0', Conversion.intToHexDigit(0));
- assertEquals('1', Conversion.intToHexDigit(1));
- assertEquals('2', Conversion.intToHexDigit(2));
- assertEquals('3', Conversion.intToHexDigit(3));
- assertEquals('4', Conversion.intToHexDigit(4));
- assertEquals('5', Conversion.intToHexDigit(5));
- assertEquals('6', Conversion.intToHexDigit(6));
- assertEquals('7', Conversion.intToHexDigit(7));
- assertEquals('8', Conversion.intToHexDigit(8));
- assertEquals('9', Conversion.intToHexDigit(9));
- assertEquals('a', Conversion.intToHexDigit(10));
- assertEquals('b', Conversion.intToHexDigit(11));
- assertEquals('c', Conversion.intToHexDigit(12));
- assertEquals('d', Conversion.intToHexDigit(13));
- assertEquals('e', Conversion.intToHexDigit(14));
- assertEquals('f', Conversion.intToHexDigit(15));
- assertThrows(IllegalArgumentException.class, () -> Conversion.intToHexDigit(16));
+ }
+ }
}
/**
- * Tests {@link Conversion#intToHexDigitMsb0(int)}.
+ * Tests {@link Conversion#binaryToInt(boolean[], int, int, int, int)}.
*/
@Test
- public void testIntToHexDigitMsb0() {
- assertEquals('0', Conversion.intToHexDigitMsb0(0));
- assertEquals('8', Conversion.intToHexDigitMsb0(1));
- assertEquals('4', Conversion.intToHexDigitMsb0(2));
- assertEquals('c', Conversion.intToHexDigitMsb0(3));
- assertEquals('2', Conversion.intToHexDigitMsb0(4));
- assertEquals('a', Conversion.intToHexDigitMsb0(5));
- assertEquals('6', Conversion.intToHexDigitMsb0(6));
- assertEquals('e', Conversion.intToHexDigitMsb0(7));
- assertEquals('1', Conversion.intToHexDigitMsb0(8));
- assertEquals('9', Conversion.intToHexDigitMsb0(9));
- assertEquals('5', Conversion.intToHexDigitMsb0(10));
- assertEquals('d', Conversion.intToHexDigitMsb0(11));
- assertEquals('3', Conversion.intToHexDigitMsb0(12));
- assertEquals('b', Conversion.intToHexDigitMsb0(13));
- assertEquals('7', Conversion.intToHexDigitMsb0(14));
- assertEquals('f', Conversion.intToHexDigitMsb0(15));
- assertThrows(IllegalArgumentException.class, () -> Conversion.intToHexDigitMsb0(16));
- }
-
- static String dbgPrint(final boolean[] src) {
- final StringBuilder sb = new StringBuilder();
- for (final boolean e : src) {
- if (e) {
- sb.append("1, ");
- } else {
- sb.append("0, ");
- }
- }
- final String out = sb.toString();
- return out.substring(0, out.length() - 1);
+ public void testBinaryToInt() {
+ final boolean[] src = {
+ false, false, true, true, true, false, true, true, true, true, true, true, true,
+ false, false, false, true, true, true, true, false, false, false, false, false,
+ false, true, true, true, false, false, false, false, false, false, false, true,
+ true, true, true, true, false, false, false, false, true, false, false, true, true,
+ false, false, false, false, true, false, true, false, true, false, false, true,
+ true, false, true, true, true, false, false, false, false, true};
+ // conversion of "CDF1F0C10F12345678" by HexToBinary
+ assertEquals(0x00000000, Conversion.binaryToInt(src, 0 * 4, 0, 0, 0 * 4));
+ assertEquals(0x0000000C, Conversion.binaryToInt(src, 0 * 4, 0, 0, 1 * 4));
+ assertEquals(0x1C0F1FDC, Conversion.binaryToInt(src, 0 * 4, 0, 0, 8 * 4));
+ assertEquals(0x01C0F1FD, Conversion.binaryToInt(src, 1 * 4, 0, 0, 8 * 4));
+ assertEquals(0x12345679, Conversion.binaryToInt(src, 0 * 4, 0x12345679, 0, 0 * 4));
+ assertEquals(0x87645679, Conversion.binaryToInt(src, 15 * 4, 0x12345679, 20, 3 * 4));
}
/**
- * Tests {@link Conversion#intArrayToLong(int[], int, long, int, int)}.
+ * Tests {@link Conversion#binaryToLong(boolean[], int, long, int, int)}.
*/
@Test
- public void testIntArrayToLong() {
- final int[] src = {0xCDF1F0C1, 0x0F123456, 0x78000000};
- assertEquals(0x0000000000000000L, Conversion.intArrayToLong(src, 0, 0L, 0, 0));
- assertEquals(0x0000000000000000L, Conversion.intArrayToLong(src, 1, 0L, 0, 0));
- assertEquals(0x00000000CDF1F0C1L, Conversion.intArrayToLong(src, 0, 0L, 0, 1));
- assertEquals(0x0F123456CDF1F0C1L, Conversion.intArrayToLong(src, 0, 0L, 0, 2));
- assertEquals(0x000000000F123456L, Conversion.intArrayToLong(src, 1, 0L, 0, 1));
+ public void testBinaryToLong() {
+ final boolean[] src = {
+ false, false, true, true, true, false, true, true, true, true, true, true, true,
+ false, false, false, true, true, true, true, false, false, false, false, false,
+ false, true, true, true, false, false, false, false, false, false, false, true,
+ true, true, true, true, false, false, false, false, true, false, false, true, true,
+ false, false, false, false, true, false, true, false, true, false, false, true,
+ true, false, true, true, true, false, false, false, false, true};
+ // conversion of "CDF1F0C10F12345678" by HexToBinary
+ assertEquals(0x0000000000000000L, Conversion.binaryToLong(src, 0, 0L, 0, 0));
+ assertEquals(0x000000000000000CL, Conversion.binaryToLong(src, 0, 0L, 0, 1 * 4));
+ assertEquals(0x000000001C0F1FDCL, Conversion.binaryToLong(src, 0, 0L, 0, 8 * 4));
+ assertEquals(0x0000000001C0F1FDL, Conversion.binaryToLong(src, 1 * 4, 0L, 0, 8 * 4));
assertEquals(
- 0x123456789ABCDEF0L, Conversion.intArrayToLong(src, 0, 0x123456789ABCDEF0L, 0, 0));
+ 0x123456798ABCDEF0L, Conversion.binaryToLong(src, 0, 0x123456798ABCDEF0L, 0, 0));
assertEquals(
- 0x1234567878000000L, Conversion.intArrayToLong(src, 2, 0x123456789ABCDEF0L, 0, 1));
- // assertEquals(0x0F12345678000000L, Conversion.intsToLong(src, 1, 0x123456789ABCDEF0L, 32, 2));
+ 0x1234567876BCDEF0L,
+ Conversion.binaryToLong(src, 15 * 4, 0x123456798ABCDEF0L, 24, 3 * 4));
}
/**
- * Tests {@link Conversion#shortArrayToLong(short[], int, long, int, int)}.
+ * Tests {@link Conversion#binaryToShort(boolean[], int, short, int, int)}.
*/
@Test
- public void testShortArrayToLong() {
- final short[] src = {
- (short) 0xCDF1, (short) 0xF0C1, (short) 0x0F12, (short) 0x3456, (short) 0x7800};
- assertEquals(0x0000000000000000L, Conversion.shortArrayToLong(src, 0, 0L, 0, 0));
- assertEquals(0x000000000000CDF1L, Conversion.shortArrayToLong(src, 0, 0L, 0, 1));
- assertEquals(0x00000000F0C1CDF1L, Conversion.shortArrayToLong(src, 0, 0L, 0, 2));
- assertEquals(0x780034560F12F0C1L, Conversion.shortArrayToLong(src, 1, 0L, 0, 4));
- assertEquals(
- 0x123456789ABCDEF0L, Conversion.shortArrayToLong(src, 0, 0x123456789ABCDEF0L, 0, 0));
+ public void testBinaryToShort() {
+ final boolean[] src = {
+ false, false, true, true, true, false, true, true, true, true, true, true, true,
+ false, false, false, true, true, true, true, false, false, false, false, false,
+ false, true, true, true, false, false, false, false, false, false, false, true,
+ true, true, true, true, false, false, false, false, true, false, false, true, true,
+ false, false, false, false, true, false, true, false, true, false, false, true,
+ true, false, true, true, true, false, false, false, false, true};
+ // conversion of "CDF1F0C10F12345678" by HexToBinary
+ assertEquals((short) 0x0000, Conversion.binaryToShort(src, 0 * 4, (short) 0, 0, 0 * 4));
+ assertEquals((short) 0x000C, Conversion.binaryToShort(src, 0 * 4, (short) 0, 0, 1 * 4));
+ assertEquals((short) 0x1FDC, Conversion.binaryToShort(src, 0 * 4, (short) 0, 0, 4 * 4));
+ assertEquals((short) 0xF1FD, Conversion.binaryToShort(src, 1 * 4, (short) 0, 0, 4 * 4));
assertEquals(
- 0x123456CDF1BCDEF0L,
- Conversion.shortArrayToLong(src, 0, 0x123456789ABCDEF0L, 24, 1));
+ (short) 0x1234, Conversion.binaryToShort(src, 0 * 4, (short) 0x1234, 0, 0 * 4));
assertEquals(
- 0x123478003456DEF0L,
- Conversion.shortArrayToLong(src, 3, 0x123456789ABCDEF0L, 16, 2));
+ (short) 0x8764, Conversion.binaryToShort(src, 15 * 4, (short) 0x1234, 4, 3 * 4));
+ }
+
+ /**
+ * Tests {@link Conversion#byteArrayToInt(byte[], int, int, int, int)}.
+ */
+ @Test
+ public void testByteArrayToInt() {
+ final byte[] src = {
+ (byte) 0xCD, (byte) 0xF1, (byte) 0xF0, (byte) 0xC1, (byte) 0x0F, (byte) 0x12, (byte) 0x34,
+ (byte) 0x56, (byte) 0x78};
+ assertEquals(0x00000000, Conversion.byteArrayToInt(src, 0, 0, 0, 0));
+ assertEquals(0x000000CD, Conversion.byteArrayToInt(src, 0, 0, 0, 1));
+ assertEquals(0xC1F0F1CD, Conversion.byteArrayToInt(src, 0, 0, 0, 4));
+ assertEquals(0x0FC1F0F1, Conversion.byteArrayToInt(src, 1, 0, 0, 4));
+ assertEquals(0x12345678, Conversion.byteArrayToInt(src, 0, 0x12345678, 0, 0));
+ assertEquals(0xCD345678, Conversion.byteArrayToInt(src, 0, 0x12345678, 24, 1));
+ // assertEquals(0x56341278, Conversion.ByteArrayToInt(src, 5, 0x01234567, 8, 4));
}
/**
@@ -563,70 +418,295 @@ public class ConversionTest extends AbstractLangTest {
}
/**
- * Tests {@link Conversion#shortArrayToInt(short[], int, int, int, int)}.
+ * Tests {@link Conversion#byteArrayToShort(byte[], int, short, int, int)}.
+ */
+ @Test
+ public void testByteArrayToShort() {
+ final byte[] src = {
+ (byte) 0xCD, (byte) 0xF1, (byte) 0xF0, (byte) 0xC1, (byte) 0x0F, (byte) 0x12, (byte) 0x34,
+ (byte) 0x56, (byte) 0x78};
+ assertEquals((short) 0x0000, Conversion.byteArrayToShort(src, 0, (short) 0, 0, 0));
+ assertEquals((short) 0x00CD, Conversion.byteArrayToShort(src, 0, (short) 0, 0, 1));
+ assertEquals((short) 0xF1CD, Conversion.byteArrayToShort(src, 0, (short) 0, 0, 2));
+ assertEquals((short) 0xF0F1, Conversion.byteArrayToShort(src, 1, (short) 0, 0, 2));
+ assertEquals((short) 0x1234, Conversion.byteArrayToShort(src, 0, (short) 0x1234, 0, 0));
+ assertEquals((short) 0xCD34, Conversion.byteArrayToShort(src, 0, (short) 0x1234, 8, 1));
+ // assertEquals((short) 0x5678, Conversion.ByteArrayToShort(src, 7, (short) 0x0123, 8,
+ // 2));
+ }
+
+ /**
+ * Tests {@link Conversion#byteArrayToUuid(byte[], int)}.
+ */
+ @Test
+ public void testByteArrayToUuid() {
+ assertEquals(
+ new UUID(0xFFFFFFFFFFFFFFFFL, 0xFFFFFFFFFFFFFFFFL),
+ Conversion.byteArrayToUuid(new byte[]{
+ (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff,
+ (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff,
+ (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff}, 0));
+ assertEquals(
+ new UUID(0xFFEEDDCCBBAA9988L, 0x7766554433221100L),
+ Conversion.byteArrayToUuid(new byte[]{
+ (byte) 0x88, (byte) 0x99, (byte) 0xaa, (byte) 0xbb, (byte) 0xcc, (byte) 0xdd,
+ (byte) 0xee, (byte) 0xff, (byte) 0x00, (byte) 0x11, (byte) 0x22, (byte) 0x33,
+ (byte) 0x44, (byte) 0x55, (byte) 0x66, (byte) 0x77}, 0));
+ assertEquals(
+ new UUID(0xFFEEDDCCBBAA9988L, 0x7766554433221100L),
+ Conversion.byteArrayToUuid(new byte[]{
+ 0, 0, (byte) 0x88, (byte) 0x99, (byte) 0xaa, (byte) 0xbb, (byte) 0xcc, (byte) 0xdd,
+ (byte) 0xee, (byte) 0xff, (byte) 0x00, (byte) 0x11, (byte) 0x22, (byte) 0x33,
+ (byte) 0x44, (byte) 0x55, (byte) 0x66, (byte) 0x77}, 2));
+ }
+
+ /**
+ * Tests {@link Conversion#byteToBinary(byte, int, boolean[], int, int)}.
+ */
+ @Test
+ public void testByteToBinary() {
+ assertArrayEquals(
+ new boolean[]{}, Conversion.byteToBinary((byte) 0x00, 0, new boolean[]{}, 0, 0));
+ assertArrayEquals(
+ new boolean[]{}, Conversion.byteToBinary((byte) 0x00, 100, new boolean[]{}, 0, 0));
+ assertArrayEquals(
+ new boolean[]{}, Conversion.byteToBinary((byte) 0x00, 0, new boolean[]{}, 100, 0));
+ assertArrayEquals(
+ new boolean[69], Conversion.byteToBinary((byte) 0xEF, 0, new boolean[69], 0, 0));
+ assertArrayEquals(new boolean[]{
+ true, false, false, false, false, false, false, false, false, false, false, false,
+ false}, Conversion.byteToBinary((byte) 0x95, 0, new boolean[13], 0, 1));
+ assertArrayEquals(new boolean[]{
+ true, false, false, false, false, false, false, false, false, false, false, false,
+ false}, Conversion.byteToBinary((byte) 0x95, 0, new boolean[13], 0, 2));
+ assertArrayEquals(new boolean[]{
+ true, false, true, false, false, false, false, false, false, false, false, false,
+ false}, Conversion.byteToBinary((byte) 0x95, 0, new boolean[13], 0, 3));
+ assertArrayEquals(new boolean[]{
+ true, false, true, false, true, false, false, false, false, false, false, false,
+ false}, Conversion.byteToBinary((byte) 0x95, 0, new boolean[13], 0, 7));
+ assertArrayEquals(new boolean[]{
+ true, false, true, false, true, false, false, true, false, false, false, false,
+ false}, Conversion.byteToBinary((byte) 0x95, 0, new boolean[13], 0, 8));
+ assertArrayEquals(new boolean[]{
+ false, false, true, false, false, false, false, false, false, false, false, false,
+ false}, Conversion.byteToBinary((byte) 0x95, 0, new boolean[13], 2, 1));
+ assertArrayEquals(new boolean[]{
+ false, false, true, false, true, false, true, false, false, true, false, false,
+ false}, Conversion.byteToBinary((byte) 0x95, 0, new boolean[13], 2, 8));
+ assertArrayEquals(new boolean[]{
+ false, true, false, true, false, false, true, false, false, false, false, false,
+ false}, Conversion.byteToBinary((byte) 0x95, 1, new boolean[13], 0, 7));
+ assertArrayEquals(new boolean[]{
+ true, false, true, false, false, true, false, false, false, false, false, false,
+ false}, Conversion.byteToBinary((byte) 0x95, 2, new boolean[13], 0, 6));
+ // assertArrayEquals(new boolean[]{false, false, false, true, true, false, true, true,
+ // false, false, false, false, false}, Conversion.byteToBinary((byte) 0x95, 2, new
+ // boolean[13], 3, 7));//rejected by assertion
+ assertArrayEquals(new boolean[]{
+ false, false, false, true, false, true, false, false, true, false, false, false,
+ false}, Conversion.byteToBinary((byte) 0x95, 2, new boolean[13], 3, 6));
+ }
+
+ /**
+ * Tests {@link Conversion#byteToHex(byte, int, String, int, int)}.
+ */
+ @Test
+ public void testByteToHex() {
+ assertEquals("", Conversion.byteToHex((byte) 0x00, 0, "", 0, 0));
+ assertEquals("", Conversion.byteToHex((byte) 0x00, 100, "", 0, 0));
+ assertEquals("", Conversion.byteToHex((byte) 0x00, 0, "", 100, 0));
+ assertEquals("00000", Conversion.byteToHex((byte) 0xEF, 0, "00000", 0, 0));
+ assertEquals("f0000", Conversion.byteToHex((byte) 0xEF, 0, "00000", 0, 1));
+ assertEquals("fe000", Conversion.byteToHex((byte) 0xEF, 0, "00000", 0, 2));
+ assertEquals("000f0", Conversion.byteToHex((byte) 0xEF, 0, "00000", 3, 1));
+ assertEquals("000fe", Conversion.byteToHex((byte) 0xEF, 0, "00000", 3, 2));
+ assertEquals("70000", Conversion.byteToHex((byte) 0xEF, 1, "00000", 0, 1));
+ assertEquals("b0000", Conversion.byteToHex((byte) 0xEF, 2, "00000", 0, 1));
+ assertEquals("000df", Conversion.byteToHex((byte) 0xEF, 3, "00000", 3, 2));
+ // assertEquals("00000", Conversion.byteToHex((byte) 0xEF, 4, "00000", 3, 2));//rejected by
+ // assertion
+ assertEquals("000e0", Conversion.byteToHex((byte) 0xEF, 4, "00000", 3, 1));
+ assertEquals("fe", Conversion.byteToHex((byte) 0xEF, 0, "", 0, 2));
+ assertThrows(StringIndexOutOfBoundsException.class, () -> Conversion.byteToHex((byte) 0xEF, 0, "", 1, 2));
+ }
+
+ /**
+ * Tests {@link Conversion#hexDigitMsb0ToBinary(char)}.
+ */
+ @Test
+ public void testHexDigitMsb0ToBinary() {
+ assertArrayEquals(
+ new boolean[]{false, false, false, false}, Conversion.hexDigitMsb0ToBinary('0'));
+ assertArrayEquals(
+ new boolean[]{false, false, false, true}, Conversion.hexDigitMsb0ToBinary('1'));
+ assertArrayEquals(
+ new boolean[]{false, false, true, false}, Conversion.hexDigitMsb0ToBinary('2'));
+ assertArrayEquals(
+ new boolean[]{false, false, true, true}, Conversion.hexDigitMsb0ToBinary('3'));
+ assertArrayEquals(
+ new boolean[]{false, true, false, false}, Conversion.hexDigitMsb0ToBinary('4'));
+ assertArrayEquals(
+ new boolean[]{false, true, false, true}, Conversion.hexDigitMsb0ToBinary('5'));
+ assertArrayEquals(
+ new boolean[]{false, true, true, false}, Conversion.hexDigitMsb0ToBinary('6'));
+ assertArrayEquals(
+ new boolean[]{false, true, true, true}, Conversion.hexDigitMsb0ToBinary('7'));
+ assertArrayEquals(
+ new boolean[]{true, false, false, false}, Conversion.hexDigitMsb0ToBinary('8'));
+ assertArrayEquals(
+ new boolean[]{true, false, false, true}, Conversion.hexDigitMsb0ToBinary('9'));
+ assertArrayEquals(
+ new boolean[]{true, false, true, false}, Conversion.hexDigitMsb0ToBinary('A'));
+ assertArrayEquals(
+ new boolean[]{true, false, true, false}, Conversion.hexDigitMsb0ToBinary('a'));
+ assertArrayEquals(
+ new boolean[]{true, false, true, true}, Conversion.hexDigitMsb0ToBinary('B'));
+ assertArrayEquals(
+ new boolean[]{true, false, true, true}, Conversion.hexDigitMsb0ToBinary('b'));
+ assertArrayEquals(
+ new boolean[]{true, true, false, false}, Conversion.hexDigitMsb0ToBinary('C'));
+ assertArrayEquals(
+ new boolean[]{true, true, false, false}, Conversion.hexDigitMsb0ToBinary('c'));
+ assertArrayEquals(
+ new boolean[]{true, true, false, true}, Conversion.hexDigitMsb0ToBinary('D'));
+ assertArrayEquals(
+ new boolean[]{true, true, false, true}, Conversion.hexDigitMsb0ToBinary('d'));
+ assertArrayEquals(
+ new boolean[]{true, true, true, false}, Conversion.hexDigitMsb0ToBinary('E'));
+ assertArrayEquals(
+ new boolean[]{true, true, true, false}, Conversion.hexDigitMsb0ToBinary('e'));
+ assertArrayEquals(
+ new boolean[]{true, true, true, true}, Conversion.hexDigitMsb0ToBinary('F'));
+ assertArrayEquals(
+ new boolean[]{true, true, true, true}, Conversion.hexDigitMsb0ToBinary('f'));
+ assertThrows(IllegalArgumentException.class, () -> Conversion.hexDigitMsb0ToBinary('G'));
+ }
+
+ /**
+ * Tests {@link Conversion#hexDigitMsb0ToInt(char)}.
*/
@Test
- public void testShortArrayToInt() {
- final short[] src = {
- (short) 0xCDF1, (short) 0xF0C1, (short) 0x0F12, (short) 0x3456, (short) 0x7800};
- assertEquals(0x00000000, Conversion.shortArrayToInt(src, 0, 0, 0, 0));
- assertEquals(0x0000CDF1, Conversion.shortArrayToInt(src, 0, 0, 0, 1));
- assertEquals(0xF0C1CDF1, Conversion.shortArrayToInt(src, 0, 0, 0, 2));
- assertEquals(0x0F12F0C1, Conversion.shortArrayToInt(src, 1, 0, 0, 2));
- assertEquals(0x12345678, Conversion.shortArrayToInt(src, 0, 0x12345678, 0, 0));
- assertEquals(0xCDF15678, Conversion.shortArrayToInt(src, 0, 0x12345678, 16, 1));
- // assertEquals(0x34567800, Conversion.ShortArrayToInt(src, 3, 0x12345678, 16, 2));
+ public void testHexDigitMsb0ToInt() {
+ assertEquals(0x0, Conversion.hexDigitMsb0ToInt('0'));
+ assertEquals(0x8, Conversion.hexDigitMsb0ToInt('1'));
+ assertEquals(0x4, Conversion.hexDigitMsb0ToInt('2'));
+ assertEquals(0xC, Conversion.hexDigitMsb0ToInt('3'));
+ assertEquals(0x2, Conversion.hexDigitMsb0ToInt('4'));
+ assertEquals(0xA, Conversion.hexDigitMsb0ToInt('5'));
+ assertEquals(0x6, Conversion.hexDigitMsb0ToInt('6'));
+ assertEquals(0xE, Conversion.hexDigitMsb0ToInt('7'));
+ assertEquals(0x1, Conversion.hexDigitMsb0ToInt('8'));
+ assertEquals(0x9, Conversion.hexDigitMsb0ToInt('9'));
+ assertEquals(0x5, Conversion.hexDigitMsb0ToInt('A'));
+ assertEquals(0x5, Conversion.hexDigitMsb0ToInt('a'));
+ assertEquals(0xD, Conversion.hexDigitMsb0ToInt('B'));
+ assertEquals(0xD, Conversion.hexDigitMsb0ToInt('b'));
+ assertEquals(0x3, Conversion.hexDigitMsb0ToInt('C'));
+ assertEquals(0x3, Conversion.hexDigitMsb0ToInt('c'));
+ assertEquals(0xB, Conversion.hexDigitMsb0ToInt('D'));
+ assertEquals(0xB, Conversion.hexDigitMsb0ToInt('d'));
+ assertEquals(0x7, Conversion.hexDigitMsb0ToInt('E'));
+ assertEquals(0x7, Conversion.hexDigitMsb0ToInt('e'));
+ assertEquals(0xF, Conversion.hexDigitMsb0ToInt('F'));
+ assertEquals(0xF, Conversion.hexDigitMsb0ToInt('f'));
+ assertThrows(IllegalArgumentException.class, () -> Conversion.hexDigitMsb0ToInt('G'));
}
/**
- * Tests {@link Conversion#byteArrayToInt(byte[], int, int, int, int)}.
+ * Tests {@link Conversion#hexDigitToBinary(char)}.
*/
@Test
- public void testByteArrayToInt() {
- final byte[] src = {
- (byte) 0xCD, (byte) 0xF1, (byte) 0xF0, (byte) 0xC1, (byte) 0x0F, (byte) 0x12, (byte) 0x34,
- (byte) 0x56, (byte) 0x78};
- assertEquals(0x00000000, Conversion.byteArrayToInt(src, 0, 0, 0, 0));
- assertEquals(0x000000CD, Conversion.byteArrayToInt(src, 0, 0, 0, 1));
- assertEquals(0xC1F0F1CD, Conversion.byteArrayToInt(src, 0, 0, 0, 4));
- assertEquals(0x0FC1F0F1, Conversion.byteArrayToInt(src, 1, 0, 0, 4));
- assertEquals(0x12345678, Conversion.byteArrayToInt(src, 0, 0x12345678, 0, 0));
- assertEquals(0xCD345678, Conversion.byteArrayToInt(src, 0, 0x12345678, 24, 1));
- // assertEquals(0x56341278, Conversion.ByteArrayToInt(src, 5, 0x01234567, 8, 4));
+ public void testHexDigitToBinary() {
+ assertArrayEquals(
+ new boolean[]{false, false, false, false}, Conversion.hexDigitToBinary('0'));
+ assertArrayEquals(
+ new boolean[]{true, false, false, false}, Conversion.hexDigitToBinary('1'));
+ assertArrayEquals(
+ new boolean[]{false, true, false, false}, Conversion.hexDigitToBinary('2'));
+ assertArrayEquals(
+ new boolean[]{true, true, false, false}, Conversion.hexDigitToBinary('3'));
+ assertArrayEquals(
+ new boolean[]{false, false, true, false}, Conversion.hexDigitToBinary('4'));
+ assertArrayEquals(
+ new boolean[]{true, false, true, false}, Conversion.hexDigitToBinary('5'));
+ assertArrayEquals(
+ new boolean[]{false, true, true, false}, Conversion.hexDigitToBinary('6'));
+ assertArrayEquals(
+ new boolean[]{true, true, true, false}, Conversion.hexDigitToBinary('7'));
+ assertArrayEquals(
+ new boolean[]{false, false, false, true}, Conversion.hexDigitToBinary('8'));
+ assertArrayEquals(
+ new boolean[]{true, false, false, true}, Conversion.hexDigitToBinary('9'));
+ assertArrayEquals(
+ new boolean[]{false, true, false, true}, Conversion.hexDigitToBinary('A'));
+ assertArrayEquals(
+ new boolean[]{false, true, false, true}, Conversion.hexDigitToBinary('a'));
+ assertArrayEquals(
+ new boolean[]{true, true, false, true}, Conversion.hexDigitToBinary('B'));
+ assertArrayEquals(
+ new boolean[]{true, true, false, true}, Conversion.hexDigitToBinary('b'));
+ assertArrayEquals(
+ new boolean[]{false, false, true, true}, Conversion.hexDigitToBinary('C'));
+ assertArrayEquals(
+ new boolean[]{false, false, true, true}, Conversion.hexDigitToBinary('c'));
+ assertArrayEquals(
+ new boolean[]{true, false, true, true}, Conversion.hexDigitToBinary('D'));
+ assertArrayEquals(
+ new boolean[]{true, false, true, true}, Conversion.hexDigitToBinary('d'));
+ assertArrayEquals(
+ new boolean[]{false, true, true, true}, Conversion.hexDigitToBinary('E'));
+ assertArrayEquals(
+ new boolean[]{false, true, true, true}, Conversion.hexDigitToBinary('e'));
+ assertArrayEquals(
+ new boolean[]{true, true, true, true}, Conversion.hexDigitToBinary('F'));
+ assertArrayEquals(
+ new boolean[]{true, true, true, true}, Conversion.hexDigitToBinary('f'));
+ assertThrows(IllegalArgumentException.class, () -> Conversion.hexDigitToBinary('G'));
}
/**
- * Tests {@link Conversion#byteArrayToShort(byte[], int, short, int, int)}.
+ * Tests {@link Conversion#hexDigitToInt(char)}.
*/
@Test
- public void testByteArrayToShort() {
- final byte[] src = {
- (byte) 0xCD, (byte) 0xF1, (byte) 0xF0, (byte) 0xC1, (byte) 0x0F, (byte) 0x12, (byte) 0x34,
- (byte) 0x56, (byte) 0x78};
- assertEquals((short) 0x0000, Conversion.byteArrayToShort(src, 0, (short) 0, 0, 0));
- assertEquals((short) 0x00CD, Conversion.byteArrayToShort(src, 0, (short) 0, 0, 1));
- assertEquals((short) 0xF1CD, Conversion.byteArrayToShort(src, 0, (short) 0, 0, 2));
- assertEquals((short) 0xF0F1, Conversion.byteArrayToShort(src, 1, (short) 0, 0, 2));
- assertEquals((short) 0x1234, Conversion.byteArrayToShort(src, 0, (short) 0x1234, 0, 0));
- assertEquals((short) 0xCD34, Conversion.byteArrayToShort(src, 0, (short) 0x1234, 8, 1));
- // assertEquals((short) 0x5678, Conversion.ByteArrayToShort(src, 7, (short) 0x0123, 8,
- // 2));
+ public void testHexDigitToInt() {
+ assertEquals(0, Conversion.hexDigitToInt('0'));
+ assertEquals(1, Conversion.hexDigitToInt('1'));
+ assertEquals(2, Conversion.hexDigitToInt('2'));
+ assertEquals(3, Conversion.hexDigitToInt('3'));
+ assertEquals(4, Conversion.hexDigitToInt('4'));
+ assertEquals(5, Conversion.hexDigitToInt('5'));
+ assertEquals(6, Conversion.hexDigitToInt('6'));
+ assertEquals(7, Conversion.hexDigitToInt('7'));
+ assertEquals(8, Conversion.hexDigitToInt('8'));
+ assertEquals(9, Conversion.hexDigitToInt('9'));
+ assertEquals(10, Conversion.hexDigitToInt('A'));
+ assertEquals(10, Conversion.hexDigitToInt('a'));
+ assertEquals(11, Conversion.hexDigitToInt('B'));
+ assertEquals(11, Conversion.hexDigitToInt('b'));
+ assertEquals(12, Conversion.hexDigitToInt('C'));
+ assertEquals(12, Conversion.hexDigitToInt('c'));
+ assertEquals(13, Conversion.hexDigitToInt('D'));
+ assertEquals(13, Conversion.hexDigitToInt('d'));
+ assertEquals(14, Conversion.hexDigitToInt('E'));
+ assertEquals(14, Conversion.hexDigitToInt('e'));
+ assertEquals(15, Conversion.hexDigitToInt('F'));
+ assertEquals(15, Conversion.hexDigitToInt('f'));
+ assertThrows(IllegalArgumentException.class, () -> Conversion.hexDigitToInt('G'));
}
/**
- * Tests {@link Conversion#hexToLong(String, int, long, int, int)}.
+ * Tests {@link Conversion#hexToByte(String, int, byte, int, int)}.
*/
@Test
- public void testHexToLong() {
+ public void testHexToByte() {
final String src = "CDF1F0C10F12345678";
- assertEquals(0x0000000000000000L, Conversion.hexToLong(src, 0, 0L, 0, 0));
- assertEquals(0x000000000000000CL, Conversion.hexToLong(src, 0, 0L, 0, 1));
- assertEquals(0x000000001C0F1FDCL, Conversion.hexToLong(src, 0, 0L, 0, 8));
- assertEquals(0x0000000001C0F1FDL, Conversion.hexToLong(src, 1, 0L, 0, 8));
- assertEquals(
- 0x123456798ABCDEF0L, Conversion.hexToLong(src, 0, 0x123456798ABCDEF0L, 0, 0));
- assertEquals(
- 0x1234567876BCDEF0L, Conversion.hexToLong(src, 15, 0x123456798ABCDEF0L, 24, 3));
+ assertEquals((byte) 0x00, Conversion.hexToByte(src, 0, (byte) 0, 0, 0));
+ assertEquals((byte) 0x0C, Conversion.hexToByte(src, 0, (byte) 0, 0, 1));
+ assertEquals((byte) 0xDC, Conversion.hexToByte(src, 0, (byte) 0, 0, 2));
+ assertEquals((byte) 0xFD, Conversion.hexToByte(src, 1, (byte) 0, 0, 2));
+ assertEquals((byte) 0x34, Conversion.hexToByte(src, 0, (byte) 0x34, 0, 0));
+ assertEquals((byte) 0x84, Conversion.hexToByte(src, 17, (byte) 0x34, 4, 1));
}
/**
@@ -644,250 +724,317 @@ public class ConversionTest extends AbstractLangTest {
}
/**
- * Tests {@link Conversion#hexToShort(String, int, short, int, int)}.
- */
- @Test
- public void testHexToShort() {
- final String src = "CDF1F0C10F12345678";
- assertEquals((short) 0x0000, Conversion.hexToShort(src, 0, (short) 0, 0, 0));
- assertEquals((short) 0x000C, Conversion.hexToShort(src, 0, (short) 0, 0, 1));
- assertEquals((short) 0x1FDC, Conversion.hexToShort(src, 0, (short) 0, 0, 4));
- assertEquals((short) 0xF1FD, Conversion.hexToShort(src, 1, (short) 0, 0, 4));
- assertEquals((short) 0x1234, Conversion.hexToShort(src, 0, (short) 0x1234, 0, 0));
- assertEquals((short) 0x8764, Conversion.hexToShort(src, 15, (short) 0x1234, 4, 3));
- }
-
- /**
- * Tests {@link Conversion#hexToByte(String, int, byte, int, int)}.
+ * Tests {@link Conversion#hexToLong(String, int, long, int, int)}.
*/
@Test
- public void testHexToByte() {
+ public void testHexToLong() {
final String src = "CDF1F0C10F12345678";
- assertEquals((byte) 0x00, Conversion.hexToByte(src, 0, (byte) 0, 0, 0));
- assertEquals((byte) 0x0C, Conversion.hexToByte(src, 0, (byte) 0, 0, 1));
- assertEquals((byte) 0xDC, Conversion.hexToByte(src, 0, (byte) 0, 0, 2));
- assertEquals((byte) 0xFD, Conversion.hexToByte(src, 1, (byte) 0, 0, 2));
- assertEquals((byte) 0x34, Conversion.hexToByte(src, 0, (byte) 0x34, 0, 0));
- assertEquals((byte) 0x84, Conversion.hexToByte(src, 17, (byte) 0x34, 4, 1));
- }
-
- /**
- * Tests {@link Conversion#binaryToLong(boolean[], int, long, int, int)}.
- */
- @Test
- public void testBinaryToLong() {
- final boolean[] src = {
- false, false, true, true, true, false, true, true, true, true, true, true, true,
- false, false, false, true, true, true, true, false, false, false, false, false,
- false, true, true, true, false, false, false, false, false, false, false, true,
- true, true, true, true, false, false, false, false, true, false, false, true, true,
- false, false, false, false, true, false, true, false, true, false, false, true,
- true, false, true, true, true, false, false, false, false, true};
- // conversion of "CDF1F0C10F12345678" by HexToBinary
- assertEquals(0x0000000000000000L, Conversion.binaryToLong(src, 0, 0L, 0, 0));
- assertEquals(0x000000000000000CL, Conversion.binaryToLong(src, 0, 0L, 0, 1 * 4));
- assertEquals(0x000000001C0F1FDCL, Conversion.binaryToLong(src, 0, 0L, 0, 8 * 4));
- assertEquals(0x0000000001C0F1FDL, Conversion.binaryToLong(src, 1 * 4, 0L, 0, 8 * 4));
+ assertEquals(0x0000000000000000L, Conversion.hexToLong(src, 0, 0L, 0, 0));
+ assertEquals(0x000000000000000CL, Conversion.hexToLong(src, 0, 0L, 0, 1));
+ assertEquals(0x000000001C0F1FDCL, Conversion.hexToLong(src, 0, 0L, 0, 8));
+ assertEquals(0x0000000001C0F1FDL, Conversion.hexToLong(src, 1, 0L, 0, 8));
assertEquals(
- 0x123456798ABCDEF0L, Conversion.binaryToLong(src, 0, 0x123456798ABCDEF0L, 0, 0));
+ 0x123456798ABCDEF0L, Conversion.hexToLong(src, 0, 0x123456798ABCDEF0L, 0, 0));
assertEquals(
- 0x1234567876BCDEF0L,
- Conversion.binaryToLong(src, 15 * 4, 0x123456798ABCDEF0L, 24, 3 * 4));
+ 0x1234567876BCDEF0L, Conversion.hexToLong(src, 15, 0x123456798ABCDEF0L, 24, 3));
}
/**
- * Tests {@link Conversion#binaryToInt(boolean[], int, int, int, int)}.
+ * Tests {@link Conversion#hexToShort(String, int, short, int, int)}.
*/
- @Test
- public void testBinaryToInt() {
- final boolean[] src = {
- false, false, true, true, true, false, true, true, true, true, true, true, true,
- false, false, false, true, true, true, true, false, false, false, false, false,
- false, true, true, true, false, false, false, false, false, false, false, true,
- true, true, true, true, false, false, false, false, true, false, false, true, true,
- false, false, false, false, true, false, true, false, true, false, false, true,
- true, false, true, true, true, false, false, false, false, true};
- // conversion of "CDF1F0C10F12345678" by HexToBinary
- assertEquals(0x00000000, Conversion.binaryToInt(src, 0 * 4, 0, 0, 0 * 4));
- assertEquals(0x0000000C, Conversion.binaryToInt(src, 0 * 4, 0, 0, 1 * 4));
- assertEquals(0x1C0F1FDC, Conversion.binaryToInt(src, 0 * 4, 0, 0, 8 * 4));
- assertEquals(0x01C0F1FD, Conversion.binaryToInt(src, 1 * 4, 0, 0, 8 * 4));
- assertEquals(0x12345679, Conversion.binaryToInt(src, 0 * 4, 0x12345679, 0, 0 * 4));
- assertEquals(0x87645679, Conversion.binaryToInt(src, 15 * 4, 0x12345679, 20, 3 * 4));
+ @Test
+ public void testHexToShort() {
+ final String src = "CDF1F0C10F12345678";
+ assertEquals((short) 0x0000, Conversion.hexToShort(src, 0, (short) 0, 0, 0));
+ assertEquals((short) 0x000C, Conversion.hexToShort(src, 0, (short) 0, 0, 1));
+ assertEquals((short) 0x1FDC, Conversion.hexToShort(src, 0, (short) 0, 0, 4));
+ assertEquals((short) 0xF1FD, Conversion.hexToShort(src, 1, (short) 0, 0, 4));
+ assertEquals((short) 0x1234, Conversion.hexToShort(src, 0, (short) 0x1234, 0, 0));
+ assertEquals((short) 0x8764, Conversion.hexToShort(src, 15, (short) 0x1234, 4, 3));
}
/**
- * Tests {@link Conversion#binaryToShort(boolean[], int, short, int, int)}.
+ * Tests {@link Conversion#intArrayToLong(int[], int, long, int, int)}.
*/
@Test
- public void testBinaryToShort() {
- final boolean[] src = {
- false, false, true, true, true, false, true, true, true, true, true, true, true,
- false, false, false, true, true, true, true, false, false, false, false, false,
- false, true, true, true, false, false, false, false, false, false, false, true,
- true, true, true, true, false, false, false, false, true, false, false, true, true,
- false, false, false, false, true, false, true, false, true, false, false, true,
- true, false, true, true, true, false, false, false, false, true};
- // conversion of "CDF1F0C10F12345678" by HexToBinary
- assertEquals((short) 0x0000, Conversion.binaryToShort(src, 0 * 4, (short) 0, 0, 0 * 4));
- assertEquals((short) 0x000C, Conversion.binaryToShort(src, 0 * 4, (short) 0, 0, 1 * 4));
- assertEquals((short) 0x1FDC, Conversion.binaryToShort(src, 0 * 4, (short) 0, 0, 4 * 4));
- assertEquals((short) 0xF1FD, Conversion.binaryToShort(src, 1 * 4, (short) 0, 0, 4 * 4));
+ public void testIntArrayToLong() {
+ final int[] src = {0xCDF1F0C1, 0x0F123456, 0x78000000};
+ assertEquals(0x0000000000000000L, Conversion.intArrayToLong(src, 0, 0L, 0, 0));
+ assertEquals(0x0000000000000000L, Conversion.intArrayToLong(src, 1, 0L, 0, 0));
+ assertEquals(0x00000000CDF1F0C1L, Conversion.intArrayToLong(src, 0, 0L, 0, 1));
+ assertEquals(0x0F123456CDF1F0C1L, Conversion.intArrayToLong(src, 0, 0L, 0, 2));
+ assertEquals(0x000000000F123456L, Conversion.intArrayToLong(src, 1, 0L, 0, 1));
assertEquals(
- (short) 0x1234, Conversion.binaryToShort(src, 0 * 4, (short) 0x1234, 0, 0 * 4));
+ 0x123456789ABCDEF0L, Conversion.intArrayToLong(src, 0, 0x123456789ABCDEF0L, 0, 0));
assertEquals(
- (short) 0x8764, Conversion.binaryToShort(src, 15 * 4, (short) 0x1234, 4, 3 * 4));
+ 0x1234567878000000L, Conversion.intArrayToLong(src, 2, 0x123456789ABCDEF0L, 0, 1));
+ // assertEquals(0x0F12345678000000L, Conversion.intsToLong(src, 1, 0x123456789ABCDEF0L, 32, 2));
}
/**
- * Tests {@link Conversion#binaryToByte(boolean[], int, byte, int, int)}.
+ * Tests {@link Conversion#intToBinary(int, int, boolean[], int, int)}.
*/
@Test
- public void testBinaryToByte() {
- final boolean[] src = {
- false, false, true, true, true, false, true, true, true, true, true, true, true,
- false, false, false, true, true, true, true, false, false, false, false, false,
- false, true, true, true, false, false, false, false, false, false, false, true,
- true, true, true, true, false, false, false, false, true, false, false, true, true,
- false, false, false, false, true, false, true, false, true, false, false, true,
- true, false, true, true, true, false, false, false, false, true};
- // conversion of "CDF1F0C10F12345678" by HexToBinary
- assertEquals((byte) 0x00, Conversion.binaryToByte(src, 0 * 4, (byte) 0, 0, 0 * 4));
- assertEquals((byte) 0x0C, Conversion.binaryToByte(src, 0 * 4, (byte) 0, 0, 1 * 4));
- assertEquals((byte) 0xDC, Conversion.binaryToByte(src, 0 * 4, (byte) 0, 0, 2 * 4));
- assertEquals((byte) 0xFD, Conversion.binaryToByte(src, 1 * 4, (byte) 0, 0, 2 * 4));
- assertEquals((byte) 0x34, Conversion.binaryToByte(src, 0 * 4, (byte) 0x34, 0, 0 * 4));
- assertEquals((byte) 0x84, Conversion.binaryToByte(src, 17 * 4, (byte) 0x34, 4, 1 * 4));
+ public void testIntToBinary() {
+ assertArrayEquals(
+ new boolean[]{}, Conversion.intToBinary(0x00000000, 0, new boolean[]{}, 0, 0));
+ assertArrayEquals(
+ new boolean[]{}, Conversion.intToBinary(0x00000000, 100, new boolean[]{}, 0, 0));
+ assertArrayEquals(
+ new boolean[]{}, Conversion.intToBinary(0x00000000, 0, new boolean[]{}, 100, 0));
+ assertArrayEquals(
+ new boolean[69], Conversion.intToBinary(0x90ABCDEF, 0, new boolean[69], 0, 0));
+ assertArrayEquals(new boolean[]{
+ true, false, false, false, false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false, false, false, false, false,
+ false}, Conversion.intToBinary(0x90ABCDEF, 0, new boolean[37], 0, 1));
+ assertArrayEquals(new boolean[]{
+ true, true, false, false, false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false, false, false, false, false,
+ false}, Conversion.intToBinary(0x90ABCDEF, 0, new boolean[37], 0, 2));
+ assertArrayEquals(new boolean[]{
+ true, true, true, false, false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false, false, false, false, false,
+ false}, Conversion.intToBinary(0x90ABCDEF, 0, new boolean[37], 0, 3));
+ assertArrayEquals(
+ new boolean[]{
+ true, true, true, true, false, true, true, true, true, false, true, true,
+ false, false, true, true, true, true, false, true, false, true, false, true,
+ false, false, false, false, true, false, false, false, false, false, false,
+ false, false}, Conversion.intToBinary(0x90ABCDEF, 0, new boolean[37], 0, 31));
+ assertArrayEquals(
+ new boolean[]{
+ true, true, true, true, false, true, true, true, true, false, true, true,
+ false, false, true, true, true, true, false, true, false, true, false, true,
+ false, false, false, false, true, false, false, true, false, false, false,
+ false, false}, Conversion.intToBinary(0x90ABCDEF, 0, new boolean[37], 0, 32));
+ assertArrayEquals(new boolean[]{
+ false, false, true, false, false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false, false, false, false, false,
+ false}, Conversion.intToBinary(0x90ABCDEF, 0, new boolean[37], 2, 1));
+ assertArrayEquals(
+ new boolean[]{
+ false, false, true, true, true, true, false, true, true, true, true, false,
+ true, true, false, false, true, true, true, true, false, true, false, true,
+ false, true, false, false, false, false, true, false, false, true, false,
+ false, false}, Conversion.intToBinary(0x90ABCDEF, 0, new boolean[37], 2, 32));
+ assertArrayEquals(
+ new boolean[]{
+ true, true, true, false, true, true, true, true, false, true, true, false,
+ false, true, true, true, true, false, true, false, true, false, true, false,
+ false, false, false, true, false, false, true, false, false, false, false,
+ false, false}, Conversion.intToBinary(0x90ABCDEF, 1, new boolean[37], 0, 31));
+ assertArrayEquals(
+ new boolean[]{
+ true, true, false, true, true, true, true, false, true, true, false, false,
+ true, true, true, true, false, true, false, true, false, true, false, false,
+ false, false, true, false, false, true, false, false, false, false, false,
+ false, false}, Conversion.intToBinary(0x90ABCDEF, 2, new boolean[37], 0, 30));
+ // assertArrayEquals(new boolean[]{false, false, false, true, true, false, true,
+ // true,
+ // true, true, false, true, true, false, false, true, true, true, true, false, true,
+ // false, true, false, true, false, false, false, false, true, false, false, false,
+ // false, false, false, false}, Conversion.intToBinary(0x90ABCDEF, 2, new boolean[37],
+ // 3, 31));//rejected by assertion
+ assertArrayEquals(
+ new boolean[]{
+ false, false, false, true, true, false, true, true, true, true, false, true,
+ true, false, false, true, true, true, true, false, true, false, true, false,
+ true, false, false, false, false, true, false, false, true, false, false,
+ false, false}, Conversion.intToBinary(0x90ABCDEF, 2, new boolean[37], 3, 30));
}
/**
- * Tests {@link Conversion#longToIntArray(long, int, int[], int, int)}.
+ * Tests {@link Conversion#intToByteArray(int, int, byte[], int, int)}.
*/
@Test
- public void testLongToIntArray() {
+ public void testIntToByteArray() {
assertArrayEquals(
- new int[]{}, Conversion.longToIntArray(0x0000000000000000L, 0, new int[]{}, 0, 0));
+ new byte[]{}, Conversion.intToByteArray(0x00000000, 0, new byte[]{}, 0, 0));
assertArrayEquals(
- new int[]{}, Conversion.longToIntArray(0x0000000000000000L, 100, new int[]{}, 0, 0));
+ new byte[]{}, Conversion.intToByteArray(0x00000000, 100, new byte[]{}, 0, 0));
assertArrayEquals(
- new int[]{}, Conversion.longToIntArray(0x0000000000000000L, 0, new int[]{}, 100, 0));
+ new byte[]{}, Conversion.intToByteArray(0x00000000, 0, new byte[]{}, 100, 0));
assertArrayEquals(
- new int[]{0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF},
- Conversion.longToIntArray(0x1234567890ABCDEFL, 0, new int[]{-1, -1, -1, -1}, 0, 0));
+ new byte[]{
+ (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF,
+ (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF},
+ Conversion.intToByteArray(0x90ABCDEF, 0, new byte[]{
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, 0, 0));
assertArrayEquals(
- new int[]{0x90ABCDEF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF},
- Conversion.longToIntArray(0x1234567890ABCDEFL, 0, new int[]{-1, -1, -1, -1}, 0, 1));
+ new byte[]{
+ (byte) 0xEF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF,
+ (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF},
+ Conversion.intToByteArray(0x90ABCDEF, 0, new byte[]{
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, 0, 1));
assertArrayEquals(
- new int[]{0x90ABCDEF, 0x12345678, 0xFFFFFFFF, 0xFFFFFFFF},
- Conversion.longToIntArray(0x1234567890ABCDEFL, 0, new int[]{-1, -1, -1, -1}, 0, 2));
- // assertArrayEquals(new
- // int[]{0x90ABCDEF, 0x12345678, 0x90ABCDEF, 0x12345678}, Conversion.longToIntArray(0x1234567890ABCDEFL,
- // 0, new int[]{-1, -1, -1, -1}, 0, 4));//rejected by assertion
- // assertArrayEquals(new
- // int[]{0xFFFFFFFF, 0x90ABCDEF, 0x12345678, 0x90ABCDEF}, Conversion.longToIntArray(0x1234567890ABCDEFL,
- // 0, new int[]{-1, -1, -1, -1}, 1, 3));
+ new byte[]{
+ (byte) 0xEF, (byte) 0xCD, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF,
+ (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF},
+ Conversion.intToByteArray(0x90ABCDEF, 0, new byte[]{
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, 0, 2));
assertArrayEquals(
- new int[]{0xFFFFFFFF, 0xFFFFFFFF, 0x90ABCDEF, 0x12345678},
- Conversion.longToIntArray(0x1234567890ABCDEFL, 0, new int[]{-1, -1, -1, -1}, 2, 2));
+ new byte[]{
+ (byte) 0xEF, (byte) 0xCD, (byte) 0xAB, (byte) 0x90, (byte) 0xFF, (byte) 0xFF,
+ (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF},
+ Conversion.intToByteArray(0x90ABCDEF, 0, new byte[]{
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, 0, 4));
assertArrayEquals(
- new int[]{0xFFFFFFFF, 0xFFFFFFFF, 0x90ABCDEF, 0xFFFFFFFF},
- Conversion.longToIntArray(0x1234567890ABCDEFL, 0, new int[]{-1, -1, -1, -1}, 2, 1));
+ new byte[]{
+ (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xEF, (byte) 0xFF, (byte) 0xFF,
+ (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF},
+ Conversion.intToByteArray(0x90ABCDEF, 0, new byte[]{
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, 3, 1));
assertArrayEquals(
- new int[]{0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x90ABCDEF},
- Conversion.longToIntArray(0x1234567890ABCDEFL, 0, new int[]{-1, -1, -1, -1}, 3, 1));
+ new byte[]{
+ (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xEF, (byte) 0xCD, (byte) 0xFF,
+ (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF},
+ Conversion.intToByteArray(0x90ABCDEF, 0, new byte[]{
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, 3, 2));
assertArrayEquals(
- new int[]{0xFFFFFFFF, 0xFFFFFFFF, 0x4855E6F7, 0xFFFFFFFF},
- Conversion.longToIntArray(0x1234567890ABCDEFL, 1, new int[]{-1, -1, -1, -1}, 2, 1));
+ new byte[]{
+ (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xEF, (byte) 0xCD, (byte) 0xAB,
+ (byte) 0x90, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF},
+ Conversion.intToByteArray(0x90ABCDEF, 0, new byte[]{
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, 3, 4));
assertArrayEquals(
- new int[]{0xFFFFFFFF, 0xFFFFFFFF, 0x242AF37B, 0xFFFFFFFF},
- Conversion.longToIntArray(0x1234567890ABCDEFL, 2, new int[]{-1, -1, -1, -1}, 2, 1));
+ new byte[]{
+ (byte) 0xF7, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF,
+ (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF},
+ Conversion.intToByteArray(0x90ABCDEF, 1, new byte[]{
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, 0, 1));
assertArrayEquals(
- new int[]{0xFFFFFFFF, 0xFFFFFFFF, 0x121579BD, 0xFFFFFFFF},
- Conversion.longToIntArray(0x1234567890ABCDEFL, 3, new int[]{-1, -1, -1, -1}, 2, 1));
+ new byte[]{
+ (byte) 0x7B, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF,
+ (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF},
+ Conversion.intToByteArray(0x90ABCDEF, 2, new byte[]{
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, 0, 1));
assertArrayEquals(
- new int[]{0xFFFFFFFF, 0xFFFFFFFF, 0x890ABCDE, 0xFFFFFFFF},
- Conversion.longToIntArray(0x1234567890ABCDEFL, 4, new int[]{-1, -1, -1, -1}, 2, 1));
+ new byte[]{
+ (byte) 0xFF, (byte) 0x00, (byte) 0xFF, (byte) 0x6F, (byte) 0x5E, (byte) 0x85,
+ (byte) 0xFC, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF},
+ Conversion.intToByteArray(0x90ABCDEF, 5, new byte[]{
+ -1, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1}, 3, 4));
// assertArrayEquals(new
- // int[]{0x4855E6F7, 0x091A2B3C, 0x4855E6F7, 0x091A2B3C}, Conversion.longToIntArray(0x1234567890ABCDEFL,
- // 1, new int[]{-1, -1, -1, -1}, 0, 4));//rejected by assertion
+ // byte[]{(byte) 0xFF, (byte) 0x00, (byte) 0xFF, (byte) 0x5E, (byte) 0x85, (byte) 0xFC, (byte) 0x00, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF}, Conversion.intToByteArray(0x90ABCDEF, 13, new
+ // byte[]{-1, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1}, 3, 4));//rejected by assertion
assertArrayEquals(
- new int[]{0x091A2B3C},
- Conversion.longToIntArray(0x1234567890ABCDEFL, 33, new int[]{0}, 0, 1));
+ new byte[]{
+ (byte) 0xFF, (byte) 0x00, (byte) 0xFF, (byte) 0x5E, (byte) 0x85, (byte) 0xFC,
+ (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF},
+ Conversion.intToByteArray(0x90ABCDEF, 13, new byte[]{
+ -1, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1}, 3, 3));
+ }
+
+ /**
+ * Tests {@link Conversion#intToHex(int, int, String, int, int)}.
+ */
+ @Test
+ public void testIntToHex() {
+ assertEquals("", Conversion.intToHex(0x00000000, 0, "", 0, 0));
+ assertEquals("", Conversion.intToHex(0x00000000, 100, "", 0, 0));
+ assertEquals("", Conversion.intToHex(0x00000000, 0, "", 100, 0));
+ assertEquals(
+ "ffffffffffffffffffffffff",
+ Conversion.intToHex(0x90ABCDEF, 0, "ffffffffffffffffffffffff", 0, 0));
+ assertEquals(
+ "3fffffffffffffffffffffff",
+ Conversion.intToHex(0x90ABCDE3, 0, "ffffffffffffffffffffffff", 0, 1));
+ assertEquals(
+ "feffffffffffffffffffffff",
+ Conversion.intToHex(0x90ABCDEF, 0, "ffffffffffffffffffffffff", 0, 2));
+ assertEquals(
+ "fedcffffffffffffffffffff",
+ Conversion.intToHex(0x90ABCDEF, 0, "ffffffffffffffffffffffff", 0, 4));
+ assertEquals(
+ "fedcba0fffffffffffffffff",
+ Conversion.intToHex(0x90ABCDEF, 0, "ffffffffffffffffffffffff", 0, 7));
+ assertEquals(
+ "fedcba09ffffffffffffffff",
+ Conversion.intToHex(0x90ABCDEF, 0, "ffffffffffffffffffffffff", 0, 8));
+ assertEquals(
+ "fff3ffffffffffffffffffff",
+ Conversion.intToHex(0x90ABCDE3, 0, "ffffffffffffffffffffffff", 3, 1));
+ assertEquals(
+ "ffffefffffffffffffffffff",
+ Conversion.intToHex(0x90ABCDEF, 0, "ffffffffffffffffffffffff", 3, 2));
+ assertEquals(
+ "ffffedcfffffffffffffffff",
+ Conversion.intToHex(0x90ABCDEF, 0, "ffffffffffffffffffffffff", 3, 4));
+ assertEquals(
+ "ffffedcba0ffffffffffffff",
+ Conversion.intToHex(0x90ABCDEF, 0, "ffffffffffffffffffffffff", 3, 7));
+ assertEquals(
+ "ffffedcba09fffffffffffff",
+ Conversion.intToHex(0x90ABCDEF, 0, "ffffffffffffffffffffffff", 3, 8));
+ assertEquals(
+ "7fffffffffffffffffffffff",
+ Conversion.intToHex(0x90ABCDEF, 1, "ffffffffffffffffffffffff", 0, 1));
+ assertEquals(
+ "bfffffffffffffffffffffff",
+ Conversion.intToHex(0x90ABCDEF, 2, "ffffffffffffffffffffffff", 0, 1));
+ assertEquals(
+ "fffdb97512ffffffffffffff",
+ Conversion.intToHex(0x90ABCDEF, 3, "ffffffffffffffffffffffff", 3, 8));
+ // assertEquals("ffffffffffffffffffffffff", Conversion.intToHex(0x90ABCDEF,
+ // 4, "ffffffffffffffffffffffff", 3, 8));//rejected by assertion
+ assertEquals(
+ "fffedcba09ffffffffffffff",
+ Conversion.intToHex(0x90ABCDEF, 4, "ffffffffffffffffffffffff", 3, 7));
+ assertEquals("fedcba09", Conversion.intToHex(0x90ABCDEF, 0, "", 0, 8));
+ assertThrows(StringIndexOutOfBoundsException.class, () -> Conversion.intToHex(0x90ABCDEF, 0, "", 1, 8));
}
/**
- * Tests {@link Conversion#longToShortArray(long, int, short[], int, int)}.
+ * Tests {@link Conversion#intToHexDigit(int)}.
*/
@Test
- public void testLongToShortArray() {
- assertArrayEquals(
- new short[]{},
- Conversion.longToShortArray(0x0000000000000000L, 0, new short[]{}, 0, 0));
- assertArrayEquals(
- new short[]{},
- Conversion.longToShortArray(0x0000000000000000L, 100, new short[]{}, 0, 0));
- assertArrayEquals(
- new short[]{},
- Conversion.longToShortArray(0x0000000000000000L, 0, new short[]{}, 100, 0));
- assertArrayEquals(
- new short[]{(short) 0xFFFF, (short) 0xFFFF, (short) 0xFFFF, (short) 0xFFFF},
- Conversion.longToShortArray(
- 0x1234567890ABCDEFL, 0, new short[]{-1, -1, -1, -1}, 0, 0));
- assertArrayEquals(
- new short[]{(short) 0xCDEF, (short) 0xFFFF, (short) 0xFFFF, (short) 0xFFFF},
- Conversion.longToShortArray(
- 0x1234567890ABCDEFL, 0, new short[]{-1, -1, -1, -1}, 0, 1));
- assertArrayEquals(
- new short[]{(short) 0xCDEF, (short) 0x90AB, (short) 0xFFFF, (short) 0xFFFF},
- Conversion.longToShortArray(
- 0x1234567890ABCDEFL, 0, new short[]{-1, -1, -1, -1}, 0, 2));
- assertArrayEquals(
- new short[]{(short) 0xCDEF, (short) 0x90AB, (short) 0x5678, (short) 0xFFFF},
- Conversion.longToShortArray(
- 0x1234567890ABCDEFL, 0, new short[]{-1, -1, -1, -1}, 0, 3));
- assertArrayEquals(
- new short[]{(short) 0xCDEF, (short) 0x90AB, (short) 0x5678, (short) 0x1234},
- Conversion.longToShortArray(
- 0x1234567890ABCDEFL, 0, new short[]{-1, -1, -1, -1}, 0, 4));
- assertArrayEquals(
- new short[]{(short) 0xFFFF, (short) 0xCDEF, (short) 0x90AB, (short) 0x5678},
- Conversion.longToShortArray(
- 0x1234567890ABCDEFL, 0, new short[]{-1, -1, -1, -1}, 1, 3));
- assertArrayEquals(
- new short[]{(short) 0xFFFF, (short) 0xFFFF, (short) 0xCDEF, (short) 0x90AB},
- Conversion.longToShortArray(
- 0x1234567890ABCDEFL, 0, new short[]{-1, -1, -1, -1}, 2, 2));
- assertArrayEquals(
- new short[]{(short) 0xFFFF, (short) 0xFFFF, (short) 0xCDEF, (short) 0xFFFF},
- Conversion.longToShortArray(
- 0x1234567890ABCDEFL, 0, new short[]{-1, -1, -1, -1}, 2, 1));
- assertArrayEquals(
- new short[]{(short) 0xFFFF, (short) 0xFFFF, (short) 0xFFFF, (short) 0xCDEF},
- Conversion.longToShortArray(
- 0x1234567890ABCDEFL, 0, new short[]{-1, -1, -1, -1}, 3, 1));
- assertArrayEquals(
- new short[]{(short) 0xFFFF, (short) 0xFFFF, (short) 0xE6F7, (short) 0xFFFF},
- Conversion.longToShortArray(
- 0x1234567890ABCDEFL, 1, new short[]{-1, -1, -1, -1}, 2, 1));
- assertArrayEquals(
- new short[]{(short) 0xFFFF, (short) 0xFFFF, (short) 0xF37B, (short) 0xFFFF},
- Conversion.longToShortArray(
- 0x1234567890ABCDEFL, 2, new short[]{-1, -1, -1, -1}, 2, 1));
- assertArrayEquals(
- new short[]{(short) 0xFFFF, (short) 0xFFFF, (short) 0x79BD, (short) 0xFFFF},
- Conversion.longToShortArray(
- 0x1234567890ABCDEFL, 3, new short[]{-1, -1, -1, -1}, 2, 1));
- assertArrayEquals(
- new short[]{(short) 0xFFFF, (short) 0xFFFF, (short) 0xBCDE, (short) 0xFFFF},
- Conversion.longToShortArray(
- 0x1234567890ABCDEFL, 4, new short[]{-1, -1, -1, -1}, 2, 1));
- assertArrayEquals(
- new short[]{(short) 0xE6F7, (short) 0x4855, (short) 0x2B3C, (short) 0x091A},
- Conversion.longToShortArray(
- 0x1234567890ABCDEFL, 1, new short[]{-1, -1, -1, -1}, 0, 4));
- assertArrayEquals(
- new short[]{(short) 0x2B3C},
- Conversion.longToShortArray(0x1234567890ABCDEFL, 33, new short[]{0}, 0, 1));
+ public void testIntToHexDigit() {
+ assertEquals('0', Conversion.intToHexDigit(0));
+ assertEquals('1', Conversion.intToHexDigit(1));
+ assertEquals('2', Conversion.intToHexDigit(2));
+ assertEquals('3', Conversion.intToHexDigit(3));
+ assertEquals('4', Conversion.intToHexDigit(4));
+ assertEquals('5', Conversion.intToHexDigit(5));
+ assertEquals('6', Conversion.intToHexDigit(6));
+ assertEquals('7', Conversion.intToHexDigit(7));
+ assertEquals('8', Conversion.intToHexDigit(8));
+ assertEquals('9', Conversion.intToHexDigit(9));
+ assertEquals('a', Conversion.intToHexDigit(10));
+ assertEquals('b', Conversion.intToHexDigit(11));
+ assertEquals('c', Conversion.intToHexDigit(12));
+ assertEquals('d', Conversion.intToHexDigit(13));
+ assertEquals('e', Conversion.intToHexDigit(14));
+ assertEquals('f', Conversion.intToHexDigit(15));
+ assertThrows(IllegalArgumentException.class, () -> Conversion.intToHexDigit(16));
+ }
+
+ /**
+ * Tests {@link Conversion#intToHexDigitMsb0(int)}.
+ */
+ @Test
+ public void testIntToHexDigitMsb0() {
+ assertEquals('0', Conversion.intToHexDigitMsb0(0));
+ assertEquals('8', Conversion.intToHexDigitMsb0(1));
+ assertEquals('4', Conversion.intToHexDigitMsb0(2));
+ assertEquals('c', Conversion.intToHexDigitMsb0(3));
+ assertEquals('2', Conversion.intToHexDigitMsb0(4));
+ assertEquals('a', Conversion.intToHexDigitMsb0(5));
+ assertEquals('6', Conversion.intToHexDigitMsb0(6));
+ assertEquals('e', Conversion.intToHexDigitMsb0(7));
+ assertEquals('1', Conversion.intToHexDigitMsb0(8));
+ assertEquals('9', Conversion.intToHexDigitMsb0(9));
+ assertEquals('5', Conversion.intToHexDigitMsb0(10));
+ assertEquals('d', Conversion.intToHexDigitMsb0(11));
+ assertEquals('3', Conversion.intToHexDigitMsb0(12));
+ assertEquals('b', Conversion.intToHexDigitMsb0(13));
+ assertEquals('7', Conversion.intToHexDigitMsb0(14));
+ assertEquals('f', Conversion.intToHexDigitMsb0(15));
+ assertThrows(IllegalArgumentException.class, () -> Conversion.intToHexDigitMsb0(16));
}
/**
@@ -951,6 +1098,129 @@ public class ConversionTest extends AbstractLangTest {
Conversion.intToShortArray(0x12345678, 17, new short[]{0}, 0, 1));
}
+ /**
+ * Tests {@link Conversion#longToBinary(long, int, boolean[], int, int)}.
+ */
+ @Test
+ public void testLongToBinary() {
+ assertArrayEquals(
+ new boolean[]{},
+ Conversion.longToBinary(0x0000000000000000L, 0, new boolean[]{}, 0, 0));
+ assertArrayEquals(
+ new boolean[]{},
+ Conversion.longToBinary(0x0000000000000000L, 100, new boolean[]{}, 0, 0));
+ assertArrayEquals(
+ new boolean[]{},
+ Conversion.longToBinary(0x0000000000000000L, 0, new boolean[]{}, 100, 0));
+ assertArrayEquals(
+ new boolean[69],
+ Conversion.longToBinary(0x1234567890ABCDEFL, 0, new boolean[69], 0, 0));
+
+ assertArrayEquals(
+ new boolean[]{
+ true, false, false, false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false, false, false, false,
+ false, false, false},
+ Conversion.longToBinary(0x1234567890ABCDEFL, 0, new boolean[69], 0, 1));
+ assertArrayEquals(
+ new boolean[]{
+ true, true, false, false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false, false, false, false,
+ false, false, false},
+ Conversion.longToBinary(0x1234567890ABCDEFL, 0, new boolean[69], 0, 2));
+ assertArrayEquals(
+ new boolean[]{
+ true, true, true, false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false, false, false, false,
+ false, false, false},
+ Conversion.longToBinary(0x1234567890ABCDEFL, 0, new boolean[69], 0, 3));
+ assertArrayEquals(
+ new boolean[]{
+ true, true, true, true, false, true, true, true, true, false, true, true,
+ false, false, true, true, true, true, false, true, false, true, false, true,
+ false, false, false, false, true, false, false, true, false, false, false,
+ true, true, true, true, false, false, true, true, false, true, false, true,
+ false, false, false, true, false, true, true, false, false, false, true, false,
+ false, true, false, false, false, false, false, false, false, false},
+ Conversion.longToBinary(0x1234567890ABCDEFL, 0, new boolean[69], 0, 63));
+ assertArrayEquals(
+ new boolean[]{
+ true, true, true, true, false, true, true, true, true, false, true, true,
+ false, false, true, true, true, true, false, true, false, true, false, true,
+ false, false, false, false, true, false, false, true, false, false, false,
+ true, true, true, true, false, false, true, true, false, true, false, true,
+ false, false, false, true, false, true, true, false, false, false, true, false,
+ false, true, false, false, false, false, false, false, false, false},
+ Conversion.longToBinary(0x1234567890ABCDEFL, 0, new boolean[69], 0, 64));
+ assertArrayEquals(
+ new boolean[]{
+ false, false, true, false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false, false, false, false,
+ false, false, false, false, false, false, false, false, false, false, false,
+ false, false, false},
+ Conversion.longToBinary(0x1234567890ABCDEFL, 0, new boolean[69], 2, 1));
+ assertArrayEquals(
+ new boolean[]{
+ false, false, true, true, true, true, false, true, true, true, true, false,
+ true, true, false, false, true, true, true, true, false, true, false, true,
+ false, true, false, false, false, false, true, false, false, true, false,
+ false, false, true, true, true, true, false, false, true, true, false, true,
+ false, true, false, false, false, true, false, true, true, false, false, false,
+ true, false, false, true, false, false, false, false, false, false},
+ Conversion.longToBinary(0x1234567890ABCDEFL, 0, new boolean[69], 2, 64));
+ assertArrayEquals(
+ new boolean[]{
+ true, true, true, false, true, true, true, true, false, true, true, false,
+ false, true, true, true, true, false, true, false, true, false, true, false,
+ false, false, false, true, false, false, true, false, false, false, true, true,
+ true, true, false, false, true, true, false, true, false, true, false, false,
+ false, true, false, true, true, false, false, false, true, false, false, true,
+ false, false, false, false, false, false, false, false, false},
+ Conversion.longToBinary(0x1234567890ABCDEFL, 1, new boolean[69], 0, 63));
+ assertArrayEquals(
+ new boolean[]{
+ true, true, false, true, true, true, true, false, true, true, false, false,
+ true, true, true, true, false, true, false, true, false, true, false, false,
+ false, false, true, false, false, true, false, false, false, true, true, true,
+ true, false, false, true, true, false, true, false, true, false, false, false,
+ true, false, true, true, false, false, false, true, false, false, true, false,
+ false, false, false, false, false, false, false, false, false},
+ Conversion.longToBinary(0x1234567890ABCDEFL, 2, new boolean[69], 0, 62));
+
+ // assertArrayEquals(new boolean[]{false, false, false, true, true, false, true, true,
+ // true, true, false, true, true, false, false, true, true, true, true, false, true,
+ // false, true, false, true, false, false, false, false, true, false, false, true,
+ // false, false, false, true, true, true, true, false, false, true, true, false, true,
+ // false, true, false, false, false, true, false, true, true, false, false, false, true,
+ // false, false, true, false, false, false
+ // , false, false, false, false}, Conversion.longToBinary(0x1234567890ABCDEFL, 2, new
+ // boolean[69], 3, 63));//rejected by assertion
+ assertArrayEquals(
+ new boolean[]{
+ false, false, false, true, true, false, true, true, true, true, false, true,
+ true, false, false, true, true, true, true, false, true, false, true, false,
+ true, false, false, false, false, true, false, false, true, false, false,
+ false, true, true, true, true, false, false, true, true, false, true, false,
+ true, false, false, false, true, false, true, true, false, false, false, true,
+ false, false, true, false, false, false, false, false, false, false},
+ Conversion.longToBinary(0x1234567890ABCDEFL, 2, new boolean[69], 3, 62));
+ }
+
/**
* Tests {@link Conversion#longToByteArray(long, int, byte[], int, int)}.
*/
@@ -1060,149 +1330,6 @@ public class ConversionTest extends AbstractLangTest {
-1, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1}, 3, 7));
}
- /**
- * Tests {@link Conversion#intToByteArray(int, int, byte[], int, int)}.
- */
- @Test
- public void testIntToByteArray() {
- assertArrayEquals(
- new byte[]{}, Conversion.intToByteArray(0x00000000, 0, new byte[]{}, 0, 0));
- assertArrayEquals(
- new byte[]{}, Conversion.intToByteArray(0x00000000, 100, new byte[]{}, 0, 0));
- assertArrayEquals(
- new byte[]{}, Conversion.intToByteArray(0x00000000, 0, new byte[]{}, 100, 0));
- assertArrayEquals(
- new byte[]{
- (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF,
- (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF},
- Conversion.intToByteArray(0x90ABCDEF, 0, new byte[]{
- -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, 0, 0));
- assertArrayEquals(
- new byte[]{
- (byte) 0xEF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF,
- (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF},
- Conversion.intToByteArray(0x90ABCDEF, 0, new byte[]{
- -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, 0, 1));
- assertArrayEquals(
- new byte[]{
- (byte) 0xEF, (byte) 0xCD, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF,
- (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF},
- Conversion.intToByteArray(0x90ABCDEF, 0, new byte[]{
- -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, 0, 2));
- assertArrayEquals(
- new byte[]{
- (byte) 0xEF, (byte) 0xCD, (byte) 0xAB, (byte) 0x90, (byte) 0xFF, (byte) 0xFF,
- (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF},
- Conversion.intToByteArray(0x90ABCDEF, 0, new byte[]{
- -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, 0, 4));
- assertArrayEquals(
- new byte[]{
- (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xEF, (byte) 0xFF, (byte) 0xFF,
- (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF},
- Conversion.intToByteArray(0x90ABCDEF, 0, new byte[]{
- -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, 3, 1));
- assertArrayEquals(
- new byte[]{
- (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xEF, (byte) 0xCD, (byte) 0xFF,
- (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF},
- Conversion.intToByteArray(0x90ABCDEF, 0, new byte[]{
- -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, 3, 2));
- assertArrayEquals(
- new byte[]{
- (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xEF, (byte) 0xCD, (byte) 0xAB,
- (byte) 0x90, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF},
- Conversion.intToByteArray(0x90ABCDEF, 0, new byte[]{
- -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, 3, 4));
- assertArrayEquals(
- new byte[]{
- (byte) 0xF7, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF,
- (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF},
- Conversion.intToByteArray(0x90ABCDEF, 1, new byte[]{
- -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, 0, 1));
- assertArrayEquals(
- new byte[]{
- (byte) 0x7B, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF,
- (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF},
- Conversion.intToByteArray(0x90ABCDEF, 2, new byte[]{
- -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, 0, 1));
- assertArrayEquals(
- new byte[]{
- (byte) 0xFF, (byte) 0x00, (byte) 0xFF, (byte) 0x6F, (byte) 0x5E, (byte) 0x85,
- (byte) 0xFC, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF},
- Conversion.intToByteArray(0x90ABCDEF, 5, new byte[]{
- -1, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1}, 3, 4));
- // assertArrayEquals(new
- // byte[]{(byte) 0xFF, (byte) 0x00, (byte) 0xFF, (byte) 0x5E, (byte) 0x85, (byte) 0xFC, (byte) 0x00, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF}, Conversion.intToByteArray(0x90ABCDEF, 13, new
- // byte[]{-1, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1}, 3, 4));//rejected by assertion
- assertArrayEquals(
- new byte[]{
- (byte) 0xFF, (byte) 0x00, (byte) 0xFF, (byte) 0x5E, (byte) 0x85, (byte) 0xFC,
- (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF},
- Conversion.intToByteArray(0x90ABCDEF, 13, new byte[]{
- -1, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1}, 3, 3));
- }
-
- /**
- * Tests {@link Conversion#shortToByteArray(short, int, byte[], int, int)}.
- */
- @Test
- public void testShortToByteArray() {
- assertArrayEquals(
- new byte[]{}, Conversion.shortToByteArray((short) 0x0000, 0, new byte[]{}, 0, 0));
- assertArrayEquals(
- new byte[]{}, Conversion.shortToByteArray((short) 0x0000, 100, new byte[]{}, 0, 0));
- assertArrayEquals(
- new byte[]{}, Conversion.shortToByteArray((short) 0x0000, 0, new byte[]{}, 100, 0));
- assertArrayEquals(
- new byte[]{
- (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF,
- (byte) 0xFF}, Conversion.shortToByteArray((short) 0xCDEF, 0, new byte[]{
- -1, -1, -1, -1, -1, -1, -1}, 0, 0));
- assertArrayEquals(
- new byte[]{
- (byte) 0xEF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF,
- (byte) 0xFF}, Conversion.shortToByteArray((short) 0xCDEF, 0, new byte[]{
- -1, -1, -1, -1, -1, -1, -1}, 0, 1));
- assertArrayEquals(
- new byte[]{
- (byte) 0xEF, (byte) 0xCD, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF,
- (byte) 0xFF}, Conversion.shortToByteArray((short) 0xCDEF, 0, new byte[]{
- -1, -1, -1, -1, -1, -1, -1}, 0, 2));
- assertArrayEquals(
- new byte[]{
- (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xEF, (byte) 0xFF, (byte) 0xFF,
- (byte) 0xFF}, Conversion.shortToByteArray((short) 0xCDEF, 0, new byte[]{
- -1, -1, -1, -1, -1, -1, -1}, 3, 1));
- assertArrayEquals(
- new byte[]{
- (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xEF, (byte) 0xCD, (byte) 0xFF,
- (byte) 0xFF}, Conversion.shortToByteArray((short) 0xCDEF, 0, new byte[]{
- -1, -1, -1, -1, -1, -1, -1}, 3, 2));
- assertArrayEquals(
- new byte[]{
- (byte) 0xF7, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF,
- (byte) 0xFF}, Conversion.shortToByteArray((short) 0xCDEF, 1, new byte[]{
- -1, -1, -1, -1, -1, -1, -1}, 0, 1));
- assertArrayEquals(
- new byte[]{
- (byte) 0x7B, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF,
- (byte) 0xFF}, Conversion.shortToByteArray((short) 0xCDEF, 2, new byte[]{
- -1, -1, -1, -1, -1, -1, -1}, 0, 1));
- assertArrayEquals(
- new byte[]{
- (byte) 0xFF, (byte) 0x00, (byte) 0xFF, (byte) 0x6F, (byte) 0xFE, (byte) 0xFF,
- (byte) 0xFF}, Conversion.shortToByteArray((short) 0xCDEF, 5, new byte[]{
- -1, 0, -1, -1, -1, -1, -1}, 3, 2));
- // assertArrayEquals(new
- // byte[]{(byte) 0xFF, (byte) 0x00, (byte) 0xFF, (byte) 0x5E, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF}, Conversion.shortToByteArray((short) 0xCDEF, 13, new
- // byte[]{-1, 0, -1, -1, -1, -1, -1}, 3, 2));//rejected by assertion
- assertArrayEquals(
- new byte[]{
- (byte) 0xFF, (byte) 0x00, (byte) 0xFF, (byte) 0xFE, (byte) 0xFF, (byte) 0xFF,
- (byte) 0xFF}, Conversion.shortToByteArray((short) 0xCDEF, 13, new byte[]{
- -1, 0, -1, -1, -1, -1, -1}, 3, 1));
- }
-
/**
* Tests {@link Conversion#longToHex(long, int, String, int, int)}.
*/
@@ -1239,357 +1366,195 @@ public class ConversionTest extends AbstractLangTest {
"ffffedcfffffffffffffffff",
Conversion.longToHex(0x1234567890ABCDEFL, 0, "ffffffffffffffffffffffff", 3, 4));
assertEquals(
- "ffffedcba098765432ffffff",
- Conversion.longToHex(0x1234567890ABCDEFL, 0, "ffffffffffffffffffffffff", 3, 15));
- assertEquals(
- "ffffedcba0987654321fffff",
- Conversion.longToHex(0x1234567890ABCDEFL, 0, "ffffffffffffffffffffffff", 3, 16));
- assertEquals(
- "7fffffffffffffffffffffff",
- Conversion.longToHex(0x1234567890ABCDEFL, 1, "ffffffffffffffffffffffff", 0, 1));
- assertEquals(
- "bfffffffffffffffffffffff",
- Conversion.longToHex(0x1234567890ABCDEFL, 2, "ffffffffffffffffffffffff", 0, 1));
- assertEquals(
- "fffdb975121fca86420fffff",
- Conversion.longToHex(0x1234567890ABCDEFL, 3, "ffffffffffffffffffffffff", 3, 16));
- // assertEquals("ffffffffffffffffffffffff", Conversion.longToHex(0x1234567890ABCDEFL, 4, "ffffffffffffffffffffffff", 3, 16));//rejected
- // by assertion
- assertEquals(
- "fffedcba0987654321ffffff",
- Conversion.longToHex(0x1234567890ABCDEFL, 4, "ffffffffffffffffffffffff", 3, 15));
- assertEquals(
- "fedcba0987654321", Conversion.longToHex(0x1234567890ABCDEFL, 0, "", 0, 16));
- assertThrows(StringIndexOutOfBoundsException.class, () -> Conversion.longToHex(0x1234567890ABCDEFL, 0, "", 1, 8));
- }
-
- /**
- * Tests {@link Conversion#intToHex(int, int, String, int, int)}.
- */
- @Test
- public void testIntToHex() {
- assertEquals("", Conversion.intToHex(0x00000000, 0, "", 0, 0));
- assertEquals("", Conversion.intToHex(0x00000000, 100, "", 0, 0));
- assertEquals("", Conversion.intToHex(0x00000000, 0, "", 100, 0));
- assertEquals(
- "ffffffffffffffffffffffff",
- Conversion.intToHex(0x90ABCDEF, 0, "ffffffffffffffffffffffff", 0, 0));
- assertEquals(
- "3fffffffffffffffffffffff",
- Conversion.intToHex(0x90ABCDE3, 0, "ffffffffffffffffffffffff", 0, 1));
- assertEquals(
- "feffffffffffffffffffffff",
- Conversion.intToHex(0x90ABCDEF, 0, "ffffffffffffffffffffffff", 0, 2));
- assertEquals(
- "fedcffffffffffffffffffff",
- Conversion.intToHex(0x90ABCDEF, 0, "ffffffffffffffffffffffff", 0, 4));
- assertEquals(
- "fedcba0fffffffffffffffff",
- Conversion.intToHex(0x90ABCDEF, 0, "ffffffffffffffffffffffff", 0, 7));
- assertEquals(
- "fedcba09ffffffffffffffff",
- Conversion.intToHex(0x90ABCDEF, 0, "ffffffffffffffffffffffff", 0, 8));
- assertEquals(
- "fff3ffffffffffffffffffff",
- Conversion.intToHex(0x90ABCDE3, 0, "ffffffffffffffffffffffff", 3, 1));
- assertEquals(
- "ffffefffffffffffffffffff",
- Conversion.intToHex(0x90ABCDEF, 0, "ffffffffffffffffffffffff", 3, 2));
- assertEquals(
- "ffffedcfffffffffffffffff",
- Conversion.intToHex(0x90ABCDEF, 0, "ffffffffffffffffffffffff", 3, 4));
- assertEquals(
- "ffffedcba0ffffffffffffff",
- Conversion.intToHex(0x90ABCDEF, 0, "ffffffffffffffffffffffff", 3, 7));
- assertEquals(
- "ffffedcba09fffffffffffff",
- Conversion.intToHex(0x90ABCDEF, 0, "ffffffffffffffffffffffff", 3, 8));
- assertEquals(
- "7fffffffffffffffffffffff",
- Conversion.intToHex(0x90ABCDEF, 1, "ffffffffffffffffffffffff", 0, 1));
- assertEquals(
- "bfffffffffffffffffffffff",
- Conversion.intToHex(0x90ABCDEF, 2, "ffffffffffffffffffffffff", 0, 1));
- assertEquals(
- "fffdb97512ffffffffffffff",
- Conversion.intToHex(0x90ABCDEF, 3, "ffffffffffffffffffffffff", 3, 8));
- // assertEquals("ffffffffffffffffffffffff", Conversion.intToHex(0x90ABCDEF,
- // 4, "ffffffffffffffffffffffff", 3, 8));//rejected by assertion
- assertEquals(
- "fffedcba09ffffffffffffff",
- Conversion.intToHex(0x90ABCDEF, 4, "ffffffffffffffffffffffff", 3, 7));
- assertEquals("fedcba09", Conversion.intToHex(0x90ABCDEF, 0, "", 0, 8));
- assertThrows(StringIndexOutOfBoundsException.class, () -> Conversion.intToHex(0x90ABCDEF, 0, "", 1, 8));
- }
-
- /**
- * Tests {@link Conversion#shortToHex(short, int, String, int, int)}.
- */
- @Test
- public void testShortToHex() {
- assertEquals("", Conversion.shortToHex((short) 0x0000, 0, "", 0, 0));
- assertEquals("", Conversion.shortToHex((short) 0x0000, 100, "", 0, 0));
- assertEquals("", Conversion.shortToHex((short) 0x0000, 0, "", 100, 0));
- assertEquals(
- "ffffffffffffffffffffffff",
- Conversion.shortToHex((short) 0xCDEF, 0, "ffffffffffffffffffffffff", 0, 0));
- assertEquals(
- "3fffffffffffffffffffffff",
- Conversion.shortToHex((short) 0xCDE3, 0, "ffffffffffffffffffffffff", 0, 1));
- assertEquals(
- "feffffffffffffffffffffff",
- Conversion.shortToHex((short) 0xCDEF, 0, "ffffffffffffffffffffffff", 0, 2));
- assertEquals(
- "fedfffffffffffffffffffff",
- Conversion.shortToHex((short) 0xCDEF, 0, "ffffffffffffffffffffffff", 0, 3));
- assertEquals(
- "fedcffffffffffffffffffff",
- Conversion.shortToHex((short) 0xCDEF, 0, "ffffffffffffffffffffffff", 0, 4));
- assertEquals(
- "fff3ffffffffffffffffffff",
- Conversion.shortToHex((short) 0xCDE3, 0, "ffffffffffffffffffffffff", 3, 1));
+ "ffffedcba098765432ffffff",
+ Conversion.longToHex(0x1234567890ABCDEFL, 0, "ffffffffffffffffffffffff", 3, 15));
assertEquals(
- "ffffefffffffffffffffffff",
- Conversion.shortToHex((short) 0xCDEF, 0, "ffffffffffffffffffffffff", 3, 2));
+ "ffffedcba0987654321fffff",
+ Conversion.longToHex(0x1234567890ABCDEFL, 0, "ffffffffffffffffffffffff", 3, 16));
assertEquals(
"7fffffffffffffffffffffff",
- Conversion.shortToHex((short) 0xCDEF, 1, "ffffffffffffffffffffffff", 0, 1));
+ Conversion.longToHex(0x1234567890ABCDEFL, 1, "ffffffffffffffffffffffff", 0, 1));
assertEquals(
"bfffffffffffffffffffffff",
- Conversion.shortToHex((short) 0xCDEF, 2, "ffffffffffffffffffffffff", 0, 1));
+ Conversion.longToHex(0x1234567890ABCDEFL, 2, "ffffffffffffffffffffffff", 0, 1));
assertEquals(
- "fffdb9ffffffffffffffffff",
- Conversion.shortToHex((short) 0xCDEF, 3, "ffffffffffffffffffffffff", 3, 4));
- // assertEquals("ffffffffffffffffffffffff", Conversion.shortToHex((short) 0xCDEF,
- // 4, "ffffffffffffffffffffffff", 3, 4));//rejected by assertion
+ "fffdb975121fca86420fffff",
+ Conversion.longToHex(0x1234567890ABCDEFL, 3, "ffffffffffffffffffffffff", 3, 16));
+ // assertEquals("ffffffffffffffffffffffff", Conversion.longToHex(0x1234567890ABCDEFL, 4, "ffffffffffffffffffffffff", 3, 16));//rejected
+ // by assertion
assertEquals(
- "fffedcffffffffffffffffff",
- Conversion.shortToHex((short) 0xCDEF, 4, "ffffffffffffffffffffffff", 3, 3));
- assertEquals("fedc", Conversion.shortToHex((short) 0xCDEF, 0, "", 0, 4));
- assertThrows(StringIndexOutOfBoundsException.class, () -> Conversion.shortToHex((short) 0xCDEF, 0, "", 1, 4));
- }
-
- /**
- * Tests {@link Conversion#byteToHex(byte, int, String, int, int)}.
- */
- @Test
- public void testByteToHex() {
- assertEquals("", Conversion.byteToHex((byte) 0x00, 0, "", 0, 0));
- assertEquals("", Conversion.byteToHex((byte) 0x00, 100, "", 0, 0));
- assertEquals("", Conversion.byteToHex((byte) 0x00, 0, "", 100, 0));
- assertEquals("00000", Conversion.byteToHex((byte) 0xEF, 0, "00000", 0, 0));
- assertEquals("f0000", Conversion.byteToHex((byte) 0xEF, 0, "00000", 0, 1));
- assertEquals("fe000", Conversion.byteToHex((byte) 0xEF, 0, "00000", 0, 2));
- assertEquals("000f0", Conversion.byteToHex((byte) 0xEF, 0, "00000", 3, 1));
- assertEquals("000fe", Conversion.byteToHex((byte) 0xEF, 0, "00000", 3, 2));
- assertEquals("70000", Conversion.byteToHex((byte) 0xEF, 1, "00000", 0, 1));
- assertEquals("b0000", Conversion.byteToHex((byte) 0xEF, 2, "00000", 0, 1));
- assertEquals("000df", Conversion.byteToHex((byte) 0xEF, 3, "00000", 3, 2));
- // assertEquals("00000", Conversion.byteToHex((byte) 0xEF, 4, "00000", 3, 2));//rejected by
- // assertion
- assertEquals("000e0", Conversion.byteToHex((byte) 0xEF, 4, "00000", 3, 1));
- assertEquals("fe", Conversion.byteToHex((byte) 0xEF, 0, "", 0, 2));
- assertThrows(StringIndexOutOfBoundsException.class, () -> Conversion.byteToHex((byte) 0xEF, 0, "", 1, 2));
+ "fffedcba0987654321ffffff",
+ Conversion.longToHex(0x1234567890ABCDEFL, 4, "ffffffffffffffffffffffff", 3, 15));
+ assertEquals(
+ "fedcba0987654321", Conversion.longToHex(0x1234567890ABCDEFL, 0, "", 0, 16));
+ assertThrows(StringIndexOutOfBoundsException.class, () -> Conversion.longToHex(0x1234567890ABCDEFL, 0, "", 1, 8));
}
/**
- * Tests {@link Conversion#longToBinary(long, int, boolean[], int, int)}.
+ * Tests {@link Conversion#longToIntArray(long, int, int[], int, int)}.
*/
@Test
- public void testLongToBinary() {
+ public void testLongToIntArray() {
assertArrayEquals(
- new boolean[]{},
- Conversion.longToBinary(0x0000000000000000L, 0, new boolean[]{}, 0, 0));
+ new int[]{}, Conversion.longToIntArray(0x0000000000000000L, 0, new int[]{}, 0, 0));
assertArrayEquals(
- new boolean[]{},
- Conversion.longToBinary(0x0000000000000000L, 100, new boolean[]{}, 0, 0));
+ new int[]{}, Conversion.longToIntArray(0x0000000000000000L, 100, new int[]{}, 0, 0));
assertArrayEquals(
- new boolean[]{},
- Conversion.longToBinary(0x0000000000000000L, 0, new boolean[]{}, 100, 0));
+ new int[]{}, Conversion.longToIntArray(0x0000000000000000L, 0, new int[]{}, 100, 0));
assertArrayEquals(
- new boolean[69],
- Conversion.longToBinary(0x1234567890ABCDEFL, 0, new boolean[69], 0, 0));
-
+ new int[]{0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF},
+ Conversion.longToIntArray(0x1234567890ABCDEFL, 0, new int[]{-1, -1, -1, -1}, 0, 0));
assertArrayEquals(
- new boolean[]{
- true, false, false, false, false, false, false, false, false, false, false,
- false, false, false, false, false, false, false, false, false, false, false,
- false, false, false, false, false, false, false, false, false, false, false,
- false, false, false, false, false, false, false, false, false, false, false,
- false, false, false, false, false, false, false, false, false, false, false,
- false, false, false, false, false, false, false, false, false, false, false,
- false, false, false},
- Conversion.longToBinary(0x1234567890ABCDEFL, 0, new boolean[69], 0, 1));
+ new int[]{0x90ABCDEF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF},
+ Conversion.longToIntArray(0x1234567890ABCDEFL, 0, new int[]{-1, -1, -1, -1}, 0, 1));
assertArrayEquals(
- new boolean[]{
- true, true, false, false, false, false, false, false, false, false, false,
- false, false, false, false, false, false, false, false, false, false, false,
- false, false, false, false, false, false, false, false, false, false, false,
- false, false, false, false, false, false, false, false, false, false, false,
- false, false, false, false, false, false, false, false, false, false, false,
- false, false, false, false, false, false, false, false, false, false, false,
- false, false, false},
- Conversion.longToBinary(0x1234567890ABCDEFL, 0, new boolean[69], 0, 2));
+ new int[]{0x90ABCDEF, 0x12345678, 0xFFFFFFFF, 0xFFFFFFFF},
+ Conversion.longToIntArray(0x1234567890ABCDEFL, 0, new int[]{-1, -1, -1, -1}, 0, 2));
+ // assertArrayEquals(new
+ // int[]{0x90ABCDEF, 0x12345678, 0x90ABCDEF, 0x12345678}, Conversion.longToIntArray(0x1234567890ABCDEFL,
+ // 0, new int[]{-1, -1, -1, -1}, 0, 4));//rejected by assertion
+ // assertArrayEquals(new
+ // int[]{0xFFFFFFFF, 0x90ABCDEF, 0x12345678, 0x90ABCDEF}, Conversion.longToIntArray(0x1234567890ABCDEFL,
+ // 0, new int[]{-1, -1, -1, -1}, 1, 3));
assertArrayEquals(
- new boolean[]{
- true, true, true, false, false, false, false, false, false, false, false,
- false, false, false, false, false, false, false, false, false, false, false,
- false, false, false, false, false, false, false, false, false, false, false,
- false, false, false, false, false, false, false, false, false, false, false,
- false, false, false, false, false, false, false, false, false, false, false,
- false, false, false, false, false, false, false, false, false, false, false,
- false, false, false},
- Conversion.longToBinary(0x1234567890ABCDEFL, 0, new boolean[69], 0, 3));
+ new int[]{0xFFFFFFFF, 0xFFFFFFFF, 0x90ABCDEF, 0x12345678},
+ Conversion.longToIntArray(0x1234567890ABCDEFL, 0, new int[]{-1, -1, -1, -1}, 2, 2));
assertArrayEquals(
- new boolean[]{
- true, true, true, true, false, true, true, true, true, false, true, true,
- false, false, true, true, true, true, false, true, false, true, false, true,
- false, false, false, false, true, false, false, true, false, false, false,
- true, true, true, true, false, false, true, true, false, true, false, true,
- false, false, false, true, false, true, true, false, false, false, true, false,
- false, true, false, false, false, false, false, false, false, false},
- Conversion.longToBinary(0x1234567890ABCDEFL, 0, new boolean[69], 0, 63));
+ new int[]{0xFFFFFFFF, 0xFFFFFFFF, 0x90ABCDEF, 0xFFFFFFFF},
+ Conversion.longToIntArray(0x1234567890ABCDEFL, 0, new int[]{-1, -1, -1, -1}, 2, 1));
assertArrayEquals(
- new boolean[]{
- true, true, true, true, false, true, true, true, true, false, true, true,
- false, false, true, true, true, true, false, true, false, true, false, true,
- false, false, false, false, true, false, false, true, false, false, false,
- true, true, true, true, false, false, true, true, false, true, false, true,
- false, false, false, true, false, true, true, false, false, false, true, false,
- false, true, false, false, false, false, false, false, false, false},
- Conversion.longToBinary(0x1234567890ABCDEFL, 0, new boolean[69], 0, 64));
+ new int[]{0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x90ABCDEF},
+ Conversion.longToIntArray(0x1234567890ABCDEFL, 0, new int[]{-1, -1, -1, -1}, 3, 1));
assertArrayEquals(
- new boolean[]{
- false, false, true, false, false, false, false, false, false, false, false,
- false, false, false, false, false, false, false, false, false, false, false,
- false, false, false, false, false, false, false, false, false, false, false,
- false, false, false, false, false, false, false, false, false, false, false,
- false, false, false, false, false, false, false, false, false, false, false,
- false, false, false, false, false, false, false, false, false, false, false,
- false, false, false},
- Conversion.longToBinary(0x1234567890ABCDEFL, 0, new boolean[69], 2, 1));
+ new int[]{0xFFFFFFFF, 0xFFFFFFFF, 0x4855E6F7, 0xFFFFFFFF},
+ Conversion.longToIntArray(0x1234567890ABCDEFL, 1, new int[]{-1, -1, -1, -1}, 2, 1));
assertArrayEquals(
- new boolean[]{
- false, false, true, true, true, true, false, true, true, true, true, false,
- true, true, false, false, true, true, true, true, false, true, false, true,
- false, true, false, false, false, false, true, false, false, true, false,
- false, false, true, true, true, true, false, false, true, true, false, true,
- false, true, false, false, false, true, false, true, true, false, false, false,
- true, false, false, true, false, false, false, false, false, false},
- Conversion.longToBinary(0x1234567890ABCDEFL, 0, new boolean[69], 2, 64));
+ new int[]{0xFFFFFFFF, 0xFFFFFFFF, 0x242AF37B, 0xFFFFFFFF},
+ Conversion.longToIntArray(0x1234567890ABCDEFL, 2, new int[]{-1, -1, -1, -1}, 2, 1));
assertArrayEquals(
- new boolean[]{
- true, true, true, false, true, true, true, true, false, true, true, false,
- false, true, true, true, true, false, true, false, true, false, true, false,
- false, false, false, true, false, false, true, false, false, false, true, true,
- true, true, false, false, true, true, false, true, false, true, false, false,
- false, true, false, true, true, false, false, false, true, false, false, true,
- false, false, false, false, false, false, false, false, false},
- Conversion.longToBinary(0x1234567890ABCDEFL, 1, new boolean[69], 0, 63));
+ new int[]{0xFFFFFFFF, 0xFFFFFFFF, 0x121579BD, 0xFFFFFFFF},
+ Conversion.longToIntArray(0x1234567890ABCDEFL, 3, new int[]{-1, -1, -1, -1}, 2, 1));
assertArrayEquals(
- new boolean[]{
- true, true, false, true, true, true, true, false, true, true, false, false,
- true, true, true, true, false, true, false, true, false, true, false, false,
- false, false, true, false, false, true, false, false, false, true, true, true,
- true, false, false, true, true, false, true, false, true, false, false, false,
- true, false, true, true, false, false, false, true, false, false, true, false,
- false, false, false, false, false, false, false, false, false},
- Conversion.longToBinary(0x1234567890ABCDEFL, 2, new boolean[69], 0, 62));
-
- // assertArrayEquals(new boolean[]{false, false, false, true, true, false, true, true,
- // true, true, false, true, true, false, false, true, true, true, true, false, true,
- // false, true, false, true, false, false, false, false, true, false, false, true,
- // false, false, false, true, true, true, true, false, false, true, true, false, true,
- // false, true, false, false, false, true, false, true, true, false, false, false, true,
- // false, false, true, false, false, false
- // , false, false, false, false}, Conversion.longToBinary(0x1234567890ABCDEFL, 2, new
- // boolean[69], 3, 63));//rejected by assertion
+ new int[]{0xFFFFFFFF, 0xFFFFFFFF, 0x890ABCDE, 0xFFFFFFFF},
+ Conversion.longToIntArray(0x1234567890ABCDEFL, 4, new int[]{-1, -1, -1, -1}, 2, 1));
+ // assertArrayEquals(new
+ // int[]{0x4855E6F7, 0x091A2B3C, 0x4855E6F7, 0x091A2B3C}, Conversion.longToIntArray(0x1234567890ABCDEFL,
+ // 1, new int[]{-1, -1, -1, -1}, 0, 4));//rejected by assertion
assertArrayEquals(
- new boolean[]{
- false, false, false, true, true, false, true, true, true, true, false, true,
- true, false, false, true, true, true, true, false, true, false, true, false,
- true, false, false, false, false, true, false, false, true, false, false,
- false, true, true, true, true, false, false, true, true, false, true, false,
- true, false, false, false, true, false, true, true, false, false, false, true,
- false, false, true, false, false, false, false, false, false, false},
- Conversion.longToBinary(0x1234567890ABCDEFL, 2, new boolean[69], 3, 62));
+ new int[]{0x091A2B3C},
+ Conversion.longToIntArray(0x1234567890ABCDEFL, 33, new int[]{0}, 0, 1));
}
/**
- * Tests {@link Conversion#intToBinary(int, int, boolean[], int, int)}.
+ * Tests {@link Conversion#longToShortArray(long, int, short[], int, int)}.
*/
@Test
- public void testIntToBinary() {
+ public void testLongToShortArray() {
assertArrayEquals(
- new boolean[]{}, Conversion.intToBinary(0x00000000, 0, new boolean[]{}, 0, 0));
+ new short[]{},
+ Conversion.longToShortArray(0x0000000000000000L, 0, new short[]{}, 0, 0));
assertArrayEquals(
- new boolean[]{}, Conversion.intToBinary(0x00000000, 100, new boolean[]{}, 0, 0));
+ new short[]{},
+ Conversion.longToShortArray(0x0000000000000000L, 100, new short[]{}, 0, 0));
assertArrayEquals(
- new boolean[]{}, Conversion.intToBinary(0x00000000, 0, new boolean[]{}, 100, 0));
+ new short[]{},
+ Conversion.longToShortArray(0x0000000000000000L, 0, new short[]{}, 100, 0));
assertArrayEquals(
- new boolean[69], Conversion.intToBinary(0x90ABCDEF, 0, new boolean[69], 0, 0));
- assertArrayEquals(new boolean[]{
- true, false, false, false, false, false, false, false, false, false, false, false,
- false, false, false, false, false, false, false, false, false, false, false, false,
- false, false, false, false, false, false, false, false, false, false, false, false,
- false}, Conversion.intToBinary(0x90ABCDEF, 0, new boolean[37], 0, 1));
- assertArrayEquals(new boolean[]{
- true, true, false, false, false, false, false, false, false, false, false, false,
- false, false, false, false, false, false, false, false, false, false, false, false,
- false, false, false, false, false, false, false, false, false, false, false, false,
- false}, Conversion.intToBinary(0x90ABCDEF, 0, new boolean[37], 0, 2));
- assertArrayEquals(new boolean[]{
- true, true, true, false, false, false, false, false, false, false, false, false,
- false, false, false, false, false, false, false, false, false, false, false, false,
- false, false, false, false, false, false, false, false, false, false, false, false,
- false}, Conversion.intToBinary(0x90ABCDEF, 0, new boolean[37], 0, 3));
+ new short[]{(short) 0xFFFF, (short) 0xFFFF, (short) 0xFFFF, (short) 0xFFFF},
+ Conversion.longToShortArray(
+ 0x1234567890ABCDEFL, 0, new short[]{-1, -1, -1, -1}, 0, 0));
assertArrayEquals(
- new boolean[]{
- true, true, true, true, false, true, true, true, true, false, true, true,
- false, false, true, true, true, true, false, true, false, true, false, true,
- false, false, false, false, true, false, false, false, false, false, false,
- false, false}, Conversion.intToBinary(0x90ABCDEF, 0, new boolean[37], 0, 31));
+ new short[]{(short) 0xCDEF, (short) 0xFFFF, (short) 0xFFFF, (short) 0xFFFF},
+ Conversion.longToShortArray(
+ 0x1234567890ABCDEFL, 0, new short[]{-1, -1, -1, -1}, 0, 1));
+ assertArrayEquals(
+ new short[]{(short) 0xCDEF, (short) 0x90AB, (short) 0xFFFF, (short) 0xFFFF},
+ Conversion.longToShortArray(
+ 0x1234567890ABCDEFL, 0, new short[]{-1, -1, -1, -1}, 0, 2));
+ assertArrayEquals(
+ new short[]{(short) 0xCDEF, (short) 0x90AB, (short) 0x5678, (short) 0xFFFF},
+ Conversion.longToShortArray(
+ 0x1234567890ABCDEFL, 0, new short[]{-1, -1, -1, -1}, 0, 3));
+ assertArrayEquals(
+ new short[]{(short) 0xCDEF, (short) 0x90AB, (short) 0x5678, (short) 0x1234},
+ Conversion.longToShortArray(
+ 0x1234567890ABCDEFL, 0, new short[]{-1, -1, -1, -1}, 0, 4));
+ assertArrayEquals(
+ new short[]{(short) 0xFFFF, (short) 0xCDEF, (short) 0x90AB, (short) 0x5678},
+ Conversion.longToShortArray(
+ 0x1234567890ABCDEFL, 0, new short[]{-1, -1, -1, -1}, 1, 3));
+ assertArrayEquals(
+ new short[]{(short) 0xFFFF, (short) 0xFFFF, (short) 0xCDEF, (short) 0x90AB},
+ Conversion.longToShortArray(
+ 0x1234567890ABCDEFL, 0, new short[]{-1, -1, -1, -1}, 2, 2));
+ assertArrayEquals(
+ new short[]{(short) 0xFFFF, (short) 0xFFFF, (short) 0xCDEF, (short) 0xFFFF},
+ Conversion.longToShortArray(
+ 0x1234567890ABCDEFL, 0, new short[]{-1, -1, -1, -1}, 2, 1));
+ assertArrayEquals(
+ new short[]{(short) 0xFFFF, (short) 0xFFFF, (short) 0xFFFF, (short) 0xCDEF},
+ Conversion.longToShortArray(
+ 0x1234567890ABCDEFL, 0, new short[]{-1, -1, -1, -1}, 3, 1));
assertArrayEquals(
- new boolean[]{
- true, true, true, true, false, true, true, true, true, false, true, true,
- false, false, true, true, true, true, false, true, false, true, false, true,
- false, false, false, false, true, false, false, true, false, false, false,
- false, false}, Conversion.intToBinary(0x90ABCDEF, 0, new boolean[37], 0, 32));
- assertArrayEquals(new boolean[]{
- false, false, true, false, false, false, false, false, false, false, false, false,
- false, false, false, false, false, false, false, false, false, false, false, false,
- false, false, false, false, false, false, false, false, false, false, false, false,
- false}, Conversion.intToBinary(0x90ABCDEF, 0, new boolean[37], 2, 1));
+ new short[]{(short) 0xFFFF, (short) 0xFFFF, (short) 0xE6F7, (short) 0xFFFF},
+ Conversion.longToShortArray(
+ 0x1234567890ABCDEFL, 1, new short[]{-1, -1, -1, -1}, 2, 1));
assertArrayEquals(
- new boolean[]{
- false, false, true, true, true, true, false, true, true, true, true, false,
- true, true, false, false, true, true, true, true, false, true, false, true,
- false, true, false, false, false, false, true, false, false, true, false,
- false, false}, Conversion.intToBinary(0x90ABCDEF, 0, new boolean[37], 2, 32));
+ new short[]{(short) 0xFFFF, (short) 0xFFFF, (short) 0xF37B, (short) 0xFFFF},
+ Conversion.longToShortArray(
+ 0x1234567890ABCDEFL, 2, new short[]{-1, -1, -1, -1}, 2, 1));
assertArrayEquals(
- new boolean[]{
- true, true, true, false, true, true, true, true, false, true, true, false,
- false, true, true, true, true, false, true, false, true, false, true, false,
- false, false, false, true, false, false, true, false, false, false, false,
- false, false}, Conversion.intToBinary(0x90ABCDEF, 1, new boolean[37], 0, 31));
+ new short[]{(short) 0xFFFF, (short) 0xFFFF, (short) 0x79BD, (short) 0xFFFF},
+ Conversion.longToShortArray(
+ 0x1234567890ABCDEFL, 3, new short[]{-1, -1, -1, -1}, 2, 1));
assertArrayEquals(
- new boolean[]{
- true, true, false, true, true, true, true, false, true, true, false, false,
- true, true, true, true, false, true, false, true, false, true, false, false,
- false, false, true, false, false, true, false, false, false, false, false,
- false, false}, Conversion.intToBinary(0x90ABCDEF, 2, new boolean[37], 0, 30));
- // assertArrayEquals(new boolean[]{false, false, false, true, true, false, true,
- // true,
- // true, true, false, true, true, false, false, true, true, true, true, false, true,
- // false, true, false, true, false, false, false, false, true, false, false, false,
- // false, false, false, false}, Conversion.intToBinary(0x90ABCDEF, 2, new boolean[37],
- // 3, 31));//rejected by assertion
+ new short[]{(short) 0xFFFF, (short) 0xFFFF, (short) 0xBCDE, (short) 0xFFFF},
+ Conversion.longToShortArray(
+ 0x1234567890ABCDEFL, 4, new short[]{-1, -1, -1, -1}, 2, 1));
assertArrayEquals(
- new boolean[]{
- false, false, false, true, true, false, true, true, true, true, false, true,
- true, false, false, true, true, true, true, false, true, false, true, false,
- true, false, false, false, false, true, false, false, true, false, false,
- false, false}, Conversion.intToBinary(0x90ABCDEF, 2, new boolean[37], 3, 30));
+ new short[]{(short) 0xE6F7, (short) 0x4855, (short) 0x2B3C, (short) 0x091A},
+ Conversion.longToShortArray(
+ 0x1234567890ABCDEFL, 1, new short[]{-1, -1, -1, -1}, 0, 4));
+ assertArrayEquals(
+ new short[]{(short) 0x2B3C},
+ Conversion.longToShortArray(0x1234567890ABCDEFL, 33, new short[]{0}, 0, 1));
+ }
+
+ /**
+ * Tests {@link Conversion#shortArrayToInt(short[], int, int, int, int)}.
+ */
+ @Test
+ public void testShortArrayToInt() {
+ final short[] src = {
+ (short) 0xCDF1, (short) 0xF0C1, (short) 0x0F12, (short) 0x3456, (short) 0x7800};
+ assertEquals(0x00000000, Conversion.shortArrayToInt(src, 0, 0, 0, 0));
+ assertEquals(0x0000CDF1, Conversion.shortArrayToInt(src, 0, 0, 0, 1));
+ assertEquals(0xF0C1CDF1, Conversion.shortArrayToInt(src, 0, 0, 0, 2));
+ assertEquals(0x0F12F0C1, Conversion.shortArrayToInt(src, 1, 0, 0, 2));
+ assertEquals(0x12345678, Conversion.shortArrayToInt(src, 0, 0x12345678, 0, 0));
+ assertEquals(0xCDF15678, Conversion.shortArrayToInt(src, 0, 0x12345678, 16, 1));
+ // assertEquals(0x34567800, Conversion.ShortArrayToInt(src, 3, 0x12345678, 16, 2));
+ }
+
+ /**
+ * Tests {@link Conversion#shortArrayToLong(short[], int, long, int, int)}.
+ */
+ @Test
+ public void testShortArrayToLong() {
+ final short[] src = {
+ (short) 0xCDF1, (short) 0xF0C1, (short) 0x0F12, (short) 0x3456, (short) 0x7800};
+ assertEquals(0x0000000000000000L, Conversion.shortArrayToLong(src, 0, 0L, 0, 0));
+ assertEquals(0x000000000000CDF1L, Conversion.shortArrayToLong(src, 0, 0L, 0, 1));
+ assertEquals(0x00000000F0C1CDF1L, Conversion.shortArrayToLong(src, 0, 0L, 0, 2));
+ assertEquals(0x780034560F12F0C1L, Conversion.shortArrayToLong(src, 1, 0L, 0, 4));
+ assertEquals(
+ 0x123456789ABCDEF0L, Conversion.shortArrayToLong(src, 0, 0x123456789ABCDEF0L, 0, 0));
+ assertEquals(
+ 0x123456CDF1BCDEF0L,
+ Conversion.shortArrayToLong(src, 0, 0x123456789ABCDEF0L, 24, 1));
+ assertEquals(
+ 0x123478003456DEF0L,
+ Conversion.shortArrayToLong(src, 3, 0x123456789ABCDEF0L, 16, 2));
}
/**
@@ -1665,51 +1630,111 @@ public class ConversionTest extends AbstractLangTest {
}
/**
- * Tests {@link Conversion#byteToBinary(byte, int, boolean[], int, int)}.
+ * Tests {@link Conversion#shortToByteArray(short, int, byte[], int, int)}.
*/
@Test
- public void testByteToBinary() {
+ public void testShortToByteArray() {
assertArrayEquals(
- new boolean[]{}, Conversion.byteToBinary((byte) 0x00, 0, new boolean[]{}, 0, 0));
+ new byte[]{}, Conversion.shortToByteArray((short) 0x0000, 0, new byte[]{}, 0, 0));
assertArrayEquals(
- new boolean[]{}, Conversion.byteToBinary((byte) 0x00, 100, new boolean[]{}, 0, 0));
+ new byte[]{}, Conversion.shortToByteArray((short) 0x0000, 100, new byte[]{}, 0, 0));
assertArrayEquals(
- new boolean[]{}, Conversion.byteToBinary((byte) 0x00, 0, new boolean[]{}, 100, 0));
+ new byte[]{}, Conversion.shortToByteArray((short) 0x0000, 0, new byte[]{}, 100, 0));
assertArrayEquals(
- new boolean[69], Conversion.byteToBinary((byte) 0xEF, 0, new boolean[69], 0, 0));
- assertArrayEquals(new boolean[]{
- true, false, false, false, false, false, false, false, false, false, false, false,
- false}, Conversion.byteToBinary((byte) 0x95, 0, new boolean[13], 0, 1));
- assertArrayEquals(new boolean[]{
- true, false, false, false, false, false, false, false, false, false, false, false,
- false}, Conversion.byteToBinary((byte) 0x95, 0, new boolean[13], 0, 2));
- assertArrayEquals(new boolean[]{
- true, false, true, false, false, false, false, false, false, false, false, false,
- false}, Conversion.byteToBinary((byte) 0x95, 0, new boolean[13], 0, 3));
- assertArrayEquals(new boolean[]{
- true, false, true, false, true, false, false, false, false, false, false, false,
- false}, Conversion.byteToBinary((byte) 0x95, 0, new boolean[13], 0, 7));
- assertArrayEquals(new boolean[]{
- true, false, true, false, true, false, false, true, false, false, false, false,
- false}, Conversion.byteToBinary((byte) 0x95, 0, new boolean[13], 0, 8));
- assertArrayEquals(new boolean[]{
- false, false, true, false, false, false, false, false, false, false, false, false,
- false}, Conversion.byteToBinary((byte) 0x95, 0, new boolean[13], 2, 1));
- assertArrayEquals(new boolean[]{
- false, false, true, false, true, false, true, false, false, true, false, false,
- false}, Conversion.byteToBinary((byte) 0x95, 0, new boolean[13], 2, 8));
- assertArrayEquals(new boolean[]{
- false, true, false, true, false, false, true, false, false, false, false, false,
- false}, Conversion.byteToBinary((byte) 0x95, 1, new boolean[13], 0, 7));
- assertArrayEquals(new boolean[]{
- true, false, true, false, false, true, false, false, false, false, false, false,
- false}, Conversion.byteToBinary((byte) 0x95, 2, new boolean[13], 0, 6));
- // assertArrayEquals(new boolean[]{false, false, false, true, true, false, true, true,
- // false, false, false, false, false}, Conversion.byteToBinary((byte) 0x95, 2, new
- // boolean[13], 3, 7));//rejected by assertion
- assertArrayEquals(new boolean[]{
- false, false, false, true, false, true, false, false, true, false, false, false,
- false}, Conversion.byteToBinary((byte) 0x95, 2, new boolean[13], 3, 6));
+ new byte[]{
+ (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF,
+ (byte) 0xFF}, Conversion.shortToByteArray((short) 0xCDEF, 0, new byte[]{
+ -1, -1, -1, -1, -1, -1, -1}, 0, 0));
+ assertArrayEquals(
+ new byte[]{
+ (byte) 0xEF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF,
+ (byte) 0xFF}, Conversion.shortToByteArray((short) 0xCDEF, 0, new byte[]{
+ -1, -1, -1, -1, -1, -1, -1}, 0, 1));
+ assertArrayEquals(
+ new byte[]{
+ (byte) 0xEF, (byte) 0xCD, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF,
+ (byte) 0xFF}, Conversion.shortToByteArray((short) 0xCDEF, 0, new byte[]{
+ -1, -1, -1, -1, -1, -1, -1}, 0, 2));
+ assertArrayEquals(
+ new byte[]{
+ (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xEF, (byte) 0xFF, (byte) 0xFF,
+ (byte) 0xFF}, Conversion.shortToByteArray((short) 0xCDEF, 0, new byte[]{
+ -1, -1, -1, -1, -1, -1, -1}, 3, 1));
+ assertArrayEquals(
+ new byte[]{
+ (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xEF, (byte) 0xCD, (byte) 0xFF,
+ (byte) 0xFF}, Conversion.shortToByteArray((short) 0xCDEF, 0, new byte[]{
+ -1, -1, -1, -1, -1, -1, -1}, 3, 2));
+ assertArrayEquals(
+ new byte[]{
+ (byte) 0xF7, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF,
+ (byte) 0xFF}, Conversion.shortToByteArray((short) 0xCDEF, 1, new byte[]{
+ -1, -1, -1, -1, -1, -1, -1}, 0, 1));
+ assertArrayEquals(
+ new byte[]{
+ (byte) 0x7B, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF,
+ (byte) 0xFF}, Conversion.shortToByteArray((short) 0xCDEF, 2, new byte[]{
+ -1, -1, -1, -1, -1, -1, -1}, 0, 1));
+ assertArrayEquals(
+ new byte[]{
+ (byte) 0xFF, (byte) 0x00, (byte) 0xFF, (byte) 0x6F, (byte) 0xFE, (byte) 0xFF,
+ (byte) 0xFF}, Conversion.shortToByteArray((short) 0xCDEF, 5, new byte[]{
+ -1, 0, -1, -1, -1, -1, -1}, 3, 2));
+ // assertArrayEquals(new
+ // byte[]{(byte) 0xFF, (byte) 0x00, (byte) 0xFF, (byte) 0x5E, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF}, Conversion.shortToByteArray((short) 0xCDEF, 13, new
+ // byte[]{-1, 0, -1, -1, -1, -1, -1}, 3, 2));//rejected by assertion
+ assertArrayEquals(
+ new byte[]{
+ (byte) 0xFF, (byte) 0x00, (byte) 0xFF, (byte) 0xFE, (byte) 0xFF, (byte) 0xFF,
+ (byte) 0xFF}, Conversion.shortToByteArray((short) 0xCDEF, 13, new byte[]{
+ -1, 0, -1, -1, -1, -1, -1}, 3, 1));
+ }
+
+ /**
+ * Tests {@link Conversion#shortToHex(short, int, String, int, int)}.
+ */
+ @Test
+ public void testShortToHex() {
+ assertEquals("", Conversion.shortToHex((short) 0x0000, 0, "", 0, 0));
+ assertEquals("", Conversion.shortToHex((short) 0x0000, 100, "", 0, 0));
+ assertEquals("", Conversion.shortToHex((short) 0x0000, 0, "", 100, 0));
+ assertEquals(
+ "ffffffffffffffffffffffff",
+ Conversion.shortToHex((short) 0xCDEF, 0, "ffffffffffffffffffffffff", 0, 0));
+ assertEquals(
+ "3fffffffffffffffffffffff",
+ Conversion.shortToHex((short) 0xCDE3, 0, "ffffffffffffffffffffffff", 0, 1));
+ assertEquals(
+ "feffffffffffffffffffffff",
+ Conversion.shortToHex((short) 0xCDEF, 0, "ffffffffffffffffffffffff", 0, 2));
+ assertEquals(
+ "fedfffffffffffffffffffff",
+ Conversion.shortToHex((short) 0xCDEF, 0, "ffffffffffffffffffffffff", 0, 3));
+ assertEquals(
+ "fedcffffffffffffffffffff",
+ Conversion.shortToHex((short) 0xCDEF, 0, "ffffffffffffffffffffffff", 0, 4));
+ assertEquals(
+ "fff3ffffffffffffffffffff",
+ Conversion.shortToHex((short) 0xCDE3, 0, "ffffffffffffffffffffffff", 3, 1));
+ assertEquals(
+ "ffffefffffffffffffffffff",
+ Conversion.shortToHex((short) 0xCDEF, 0, "ffffffffffffffffffffffff", 3, 2));
+ assertEquals(
+ "7fffffffffffffffffffffff",
+ Conversion.shortToHex((short) 0xCDEF, 1, "ffffffffffffffffffffffff", 0, 1));
+ assertEquals(
+ "bfffffffffffffffffffffff",
+ Conversion.shortToHex((short) 0xCDEF, 2, "ffffffffffffffffffffffff", 0, 1));
+ assertEquals(
+ "fffdb9ffffffffffffffffff",
+ Conversion.shortToHex((short) 0xCDEF, 3, "ffffffffffffffffffffffff", 3, 4));
+ // assertEquals("ffffffffffffffffffffffff", Conversion.shortToHex((short) 0xCDEF,
+ // 4, "ffffffffffffffffffffffff", 3, 4));//rejected by assertion
+ assertEquals(
+ "fffedcffffffffffffffffff",
+ Conversion.shortToHex((short) 0xCDEF, 4, "ffffffffffffffffffffffff", 3, 3));
+ assertEquals("fedc", Conversion.shortToHex((short) 0xCDEF, 0, "", 0, 4));
+ assertThrows(StringIndexOutOfBoundsException.class, () -> Conversion.shortToHex((short) 0xCDEF, 0, "", 1, 4));
}
/**
@@ -1738,29 +1763,4 @@ public class ConversionTest extends AbstractLangTest {
(byte) 0x00, (byte) 0x00}, Conversion.uuidToByteArray(new UUID(
0xFFEEDDCCBBAA9988L, 0x7766554433221100L), new byte[16], 2, 12));
}
-
- /**
- * Tests {@link Conversion#byteArrayToUuid(byte[], int)}.
- */
- @Test
- public void testByteArrayToUuid() {
- assertEquals(
- new UUID(0xFFFFFFFFFFFFFFFFL, 0xFFFFFFFFFFFFFFFFL),
- Conversion.byteArrayToUuid(new byte[]{
- (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff,
- (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff,
- (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff}, 0));
- assertEquals(
- new UUID(0xFFEEDDCCBBAA9988L, 0x7766554433221100L),
- Conversion.byteArrayToUuid(new byte[]{
- (byte) 0x88, (byte) 0x99, (byte) 0xaa, (byte) 0xbb, (byte) 0xcc, (byte) 0xdd,
- (byte) 0xee, (byte) 0xff, (byte) 0x00, (byte) 0x11, (byte) 0x22, (byte) 0x33,
- (byte) 0x44, (byte) 0x55, (byte) 0x66, (byte) 0x77}, 0));
- assertEquals(
- new UUID(0xFFEEDDCCBBAA9988L, 0x7766554433221100L),
- Conversion.byteArrayToUuid(new byte[]{
- 0, 0, (byte) 0x88, (byte) 0x99, (byte) 0xaa, (byte) 0xbb, (byte) 0xcc, (byte) 0xdd,
- (byte) 0xee, (byte) 0xff, (byte) 0x00, (byte) 0x11, (byte) 0x22, (byte) 0x33,
- (byte) 0x44, (byte) 0x55, (byte) 0x66, (byte) 0x77}, 2));
- }
}
diff --git a/src/test/java/org/apache/commons/lang3/HashSetvBitSetTest.java b/src/test/java/org/apache/commons/lang3/HashSetvBitSetTest.java
index a5ba1085c..a22195f8a 100644
--- a/src/test/java/org/apache/commons/lang3/HashSetvBitSetTest.java
+++ b/src/test/java/org/apache/commons/lang3/HashSetvBitSetTest.java
@@ -37,22 +37,42 @@ public class HashSetvBitSetTest extends AbstractLangTest {
private static final int numberOfElementsToCompute = 10;
+ private static int[] extractIndices(final BitSet coll) {
+ final int[] result = new int[coll.cardinality()];
+ int i = 0;
+ int j=0;
+ while ((j=coll.nextSetBit(j)) != -1) {
+ result[i++] = j++;
+ }
+ return result;
+ }
+
+ // --- utility methods
+ private static int[] extractIndices(final HashSet<Integer> coll) {
+ final int[] result = new int[coll.size()];
+ int i = 0;
+ for (final Integer index : coll) {
+ result[i++] = index.intValue();
+ }
+ return result;
+ }
+
@Benchmark
- public int[] testHashSet() {
- final HashSet<Integer> toRemove = new HashSet<>();
+ public int[] testBitSet() {
+ final BitSet toRemove = new BitSet();
int found = 0;
for (int i = 0; i < numberOfElementsToCompute; i++) {
- toRemove.add(found++);
+ toRemove.set(found++);
}
return extractIndices(toRemove);
}
@Benchmark
- public int[] testBitSet() {
- final BitSet toRemove = new BitSet();
+ public int[] testHashSet() {
+ final HashSet<Integer> toRemove = new HashSet<>();
int found = 0;
for (int i = 0; i < numberOfElementsToCompute; i++) {
- toRemove.set(found++);
+ toRemove.add(found++);
}
return extractIndices(toRemove);
}
@@ -73,24 +93,4 @@ public class HashSetvBitSetTest extends AbstractLangTest {
final int[] extractIndices = extractIndices(toRemove);
return (int[]) ArrayUtils.removeAll((Object) array, extractIndices);
}
-
- // --- utility methods
- private static int[] extractIndices(final HashSet<Integer> coll) {
- final int[] result = new int[coll.size()];
- int i = 0;
- for (final Integer index : coll) {
- result[i++] = index.intValue();
- }
- return result;
- }
-
- private static int[] extractIndices(final BitSet coll) {
- final int[] result = new int[coll.cardinality()];
- int i = 0;
- int j=0;
- while ((j=coll.nextSetBit(j)) != -1) {
- result[i++] = j++;
- }
- return result;
- }
}
diff --git a/src/test/java/org/apache/commons/lang3/JavaVersionTest.java b/src/test/java/org/apache/commons/lang3/JavaVersionTest.java
index 0fa5bf67c..fc08d8d8a 100644
--- a/src/test/java/org/apache/commons/lang3/JavaVersionTest.java
+++ b/src/test/java/org/apache/commons/lang3/JavaVersionTest.java
@@ -41,6 +41,16 @@ import org.junit.jupiter.api.Test;
*/
public class JavaVersionTest extends AbstractLangTest {
+ @Test
+ public void testAtLeast() {
+ assertFalse(JAVA_1_2.atLeast(JAVA_1_5), "1.2 at least 1.5 passed");
+ assertTrue(JAVA_1_5.atLeast(JAVA_1_2), "1.5 at least 1.2 failed");
+ assertFalse(JAVA_1_6.atLeast(JAVA_1_7), "1.6 at least 1.7 passed");
+
+ assertTrue(JAVA_0_9.atLeast(JAVA_1_5), "0.9 at least 1.5 failed");
+ assertFalse(JAVA_0_9.atLeast(JAVA_1_6), "0.9 at least 1.6 passed");
+ }
+
@Test
public void testGetJavaVersion() throws Exception {
assertEquals(JAVA_0_9, get("0.9"), "0.9 failed");
@@ -64,16 +74,6 @@ public class JavaVersionTest extends AbstractLangTest {
assertEquals(JAVA_RECENT, get("22"), "Unhandled"); // LANG-1384
}
- @Test
- public void testAtLeast() {
- assertFalse(JAVA_1_2.atLeast(JAVA_1_5), "1.2 at least 1.5 passed");
- assertTrue(JAVA_1_5.atLeast(JAVA_1_2), "1.5 at least 1.2 failed");
- assertFalse(JAVA_1_6.atLeast(JAVA_1_7), "1.6 at least 1.7 passed");
-
- assertTrue(JAVA_0_9.atLeast(JAVA_1_5), "0.9 at least 1.5 failed");
- assertFalse(JAVA_0_9.atLeast(JAVA_1_6), "0.9 at least 1.6 passed");
- }
-
@Test
public void testToString() {
assertEquals("1.2", JAVA_1_2.toString());
diff --git a/src/test/java/org/apache/commons/lang3/LocaleUtilsTest.java b/src/test/java/org/apache/commons/lang3/LocaleUtilsTest.java
index d6f76de31..2168cdc86 100644
--- a/src/test/java/org/apache/commons/lang3/LocaleUtilsTest.java
+++ b/src/test/java/org/apache/commons/lang3/LocaleUtilsTest.java
@@ -54,23 +54,97 @@ public class LocaleUtilsTest extends AbstractLangTest {
private static final Locale LOCALE_QQ = new Locale("qq", "");
private static final Locale LOCALE_QQ_ZZ = new Locale("qq", "ZZ");
- @BeforeEach
- public void setUp() {
- // Testing #LANG-304. Must be called before availableLocaleSet is called.
- LocaleUtils.isAvailableLocale(Locale.getDefault());
+ /**
+ * Make sure the country by language is correct. It checks that
+ * the LocaleUtils.countryByLanguage(language) call contains the
+ * array of countries passed in. It may contain more due to JVM
+ * variations.
+ *
+ *
+ * @param language
+ * @param countries array of countries that should be returned
+ */
+ private static void assertCountriesByLanguage(final String language, final String[] countries) {
+ final List<Locale> list = LocaleUtils.countriesByLanguage(language);
+ final List<Locale> list2 = LocaleUtils.countriesByLanguage(language);
+ assertNotNull(list);
+ assertSame(list, list2);
+ //search through languages
+ for (final String country : countries) {
+ final Iterator<Locale> iterator = list.iterator();
+ boolean found = false;
+ // see if it was returned by the set
+ while (iterator.hasNext()) {
+ final Locale locale = iterator.next();
+ // should have an en empty variant
+ assertTrue(StringUtils.isEmpty(locale.getVariant()));
+ assertEquals(language, locale.getLanguage());
+ if (country.equals(locale.getCountry())) {
+ found = true;
+ break;
+ }
+ }
+ assertTrue(found, "Could not find language: " + country + " for country: " + language);
+ }
+ assertUnmodifiableCollection(list);
}
/**
- * Test that constructors are public, and work, etc.
+ * Make sure the language by country is correct. It checks that
+ * the LocaleUtils.languagesByCountry(country) call contains the
+ * array of languages passed in. It may contain more due to JVM
+ * variations.
+ *
+ * @param country
+ * @param languages array of languages that should be returned
*/
- @Test
- public void testConstructor() {
- assertNotNull(new LocaleUtils());
- final Constructor<?>[] cons = LocaleUtils.class.getDeclaredConstructors();
- assertEquals(1, cons.length);
- assertTrue(Modifier.isPublic(cons[0].getModifiers()));
- assertTrue(Modifier.isPublic(LocaleUtils.class.getModifiers()));
- assertFalse(Modifier.isFinal(LocaleUtils.class.getModifiers()));
+ private static void assertLanguageByCountry(final String country, final String[] languages) {
+ final List<Locale> list = LocaleUtils.languagesByCountry(country);
+ final List<Locale> list2 = LocaleUtils.languagesByCountry(country);
+ assertNotNull(list);
+ assertSame(list, list2);
+ //search through languages
+ for (final String language : languages) {
+ final Iterator<Locale> iterator = list.iterator();
+ boolean found = false;
+ // see if it was returned by the set
+ while (iterator.hasNext()) {
+ final Locale locale = iterator.next();
+ // should have an en empty variant
+ assertTrue(StringUtils.isEmpty(locale.getVariant()));
+ assertEquals(country, locale.getCountry());
+ if (language.equals(locale.getLanguage())) {
+ found = true;
+ break;
+ }
+ }
+ assertTrue(found, "Could not find language: " + language + " for country: " + country);
+ }
+ assertUnmodifiableCollection(list);
+ }
+
+ /**
+ * Helper method for local lookups.
+ *
+ * @param locale the input locale
+ * @param defaultLocale the input default locale
+ * @param expected expected results
+ */
+ private static void assertLocaleLookupList(final Locale locale, final Locale defaultLocale, final Locale[] expected) {
+ final List<Locale> localeList = defaultLocale == null ?
+ LocaleUtils.localeLookupList(locale) :
+ LocaleUtils.localeLookupList(locale, defaultLocale);
+
+ assertEquals(expected.length, localeList.size());
+ assertEquals(Arrays.asList(expected), localeList);
+ assertUnmodifiableCollection(localeList);
+ }
+
+ /**
+ * @param coll the collection to check
+ */
+ private static void assertUnmodifiableCollection(final Collection<?> coll) {
+ assertThrows(UnsupportedOperationException.class, () -> coll.add(null));
}
/**
@@ -121,120 +195,168 @@ public class LocaleUtilsTest extends AbstractLangTest {
assertEquals(variant, locale.getVariant());
}
+ @BeforeEach
+ public void setUp() {
+ // Testing #LANG-304. Must be called before availableLocaleSet is called.
+ LocaleUtils.isAvailableLocale(Locale.getDefault());
+ }
+
/**
- * Test toLocale(Locale) method.
+ * Test availableLocaleList() method.
*/
@Test
- public void testToLocale_Locale_defaults() {
- assertNull(LocaleUtils.toLocale((String) null));
- assertEquals(Locale.getDefault(), LocaleUtils.toLocale((Locale) null));
- assertEquals(Locale.getDefault(), LocaleUtils.toLocale(Locale.getDefault()));
+ public void testAvailableLocaleList() {
+ final List<Locale> list = LocaleUtils.availableLocaleList();
+ final List<Locale> list2 = LocaleUtils.availableLocaleList();
+ assertNotNull(list);
+ assertSame(list, list2);
+ assertUnmodifiableCollection(list);
+
+ final Locale[] jdkLocaleArray = Locale.getAvailableLocales();
+ final List<Locale> jdkLocaleList = Arrays.asList(jdkLocaleArray);
+ assertEquals(jdkLocaleList, list);
}
/**
- * Test toLocale(Locale) method.
+ * Test availableLocaleSet() method.
*/
- @ParameterizedTest
- @MethodSource("java.util.Locale#getAvailableLocales")
- public void testToLocales(final Locale actualLocale) {
- assertEquals(actualLocale, LocaleUtils.toLocale(actualLocale));
+ @Test
+ public void testAvailableLocaleSet() {
+ final Set<Locale> set = LocaleUtils.availableLocaleSet();
+ final Set<Locale> set2 = LocaleUtils.availableLocaleSet();
+ assertNotNull(set);
+ assertSame(set, set2);
+ assertUnmodifiableCollection(set);
+
+ final Locale[] jdkLocaleArray = Locale.getAvailableLocales();
+ final List<Locale> jdkLocaleList = Arrays.asList(jdkLocaleArray);
+ final Set<Locale> jdkLocaleSet = new HashSet<>(jdkLocaleList);
+ assertEquals(jdkLocaleSet, set);
}
/**
- * Test toLocale(String) method.
+ * Test that constructors are public, and work, etc.
*/
@Test
- public void testToLocale_1Part() {
- assertNull(LocaleUtils.toLocale((String) null));
+ public void testConstructor() {
+ assertNotNull(new LocaleUtils());
+ final Constructor<?>[] cons = LocaleUtils.class.getDeclaredConstructors();
+ assertEquals(1, cons.length);
+ assertTrue(Modifier.isPublic(cons[0].getModifiers()));
+ assertTrue(Modifier.isPublic(LocaleUtils.class.getModifiers()));
+ assertFalse(Modifier.isFinal(LocaleUtils.class.getModifiers()));
+ }
- assertValidToLocale("us");
- assertValidToLocale("fr");
- assertValidToLocale("de");
- assertValidToLocale("zh");
- // Valid format but lang doesn't exist, should make instance anyway
- assertValidToLocale("qq");
- // LANG-941: JDK 8 introduced the empty locale as one of the default locales
- assertValidToLocale("");
+ /**
+ * Test countriesByLanguage() method.
+ */
+ @Test
+ public void testCountriesByLanguage() {
+ assertCountriesByLanguage(null, new String[0]);
+ assertCountriesByLanguage("de", new String[]{"DE", "CH", "AT", "LU"});
+ assertCountriesByLanguage("zz", new String[0]);
+ assertCountriesByLanguage("it", new String[]{"IT", "CH"});
+ }
- assertThrows(IllegalArgumentException.class, () -> LocaleUtils.toLocale("Us"), "Should fail if not lowercase");
- assertThrows(IllegalArgumentException.class, () -> LocaleUtils.toLocale("uS"), "Should fail if not lowercase");
- assertThrows(IllegalArgumentException.class, () -> LocaleUtils.toLocale("u#"), "Should fail if not lowercase");
- assertThrows(
- IllegalArgumentException.class, () -> LocaleUtils.toLocale("u"), "Must be 2 chars if less than 5");
- assertThrows(
- IllegalArgumentException.class, () -> LocaleUtils.toLocale("uu_U"), "Must be 2 chars if less than 5");
+ /**
+ * Test availableLocaleSet() method.
+ */
+ @SuppressWarnings("boxing") // JUnit4 does not support primitive equality testing apart from long
+ @Test
+ public void testIsAvailableLocale() {
+ final Set<Locale> set = LocaleUtils.availableLocaleSet();
+ assertEquals(set.contains(LOCALE_EN), LocaleUtils.isAvailableLocale(LOCALE_EN));
+ assertEquals(set.contains(LOCALE_EN_US), LocaleUtils.isAvailableLocale(LOCALE_EN_US));
+ assertEquals(set.contains(LOCALE_EN_US_ZZZZ), LocaleUtils.isAvailableLocale(LOCALE_EN_US_ZZZZ));
+ assertEquals(set.contains(LOCALE_FR), LocaleUtils.isAvailableLocale(LOCALE_FR));
+ assertEquals(set.contains(LOCALE_FR_CA), LocaleUtils.isAvailableLocale(LOCALE_FR_CA));
+ assertEquals(set.contains(LOCALE_QQ), LocaleUtils.isAvailableLocale(LOCALE_QQ));
+ assertEquals(set.contains(LOCALE_QQ_ZZ), LocaleUtils.isAvailableLocale(LOCALE_QQ_ZZ));
+ }
+
+ @Test
+ public void testIsLanguageUndetermined() {
+ final Set<Locale> set = LocaleUtils.availableLocaleSet();
+ // Determined
+ assertNotEquals(set.contains(LOCALE_EN), LocaleUtils.isLanguageUndetermined(LOCALE_EN));
+ assertNotEquals(set.contains(LOCALE_EN_US), LocaleUtils.isLanguageUndetermined(LOCALE_EN_US));
+ assertNotEquals(set.contains(LOCALE_FR), LocaleUtils.isLanguageUndetermined(LOCALE_FR));
+ assertNotEquals(set.contains(LOCALE_FR_CA), LocaleUtils.isLanguageUndetermined(LOCALE_FR_CA));
+ // Undetermined
+ assertEquals(set.contains(LOCALE_EN_US_ZZZZ), LocaleUtils.isLanguageUndetermined(LOCALE_EN_US_ZZZZ));
+ assertEquals(set.contains(LOCALE_QQ), LocaleUtils.isLanguageUndetermined(LOCALE_QQ));
+ assertEquals(set.contains(LOCALE_QQ_ZZ), LocaleUtils.isLanguageUndetermined(LOCALE_QQ_ZZ));
+ //
+ assertTrue(LocaleUtils.isLanguageUndetermined(null));
}
/**
- * Test toLocale() method.
+ * Tests #LANG-328 - only language+variant
*/
@Test
- public void testToLocale_2Part() {
- assertValidToLocale("us_EN", "us", "EN");
- assertValidToLocale("us-EN", "us", "EN");
- //valid though doesn't exist
- assertValidToLocale("us_ZH", "us", "ZH");
+ public void testLang328() {
+ assertValidToLocale("fr__P", "fr", "", "P");
+ assertValidToLocale("fr__POSIX", "fr", "", "POSIX");
+ }
+ /**
+ * Tests #LANG-865, strings starting with an underscore.
+ */
+ @Test
+ public void testLang865() {
+ assertValidToLocale("_GB", "", "GB", "");
+ assertValidToLocale("_GB_P", "", "GB", "P");
+ assertValidToLocale("_GB_POSIX", "", "GB", "POSIX");
assertThrows(
IllegalArgumentException.class,
- () -> LocaleUtils.toLocale("us_En"),
- "Should fail second part not uppercase");
+ () -> LocaleUtils.toLocale("_G"),
+ "Must be at least 3 chars if starts with underscore");
assertThrows(
IllegalArgumentException.class,
- () -> LocaleUtils.toLocale("us_en"),
- "Should fail second part not uppercase");
+ () -> LocaleUtils.toLocale("_Gb"),
+ "Must be uppercase if starts with underscore");
assertThrows(
IllegalArgumentException.class,
- () -> LocaleUtils.toLocale("us_eN"),
- "Should fail second part not uppercase");
+ () -> LocaleUtils.toLocale("_gB"),
+ "Must be uppercase if starts with underscore");
assertThrows(
IllegalArgumentException.class,
- () -> LocaleUtils.toLocale("uS_EN"),
- "Should fail first part not lowercase");
+ () -> LocaleUtils.toLocale("_1B"),
+ "Must be letter if starts with underscore");
assertThrows(
IllegalArgumentException.class,
- () -> LocaleUtils.toLocale("us_E3"),
- "Should fail second part not uppercase");
+ () -> LocaleUtils.toLocale("_G1"),
+ "Must be letter if starts with underscore");
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> LocaleUtils.toLocale("_GB_"),
+ "Must be at least 5 chars if starts with underscore");
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> LocaleUtils.toLocale("_GBAP"),
+ "Must have underscore after the country if starts with underscore and is at least 5 chars");
}
- /**
- * Test toLocale() method.
- */
@Test
- public void testToLocale_3Part() {
- assertValidToLocale("us_EN_A", "us", "EN", "A");
- assertValidToLocale("us-EN-A", "us", "EN", "A");
- // this isn't pretty, but was caused by a jdk bug it seems
- // https://bugs.java.com/bugdatabase/view_bug.do?bug_id=4210525
- if (SystemUtils.isJavaVersionAtLeast(JAVA_1_4)) {
- assertValidToLocale("us_EN_a", "us", "EN", "a");
- assertValidToLocale("us_EN_SFsafdFDsdfF", "us", "EN", "SFsafdFDsdfF");
- } else {
- assertValidToLocale("us_EN_a", "us", "EN", "A");
- assertValidToLocale("us_EN_SFsafdFDsdfF", "us", "EN", "SFSAFDFDSDFF");
- }
+ public void testLanguageAndUNM49Numeric3AreaCodeLang1312() {
+ assertValidToLocale("en_001", "en", "001");
+ assertValidToLocale("en_150", "en", "150");
+ assertValidToLocale("ar_001", "ar", "001");
- assertThrows(
- IllegalArgumentException.class, () -> LocaleUtils.toLocale("us_EN-a"), "Should fail as no consistent delimiter");
- assertThrows(
- IllegalArgumentException.class, () -> LocaleUtils.toLocale("uu_UU_"), "Must be 3, 5 or 7+ in length");
+ // LANG-1312
+ assertValidToLocale("en_001_GB", "en", "001", "GB");
+ assertValidToLocale("en_150_US", "en", "150", "US");
}
/**
- * Helper method for local lookups.
- *
- * @param locale the input locale
- * @param defaultLocale the input default locale
- * @param expected expected results
+ * Test languagesByCountry() method.
*/
- private static void assertLocaleLookupList(final Locale locale, final Locale defaultLocale, final Locale[] expected) {
- final List<Locale> localeList = defaultLocale == null ?
- LocaleUtils.localeLookupList(locale) :
- LocaleUtils.localeLookupList(locale, defaultLocale);
-
- assertEquals(expected.length, localeList.size());
- assertEquals(Arrays.asList(expected), localeList);
- assertUnmodifiableCollection(localeList);
+ @Test
+ public void testLanguagesByCountry() {
+ assertLanguageByCountry(null, new String[0]);
+ assertLanguageByCountry("GB", new String[]{"en"});
+ assertLanguageByCountry("ZZ", new String[0]);
+ assertLanguageByCountry("CH", new String[]{"fr", "de", "it"});
}
/**
@@ -311,69 +433,27 @@ public class LocaleUtilsTest extends AbstractLangTest {
LOCALE_EN});
}
- /**
- * Test availableLocaleList() method.
- */
- @Test
- public void testAvailableLocaleList() {
- final List<Locale> list = LocaleUtils.availableLocaleList();
- final List<Locale> list2 = LocaleUtils.availableLocaleList();
- assertNotNull(list);
- assertSame(list, list2);
- assertUnmodifiableCollection(list);
-
- final Locale[] jdkLocaleArray = Locale.getAvailableLocales();
- final List<Locale> jdkLocaleList = Arrays.asList(jdkLocaleArray);
- assertEquals(jdkLocaleList, list);
- }
-
- /**
- * Test availableLocaleSet() method.
- */
- @Test
- public void testAvailableLocaleSet() {
- final Set<Locale> set = LocaleUtils.availableLocaleSet();
- final Set<Locale> set2 = LocaleUtils.availableLocaleSet();
- assertNotNull(set);
- assertSame(set, set2);
- assertUnmodifiableCollection(set);
-
- final Locale[] jdkLocaleArray = Locale.getAvailableLocales();
- final List<Locale> jdkLocaleList = Arrays.asList(jdkLocaleArray);
- final Set<Locale> jdkLocaleSet = new HashSet<>(jdkLocaleList);
- assertEquals(jdkLocaleSet, set);
- }
-
- /**
- * Test availableLocaleSet() method.
- */
- @SuppressWarnings("boxing") // JUnit4 does not support primitive equality testing apart from long
- @Test
- public void testIsAvailableLocale() {
- final Set<Locale> set = LocaleUtils.availableLocaleSet();
- assertEquals(set.contains(LOCALE_EN), LocaleUtils.isAvailableLocale(LOCALE_EN));
- assertEquals(set.contains(LOCALE_EN_US), LocaleUtils.isAvailableLocale(LOCALE_EN_US));
- assertEquals(set.contains(LOCALE_EN_US_ZZZZ), LocaleUtils.isAvailableLocale(LOCALE_EN_US_ZZZZ));
- assertEquals(set.contains(LOCALE_FR), LocaleUtils.isAvailableLocale(LOCALE_FR));
- assertEquals(set.contains(LOCALE_FR_CA), LocaleUtils.isAvailableLocale(LOCALE_FR_CA));
- assertEquals(set.contains(LOCALE_QQ), LocaleUtils.isAvailableLocale(LOCALE_QQ));
- assertEquals(set.contains(LOCALE_QQ_ZZ), LocaleUtils.isAvailableLocale(LOCALE_QQ_ZZ));
- }
-
- @Test
- public void testIsLanguageUndetermined() {
- final Set<Locale> set = LocaleUtils.availableLocaleSet();
- // Determined
- assertNotEquals(set.contains(LOCALE_EN), LocaleUtils.isLanguageUndetermined(LOCALE_EN));
- assertNotEquals(set.contains(LOCALE_EN_US), LocaleUtils.isLanguageUndetermined(LOCALE_EN_US));
- assertNotEquals(set.contains(LOCALE_FR), LocaleUtils.isLanguageUndetermined(LOCALE_FR));
- assertNotEquals(set.contains(LOCALE_FR_CA), LocaleUtils.isLanguageUndetermined(LOCALE_FR_CA));
- // Undetermined
- assertEquals(set.contains(LOCALE_EN_US_ZZZZ), LocaleUtils.isLanguageUndetermined(LOCALE_EN_US_ZZZZ));
- assertEquals(set.contains(LOCALE_QQ), LocaleUtils.isLanguageUndetermined(LOCALE_QQ));
- assertEquals(set.contains(LOCALE_QQ_ZZ), LocaleUtils.isLanguageUndetermined(LOCALE_QQ_ZZ));
- //
- assertTrue(LocaleUtils.isLanguageUndetermined(null));
+ @ParameterizedTest
+ @MethodSource("java.util.Locale#getAvailableLocales")
+ public void testParseAllLocales(final Locale actualLocale) {
+ // Check if it's possible to recreate the Locale using just the standard constructor
+ final Locale locale = new Locale(actualLocale.getLanguage(), actualLocale.getCountry(), actualLocale.getVariant());
+ if (actualLocale.equals(locale)) { // it is possible for LocaleUtils.toLocale to handle these Locales
+ final String str = actualLocale.toString();
+ // Look for the script/extension suffix
+ int suff = str.indexOf("_#");
+ if (suff == - 1) {
+ suff = str.indexOf("#");
+ }
+ String localeStr = str;
+ if (suff >= 0) { // we have a suffix
+ assertThrows(IllegalArgumentException.class, () -> LocaleUtils.toLocale(str));
+ // try without suffix
+ localeStr = str.substring(0, suff);
+ }
+ final Locale loc = LocaleUtils.toLocale(localeStr);
+ assertEquals(actualLocale, loc);
+ }
}
/**
@@ -392,181 +472,101 @@ public class LocaleUtilsTest extends AbstractLangTest {
}
/**
- * Make sure the language by country is correct. It checks that
- * the LocaleUtils.languagesByCountry(country) call contains the
- * array of languages passed in. It may contain more due to JVM
- * variations.
- *
- * @param country
- * @param languages array of languages that should be returned
- */
- private static void assertLanguageByCountry(final String country, final String[] languages) {
- final List<Locale> list = LocaleUtils.languagesByCountry(country);
- final List<Locale> list2 = LocaleUtils.languagesByCountry(country);
- assertNotNull(list);
- assertSame(list, list2);
- //search through languages
- for (final String language : languages) {
- final Iterator<Locale> iterator = list.iterator();
- boolean found = false;
- // see if it was returned by the set
- while (iterator.hasNext()) {
- final Locale locale = iterator.next();
- // should have an en empty variant
- assertTrue(StringUtils.isEmpty(locale.getVariant()));
- assertEquals(country, locale.getCountry());
- if (language.equals(locale.getLanguage())) {
- found = true;
- break;
- }
- }
- assertTrue(found, "Could not find language: " + language + " for country: " + country);
- }
- assertUnmodifiableCollection(list);
- }
-
- /**
- * Test languagesByCountry() method.
+ * Test toLocale(String) method.
*/
@Test
- public void testLanguagesByCountry() {
- assertLanguageByCountry(null, new String[0]);
- assertLanguageByCountry("GB", new String[]{"en"});
- assertLanguageByCountry("ZZ", new String[0]);
- assertLanguageByCountry("CH", new String[]{"fr", "de", "it"});
- }
-
- /**
- * Make sure the country by language is correct. It checks that
- * the LocaleUtils.countryByLanguage(language) call contains the
- * array of countries passed in. It may contain more due to JVM
- * variations.
- *
- *
- * @param language
- * @param countries array of countries that should be returned
- */
- private static void assertCountriesByLanguage(final String language, final String[] countries) {
- final List<Locale> list = LocaleUtils.countriesByLanguage(language);
- final List<Locale> list2 = LocaleUtils.countriesByLanguage(language);
- assertNotNull(list);
- assertSame(list, list2);
- //search through languages
- for (final String country : countries) {
- final Iterator<Locale> iterator = list.iterator();
- boolean found = false;
- // see if it was returned by the set
- while (iterator.hasNext()) {
- final Locale locale = iterator.next();
- // should have an en empty variant
- assertTrue(StringUtils.isEmpty(locale.getVariant()));
- assertEquals(language, locale.getLanguage());
- if (country.equals(locale.getCountry())) {
- found = true;
- break;
- }
- }
- assertTrue(found, "Could not find language: " + country + " for country: " + language);
- }
- assertUnmodifiableCollection(list);
- }
+ public void testToLocale_1Part() {
+ assertNull(LocaleUtils.toLocale((String) null));
- /**
- * Test countriesByLanguage() method.
- */
- @Test
- public void testCountriesByLanguage() {
- assertCountriesByLanguage(null, new String[0]);
- assertCountriesByLanguage("de", new String[]{"DE", "CH", "AT", "LU"});
- assertCountriesByLanguage("zz", new String[0]);
- assertCountriesByLanguage("it", new String[]{"IT", "CH"});
- }
+ assertValidToLocale("us");
+ assertValidToLocale("fr");
+ assertValidToLocale("de");
+ assertValidToLocale("zh");
+ // Valid format but lang doesn't exist, should make instance anyway
+ assertValidToLocale("qq");
+ // LANG-941: JDK 8 introduced the empty locale as one of the default locales
+ assertValidToLocale("");
- /**
- * @param coll the collection to check
- */
- private static void assertUnmodifiableCollection(final Collection<?> coll) {
- assertThrows(UnsupportedOperationException.class, () -> coll.add(null));
+ assertThrows(IllegalArgumentException.class, () -> LocaleUtils.toLocale("Us"), "Should fail if not lowercase");
+ assertThrows(IllegalArgumentException.class, () -> LocaleUtils.toLocale("uS"), "Should fail if not lowercase");
+ assertThrows(IllegalArgumentException.class, () -> LocaleUtils.toLocale("u#"), "Should fail if not lowercase");
+ assertThrows(
+ IllegalArgumentException.class, () -> LocaleUtils.toLocale("u"), "Must be 2 chars if less than 5");
+ assertThrows(
+ IllegalArgumentException.class, () -> LocaleUtils.toLocale("uu_U"), "Must be 2 chars if less than 5");
}
/**
- * Tests #LANG-328 - only language+variant
+ * Test toLocale() method.
*/
@Test
- public void testLang328() {
- assertValidToLocale("fr__P", "fr", "", "P");
- assertValidToLocale("fr__POSIX", "fr", "", "POSIX");
- }
-
- @Test
- public void testLanguageAndUNM49Numeric3AreaCodeLang1312() {
- assertValidToLocale("en_001", "en", "001");
- assertValidToLocale("en_150", "en", "150");
- assertValidToLocale("ar_001", "ar", "001");
-
- // LANG-1312
- assertValidToLocale("en_001_GB", "en", "001", "GB");
- assertValidToLocale("en_150_US", "en", "150", "US");
- }
+ public void testToLocale_2Part() {
+ assertValidToLocale("us_EN", "us", "EN");
+ assertValidToLocale("us-EN", "us", "EN");
+ //valid though doesn't exist
+ assertValidToLocale("us_ZH", "us", "ZH");
- /**
- * Tests #LANG-865, strings starting with an underscore.
- */
- @Test
- public void testLang865() {
- assertValidToLocale("_GB", "", "GB", "");
- assertValidToLocale("_GB_P", "", "GB", "P");
- assertValidToLocale("_GB_POSIX", "", "GB", "POSIX");
assertThrows(
IllegalArgumentException.class,
- () -> LocaleUtils.toLocale("_G"),
- "Must be at least 3 chars if starts with underscore");
+ () -> LocaleUtils.toLocale("us_En"),
+ "Should fail second part not uppercase");
assertThrows(
IllegalArgumentException.class,
- () -> LocaleUtils.toLocale("_Gb"),
- "Must be uppercase if starts with underscore");
+ () -> LocaleUtils.toLocale("us_en"),
+ "Should fail second part not uppercase");
assertThrows(
IllegalArgumentException.class,
- () -> LocaleUtils.toLocale("_gB"),
- "Must be uppercase if starts with underscore");
+ () -> LocaleUtils.toLocale("us_eN"),
+ "Should fail second part not uppercase");
assertThrows(
IllegalArgumentException.class,
- () -> LocaleUtils.toLocale("_1B"),
- "Must be letter if starts with underscore");
+ () -> LocaleUtils.toLocale("uS_EN"),
+ "Should fail first part not lowercase");
assertThrows(
IllegalArgumentException.class,
- () -> LocaleUtils.toLocale("_G1"),
- "Must be letter if starts with underscore");
+ () -> LocaleUtils.toLocale("us_E3"),
+ "Should fail second part not uppercase");
+ }
+
+ /**
+ * Test toLocale() method.
+ */
+ @Test
+ public void testToLocale_3Part() {
+ assertValidToLocale("us_EN_A", "us", "EN", "A");
+ assertValidToLocale("us-EN-A", "us", "EN", "A");
+ // this isn't pretty, but was caused by a jdk bug it seems
+ // https://bugs.java.com/bugdatabase/view_bug.do?bug_id=4210525
+ if (SystemUtils.isJavaVersionAtLeast(JAVA_1_4)) {
+ assertValidToLocale("us_EN_a", "us", "EN", "a");
+ assertValidToLocale("us_EN_SFsafdFDsdfF", "us", "EN", "SFsafdFDsdfF");
+ } else {
+ assertValidToLocale("us_EN_a", "us", "EN", "A");
+ assertValidToLocale("us_EN_SFsafdFDsdfF", "us", "EN", "SFSAFDFDSDFF");
+ }
+
assertThrows(
- IllegalArgumentException.class,
- () -> LocaleUtils.toLocale("_GB_"),
- "Must be at least 5 chars if starts with underscore");
+ IllegalArgumentException.class, () -> LocaleUtils.toLocale("us_EN-a"), "Should fail as no consistent delimiter");
assertThrows(
- IllegalArgumentException.class,
- () -> LocaleUtils.toLocale("_GBAP"),
- "Must have underscore after the country if starts with underscore and is at least 5 chars");
+ IllegalArgumentException.class, () -> LocaleUtils.toLocale("uu_UU_"), "Must be 3, 5 or 7+ in length");
+ }
+
+ /**
+ * Test toLocale(Locale) method.
+ */
+ @Test
+ public void testToLocale_Locale_defaults() {
+ assertNull(LocaleUtils.toLocale((String) null));
+ assertEquals(Locale.getDefault(), LocaleUtils.toLocale((Locale) null));
+ assertEquals(Locale.getDefault(), LocaleUtils.toLocale(Locale.getDefault()));
}
+ /**
+ * Test toLocale(Locale) method.
+ */
@ParameterizedTest
@MethodSource("java.util.Locale#getAvailableLocales")
- public void testParseAllLocales(final Locale actualLocale) {
- // Check if it's possible to recreate the Locale using just the standard constructor
- final Locale locale = new Locale(actualLocale.getLanguage(), actualLocale.getCountry(), actualLocale.getVariant());
- if (actualLocale.equals(locale)) { // it is possible for LocaleUtils.toLocale to handle these Locales
- final String str = actualLocale.toString();
- // Look for the script/extension suffix
- int suff = str.indexOf("_#");
- if (suff == - 1) {
- suff = str.indexOf("#");
- }
- String localeStr = str;
- if (suff >= 0) { // we have a suffix
- assertThrows(IllegalArgumentException.class, () -> LocaleUtils.toLocale(str));
- // try without suffix
- localeStr = str.substring(0, suff);
- }
- final Locale loc = LocaleUtils.toLocale(localeStr);
- assertEquals(actualLocale, loc);
- }
+ public void testToLocales(final Locale actualLocale) {
+ assertEquals(actualLocale, LocaleUtils.toLocale(actualLocale));
}
}
diff --git a/src/test/java/org/apache/commons/lang3/NotImplementedExceptionTest.java b/src/test/java/org/apache/commons/lang3/NotImplementedExceptionTest.java
index 25852a3d5..98e5e9828 100644
--- a/src/test/java/org/apache/commons/lang3/NotImplementedExceptionTest.java
+++ b/src/test/java/org/apache/commons/lang3/NotImplementedExceptionTest.java
@@ -27,6 +27,13 @@ import org.junit.jupiter.api.Test;
*/
public class NotImplementedExceptionTest extends AbstractLangTest {
+ private void assertCorrect(final String assertMessage, final NotImplementedException nie, final String message, final Throwable nested, final String code) {
+ assertNotNull(nie, assertMessage + ": target is null");
+ assertEquals(message, nie.getMessage(), assertMessage + ": Message not equal");
+ assertEquals(nested, nie.getCause(), assertMessage + ": Nested throwable not equal");
+ assertEquals(code, nie.getCode(), assertMessage + ": Code not equal");
+ }
+
@Test
public void testConstructors() {
final Throwable nested = new RuntimeException();
@@ -48,11 +55,4 @@ public class NotImplementedExceptionTest extends AbstractLangTest {
assertNull(new NotImplementedException().getCode());
}
-
- private void assertCorrect(final String assertMessage, final NotImplementedException nie, final String message, final Throwable nested, final String code) {
- assertNotNull(nie, assertMessage + ": target is null");
- assertEquals(message, nie.getMessage(), assertMessage + ": Message not equal");
- assertEquals(nested, nie.getCause(), assertMessage + ": Nested throwable not equal");
- assertEquals(code, nie.getCode(), assertMessage + ": Code not equal");
- }
}
diff --git a/src/test/java/org/apache/commons/lang3/ObjectUtilsTest.java b/src/test/java/org/apache/commons/lang3/ObjectUtilsTest.java
index 8f297918c..bc080cacb 100644
--- a/src/test/java/org/apache/commons/lang3/ObjectUtilsTest.java
+++ b/src/test/java/org/apache/commons/lang3/ObjectUtilsTest.java
@@ -59,8 +59,6 @@ import org.junit.jupiter.api.Test;
@SuppressWarnings("deprecation") // deliberate use of deprecated code
public class ObjectUtilsTest extends AbstractLangTest {
- private static final Supplier<?> NULL_SUPPLIER = null;
-
static final class CharSequenceComparator implements Comparator<CharSequence> {
@Override
@@ -129,6 +127,8 @@ public class ObjectUtilsTest extends AbstractLangTest {
}
}
+ private static final Supplier<?> NULL_SUPPLIER = null;
+
private static final String FOO = "foo";
private static final String BAR = "bar";
private static final String[] NON_EMPTY_ARRAY = { FOO, BAR, };
diff --git a/src/test/java/org/apache/commons/lang3/RandomStringUtilsTest.java b/src/test/java/org/apache/commons/lang3/RandomStringUtilsTest.java
index 7abc149b6..81f902854 100644
--- a/src/test/java/org/apache/commons/lang3/RandomStringUtilsTest.java
+++ b/src/test/java/org/apache/commons/lang3/RandomStringUtilsTest.java
@@ -44,127 +44,54 @@ public class RandomStringUtilsTest extends AbstractLangTest {
private static final int LOOP_COUNT = 1_000;
- @Test
- public void testConstructor() {
- assertNotNull(new RandomStringUtils());
- final Constructor<?>[] cons = RandomStringUtils.class.getDeclaredConstructors();
- assertEquals(1, cons.length);
- assertTrue(Modifier.isPublic(cons[0].getModifiers()));
- assertTrue(Modifier.isPublic(RandomStringUtils.class.getModifiers()));
- assertFalse(Modifier.isFinal(RandomStringUtils.class.getModifiers()));
+ /**
+ * Computes Chi-Square statistic given observed and expected counts
+ * @param observed array of observed frequency counts
+ * @param expected array of expected frequency counts
+ */
+ private double chiSquare(final int[] expected, final int[] observed) {
+ double sumSq = 0.0d;
+ double dev = 0.0d;
+ for (int i = 0; i < observed.length; i++) {
+ dev = observed[i] - expected[i];
+ sumSq += dev * dev / expected[i];
+ }
+ return sumSq;
}
/**
- * Test the implementation
+ * Test for LANG-1286. Creates situation where old code would
+ * overflow a char and result in a code point outside the specified
+ * range.
*/
@Test
- public void testRandomStringUtils() {
- String r1 = RandomStringUtils.random(50);
- assertEquals(50, r1.length(), "random(50) length");
- String r2 = RandomStringUtils.random(50);
- assertEquals(50, r2.length(), "random(50) length");
- assertFalse(r1.equals(r2), "!r1.equals(r2)");
-
- r1 = RandomStringUtils.randomAscii(50);
- assertEquals(50, r1.length(), "randomAscii(50) length");
- for (int i = 0; i < r1.length(); i++) {
- assertThat("char >= 32 && <= 127", ((int) r1.charAt(i)), allOf(greaterThanOrEqualTo(32), lessThanOrEqualTo(127)));
- }
- r2 = RandomStringUtils.randomAscii(50);
- assertFalse(r1.equals(r2), "!r1.equals(r2)");
-
- r1 = RandomStringUtils.randomAlphabetic(50);
- assertEquals(50, r1.length(), "randomAlphabetic(50)");
- for (int i = 0; i < r1.length(); i++) {
- assertTrue(Character.isLetter(r1.charAt(i)) && !Character.isDigit(r1.charAt(i)), "r1 contains alphabetic");
- }
- r2 = RandomStringUtils.randomAlphabetic(50);
- assertFalse(r1.equals(r2), "!r1.equals(r2)");
-
- r1 = RandomStringUtils.randomAlphanumeric(50);
- assertEquals(50, r1.length(), "randomAlphanumeric(50)");
- for (int i = 0; i < r1.length(); i++) {
- assertTrue(Character.isLetterOrDigit(r1.charAt(i)), "r1 contains alphanumeric");
- }
- r2 = RandomStringUtils.randomAlphabetic(50);
- assertFalse(r1.equals(r2), "!r1.equals(r2)");
-
- r1 = RandomStringUtils.randomGraph(50);
- assertEquals(50, r1.length(), "randomGraph(50) length");
- for (int i = 0; i < r1.length(); i++) {
- assertTrue(r1.charAt(i) >= 33 && r1.charAt(i) <= 126, "char between 33 and 126");
- }
- r2 = RandomStringUtils.randomGraph(50);
- assertFalse(r1.equals(r2), "!r1.equals(r2)");
-
- r1 = RandomStringUtils.randomNumeric(50);
- assertEquals(50, r1.length(), "randomNumeric(50)");
- for (int i = 0; i < r1.length(); i++) {
- assertTrue(Character.isDigit(r1.charAt(i)) && !Character.isLetter(r1.charAt(i)), "r1 contains numeric");
- }
- r2 = RandomStringUtils.randomNumeric(50);
- assertFalse(r1.equals(r2), "!r1.equals(r2)");
-
- r1 = RandomStringUtils.randomPrint(50);
- assertEquals(50, r1.length(), "randomPrint(50) length");
- for (int i = 0; i < r1.length(); i++) {
- assertTrue(r1.charAt(i) >= 32 && r1.charAt(i) <= 126, "char between 32 and 126");
- }
- r2 = RandomStringUtils.randomPrint(50);
- assertFalse(r1.equals(r2), "!r1.equals(r2)");
-
- String set = "abcdefg";
- r1 = RandomStringUtils.random(50, set);
- assertEquals(50, r1.length(), "random(50, \"abcdefg\")");
- for (int i = 0; i < r1.length(); i++) {
- assertTrue(set.indexOf(r1.charAt(i)) > -1, "random char in set");
- }
- r2 = RandomStringUtils.random(50, set);
- assertFalse(r1.equals(r2), "!r1.equals(r2)");
-
- r1 = RandomStringUtils.random(50, (String) null);
- assertEquals(50, r1.length(), "random(50) length");
- r2 = RandomStringUtils.random(50, (String) null);
- assertEquals(50, r2.length(), "random(50) length");
- assertFalse(r1.equals(r2), "!r1.equals(r2)");
-
- set = "stuvwxyz";
- r1 = RandomStringUtils.random(50, set.toCharArray());
- assertEquals(50, r1.length(), "random(50, \"stuvwxyz\")");
- for (int i = 0; i < r1.length(); i++) {
- assertTrue(set.indexOf(r1.charAt(i)) > -1, "random char in set");
- }
- r2 = RandomStringUtils.random(50, set);
- assertFalse(r1.equals(r2), "!r1.equals(r2)");
-
- r1 = RandomStringUtils.random(50, (char[]) null);
- assertEquals(50, r1.length(), "random(50) length");
- r2 = RandomStringUtils.random(50, (char[]) null);
- assertEquals(50, r2.length(), "random(50) length");
- assertFalse(r1.equals(r2), "!r1.equals(r2)");
-
- final long seedMillis = System.currentTimeMillis();
- r1 = RandomStringUtils.random(50, 0, 0, true, true, null, new Random(seedMillis));
- r2 = RandomStringUtils.random(50, 0, 0, true, true, null, new Random(seedMillis));
- assertEquals(r1, r2, "r1.equals(r2)");
+ public void testCharOverflow() {
+ final int start = Character.MAX_VALUE;
+ final int end = Integer.MAX_VALUE;
- r1 = RandomStringUtils.random(0);
- assertEquals("", r1, "random(0).equals(\"\")");
- }
+ @SuppressWarnings("serial")
+ final
+ Random fixedRandom = new Random() {
+ @Override
+ public int nextInt(final int n) {
+ // Prevents selection of 'start' as the character
+ return super.nextInt(n - 1) + 1;
+ }
+ };
- @Test
- public void testLANG805() {
- final long seedMillis = System.currentTimeMillis();
- assertEquals("aaa", RandomStringUtils.random(3, 0, 0, false, false, new char[]{'a'}, new Random(seedMillis)));
+ final String result = RandomStringUtils.random(2, start, end, false, false, null, fixedRandom);
+ final int c = result.codePointAt(0);
+ assertTrue(c >= start && c < end, String.format("Character '%d' not in range [%d,%d).", c, start, end));
}
@Test
- public void testLANG807() {
- final IllegalArgumentException ex =
- assertThrows(IllegalArgumentException.class, () -> RandomStringUtils.random(3, 5, 5, false, false));
- final String msg = ex.getMessage();
- assertTrue(msg.contains("start"), "Message (" + msg + ") must contain 'start'");
- assertTrue(msg.contains("end"), "Message (" + msg + ") must contain 'end'");
+ public void testConstructor() {
+ assertNotNull(new RandomStringUtils());
+ final Constructor<?>[] cons = RandomStringUtils.class.getDeclaredConstructors();
+ assertEquals(1, cons.length);
+ assertTrue(Modifier.isPublic(cons[0].getModifiers()));
+ assertTrue(Modifier.isPublic(RandomStringUtils.class.getModifiers()));
+ assertFalse(Modifier.isFinal(RandomStringUtils.class.getModifiers()));
}
@Test
@@ -191,49 +118,46 @@ public class RandomStringUtilsTest extends AbstractLangTest {
}
/**
- * Make sure boundary alphanumeric characters are generated by randomAlphaNumeric
- * This test will fail randomly with probability = 6 * (61/62)**1000 ~ 5.2E-7
+ * Checks if the string got by {@link RandomStringUtils#random(int)}
+ * can be converted to UTF-8 and back without loss.
+ *
+ * @see <a href="https://issues.apache.org/jira/browse/LANG-100">LANG-100</a>
*/
@Test
- public void testRandomAlphaNumeric() {
- final char[] testChars = {'a', 'z', 'A', 'Z', '0', '9'};
- final boolean[] found = {false, false, false, false, false, false};
- for (int i = 0; i < LOOP_COUNT; i++) {
- final String randString = RandomStringUtils.randomAlphanumeric(10);
- for (int j = 0; j < testChars.length; j++) {
- if (randString.indexOf(testChars[j]) > 0) {
- found[j] = true;
- }
- }
- }
- for (int i = 0; i < testChars.length; i++) {
- assertTrue(found[i],
- "alphanumeric character not generated in 1000 attempts: " +
- testChars[i] + " -- repeated failures indicate a problem ");
+ public void testLang100() {
+ final int size = 5000;
+ final Charset charset = StandardCharsets.UTF_8;
+ final String orig = RandomStringUtils.random(size);
+ final byte[] bytes = orig.getBytes(charset);
+ final String copy = new String(bytes, charset);
+
+ // for a verbose compare:
+ for (int i=0; i < orig.length() && i < copy.length(); i++) {
+ final char o = orig.charAt(i);
+ final char c = copy.charAt(i);
+ assertEquals(o, c,
+ "differs at " + i + "(" + Integer.toHexString(Character.valueOf(o).hashCode()) + "," +
+ Integer.toHexString(Character.valueOf(c).hashCode()) + ")");
}
+ // compare length also
+ assertEquals(orig.length(), copy.length());
+ // just to be complete
+ assertEquals(orig, copy);
}
- /**
- * Make sure '0' and '9' are generated by randomNumeric
- * This test will fail randomly with probability = 2 * (9/10)**1000 ~ 3.5E-46
- */
@Test
- public void testRandomNumeric() {
- final char[] testChars = {'0', '9'};
- final boolean[] found = {false, false};
- for (int i = 0; i < LOOP_COUNT; i++) {
- final String randString = RandomStringUtils.randomNumeric(10);
- for (int j = 0; j < testChars.length; j++) {
- if (randString.indexOf(testChars[j]) > 0) {
- found[j] = true;
- }
- }
- }
- for (int i = 0; i < testChars.length; i++) {
- assertTrue(found[i],
- "digit not generated in 1000 attempts: " + testChars[i] +
- " -- repeated failures indicate a problem ");
- }
+ public void testLANG805() {
+ final long seedMillis = System.currentTimeMillis();
+ assertEquals("aaa", RandomStringUtils.random(3, 0, 0, false, false, new char[]{'a'}, new Random(seedMillis)));
+ }
+
+ @Test
+ public void testLANG807() {
+ final IllegalArgumentException ex =
+ assertThrows(IllegalArgumentException.class, () -> RandomStringUtils.random(3, 5, 5, false, false));
+ final String msg = ex.getMessage();
+ assertTrue(msg.contains("start"), "Message (" + msg + ") must contain 'start'");
+ assertTrue(msg.contains("end"), "Message (" + msg + ") must contain 'end'");
}
/**
@@ -259,40 +183,16 @@ public class RandomStringUtilsTest extends AbstractLangTest {
}
}
- /**
- * Make sure 32 and 127 are generated by randomNumeric
- * This test will fail randomly with probability = 2*(95/96)**1000 ~ 5.7E-5
- */
@Test
- public void testRandomAscii() {
- final char[] testChars = {(char) 32, (char) 126};
- final boolean[] found = {false, false};
- // Test failures have been observed on GitHub builds with a 100 limit.
- for (int i = 0; i < LOOP_COUNT; i++) {
- final String randString = RandomStringUtils.randomAscii(10);
- for (int j = 0; j < testChars.length; j++) {
- if (randString.indexOf(testChars[j]) > 0) {
- found[j] = true;
- }
- }
- }
- for (int i = 0; i < testChars.length; i++) {
- assertTrue(found[i],
- "ascii character not generated in 1000 attempts: " + (int) testChars[i] +
- " -- repeated failures indicate a problem");
- }
- }
-
- @Test
- public void testRandomAsciiRange() {
+ public void testRandomAlphabeticRange() {
final int expectedMinLengthInclusive = 1;
final int expectedMaxLengthExclusive = 11;
- final String pattern = "^\\p{ASCII}{" + expectedMinLengthInclusive + ',' + expectedMaxLengthExclusive + "}$";
+ final String pattern = "^\\p{Alpha}{" + expectedMinLengthInclusive + ',' + expectedMaxLengthExclusive + "}$";
int maxCreatedLength = expectedMinLengthInclusive;
int minCreatedLength = expectedMaxLengthExclusive - 1;
for (int i = 0; i < LOOP_COUNT; i++) {
- final String s = RandomStringUtils.randomAscii(expectedMinLengthInclusive, expectedMaxLengthExclusive);
+ final String s = RandomStringUtils.randomAlphabetic(expectedMinLengthInclusive, expectedMaxLengthExclusive);
assertThat("within range", s.length(), allOf(greaterThanOrEqualTo(expectedMinLengthInclusive), lessThanOrEqualTo(expectedMaxLengthExclusive - 1)));
assertTrue(s.matches(pattern), s);
@@ -308,16 +208,39 @@ public class RandomStringUtilsTest extends AbstractLangTest {
assertThat("max generated, may fail randomly rarely", maxCreatedLength, is(expectedMaxLengthExclusive - 1));
}
+ /**
+ * Make sure boundary alphanumeric characters are generated by randomAlphaNumeric
+ * This test will fail randomly with probability = 6 * (61/62)**1000 ~ 5.2E-7
+ */
@Test
- public void testRandomAlphabeticRange() {
+ public void testRandomAlphaNumeric() {
+ final char[] testChars = {'a', 'z', 'A', 'Z', '0', '9'};
+ final boolean[] found = {false, false, false, false, false, false};
+ for (int i = 0; i < LOOP_COUNT; i++) {
+ final String randString = RandomStringUtils.randomAlphanumeric(10);
+ for (int j = 0; j < testChars.length; j++) {
+ if (randString.indexOf(testChars[j]) > 0) {
+ found[j] = true;
+ }
+ }
+ }
+ for (int i = 0; i < testChars.length; i++) {
+ assertTrue(found[i],
+ "alphanumeric character not generated in 1000 attempts: " +
+ testChars[i] + " -- repeated failures indicate a problem ");
+ }
+ }
+
+ @Test
+ public void testRandomAlphanumericRange() {
final int expectedMinLengthInclusive = 1;
final int expectedMaxLengthExclusive = 11;
- final String pattern = "^\\p{Alpha}{" + expectedMinLengthInclusive + ',' + expectedMaxLengthExclusive + "}$";
+ final String pattern = "^\\p{Alnum}{" + expectedMinLengthInclusive + ',' + expectedMaxLengthExclusive + "}$";
int maxCreatedLength = expectedMinLengthInclusive;
int minCreatedLength = expectedMaxLengthExclusive - 1;
for (int i = 0; i < LOOP_COUNT; i++) {
- final String s = RandomStringUtils.randomAlphabetic(expectedMinLengthInclusive, expectedMaxLengthExclusive);
+ final String s = RandomStringUtils.randomAlphanumeric(expectedMinLengthInclusive, expectedMaxLengthExclusive);
assertThat("within range", s.length(), allOf(greaterThanOrEqualTo(expectedMinLengthInclusive), lessThanOrEqualTo(expectedMaxLengthExclusive - 1)));
assertTrue(s.matches(pattern), s);
@@ -333,16 +256,40 @@ public class RandomStringUtilsTest extends AbstractLangTest {
assertThat("max generated, may fail randomly rarely", maxCreatedLength, is(expectedMaxLengthExclusive - 1));
}
+ /**
+ * Make sure 32 and 127 are generated by randomNumeric
+ * This test will fail randomly with probability = 2*(95/96)**1000 ~ 5.7E-5
+ */
@Test
- public void testRandomAlphanumericRange() {
+ public void testRandomAscii() {
+ final char[] testChars = {(char) 32, (char) 126};
+ final boolean[] found = {false, false};
+ // Test failures have been observed on GitHub builds with a 100 limit.
+ for (int i = 0; i < LOOP_COUNT; i++) {
+ final String randString = RandomStringUtils.randomAscii(10);
+ for (int j = 0; j < testChars.length; j++) {
+ if (randString.indexOf(testChars[j]) > 0) {
+ found[j] = true;
+ }
+ }
+ }
+ for (int i = 0; i < testChars.length; i++) {
+ assertTrue(found[i],
+ "ascii character not generated in 1000 attempts: " + (int) testChars[i] +
+ " -- repeated failures indicate a problem");
+ }
+ }
+
+ @Test
+ public void testRandomAsciiRange() {
final int expectedMinLengthInclusive = 1;
final int expectedMaxLengthExclusive = 11;
- final String pattern = "^\\p{Alnum}{" + expectedMinLengthInclusive + ',' + expectedMaxLengthExclusive + "}$";
+ final String pattern = "^\\p{ASCII}{" + expectedMinLengthInclusive + ',' + expectedMaxLengthExclusive + "}$";
int maxCreatedLength = expectedMinLengthInclusive;
int minCreatedLength = expectedMaxLengthExclusive - 1;
for (int i = 0; i < LOOP_COUNT; i++) {
- final String s = RandomStringUtils.randomAlphanumeric(expectedMinLengthInclusive, expectedMaxLengthExclusive);
+ final String s = RandomStringUtils.randomAscii(expectedMinLengthInclusive, expectedMaxLengthExclusive);
assertThat("within range", s.length(), allOf(greaterThanOrEqualTo(expectedMinLengthInclusive), lessThanOrEqualTo(expectedMaxLengthExclusive - 1)));
assertTrue(s.matches(pattern), s);
@@ -383,6 +330,29 @@ public class RandomStringUtilsTest extends AbstractLangTest {
assertThat("max generated, may fail randomly rarely", maxCreatedLength, is(expectedMaxLengthExclusive - 1));
}
+ /**
+ * Make sure '0' and '9' are generated by randomNumeric
+ * This test will fail randomly with probability = 2 * (9/10)**1000 ~ 3.5E-46
+ */
+ @Test
+ public void testRandomNumeric() {
+ final char[] testChars = {'0', '9'};
+ final boolean[] found = {false, false};
+ for (int i = 0; i < LOOP_COUNT; i++) {
+ final String randString = RandomStringUtils.randomNumeric(10);
+ for (int j = 0; j < testChars.length; j++) {
+ if (randString.indexOf(testChars[j]) > 0) {
+ found[j] = true;
+ }
+ }
+ }
+ for (int i = 0; i < testChars.length; i++) {
+ assertTrue(found[i],
+ "digit not generated in 1000 attempts: " + testChars[i] +
+ " -- repeated failures indicate a problem ");
+ }
+ }
+
@Test
public void testRandomNumericRange() {
final int expectedMinLengthInclusive = 1;
@@ -433,6 +403,105 @@ public class RandomStringUtilsTest extends AbstractLangTest {
assertThat("max generated, may fail randomly rarely", maxCreatedLength, is(expectedMaxLengthExclusive - 1));
}
+ /**
+ * Test the implementation
+ */
+ @Test
+ public void testRandomStringUtils() {
+ String r1 = RandomStringUtils.random(50);
+ assertEquals(50, r1.length(), "random(50) length");
+ String r2 = RandomStringUtils.random(50);
+ assertEquals(50, r2.length(), "random(50) length");
+ assertFalse(r1.equals(r2), "!r1.equals(r2)");
+
+ r1 = RandomStringUtils.randomAscii(50);
+ assertEquals(50, r1.length(), "randomAscii(50) length");
+ for (int i = 0; i < r1.length(); i++) {
+ assertThat("char >= 32 && <= 127", ((int) r1.charAt(i)), allOf(greaterThanOrEqualTo(32), lessThanOrEqualTo(127)));
+ }
+ r2 = RandomStringUtils.randomAscii(50);
+ assertFalse(r1.equals(r2), "!r1.equals(r2)");
+
+ r1 = RandomStringUtils.randomAlphabetic(50);
+ assertEquals(50, r1.length(), "randomAlphabetic(50)");
+ for (int i = 0; i < r1.length(); i++) {
+ assertTrue(Character.isLetter(r1.charAt(i)) && !Character.isDigit(r1.charAt(i)), "r1 contains alphabetic");
+ }
+ r2 = RandomStringUtils.randomAlphabetic(50);
+ assertFalse(r1.equals(r2), "!r1.equals(r2)");
+
+ r1 = RandomStringUtils.randomAlphanumeric(50);
+ assertEquals(50, r1.length(), "randomAlphanumeric(50)");
+ for (int i = 0; i < r1.length(); i++) {
+ assertTrue(Character.isLetterOrDigit(r1.charAt(i)), "r1 contains alphanumeric");
+ }
+ r2 = RandomStringUtils.randomAlphabetic(50);
+ assertFalse(r1.equals(r2), "!r1.equals(r2)");
+
+ r1 = RandomStringUtils.randomGraph(50);
+ assertEquals(50, r1.length(), "randomGraph(50) length");
+ for (int i = 0; i < r1.length(); i++) {
+ assertTrue(r1.charAt(i) >= 33 && r1.charAt(i) <= 126, "char between 33 and 126");
+ }
+ r2 = RandomStringUtils.randomGraph(50);
+ assertFalse(r1.equals(r2), "!r1.equals(r2)");
+
+ r1 = RandomStringUtils.randomNumeric(50);
+ assertEquals(50, r1.length(), "randomNumeric(50)");
+ for (int i = 0; i < r1.length(); i++) {
+ assertTrue(Character.isDigit(r1.charAt(i)) && !Character.isLetter(r1.charAt(i)), "r1 contains numeric");
+ }
+ r2 = RandomStringUtils.randomNumeric(50);
+ assertFalse(r1.equals(r2), "!r1.equals(r2)");
+
+ r1 = RandomStringUtils.randomPrint(50);
+ assertEquals(50, r1.length(), "randomPrint(50) length");
+ for (int i = 0; i < r1.length(); i++) {
+ assertTrue(r1.charAt(i) >= 32 && r1.charAt(i) <= 126, "char between 32 and 126");
+ }
+ r2 = RandomStringUtils.randomPrint(50);
+ assertFalse(r1.equals(r2), "!r1.equals(r2)");
+
+ String set = "abcdefg";
+ r1 = RandomStringUtils.random(50, set);
+ assertEquals(50, r1.length(), "random(50, \"abcdefg\")");
+ for (int i = 0; i < r1.length(); i++) {
+ assertTrue(set.indexOf(r1.charAt(i)) > -1, "random char in set");
+ }
+ r2 = RandomStringUtils.random(50, set);
+ assertFalse(r1.equals(r2), "!r1.equals(r2)");
+
+ r1 = RandomStringUtils.random(50, (String) null);
+ assertEquals(50, r1.length(), "random(50) length");
+ r2 = RandomStringUtils.random(50, (String) null);
+ assertEquals(50, r2.length(), "random(50) length");
+ assertFalse(r1.equals(r2), "!r1.equals(r2)");
+
+ set = "stuvwxyz";
+ r1 = RandomStringUtils.random(50, set.toCharArray());
+ assertEquals(50, r1.length(), "random(50, \"stuvwxyz\")");
+ for (int i = 0; i < r1.length(); i++) {
+ assertTrue(set.indexOf(r1.charAt(i)) > -1, "random char in set");
+ }
+ r2 = RandomStringUtils.random(50, set);
+ assertFalse(r1.equals(r2), "!r1.equals(r2)");
+
+ r1 = RandomStringUtils.random(50, (char[]) null);
+ assertEquals(50, r1.length(), "random(50) length");
+ r2 = RandomStringUtils.random(50, (char[]) null);
+ assertEquals(50, r2.length(), "random(50) length");
+ assertFalse(r1.equals(r2), "!r1.equals(r2)");
+
+ final long seedMillis = System.currentTimeMillis();
+ r1 = RandomStringUtils.random(50, 0, 0, true, true, null, new Random(seedMillis));
+ r2 = RandomStringUtils.random(50, 0, 0, true, true, null, new Random(seedMillis));
+ assertEquals(r1, r2, "r1.equals(r2)");
+
+ r1 = RandomStringUtils.random(0);
+ assertEquals("", r1, "random(0).equals(\"\")");
+ }
+
+
/**
* Test homogeneity of random strings generated --
* i.e., test that characters show up with expected frequencies
@@ -473,74 +542,5 @@ public class RandomStringUtilsTest extends AbstractLangTest {
// critical value: from scipy.stats import chi2; chi2(2).isf(1e-5)
assertThat("test homogeneity -- will fail about 1 in 100,000 times", chiSquare(expected, counts), lessThan(23.025850929940457d));
}
-
- /**
- * Computes Chi-Square statistic given observed and expected counts
- * @param observed array of observed frequency counts
- * @param expected array of expected frequency counts
- */
- private double chiSquare(final int[] expected, final int[] observed) {
- double sumSq = 0.0d;
- double dev = 0.0d;
- for (int i = 0; i < observed.length; i++) {
- dev = observed[i] - expected[i];
- sumSq += dev * dev / expected[i];
- }
- return sumSq;
- }
-
- /**
- * Checks if the string got by {@link RandomStringUtils#random(int)}
- * can be converted to UTF-8 and back without loss.
- *
- * @see <a href="https://issues.apache.org/jira/browse/LANG-100">LANG-100</a>
- */
- @Test
- public void testLang100() {
- final int size = 5000;
- final Charset charset = StandardCharsets.UTF_8;
- final String orig = RandomStringUtils.random(size);
- final byte[] bytes = orig.getBytes(charset);
- final String copy = new String(bytes, charset);
-
- // for a verbose compare:
- for (int i=0; i < orig.length() && i < copy.length(); i++) {
- final char o = orig.charAt(i);
- final char c = copy.charAt(i);
- assertEquals(o, c,
- "differs at " + i + "(" + Integer.toHexString(Character.valueOf(o).hashCode()) + "," +
- Integer.toHexString(Character.valueOf(c).hashCode()) + ")");
- }
- // compare length also
- assertEquals(orig.length(), copy.length());
- // just to be complete
- assertEquals(orig, copy);
- }
-
-
- /**
- * Test for LANG-1286. Creates situation where old code would
- * overflow a char and result in a code point outside the specified
- * range.
- */
- @Test
- public void testCharOverflow() {
- final int start = Character.MAX_VALUE;
- final int end = Integer.MAX_VALUE;
-
- @SuppressWarnings("serial")
- final
- Random fixedRandom = new Random() {
- @Override
- public int nextInt(final int n) {
- // Prevents selection of 'start' as the character
- return super.nextInt(n - 1) + 1;
- }
- };
-
- final String result = RandomStringUtils.random(2, start, end, false, false, null, fixedRandom);
- final int c = result.codePointAt(0);
- assertTrue(c >= start && c < end, String.format("Character '%d' not in range [%d,%d).", c, start, end));
- }
}
diff --git a/src/test/java/org/apache/commons/lang3/RandomUtilsTest.java b/src/test/java/org/apache/commons/lang3/RandomUtilsTest.java
index 99e12ecc6..eda6dc712 100644
--- a/src/test/java/org/apache/commons/lang3/RandomUtilsTest.java
+++ b/src/test/java/org/apache/commons/lang3/RandomUtilsTest.java
@@ -43,6 +43,15 @@ public class RandomUtilsTest extends AbstractLangTest {
*/
private static final double DELTA = 1e-5;
+ /**
+ * Tests next boolean
+ */
+ @Test
+ public void testBoolean() {
+ final boolean result = RandomUtils.nextBoolean();
+ assertTrue(result || !result);
+ }
+
@Test
public void testConstructor() {
assertNotNull(new RandomUtils());
@@ -53,66 +62,64 @@ public class RandomUtilsTest extends AbstractLangTest {
assertFalse(Modifier.isFinal(RandomUtils.class.getModifiers()));
}
+ /**
+ * Tests extreme range.
+ */
@Test
- public void testNextBytesNegative() {
- assertThrows(IllegalArgumentException.class, () -> RandomUtils.nextBytes(-1));
- }
-
- @Test
- public void testNextIntNegative() {
- assertThrows(IllegalArgumentException.class, () -> RandomUtils.nextInt(-1, 1));
- }
-
- @Test
- public void testNextLongNegative() {
- assertThrows(IllegalArgumentException.class, () -> RandomUtils.nextLong(-1, 1));
- }
-
- @Test
- public void testNextDoubleNegative() {
- assertThrows(IllegalArgumentException.class, () -> RandomUtils.nextDouble(-1, 1));
- }
-
- @Test
- public void testNextFloatNegative() {
- assertThrows(IllegalArgumentException.class, () -> RandomUtils.nextFloat(-1, 1));
- }
-
- @Test
- public void testNextIntLowerGreaterUpper() {
- assertThrows(IllegalArgumentException.class, () -> RandomUtils.nextInt(2, 1));
- }
-
- @Test
- public void testNextLongLowerGreaterUpper() {
- assertThrows(IllegalArgumentException.class, () -> RandomUtils.nextLong(2, 1));
+ public void testExtremeRangeDouble() {
+ final double result = RandomUtils.nextDouble(0, Double.MAX_VALUE);
+ assertTrue(result >= 0 && result <= Double.MAX_VALUE); // TODO: should be <max?
}
+ /**
+ * Tests extreme range.
+ */
@Test
- public void testNextDoubleLowerGreaterUpper() {
- assertThrows(IllegalArgumentException.class, () -> RandomUtils.nextDouble(2, 1));
+ public void testExtremeRangeFloat() {
+ final float result = RandomUtils.nextFloat(0, Float.MAX_VALUE);
+ assertTrue(result >= 0f && result <= Float.MAX_VALUE); // TODO: should be <max?
}
+ /**
+ * Tests extreme range.
+ */
@Test
- public void testNextFloatLowerGreaterUpper() {
- assertThrows(IllegalArgumentException.class, () -> RandomUtils.nextFloat(2, 1));
+ public void testExtremeRangeInt() {
+ final int result = RandomUtils.nextInt(0, Integer.MAX_VALUE);
+ assertThat("result >= 0 && result < Integer.MAX_VALUE", result, allOf(greaterThanOrEqualTo(0), lessThan(Integer.MAX_VALUE)));
}
/**
- * Tests next boolean
+ * Tests extreme range.
*/
@Test
- public void testBoolean() {
- final boolean result = RandomUtils.nextBoolean();
- assertTrue(result || !result);
+ public void testExtremeRangeLong() {
+ final long result = RandomUtils.nextLong(0, Long.MAX_VALUE);
+ assertThat("result >= 0 && result < Long.MAX_VALUE", result, allOf(greaterThanOrEqualTo(0L), lessThan(Long.MAX_VALUE)));
}
/**
- * Tests a zero byte array length.
+ * Test a large value for long. A previous implementation using
+ * {@link RandomUtils#nextDouble(double, double)} could generate a value equal
+ * to the upper limit.
+ *
+ * <pre>
+ * return (long) nextDouble(startInclusive, endExclusive);
+ * </pre>
+ *
+ * <p>See LANG-1592.</p>
*/
@Test
- public void testZeroLengthNextBytes() {
- assertArrayEquals(new byte[0], RandomUtils.nextBytes(0));
+ public void testLargeValueRangeLong() {
+ final long startInclusive = 12900000000001L;
+ final long endExclusive = 12900000000016L;
+ // Note: The method using 'return (long) nextDouble(startInclusive, endExclusive)'
+ // takes thousands of calls to generate an error. This size loop fails most
+ // of the time with the previous method.
+ final int n = (int) (endExclusive - startInclusive) * 1000;
+ for (int i = 0; i < n; i++) {
+ assertNotEquals(endExclusive, RandomUtils.nextLong(startInclusive, endExclusive));
+ }
}
/**
@@ -124,31 +131,23 @@ public class RandomUtilsTest extends AbstractLangTest {
assertEquals(20, result.length);
}
- /**
- * Test next int range with minimal range.
- */
@Test
- public void testNextIntMinimalRange() {
- assertEquals(42, RandomUtils.nextInt(42, 42));
+ public void testNextBytesNegative() {
+ assertThrows(IllegalArgumentException.class, () -> RandomUtils.nextBytes(-1));
}
/**
- * Tests next int range.
+ * Tests next double range.
*/
@Test
- public void testNextInt() {
- final int result = RandomUtils.nextInt(33, 42);
- assertThat("result >= 33 && result < 42", result, allOf(greaterThanOrEqualTo(33), lessThan(42)));
+ public void testNextDouble() {
+ final double result = RandomUtils.nextDouble(33d, 42d);
+ assertThat("result >= 33d && result < 42d", result, allOf(greaterThanOrEqualTo(33d), lessThan(42d)));
}
- /**
- * Tests next int range, random result.
- */
@Test
- public void testNextIntRandomResult() {
- final int randomResult = RandomUtils.nextInt();
- assertTrue(randomResult > 0);
- assertTrue(randomResult < Integer.MAX_VALUE);
+ public void testNextDoubleLowerGreaterUpper() {
+ assertThrows(IllegalArgumentException.class, () -> RandomUtils.nextDouble(2, 1));
}
/**
@@ -159,21 +158,9 @@ public class RandomUtilsTest extends AbstractLangTest {
assertEquals(42.1, RandomUtils.nextDouble(42.1, 42.1), DELTA);
}
- /**
- * Test next float range with minimal range.
- */
- @Test
- public void testNextFloatMinimalRange() {
- assertEquals(42.1f, RandomUtils.nextFloat(42.1f, 42.1f), DELTA);
- }
-
- /**
- * Tests next double range.
- */
@Test
- public void testNextDouble() {
- final double result = RandomUtils.nextDouble(33d, 42d);
- assertThat("result >= 33d && result < 42d", result, allOf(greaterThanOrEqualTo(33d), lessThan(42d)));
+ public void testNextDoubleNegative() {
+ assertThrows(IllegalArgumentException.class, () -> RandomUtils.nextDouble(-1, 1));
}
/**
@@ -194,6 +181,24 @@ public class RandomUtilsTest extends AbstractLangTest {
assertThat("result >= 33f && result < 42f", result, allOf(greaterThanOrEqualTo(33f), lessThan(42f)));
}
+ @Test
+ public void testNextFloatLowerGreaterUpper() {
+ assertThrows(IllegalArgumentException.class, () -> RandomUtils.nextFloat(2, 1));
+ }
+
+ /**
+ * Test next float range with minimal range.
+ */
+ @Test
+ public void testNextFloatMinimalRange() {
+ assertEquals(42.1f, RandomUtils.nextFloat(42.1f, 42.1f), DELTA);
+ }
+
+ @Test
+ public void testNextFloatNegative() {
+ assertThrows(IllegalArgumentException.class, () -> RandomUtils.nextFloat(-1, 1));
+ }
+
/**
* Tests next float range, random result.
*/
@@ -204,88 +209,83 @@ public class RandomUtilsTest extends AbstractLangTest {
}
/**
- * Test next long range with minimal range.
+ * Tests next int range.
*/
@Test
- public void testNextLongMinimalRange() {
- assertEquals(42L, RandomUtils.nextLong(42L, 42L));
+ public void testNextInt() {
+ final int result = RandomUtils.nextInt(33, 42);
+ assertThat("result >= 33 && result < 42", result, allOf(greaterThanOrEqualTo(33), lessThan(42)));
}
- /**
- * Tests next long range.
- */
@Test
- public void testNextLong() {
- final long result = RandomUtils.nextLong(33L, 42L);
- assertThat("result >= 33L && result < 42L", result, allOf(greaterThanOrEqualTo(33L), lessThan(42L)));
+ public void testNextIntLowerGreaterUpper() {
+ assertThrows(IllegalArgumentException.class, () -> RandomUtils.nextInt(2, 1));
}
/**
- * Tests next long range, random result.
+ * Test next int range with minimal range.
*/
@Test
- public void testNextLongRandomResult() {
- final long randomResult = RandomUtils.nextLong();
- assertThat("randomResult >= 0 && randomResult < Long.MAX_VALUE", randomResult, allOf(greaterThanOrEqualTo(0L), lessThan(Long.MAX_VALUE)));
+ public void testNextIntMinimalRange() {
+ assertEquals(42, RandomUtils.nextInt(42, 42));
+ }
+
+ @Test
+ public void testNextIntNegative() {
+ assertThrows(IllegalArgumentException.class, () -> RandomUtils.nextInt(-1, 1));
}
/**
- * Tests extreme range.
+ * Tests next int range, random result.
*/
@Test
- public void testExtremeRangeInt() {
- final int result = RandomUtils.nextInt(0, Integer.MAX_VALUE);
- assertThat("result >= 0 && result < Integer.MAX_VALUE", result, allOf(greaterThanOrEqualTo(0), lessThan(Integer.MAX_VALUE)));
+ public void testNextIntRandomResult() {
+ final int randomResult = RandomUtils.nextInt();
+ assertTrue(randomResult > 0);
+ assertTrue(randomResult < Integer.MAX_VALUE);
}
/**
- * Tests extreme range.
+ * Tests next long range.
*/
@Test
- public void testExtremeRangeLong() {
- final long result = RandomUtils.nextLong(0, Long.MAX_VALUE);
- assertThat("result >= 0 && result < Long.MAX_VALUE", result, allOf(greaterThanOrEqualTo(0L), lessThan(Long.MAX_VALUE)));
+ public void testNextLong() {
+ final long result = RandomUtils.nextLong(33L, 42L);
+ assertThat("result >= 33L && result < 42L", result, allOf(greaterThanOrEqualTo(33L), lessThan(42L)));
+ }
+
+ @Test
+ public void testNextLongLowerGreaterUpper() {
+ assertThrows(IllegalArgumentException.class, () -> RandomUtils.nextLong(2, 1));
}
/**
- * Tests extreme range.
+ * Test next long range with minimal range.
*/
@Test
- public void testExtremeRangeFloat() {
- final float result = RandomUtils.nextFloat(0, Float.MAX_VALUE);
- assertTrue(result >= 0f && result <= Float.MAX_VALUE); // TODO: should be <max?
+ public void testNextLongMinimalRange() {
+ assertEquals(42L, RandomUtils.nextLong(42L, 42L));
+ }
+
+ @Test
+ public void testNextLongNegative() {
+ assertThrows(IllegalArgumentException.class, () -> RandomUtils.nextLong(-1, 1));
}
/**
- * Tests extreme range.
+ * Tests next long range, random result.
*/
@Test
- public void testExtremeRangeDouble() {
- final double result = RandomUtils.nextDouble(0, Double.MAX_VALUE);
- assertTrue(result >= 0 && result <= Double.MAX_VALUE); // TODO: should be <max?
+ public void testNextLongRandomResult() {
+ final long randomResult = RandomUtils.nextLong();
+ assertThat("randomResult >= 0 && randomResult < Long.MAX_VALUE", randomResult, allOf(greaterThanOrEqualTo(0L), lessThan(Long.MAX_VALUE)));
}
/**
- * Test a large value for long. A previous implementation using
- * {@link RandomUtils#nextDouble(double, double)} could generate a value equal
- * to the upper limit.
- *
- * <pre>
- * return (long) nextDouble(startInclusive, endExclusive);
- * </pre>
- *
- * <p>See LANG-1592.</p>
+ * Tests a zero byte array length.
*/
@Test
- public void testLargeValueRangeLong() {
- final long startInclusive = 12900000000001L;
- final long endExclusive = 12900000000016L;
- // Note: The method using 'return (long) nextDouble(startInclusive, endExclusive)'
- // takes thousands of calls to generate an error. This size loop fails most
- // of the time with the previous method.
- final int n = (int) (endExclusive - startInclusive) * 1000;
- for (int i = 0; i < n; i++) {
- assertNotEquals(endExclusive, RandomUtils.nextLong(startInclusive, endExclusive));
- }
+ public void testZeroLengthNextBytes() {
+ assertArrayEquals(new byte[0], RandomUtils.nextBytes(0));
}
}
diff --git a/src/test/java/org/apache/commons/lang3/RangeTest.java b/src/test/java/org/apache/commons/lang3/RangeTest.java
index 8b477c354..641f0f165 100644
--- a/src/test/java/org/apache/commons/lang3/RangeTest.java
+++ b/src/test/java/org/apache/commons/lang3/RangeTest.java
@@ -102,39 +102,6 @@ public class RangeTest extends AbstractLangTest {
assertThrows(NullPointerException.class, () -> Range.between(null, null, lengthComp));
}
- @Test
- public void testOfWithCompare() {
- // all integers are equal
- final Comparator<Integer> c = (o1, o2) -> 0;
- final Comparator<String> lengthComp = Comparator.comparingInt(String::length);
- Range<Integer> rb = Range.of(-10, 20);
- assertFalse(rb.contains(null), "should not contain null");
- assertTrue(rb.contains(10), "should contain 10");
- assertTrue(rb.contains(-10), "should contain -10");
- assertFalse(rb.contains(21), "should not contain 21");
- assertFalse(rb.contains(-11), "should not contain -11");
- rb = Range.of(-10, 20, c);
- assertFalse(rb.contains(null), "should not contain null");
- assertTrue(rb.contains(10), "should contain 10");
- assertTrue(rb.contains(-10), "should contain -10");
- assertTrue(rb.contains(21), "should contain 21");
- assertTrue(rb.contains(-11), "should contain -11");
- Range<String> rbstr = Range.of("house", "i");
- assertFalse(rbstr.contains(null), "should not contain null");
- assertTrue(rbstr.contains("house"), "should contain house");
- assertTrue(rbstr.contains("i"), "should contain i");
- assertFalse(rbstr.contains("hose"), "should not contain hose");
- assertFalse(rbstr.contains("ice"), "should not contain ice");
- rbstr = Range.of("house", "i", lengthComp);
- assertFalse(rbstr.contains(null), "should not contain null");
- assertTrue(rbstr.contains("house"), "should contain house");
- assertTrue(rbstr.contains("i"), "should contain i");
- assertFalse(rbstr.contains("houses"), "should not contain houses");
- assertFalse(rbstr.contains(""), "should not contain ''");
-
- assertThrows(NullPointerException.class, () -> Range.of(null, null, lengthComp));
- }
-
@SuppressWarnings({"rawtypes", "unchecked"})
@Test
public void testComparableConstructors() {
@@ -421,6 +388,39 @@ public class RangeTest extends AbstractLangTest {
assertTrue(ri.contains(11), "should contain 11");
}
+ @Test
+ public void testOfWithCompare() {
+ // all integers are equal
+ final Comparator<Integer> c = (o1, o2) -> 0;
+ final Comparator<String> lengthComp = Comparator.comparingInt(String::length);
+ Range<Integer> rb = Range.of(-10, 20);
+ assertFalse(rb.contains(null), "should not contain null");
+ assertTrue(rb.contains(10), "should contain 10");
+ assertTrue(rb.contains(-10), "should contain -10");
+ assertFalse(rb.contains(21), "should not contain 21");
+ assertFalse(rb.contains(-11), "should not contain -11");
+ rb = Range.of(-10, 20, c);
+ assertFalse(rb.contains(null), "should not contain null");
+ assertTrue(rb.contains(10), "should contain 10");
+ assertTrue(rb.contains(-10), "should contain -10");
+ assertTrue(rb.contains(21), "should contain 21");
+ assertTrue(rb.contains(-11), "should contain -11");
+ Range<String> rbstr = Range.of("house", "i");
+ assertFalse(rbstr.contains(null), "should not contain null");
+ assertTrue(rbstr.contains("house"), "should contain house");
+ assertTrue(rbstr.contains("i"), "should contain i");
+ assertFalse(rbstr.contains("hose"), "should not contain hose");
+ assertFalse(rbstr.contains("ice"), "should not contain ice");
+ rbstr = Range.of("house", "i", lengthComp);
+ assertFalse(rbstr.contains(null), "should not contain null");
+ assertTrue(rbstr.contains("house"), "should contain house");
+ assertTrue(rbstr.contains("i"), "should contain i");
+ assertFalse(rbstr.contains("houses"), "should not contain houses");
+ assertFalse(rbstr.contains(""), "should not contain ''");
+
+ assertThrows(NullPointerException.class, () -> Range.of(null, null, lengthComp));
+ }
+
@Test
public void testRangeOfChars() {
final Range<Character> chars = Range.between('a', 'z');
diff --git a/src/test/java/org/apache/commons/lang3/SerializationUtilsTest.java b/src/test/java/org/apache/commons/lang3/SerializationUtilsTest.java
index f31610343..76f27d2ae 100644
--- a/src/test/java/org/apache/commons/lang3/SerializationUtilsTest.java
+++ b/src/test/java/org/apache/commons/lang3/SerializationUtilsTest.java
@@ -41,6 +41,15 @@ import java.util.HashMap;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
+class ClassNotFoundSerialization implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ private void readObject(final ObjectInputStream in) throws ClassNotFoundException {
+ throw new ClassNotFoundException(SerializationUtilsTest.CLASS_NOT_FOUND_MESSAGE);
+ }
+}
+
/**
* Unit tests {@link org.apache.commons.lang3.SerializationUtils}.
*/
@@ -63,6 +72,33 @@ public class SerializationUtilsTest extends AbstractLangTest {
}
+ @Test
+ public void testClone() {
+ final Object test = SerializationUtils.clone(iMap);
+ assertNotNull(test);
+ assertTrue(test instanceof HashMap<?, ?>);
+ assertNotSame(test, iMap);
+ final HashMap<?, ?> testMap = (HashMap<?, ?>) test;
+ assertEquals(iString, testMap.get("FOO"));
+ assertNotSame(iString, testMap.get("FOO"));
+ assertEquals(iInteger, testMap.get("BAR"));
+ assertNotSame(iInteger, testMap.get("BAR"));
+ assertEquals(iMap, testMap);
+ }
+
+ @Test
+ public void testCloneNull() {
+ final Object test = SerializationUtils.clone(null);
+ assertNull(test);
+ }
+
+
+ @Test
+ public void testCloneUnserializable() {
+ iMap.put(new Object(), new Object());
+ assertThrows(SerializationException.class, () -> SerializationUtils.clone(iMap));
+ }
+
@Test
public void testConstructor() {
assertNotNull(new SerializationUtils());
@@ -74,95 +110,60 @@ public class SerializationUtilsTest extends AbstractLangTest {
}
@Test
- public void testException() {
- SerializationException serEx;
- final Exception ex = new Exception();
-
- serEx = new SerializationException();
- assertSame(null, serEx.getMessage());
- assertSame(null, serEx.getCause());
-
- serEx = new SerializationException("Message");
- assertSame("Message", serEx.getMessage());
- assertSame(null, serEx.getCause());
-
- serEx = new SerializationException(ex);
- assertEquals("java.lang.Exception", serEx.getMessage());
- assertSame(ex, serEx.getCause());
-
- serEx = new SerializationException("Message", ex);
- assertSame("Message", serEx.getMessage());
- assertSame(ex, serEx.getCause());
- }
-
-
- @Test
- public void testSerializeStream() throws Exception {
- final ByteArrayOutputStream streamTest = new ByteArrayOutputStream();
- SerializationUtils.serialize(iMap, streamTest);
-
+ public void testDeserializeBytes() throws Exception {
final ByteArrayOutputStream streamReal = new ByteArrayOutputStream();
try (ObjectOutputStream oos = new ObjectOutputStream(streamReal)) {
oos.writeObject(iMap);
oos.flush();
}
- final byte[] testBytes = streamTest.toByteArray();
- final byte[] realBytes = streamReal.toByteArray();
- assertEquals(testBytes.length, realBytes.length);
- assertArrayEquals(realBytes, testBytes);
+ final Object test = SerializationUtils.deserialize(streamReal.toByteArray());
+ assertNotNull(test);
+ assertTrue(test instanceof HashMap<?, ?>);
+ assertNotSame(test, iMap);
+ final HashMap<?, ?> testMap = (HashMap<?, ?>) test;
+ assertEquals(iString, testMap.get("FOO"));
+ assertNotSame(iString, testMap.get("FOO"));
+ assertEquals(iInteger, testMap.get("BAR"));
+ assertNotSame(iInteger, testMap.get("BAR"));
+ assertEquals(iMap, testMap);
}
@Test
- public void testSerializeStreamUnserializable() {
- final ByteArrayOutputStream streamTest = new ByteArrayOutputStream();
- iMap.put(new Object(), new Object());
- assertThrows(SerializationException.class, () -> SerializationUtils.serialize(iMap, streamTest));
+ public void testDeserializeBytesBadStream() {
+ assertThrows(SerializationException.class, () -> SerializationUtils.deserialize(new byte[0]));
}
@Test
- public void testSerializeStreamNullObj() throws Exception {
- final ByteArrayOutputStream streamTest = new ByteArrayOutputStream();
- SerializationUtils.serialize(null, streamTest);
+ public void testDeserializeBytesNull() {
+ assertThrows(NullPointerException.class, () -> SerializationUtils.deserialize((byte[]) null));
+ }
+ @Test
+ public void testDeserializeBytesOfNull() throws Exception {
final ByteArrayOutputStream streamReal = new ByteArrayOutputStream();
try (ObjectOutputStream oos = new ObjectOutputStream(streamReal)) {
oos.writeObject(null);
oos.flush();
}
- final byte[] testBytes = streamTest.toByteArray();
- final byte[] realBytes = streamReal.toByteArray();
- assertEquals(testBytes.length, realBytes.length);
- assertArrayEquals(realBytes, testBytes);
- }
-
- @Test
- public void testSerializeStreamObjNull() {
- assertThrows(NullPointerException.class, () -> SerializationUtils.serialize(iMap, null));
+ final Object test = SerializationUtils.deserialize(streamReal.toByteArray());
+ assertNull(test);
}
- @Test
- public void testSerializeStreamNullNull() {
- assertThrows(NullPointerException.class, () -> SerializationUtils.serialize(null, null));
- }
@Test
- public void testSerializeIOException() {
- // forces an IOException when the ObjectOutputStream is created, to test not closing the stream
- // in the finally block
- final OutputStream streamTest = new OutputStream() {
- @Override
- public void write(final int arg0) throws IOException {
- throw new IOException(SERIALIZE_IO_EXCEPTION_MESSAGE);
- }
- };
- final SerializationException e =
- assertThrows(SerializationException.class, () -> SerializationUtils.serialize(iMap, streamTest));
- assertEquals("java.io.IOException: " + SERIALIZE_IO_EXCEPTION_MESSAGE, e.getMessage());
+ public void testDeserializeClassCastException() {
+ final String value = "Hello";
+ final byte[] serialized = SerializationUtils.serialize(value);
+ assertEquals(value, SerializationUtils.deserialize(serialized));
+ assertThrows(ClassCastException.class, () -> {
+ // Causes ClassCastException in call site, not in SerializationUtils.deserialize
+ @SuppressWarnings("unused") // needed to cause Exception
+ final Integer i = SerializationUtils.deserialize(serialized);
+ });
}
-
@Test
public void testDeserializeStream() throws Exception {
final ByteArrayOutputStream streamReal = new ByteArrayOutputStream();
@@ -185,28 +186,22 @@ public class SerializationUtilsTest extends AbstractLangTest {
}
@Test
- public void testDeserializeClassCastException() {
- final String value = "Hello";
- final byte[] serialized = SerializationUtils.serialize(value);
- assertEquals(value, SerializationUtils.deserialize(serialized));
- assertThrows(ClassCastException.class, () -> {
- // Causes ClassCastException in call site, not in SerializationUtils.deserialize
- @SuppressWarnings("unused") // needed to cause Exception
- final Integer i = SerializationUtils.deserialize(serialized);
- });
+ public void testDeserializeStreamBadStream() {
+ assertThrows(SerializationException.class,
+ () -> SerializationUtils.deserialize(new ByteArrayInputStream(new byte[0])));
}
@Test
- public void testDeserializeStreamOfNull() throws Exception {
+ public void testDeserializeStreamClassNotFound() throws Exception {
final ByteArrayOutputStream streamReal = new ByteArrayOutputStream();
try (ObjectOutputStream oos = new ObjectOutputStream(streamReal)) {
- oos.writeObject(null);
+ oos.writeObject(new ClassNotFoundSerialization());
oos.flush();
}
final ByteArrayInputStream inTest = new ByteArrayInputStream(streamReal.toByteArray());
- final Object test = SerializationUtils.deserialize(inTest);
- assertNull(test);
+ final SerializationException se = assertThrows(SerializationException.class, () -> SerializationUtils.deserialize(inTest));
+ assertEquals("java.lang.ClassNotFoundException: " + CLASS_NOT_FOUND_MESSAGE, se.getMessage());
}
@Test
@@ -215,22 +210,49 @@ public class SerializationUtilsTest extends AbstractLangTest {
}
@Test
- public void testDeserializeStreamBadStream() {
- assertThrows(SerializationException.class,
- () -> SerializationUtils.deserialize(new ByteArrayInputStream(new byte[0])));
- }
-
- @Test
- public void testDeserializeStreamClassNotFound() throws Exception {
+ public void testDeserializeStreamOfNull() throws Exception {
final ByteArrayOutputStream streamReal = new ByteArrayOutputStream();
try (ObjectOutputStream oos = new ObjectOutputStream(streamReal)) {
- oos.writeObject(new ClassNotFoundSerialization());
+ oos.writeObject(null);
oos.flush();
}
final ByteArrayInputStream inTest = new ByteArrayInputStream(streamReal.toByteArray());
- final SerializationException se = assertThrows(SerializationException.class, () -> SerializationUtils.deserialize(inTest));
- assertEquals("java.lang.ClassNotFoundException: " + CLASS_NOT_FOUND_MESSAGE, se.getMessage());
+ final Object test = SerializationUtils.deserialize(inTest);
+ assertNull(test);
+ }
+
+ @Test
+ public void testException() {
+ SerializationException serEx;
+ final Exception ex = new Exception();
+
+ serEx = new SerializationException();
+ assertSame(null, serEx.getMessage());
+ assertSame(null, serEx.getCause());
+
+ serEx = new SerializationException("Message");
+ assertSame("Message", serEx.getMessage());
+ assertSame(null, serEx.getCause());
+
+ serEx = new SerializationException(ex);
+ assertEquals("java.lang.Exception", serEx.getMessage());
+ assertSame(ex, serEx.getCause());
+
+ serEx = new SerializationException("Message", ex);
+ assertSame("Message", serEx.getMessage());
+ assertSame(ex, serEx.getCause());
+ }
+
+ @Test
+ public void testPrimitiveTypeClassSerialization() {
+ final Class<?>[] primitiveTypes = { byte.class, short.class, int.class, long.class, float.class, double.class,
+ boolean.class, char.class, void.class };
+
+ for (final Class<?> primitiveType : primitiveTypes) {
+ final Class<?> clone = SerializationUtils.clone(primitiveType);
+ assertEquals(primitiveType, clone);
+ }
}
@Test
@@ -254,11 +276,6 @@ public class SerializationUtilsTest extends AbstractLangTest {
assertArrayEquals(realBytes, testBytes);
}
- @Test
- public void testSerializeBytesUnserializable() {
- iMap.put(new Object(), new Object());
- assertThrows(SerializationException.class, () -> SerializationUtils.serialize(iMap));
- }
@Test
public void testSerializeBytesNull() throws Exception {
@@ -275,94 +292,77 @@ public class SerializationUtilsTest extends AbstractLangTest {
assertArrayEquals(realBytes, testBytes);
}
-
@Test
- public void testDeserializeBytes() throws Exception {
- final ByteArrayOutputStream streamReal = new ByteArrayOutputStream();
- try (ObjectOutputStream oos = new ObjectOutputStream(streamReal)) {
- oos.writeObject(iMap);
- oos.flush();
- }
+ public void testSerializeBytesUnserializable() {
+ iMap.put(new Object(), new Object());
+ assertThrows(SerializationException.class, () -> SerializationUtils.serialize(iMap));
+ }
- final Object test = SerializationUtils.deserialize(streamReal.toByteArray());
- assertNotNull(test);
- assertTrue(test instanceof HashMap<?, ?>);
- assertNotSame(test, iMap);
- final HashMap<?, ?> testMap = (HashMap<?, ?>) test;
- assertEquals(iString, testMap.get("FOO"));
- assertNotSame(iString, testMap.get("FOO"));
- assertEquals(iInteger, testMap.get("BAR"));
- assertNotSame(iInteger, testMap.get("BAR"));
- assertEquals(iMap, testMap);
+ @Test
+ public void testSerializeIOException() {
+ // forces an IOException when the ObjectOutputStream is created, to test not closing the stream
+ // in the finally block
+ final OutputStream streamTest = new OutputStream() {
+ @Override
+ public void write(final int arg0) throws IOException {
+ throw new IOException(SERIALIZE_IO_EXCEPTION_MESSAGE);
+ }
+ };
+ final SerializationException e =
+ assertThrows(SerializationException.class, () -> SerializationUtils.serialize(iMap, streamTest));
+ assertEquals("java.io.IOException: " + SERIALIZE_IO_EXCEPTION_MESSAGE, e.getMessage());
}
@Test
- public void testDeserializeBytesOfNull() throws Exception {
+ public void testSerializeStream() throws Exception {
+ final ByteArrayOutputStream streamTest = new ByteArrayOutputStream();
+ SerializationUtils.serialize(iMap, streamTest);
+
final ByteArrayOutputStream streamReal = new ByteArrayOutputStream();
try (ObjectOutputStream oos = new ObjectOutputStream(streamReal)) {
- oos.writeObject(null);
+ oos.writeObject(iMap);
oos.flush();
}
- final Object test = SerializationUtils.deserialize(streamReal.toByteArray());
- assertNull(test);
+ final byte[] testBytes = streamTest.toByteArray();
+ final byte[] realBytes = streamReal.toByteArray();
+ assertEquals(testBytes.length, realBytes.length);
+ assertArrayEquals(realBytes, testBytes);
}
+
@Test
- public void testDeserializeBytesNull() {
- assertThrows(NullPointerException.class, () -> SerializationUtils.deserialize((byte[]) null));
+ public void testSerializeStreamNullNull() {
+ assertThrows(NullPointerException.class, () -> SerializationUtils.serialize(null, null));
}
@Test
- public void testDeserializeBytesBadStream() {
- assertThrows(SerializationException.class, () -> SerializationUtils.deserialize(new byte[0]));
- }
+ public void testSerializeStreamNullObj() throws Exception {
+ final ByteArrayOutputStream streamTest = new ByteArrayOutputStream();
+ SerializationUtils.serialize(null, streamTest);
+ final ByteArrayOutputStream streamReal = new ByteArrayOutputStream();
+ try (ObjectOutputStream oos = new ObjectOutputStream(streamReal)) {
+ oos.writeObject(null);
+ oos.flush();
+ }
- @Test
- public void testClone() {
- final Object test = SerializationUtils.clone(iMap);
- assertNotNull(test);
- assertTrue(test instanceof HashMap<?, ?>);
- assertNotSame(test, iMap);
- final HashMap<?, ?> testMap = (HashMap<?, ?>) test;
- assertEquals(iString, testMap.get("FOO"));
- assertNotSame(iString, testMap.get("FOO"));
- assertEquals(iInteger, testMap.get("BAR"));
- assertNotSame(iInteger, testMap.get("BAR"));
- assertEquals(iMap, testMap);
+ final byte[] testBytes = streamTest.toByteArray();
+ final byte[] realBytes = streamReal.toByteArray();
+ assertEquals(testBytes.length, realBytes.length);
+ assertArrayEquals(realBytes, testBytes);
}
@Test
- public void testCloneNull() {
- final Object test = SerializationUtils.clone(null);
- assertNull(test);
+ public void testSerializeStreamObjNull() {
+ assertThrows(NullPointerException.class, () -> SerializationUtils.serialize(iMap, null));
}
@Test
- public void testCloneUnserializable() {
+ public void testSerializeStreamUnserializable() {
+ final ByteArrayOutputStream streamTest = new ByteArrayOutputStream();
iMap.put(new Object(), new Object());
- assertThrows(SerializationException.class, () -> SerializationUtils.clone(iMap));
- }
-
- @Test
- public void testPrimitiveTypeClassSerialization() {
- final Class<?>[] primitiveTypes = { byte.class, short.class, int.class, long.class, float.class, double.class,
- boolean.class, char.class, void.class };
-
- for (final Class<?> primitiveType : primitiveTypes) {
- final Class<?> clone = SerializationUtils.clone(primitiveType);
- assertEquals(primitiveType, clone);
- }
+ assertThrows(SerializationException.class, () -> SerializationUtils.serialize(iMap, streamTest));
}
}
-
-class ClassNotFoundSerialization implements Serializable {
-
- private static final long serialVersionUID = 1L;
-
- private void readObject(final ObjectInputStream in) throws ClassNotFoundException {
- throw new ClassNotFoundException(SerializationUtilsTest.CLASS_NOT_FOUND_MESSAGE);
- }
-}
diff --git a/src/test/java/org/apache/commons/lang3/StreamsTest.java b/src/test/java/org/apache/commons/lang3/StreamsTest.java
index fc6d30681..8819a61a1 100644
--- a/src/test/java/org/apache/commons/lang3/StreamsTest.java
+++ b/src/test/java/org/apache/commons/lang3/StreamsTest.java
@@ -43,45 +43,6 @@ import org.xml.sax.SAXException;
public class StreamsTest extends AbstractLangTest {
- @Test
- public void testSimpleStreamMap() {
- final List<String> input = Arrays.asList("1", "2", "3", "4", "5", "6");
- final List<Integer> output = Functions.stream(input).map(Integer::valueOf).collect(Collectors.toList());
- assertEquals(6, output.size());
- for (int i = 0; i < 6; i++) {
- assertEquals(i+1, output.get(i).intValue());
- }
- }
-
- @Test
- public void testSimpleStreamMapFailing() {
- final List<String> input = Arrays.asList("1", "2", "3", "4 ", "5", "6");
- final Executable testMethod = () -> Functions.stream(input).map(Integer::valueOf).collect(Collectors.toList());
- final NumberFormatException thrown = assertThrows(NumberFormatException.class, testMethod);
- assertEquals("For input string: \"4 \"", thrown.getMessage());
- }
-
- @Test
- public void testSimpleStreamForEach() {
- final List<String> input = Arrays.asList("1", "2", "3", "4", "5", "6");
- final List<Integer> output = new ArrayList<>();
- Functions.stream(input).forEach(s -> output.add(Integer.valueOf(s)));
- assertEquals(6, output.size());
- for (int i = 0; i < 6; i++) {
- assertEquals(i+1, output.get(i).intValue());
- }
- }
-
- @Test
- public void testToArray() {
- final String[] array = Arrays.asList("2", "3", "1").stream().collect(Streams.toArray(String.class));
- assertNotNull(array);
- assertEquals(3, array.length);
- assertEquals("2", array[0]);
- assertEquals("3", array[1]);
- assertEquals("1", array[2]);
- }
-
protected <T extends Throwable> FailableConsumer<String, T> asIntConsumer(final T pThrowable) {
return s -> {
final int i = Integer.parseInt(s);
@@ -91,58 +52,6 @@ public class StreamsTest extends AbstractLangTest {
};
}
- @TestFactory
- public Stream<DynamicTest> simpleStreamForEachFailing() {
- final List<String> input = Arrays.asList("1", "2", "3", "4", "5", "6");
-
- return Stream.of(
-
- dynamicTest("IllegalArgumentException", () -> {
- final IllegalArgumentException ise = new IllegalArgumentException();
- final Executable testMethod = () -> Functions.stream(input)
- .forEach(asIntConsumer(ise));
- final IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, testMethod);
- assertThat(thrown.getMessage(), is(nullValue()));
- }),
-
- dynamicTest("OutOfMemoryError", () -> {
- final OutOfMemoryError oome = new OutOfMemoryError();
- final Executable oomeTestMethod = () -> Functions.stream(input)
- .forEach(asIntConsumer(oome));
- final OutOfMemoryError oomeThrown = assertThrows(OutOfMemoryError.class, oomeTestMethod);
- assertThat(oomeThrown.getMessage(), is(nullValue()));
- }),
-
- dynamicTest("SAXException", () -> {
- final SAXException se = new SAXException();
- final Executable seTestMethod = () -> Functions.stream(input)
- .forEach(asIntConsumer(se));
- final UndeclaredThrowableException seThrown = assertThrows(UndeclaredThrowableException.class, seTestMethod);
- assertAll(
- () -> assertThat(seThrown.getMessage(), is(nullValue())),
- () -> assertThat(seThrown.getCause(), is(equalTo(se)))
- );
- })
- );
- }
-
- @Test
- public void testSimpleStreamFilter() {
- final List<String> input = Arrays.asList("1", "2", "3", "4", "5", "6");
- final List<Integer> output = Functions.stream(input)
- .map(Integer::valueOf)
- .filter(i -> (i.intValue() %2 == 0))
- .collect(Collectors.toList());
- assertEvenNumbers(output);
- }
-
- private void assertEvenNumbers(final List<Integer> output) {
- assertEquals(3, output.size());
- for (int i = 0; i < 3; i++) {
- assertEquals((i+1)*2, output.get(i).intValue());
- }
- }
-
protected <T extends Throwable> FailablePredicate<Integer, T> asIntPredicate(final T pThrowable) {
return i -> {
if (i.intValue() == 5 && pThrowable != null) {
@@ -152,6 +61,13 @@ public class StreamsTest extends AbstractLangTest {
};
}
+ private void assertEvenNumbers(final List<Integer> output) {
+ assertEquals(3, output.size());
+ for (int i = 0; i < 3; i++) {
+ assertEquals((i+1)*2, output.get(i).intValue());
+ }
+ }
+
@TestFactory
public Stream<DynamicTest> simpleStreamFilterFailing() {
final List<String> input = Arrays.asList("1", "2", "3", "4", "5", "6");
@@ -198,4 +114,88 @@ public class StreamsTest extends AbstractLangTest {
);
}
+ @TestFactory
+ public Stream<DynamicTest> simpleStreamForEachFailing() {
+ final List<String> input = Arrays.asList("1", "2", "3", "4", "5", "6");
+
+ return Stream.of(
+
+ dynamicTest("IllegalArgumentException", () -> {
+ final IllegalArgumentException ise = new IllegalArgumentException();
+ final Executable testMethod = () -> Functions.stream(input)
+ .forEach(asIntConsumer(ise));
+ final IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, testMethod);
+ assertThat(thrown.getMessage(), is(nullValue()));
+ }),
+
+ dynamicTest("OutOfMemoryError", () -> {
+ final OutOfMemoryError oome = new OutOfMemoryError();
+ final Executable oomeTestMethod = () -> Functions.stream(input)
+ .forEach(asIntConsumer(oome));
+ final OutOfMemoryError oomeThrown = assertThrows(OutOfMemoryError.class, oomeTestMethod);
+ assertThat(oomeThrown.getMessage(), is(nullValue()));
+ }),
+
+ dynamicTest("SAXException", () -> {
+ final SAXException se = new SAXException();
+ final Executable seTestMethod = () -> Functions.stream(input)
+ .forEach(asIntConsumer(se));
+ final UndeclaredThrowableException seThrown = assertThrows(UndeclaredThrowableException.class, seTestMethod);
+ assertAll(
+ () -> assertThat(seThrown.getMessage(), is(nullValue())),
+ () -> assertThat(seThrown.getCause(), is(equalTo(se)))
+ );
+ })
+ );
+ }
+
+ @Test
+ public void testSimpleStreamFilter() {
+ final List<String> input = Arrays.asList("1", "2", "3", "4", "5", "6");
+ final List<Integer> output = Functions.stream(input)
+ .map(Integer::valueOf)
+ .filter(i -> (i.intValue() %2 == 0))
+ .collect(Collectors.toList());
+ assertEvenNumbers(output);
+ }
+
+ @Test
+ public void testSimpleStreamForEach() {
+ final List<String> input = Arrays.asList("1", "2", "3", "4", "5", "6");
+ final List<Integer> output = new ArrayList<>();
+ Functions.stream(input).forEach(s -> output.add(Integer.valueOf(s)));
+ assertEquals(6, output.size());
+ for (int i = 0; i < 6; i++) {
+ assertEquals(i+1, output.get(i).intValue());
+ }
+ }
+
+ @Test
+ public void testSimpleStreamMap() {
+ final List<String> input = Arrays.asList("1", "2", "3", "4", "5", "6");
+ final List<Integer> output = Functions.stream(input).map(Integer::valueOf).collect(Collectors.toList());
+ assertEquals(6, output.size());
+ for (int i = 0; i < 6; i++) {
+ assertEquals(i+1, output.get(i).intValue());
+ }
+ }
+
+ @Test
+ public void testSimpleStreamMapFailing() {
+ final List<String> input = Arrays.asList("1", "2", "3", "4 ", "5", "6");
+ final Executable testMethod = () -> Functions.stream(input).map(Integer::valueOf).collect(Collectors.toList());
+ final NumberFormatException thrown = assertThrows(NumberFormatException.class, testMethod);
+ assertEquals("For input string: \"4 \"", thrown.getMessage());
+ }
+
+ @Test
+ public void testToArray() {
+ final String[] array = Arrays.asList("2", "3", "1").stream().collect(Streams.toArray(String.class));
+ assertNotNull(array);
+ assertEquals(3, array.length);
+ assertEquals("2", array[0]);
+ assertEquals("3", array[1]);
+ assertEquals("1", array[2]);
+ }
+
}
diff --git a/src/test/java/org/apache/commons/lang3/StringEscapeUtilsTest.java b/src/test/java/org/apache/commons/lang3/StringEscapeUtilsTest.java
index 87e12e108..4d4de247a 100644
--- a/src/test/java/org/apache/commons/lang3/StringEscapeUtilsTest.java
+++ b/src/test/java/org/apache/commons/lang3/StringEscapeUtilsTest.java
@@ -42,58 +42,20 @@ import org.junit.jupiter.api.Test;
public class StringEscapeUtilsTest extends AbstractLangTest {
private static final String FOO = "foo";
- @Test
- public void testConstructor() {
- assertNotNull(new StringEscapeUtils());
- final Constructor<?>[] cons = StringEscapeUtils.class.getDeclaredConstructors();
- assertEquals(1, cons.length);
- assertTrue(Modifier.isPublic(cons[0].getModifiers()));
- assertTrue(Modifier.isPublic(StringEscapeUtils.class.getModifiers()));
- assertFalse(Modifier.isFinal(StringEscapeUtils.class.getModifiers()));
- }
-
- @Test
- public void testEscapeJava() throws IOException {
- assertNull(StringEscapeUtils.escapeJava(null));
- assertThrows(NullPointerException.class, () -> StringEscapeUtils.ESCAPE_JAVA.translate(null, null));
- assertThrows(NullPointerException.class, () -> StringEscapeUtils.ESCAPE_JAVA.translate("", null));
-
- assertEscapeJava("empty string", "", "");
- assertEscapeJava(FOO, FOO);
- assertEscapeJava("tab", "\\t", "\t");
- assertEscapeJava("backslash", "\\\\", "\\");
- assertEscapeJava("single quote should not be escaped", "'", "'");
- assertEscapeJava("\\\\\\b\\t\\r", "\\\b\t\r");
- assertEscapeJava("\\u1234", "\u1234");
- assertEscapeJava("\\u0234", "\u0234");
- assertEscapeJava("\\u00EF", "\u00ef");
- assertEscapeJava("\\u0001", "\u0001");
- assertEscapeJava("Should use capitalized Unicode hex", "\\uABCD", "\uabcd");
-
- assertEscapeJava("He didn't say, \\\"stop!\\\"",
- "He didn't say, \"stop!\"");
- assertEscapeJava("non-breaking space", "This space is non-breaking:" + "\\u00A0",
- "This space is non-breaking:\u00a0");
- assertEscapeJava("\\uABCD\\u1234\\u012C",
- "\uABCD\u1234\u012C");
- }
-
- /**
- * Tests https://issues.apache.org/jira/browse/LANG-421
- */
- @Test
- public void testEscapeJavaWithSlash() {
- final String input = "String with a slash (/) in it";
-
- final String expected = input;
- final String actual = StringEscapeUtils.escapeJava(input);
-
- /*
- * In 2.4 StringEscapeUtils.escapeJava(String) escapes '/' characters, which are not a valid character to escape
- * in a Java string.
- */
- assertEquals(expected, actual);
- }
+ /** HTML and XML */
+ private static final String[][] HTML_ESCAPES = {
+ {"no escaping", "plain text", "plain text"},
+ {"no escaping", "plain text", "plain text"},
+ {"empty string", "", ""},
+ {"null", null, null},
+ {"ampersand", "bread & butter", "bread & butter"},
+ {"quotes", ""bread" & butter", "\"bread\" & butter"},
+ {"final character only", "greater than >", "greater than >"},
+ {"first character only", "< less than", "< less than"},
+ {"apostrophe", "Huntington's chorea", "Huntington's chorea"},
+ {"languages", "English,Français,\u65E5\u672C\u8A9E (nihongo)", "English,Fran\u00E7ais,\u65E5\u672C\u8A9E (nihongo)"},
+ {"8-bit ascii shouldn't number-escape", "\u0080\u009F", "\u0080\u009F"},
+ };
private void assertEscapeJava(final String escaped, final String original) throws IOException {
assertEscapeJava(null, escaped, original);
@@ -109,25 +71,6 @@ public class StringEscapeUtilsTest extends AbstractLangTest {
assertEquals(expected, writer.toString());
}
- @Test
- public void testUnescapeJava() throws IOException {
- assertNull(StringEscapeUtils.unescapeJava(null));
- assertThrows(NullPointerException.class, () -> StringEscapeUtils.UNESCAPE_JAVA.translate(null, null));
- assertThrows(NullPointerException.class, () -> StringEscapeUtils.UNESCAPE_JAVA.translate("", null));
- assertThrows(RuntimeException.class, () -> StringEscapeUtils.unescapeJava("\\u02-3"));
-
- assertUnescapeJava("", "");
- assertUnescapeJava("test", "test");
- assertUnescapeJava("\ntest\b", "\\ntest\\b");
- assertUnescapeJava("\u123425foo\ntest\b", "\\u123425foo\\ntest\\b");
- assertUnescapeJava("'\foo\teste\r", "\\'\\foo\\teste\\r");
- assertUnescapeJava("", "\\");
- //foo
- assertUnescapeJava("lowercase Unicode", "\uABCDx", "\\uabcdx");
- assertUnescapeJava("uppercase Unicode", "\uABCDx", "\\uABCDx");
- assertUnescapeJava("Unicode as final character", "\uABCD", "\\uabcd");
- }
-
private void assertUnescapeJava(final String unescaped, final String original) throws IOException {
assertUnescapeJava(null, unescaped, original);
}
@@ -149,6 +92,59 @@ public class StringEscapeUtilsTest extends AbstractLangTest {
}
+ private void checkCsvEscapeWriter(final String expected, final String value) throws IOException {
+ final StringWriter writer = new StringWriter();
+ StringEscapeUtils.ESCAPE_CSV.translate(value, writer);
+ assertEquals(expected, writer.toString());
+ }
+
+ private void checkCsvUnescapeWriter(final String expected, final String value) throws IOException {
+ final StringWriter writer = new StringWriter();
+ StringEscapeUtils.UNESCAPE_CSV.translate(value, writer);
+ assertEquals(expected, writer.toString());
+ }
+
+ @Test
+ public void testConstructor() {
+ assertNotNull(new StringEscapeUtils());
+ final Constructor<?>[] cons = StringEscapeUtils.class.getDeclaredConstructors();
+ assertEquals(1, cons.length);
+ assertTrue(Modifier.isPublic(cons[0].getModifiers()));
+ assertTrue(Modifier.isPublic(StringEscapeUtils.class.getModifiers()));
+ assertFalse(Modifier.isFinal(StringEscapeUtils.class.getModifiers()));
+ }
+
+ @Test
+ public void testEscapeCsvIllegalStateException() {
+ final StringWriter writer = new StringWriter();
+ assertThrows(IllegalStateException.class, () -> StringEscapeUtils.ESCAPE_CSV.translate("foo", -1, writer));
+ }
+
+ @Test
+ public void testEscapeCsvString() {
+ assertEquals("foo.bar", StringEscapeUtils.escapeCsv("foo.bar"));
+ assertEquals("\"foo,bar\"", StringEscapeUtils.escapeCsv("foo,bar"));
+ assertEquals("\"foo\nbar\"", StringEscapeUtils.escapeCsv("foo\nbar"));
+ assertEquals("\"foo\rbar\"", StringEscapeUtils.escapeCsv("foo\rbar"));
+ assertEquals("\"foo\"\"bar\"", StringEscapeUtils.escapeCsv("foo\"bar"));
+ assertEquals("foo\uD84C\uDFB4bar", StringEscapeUtils.escapeCsv("foo\uD84C\uDFB4bar"));
+ assertEquals("", StringEscapeUtils.escapeCsv(""));
+ assertNull(StringEscapeUtils.escapeCsv(null));
+ }
+
+
+ @Test
+ public void testEscapeCsvWriter() throws Exception {
+ checkCsvEscapeWriter("foo.bar", "foo.bar");
+ checkCsvEscapeWriter("\"foo,bar\"", "foo,bar");
+ checkCsvEscapeWriter("\"foo\nbar\"", "foo\nbar");
+ checkCsvEscapeWriter("\"foo\rbar\"", "foo\rbar");
+ checkCsvEscapeWriter("\"foo\"\"bar\"", "foo\"bar");
+ checkCsvEscapeWriter("foo\uD84C\uDFB4bar", "foo\uD84C\uDFB4bar");
+ checkCsvEscapeWriter("", null);
+ checkCsvEscapeWriter("", "");
+ }
+
@Test
public void testEscapeEcmaScript() {
assertNull(StringEscapeUtils.escapeEcmaScript(null));
@@ -160,32 +156,21 @@ public class StringEscapeUtilsTest extends AbstractLangTest {
StringEscapeUtils.escapeEcmaScript("document.getElementById(\"test\").value = '<script>alert('aaa');</script>';"));
}
+ /**
+ * Tests https://issues.apache.org/jira/browse/LANG-339
+ */
@Test
- public void testUnescapeEcmaScript() {
- assertNull(StringEscapeUtils.escapeEcmaScript(null));
- assertThrows(NullPointerException.class, () -> StringEscapeUtils.UNESCAPE_ECMASCRIPT.translate(null, null));
- assertThrows(NullPointerException.class, () -> StringEscapeUtils.UNESCAPE_ECMASCRIPT.translate("", null));
-
- assertEquals("He didn't say, \"stop!\"", StringEscapeUtils.unescapeEcmaScript("He didn\\'t say, \\\"stop!\\\""));
- assertEquals("document.getElementById(\"test\").value = '<script>alert('aaa');</script>';",
- StringEscapeUtils.unescapeEcmaScript("document.getElementById(\\\"test\\\").value = \\'<script>alert(\\'aaa\\');<\\/script>\\';"));
- }
+ public void testEscapeHiragana() {
+ // Some random Japanese Unicode characters
+ final String original = "\u304B\u304C\u3068";
+ final String escaped = StringEscapeUtils.escapeHtml4(original);
+ assertEquals(original, escaped,
+ "Hiragana character Unicode behavior should not be being escaped by escapeHtml4");
+ final String unescaped = StringEscapeUtils.unescapeHtml4( escaped );
- /** HTML and XML */
- private static final String[][] HTML_ESCAPES = {
- {"no escaping", "plain text", "plain text"},
- {"no escaping", "plain text", "plain text"},
- {"empty string", "", ""},
- {"null", null, null},
- {"ampersand", "bread & butter", "bread & butter"},
- {"quotes", ""bread" & butter", "\"bread\" & butter"},
- {"final character only", "greater than >", "greater than >"},
- {"first character only", "< less than", "< less than"},
- {"apostrophe", "Huntington's chorea", "Huntington's chorea"},
- {"languages", "English,Français,\u65E5\u672C\u8A9E (nihongo)", "English,Fran\u00E7ais,\u65E5\u672C\u8A9E (nihongo)"},
- {"8-bit ascii shouldn't number-escape", "\u0080\u009F", "\u0080\u009F"},
- };
+ assertEquals(escaped, unescaped, "Hiragana character Unicode behavior has changed - expected no unescaping");
+ }
@Test
public void testEscapeHtml() throws IOException {
@@ -201,49 +186,28 @@ public class StringEscapeUtilsTest extends AbstractLangTest {
}
}
+ /**
+ * Tests // https://issues.apache.org/jira/browse/LANG-480
+ */
@Test
- public void testUnescapeHtml4() throws IOException {
- for (final String[] element : HTML_ESCAPES) {
- final String message = element[0];
- final String expected = element[2];
- final String original = element[1];
- assertEquals(expected, StringEscapeUtils.unescapeHtml4(original), message);
+ public void testEscapeHtmlHighUnicode() {
+ // this is the utf8 representation of the character:
+ // COUNTING ROD UNIT DIGIT THREE
+ // in Unicode
+ // code point: U+1D362
+ final byte[] data = { (byte) 0xF0, (byte) 0x9D, (byte) 0x8D, (byte) 0xA2 };
- final StringWriter sw = new StringWriter();
- StringEscapeUtils.UNESCAPE_HTML4.translate(original, sw);
- final String actual = original == null ? null : sw.toString();
- assertEquals(expected, actual, message);
- }
- // \u00E7 is a cedilla (c with wiggle under)
- // note that the test string must be 7-bit-clean (Unicode escaped) or else it will compile incorrectly
- // on some locales
- assertEquals("Fran\u00E7ais", StringEscapeUtils.unescapeHtml4("Fran\u00E7ais"), "funny chars pass through OK");
+ final String original = new String(data, StandardCharsets.UTF_8);
- assertEquals("Hello&;World", StringEscapeUtils.unescapeHtml4("Hello&;World"));
- assertEquals("Hello&#;World", StringEscapeUtils.unescapeHtml4("Hello&#;World"));
- assertEquals("Hello&# ;World", StringEscapeUtils.unescapeHtml4("Hello&# ;World"));
- assertEquals("Hello&##;World", StringEscapeUtils.unescapeHtml4("Hello&##;World"));
- }
+ final String escaped = StringEscapeUtils.escapeHtml4( original );
+ assertEquals(original, escaped, "High Unicode should not have been escaped");
- @Test
- public void testUnescapeHexCharsHtml() {
- // Simple easy to grok test
- assertEquals("\u0080\u009F", StringEscapeUtils.unescapeHtml4("€Ÿ"), "hex number unescape");
- assertEquals("\u0080\u009F", StringEscapeUtils.unescapeHtml4("€Ÿ"), "hex number unescape");
- // Test all Character values:
- for (char i = Character.MIN_VALUE; i < Character.MAX_VALUE; i++) {
- final Character c1 = Character.valueOf(i);
- final Character c2 = Character.valueOf((char) (i+1));
- final String expected = c1.toString() + c2.toString();
- final String escapedC1 = "&#x" + Integer.toHexString((c1.charValue())) + ";";
- final String escapedC2 = "&#x" + Integer.toHexString((c2.charValue())) + ";";
- assertEquals(expected, StringEscapeUtils.unescapeHtml4(escapedC1 + escapedC2), "hex number unescape index " + (int) i);
- }
- }
+ final String unescaped = StringEscapeUtils.unescapeHtml4( escaped );
+ assertEquals(original, unescaped, "High Unicode should have been unchanged");
- @Test
- public void testUnescapeUnknownEntity() {
- assertEquals("&zzzz;", StringEscapeUtils.unescapeHtml4("&zzzz;"));
+// TODO: I think this should hold, needs further investigation
+// String unescapedFromEntity = StringEscapeUtils.unescapeHtml4( "𝍢" );
+// assertEquals( "High Unicode should have been unescaped", original, unescapedFromEntity);
}
@Test
@@ -254,6 +218,63 @@ public class StringEscapeUtilsTest extends AbstractLangTest {
// TODO: refine API for escaping/unescaping specific HTML versions
}
+ @Test
+ public void testEscapeJava() throws IOException {
+ assertNull(StringEscapeUtils.escapeJava(null));
+ assertThrows(NullPointerException.class, () -> StringEscapeUtils.ESCAPE_JAVA.translate(null, null));
+ assertThrows(NullPointerException.class, () -> StringEscapeUtils.ESCAPE_JAVA.translate("", null));
+
+ assertEscapeJava("empty string", "", "");
+ assertEscapeJava(FOO, FOO);
+ assertEscapeJava("tab", "\\t", "\t");
+ assertEscapeJava("backslash", "\\\\", "\\");
+ assertEscapeJava("single quote should not be escaped", "'", "'");
+ assertEscapeJava("\\\\\\b\\t\\r", "\\\b\t\r");
+ assertEscapeJava("\\u1234", "\u1234");
+ assertEscapeJava("\\u0234", "\u0234");
+ assertEscapeJava("\\u00EF", "\u00ef");
+ assertEscapeJava("\\u0001", "\u0001");
+ assertEscapeJava("Should use capitalized Unicode hex", "\\uABCD", "\uabcd");
+
+ assertEscapeJava("He didn't say, \\\"stop!\\\"",
+ "He didn't say, \"stop!\"");
+ assertEscapeJava("non-breaking space", "This space is non-breaking:" + "\\u00A0",
+ "This space is non-breaking:\u00a0");
+ assertEscapeJava("\\uABCD\\u1234\\u012C",
+ "\uABCD\u1234\u012C");
+ }
+
+ /**
+ * Tests https://issues.apache.org/jira/browse/LANG-421
+ */
+ @Test
+ public void testEscapeJavaWithSlash() {
+ final String input = "String with a slash (/) in it";
+
+ final String expected = input;
+ final String actual = StringEscapeUtils.escapeJava(input);
+
+ /*
+ * In 2.4 StringEscapeUtils.escapeJava(String) escapes '/' characters, which are not a valid character to escape
+ * in a Java string.
+ */
+ assertEquals(expected, actual);
+ }
+
+ @Test
+ public void testEscapeJson() {
+ assertNull(StringEscapeUtils.escapeJson(null));
+ assertThrows(NullPointerException.class, () -> StringEscapeUtils.ESCAPE_JSON.translate(null, null));
+ assertThrows(NullPointerException.class, () -> StringEscapeUtils.ESCAPE_JSON.translate("", null));
+
+ assertEquals("He didn't say, \\\"stop!\\\"", StringEscapeUtils.escapeJson("He didn't say, \"stop!\""));
+
+ final String expected = "\\\"foo\\\" isn't \\\"bar\\\". specials: \\b\\r\\n\\f\\t\\\\\\/";
+ final String input ="\"foo\" isn't \"bar\". specials: \b\r\n\f\t\\/";
+
+ assertEquals(expected, StringEscapeUtils.escapeJson(input));
+ }
+
@Test
public void testEscapeXml() throws Exception {
assertEquals("<abc>", StringEscapeUtils.escapeXml("<abc>"));
@@ -315,6 +336,24 @@ public class StringEscapeUtilsTest extends AbstractLangTest {
"XML 1.1 should omit #xfffe | #xffff");
}
+ @Test
+ public void testEscapeXmlAllCharacters() {
+ // https://www.w3.org/TR/xml/#charsets says:
+ // Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF] /* any Unicode character,
+ // excluding the surrogate blocks, FFFE, and FFFF. */
+ final CharSequenceTranslator escapeXml = StringEscapeUtils.ESCAPE_XML
+ .with(NumericEntityEscaper.below(9), NumericEntityEscaper.between(0xB, 0xC), NumericEntityEscaper.between(0xE, 0x19),
+ NumericEntityEscaper.between(0xD800, 0xDFFF), NumericEntityEscaper.between(0xFFFE, 0xFFFF), NumericEntityEscaper.above(0x110000));
+
+ assertEquals("�", escapeXml.translate("\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\u0008"));
+ assertEquals("\t", escapeXml.translate("\t")); // 0x9
+ assertEquals("\n", escapeXml.translate("\n")); // 0xA
+ assertEquals("", escapeXml.translate("\u000B\u000C"));
+ assertEquals("\r", escapeXml.translate("\r")); // 0xD
+ assertEquals("Hello World! Ain't this great?", escapeXml.translate("Hello World! Ain't this great?"));
+ assertEquals("", escapeXml.translate("\u000E\u000F\u0018\u0019"));
+ }
+
/**
* Tests Supplementary characters.
* <p>
@@ -343,35 +382,46 @@ public class StringEscapeUtilsTest extends AbstractLangTest {
}
@Test
- public void testEscapeXmlAllCharacters() {
- // https://www.w3.org/TR/xml/#charsets says:
- // Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF] /* any Unicode character,
- // excluding the surrogate blocks, FFFE, and FFFF. */
- final CharSequenceTranslator escapeXml = StringEscapeUtils.ESCAPE_XML
- .with(NumericEntityEscaper.below(9), NumericEntityEscaper.between(0xB, 0xC), NumericEntityEscaper.between(0xE, 0x19),
- NumericEntityEscaper.between(0xD800, 0xDFFF), NumericEntityEscaper.between(0xFFFE, 0xFFFF), NumericEntityEscaper.above(0x110000));
-
- assertEquals("�", escapeXml.translate("\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\u0008"));
- assertEquals("\t", escapeXml.translate("\t")); // 0x9
- assertEquals("\n", escapeXml.translate("\n")); // 0xA
- assertEquals("", escapeXml.translate("\u000B\u000C"));
- assertEquals("\r", escapeXml.translate("\r")); // 0xD
- assertEquals("Hello World! Ain't this great?", escapeXml.translate("Hello World! Ain't this great?"));
- assertEquals("", escapeXml.translate("\u000E\u000F\u0018\u0019"));
+ public void testLang313() {
+ assertEquals("& &", StringEscapeUtils.unescapeHtml4("& &"));
}
/**
- * Reverse of the above.
+ * Tests https://issues.apache.org/jira/browse/LANG-708
*
- * @see <a href="https://issues.apache.org/jira/browse/LANG-729">LANG-729</a>
+ * @throws IOException
+ * if an I/O error occurs
*/
@Test
- public void testUnescapeXmlSupplementaryCharacters() {
- assertEquals("\uD84C\uDFB4", StringEscapeUtils.unescapeXml("𣎴"),
- "Supplementary character must be represented using a single escape");
+ public void testLang708() throws IOException {
+ final byte[] inputBytes = Files.readAllBytes(Paths.get("src/test/resources/lang-708-input.txt"));
+ final String input = new String(inputBytes, StandardCharsets.UTF_8);
+ final String escaped = StringEscapeUtils.escapeEcmaScript(input);
+ // just the end:
+ assertTrue(escaped.endsWith("}]"), escaped);
+ // a little more:
+ assertTrue(escaped.endsWith("\"valueCode\\\":\\\"\\\"}]"), escaped);
+ }
- assertEquals("a b c \uD84C\uDFB4", StringEscapeUtils.unescapeXml("a b c 𣎴"),
- "Supplementary characters mixed with basic characters should be decoded correctly");
+ /**
+ * Tests https://issues.apache.org/jira/browse/LANG-720
+ */
+ @Test
+ public void testLang720() {
+ final String input = "\ud842\udfb7" + "A";
+ final String escaped = StringEscapeUtils.escapeXml(input);
+ assertEquals(input, escaped);
+ }
+
+ /**
+ * Tests https://issues.apache.org/jira/browse/LANG-911
+ */
+ @Test
+ public void testLang911() {
+ final String bellsTest = "\ud83d\udc80\ud83d\udd14";
+ final String value = StringEscapeUtils.escapeJava(bellsTest);
+ final String valueTest = StringEscapeUtils.unescapeJava(value);
+ assertEquals(bellsTest, valueTest);
}
// Tests issue LANG-150
@@ -385,44 +435,9 @@ public class StringEscapeUtilsTest extends AbstractLangTest {
}
@Test
- public void testLang313() {
- assertEquals("& &", StringEscapeUtils.unescapeHtml4("& &"));
- }
-
- @Test
- public void testEscapeCsvString() {
- assertEquals("foo.bar", StringEscapeUtils.escapeCsv("foo.bar"));
- assertEquals("\"foo,bar\"", StringEscapeUtils.escapeCsv("foo,bar"));
- assertEquals("\"foo\nbar\"", StringEscapeUtils.escapeCsv("foo\nbar"));
- assertEquals("\"foo\rbar\"", StringEscapeUtils.escapeCsv("foo\rbar"));
- assertEquals("\"foo\"\"bar\"", StringEscapeUtils.escapeCsv("foo\"bar"));
- assertEquals("foo\uD84C\uDFB4bar", StringEscapeUtils.escapeCsv("foo\uD84C\uDFB4bar"));
- assertEquals("", StringEscapeUtils.escapeCsv(""));
- assertNull(StringEscapeUtils.escapeCsv(null));
- }
-
- @Test
- public void testEscapeCsvWriter() throws Exception {
- checkCsvEscapeWriter("foo.bar", "foo.bar");
- checkCsvEscapeWriter("\"foo,bar\"", "foo,bar");
- checkCsvEscapeWriter("\"foo\nbar\"", "foo\nbar");
- checkCsvEscapeWriter("\"foo\rbar\"", "foo\rbar");
- checkCsvEscapeWriter("\"foo\"\"bar\"", "foo\"bar");
- checkCsvEscapeWriter("foo\uD84C\uDFB4bar", "foo\uD84C\uDFB4bar");
- checkCsvEscapeWriter("", null);
- checkCsvEscapeWriter("", "");
- }
-
- private void checkCsvEscapeWriter(final String expected, final String value) throws IOException {
- final StringWriter writer = new StringWriter();
- StringEscapeUtils.ESCAPE_CSV.translate(value, writer);
- assertEquals(expected, writer.toString());
- }
-
- @Test
- public void testEscapeCsvIllegalStateException() {
+ public void testUnescapeCsvIllegalStateException() {
final StringWriter writer = new StringWriter();
- assertThrows(IllegalStateException.class, () -> StringEscapeUtils.ESCAPE_CSV.translate("foo", -1, writer));
+ assertThrows(IllegalStateException.class, () -> StringEscapeUtils.UNESCAPE_CSV.translate("foo", -1, writer));
}
@Test
@@ -453,108 +468,74 @@ public class StringEscapeUtilsTest extends AbstractLangTest {
checkCsvUnescapeWriter("\"foo.bar\"", "\"foo.bar\"");
}
- private void checkCsvUnescapeWriter(final String expected, final String value) throws IOException {
- final StringWriter writer = new StringWriter();
- StringEscapeUtils.UNESCAPE_CSV.translate(value, writer);
- assertEquals(expected, writer.toString());
- }
-
- @Test
- public void testUnescapeCsvIllegalStateException() {
- final StringWriter writer = new StringWriter();
- assertThrows(IllegalStateException.class, () -> StringEscapeUtils.UNESCAPE_CSV.translate("foo", -1, writer));
- }
-
- /**
- * Tests // https://issues.apache.org/jira/browse/LANG-480
- */
@Test
- public void testEscapeHtmlHighUnicode() {
- // this is the utf8 representation of the character:
- // COUNTING ROD UNIT DIGIT THREE
- // in Unicode
- // code point: U+1D362
- final byte[] data = { (byte) 0xF0, (byte) 0x9D, (byte) 0x8D, (byte) 0xA2 };
-
- final String original = new String(data, StandardCharsets.UTF_8);
-
- final String escaped = StringEscapeUtils.escapeHtml4( original );
- assertEquals(original, escaped, "High Unicode should not have been escaped");
-
- final String unescaped = StringEscapeUtils.unescapeHtml4( escaped );
- assertEquals(original, unescaped, "High Unicode should have been unchanged");
+ public void testUnescapeEcmaScript() {
+ assertNull(StringEscapeUtils.escapeEcmaScript(null));
+ assertThrows(NullPointerException.class, () -> StringEscapeUtils.UNESCAPE_ECMASCRIPT.translate(null, null));
+ assertThrows(NullPointerException.class, () -> StringEscapeUtils.UNESCAPE_ECMASCRIPT.translate("", null));
-// TODO: I think this should hold, needs further investigation
-// String unescapedFromEntity = StringEscapeUtils.unescapeHtml4( "𝍢" );
-// assertEquals( "High Unicode should have been unescaped", original, unescapedFromEntity);
+ assertEquals("He didn't say, \"stop!\"", StringEscapeUtils.unescapeEcmaScript("He didn\\'t say, \\\"stop!\\\""));
+ assertEquals("document.getElementById(\"test\").value = '<script>alert('aaa');</script>';",
+ StringEscapeUtils.unescapeEcmaScript("document.getElementById(\\\"test\\\").value = \\'<script>alert(\\'aaa\\');<\\/script>\\';"));
}
- /**
- * Tests https://issues.apache.org/jira/browse/LANG-339
- */
@Test
- public void testEscapeHiragana() {
- // Some random Japanese Unicode characters
- final String original = "\u304B\u304C\u3068";
- final String escaped = StringEscapeUtils.escapeHtml4(original);
- assertEquals(original, escaped,
- "Hiragana character Unicode behavior should not be being escaped by escapeHtml4");
-
- final String unescaped = StringEscapeUtils.unescapeHtml4( escaped );
-
- assertEquals(escaped, unescaped, "Hiragana character Unicode behavior has changed - expected no unescaping");
+ public void testUnescapeHexCharsHtml() {
+ // Simple easy to grok test
+ assertEquals("\u0080\u009F", StringEscapeUtils.unescapeHtml4("€Ÿ"), "hex number unescape");
+ assertEquals("\u0080\u009F", StringEscapeUtils.unescapeHtml4("€Ÿ"), "hex number unescape");
+ // Test all Character values:
+ for (char i = Character.MIN_VALUE; i < Character.MAX_VALUE; i++) {
+ final Character c1 = Character.valueOf(i);
+ final Character c2 = Character.valueOf((char) (i+1));
+ final String expected = c1.toString() + c2.toString();
+ final String escapedC1 = "&#x" + Integer.toHexString((c1.charValue())) + ";";
+ final String escapedC2 = "&#x" + Integer.toHexString((c2.charValue())) + ";";
+ assertEquals(expected, StringEscapeUtils.unescapeHtml4(escapedC1 + escapedC2), "hex number unescape index " + (int) i);
+ }
}
- /**
- * Tests https://issues.apache.org/jira/browse/LANG-708
- *
- * @throws IOException
- * if an I/O error occurs
- */
@Test
- public void testLang708() throws IOException {
- final byte[] inputBytes = Files.readAllBytes(Paths.get("src/test/resources/lang-708-input.txt"));
- final String input = new String(inputBytes, StandardCharsets.UTF_8);
- final String escaped = StringEscapeUtils.escapeEcmaScript(input);
- // just the end:
- assertTrue(escaped.endsWith("}]"), escaped);
- // a little more:
- assertTrue(escaped.endsWith("\"valueCode\\\":\\\"\\\"}]"), escaped);
- }
+ public void testUnescapeHtml4() throws IOException {
+ for (final String[] element : HTML_ESCAPES) {
+ final String message = element[0];
+ final String expected = element[2];
+ final String original = element[1];
+ assertEquals(expected, StringEscapeUtils.unescapeHtml4(original), message);
- /**
- * Tests https://issues.apache.org/jira/browse/LANG-720
- */
- @Test
- public void testLang720() {
- final String input = "\ud842\udfb7" + "A";
- final String escaped = StringEscapeUtils.escapeXml(input);
- assertEquals(input, escaped);
- }
+ final StringWriter sw = new StringWriter();
+ StringEscapeUtils.UNESCAPE_HTML4.translate(original, sw);
+ final String actual = original == null ? null : sw.toString();
+ assertEquals(expected, actual, message);
+ }
+ // \u00E7 is a cedilla (c with wiggle under)
+ // note that the test string must be 7-bit-clean (Unicode escaped) or else it will compile incorrectly
+ // on some locales
+ assertEquals("Fran\u00E7ais", StringEscapeUtils.unescapeHtml4("Fran\u00E7ais"), "funny chars pass through OK");
- /**
- * Tests https://issues.apache.org/jira/browse/LANG-911
- */
- @Test
- public void testLang911() {
- final String bellsTest = "\ud83d\udc80\ud83d\udd14";
- final String value = StringEscapeUtils.escapeJava(bellsTest);
- final String valueTest = StringEscapeUtils.unescapeJava(value);
- assertEquals(bellsTest, valueTest);
+ assertEquals("Hello&;World", StringEscapeUtils.unescapeHtml4("Hello&;World"));
+ assertEquals("Hello&#;World", StringEscapeUtils.unescapeHtml4("Hello&#;World"));
+ assertEquals("Hello&# ;World", StringEscapeUtils.unescapeHtml4("Hello&# ;World"));
+ assertEquals("Hello&##;World", StringEscapeUtils.unescapeHtml4("Hello&##;World"));
}
@Test
- public void testEscapeJson() {
- assertNull(StringEscapeUtils.escapeJson(null));
- assertThrows(NullPointerException.class, () -> StringEscapeUtils.ESCAPE_JSON.translate(null, null));
- assertThrows(NullPointerException.class, () -> StringEscapeUtils.ESCAPE_JSON.translate("", null));
-
- assertEquals("He didn't say, \\\"stop!\\\"", StringEscapeUtils.escapeJson("He didn't say, \"stop!\""));
-
- final String expected = "\\\"foo\\\" isn't \\\"bar\\\". specials: \\b\\r\\n\\f\\t\\\\\\/";
- final String input ="\"foo\" isn't \"bar\". specials: \b\r\n\f\t\\/";
+ public void testUnescapeJava() throws IOException {
+ assertNull(StringEscapeUtils.unescapeJava(null));
+ assertThrows(NullPointerException.class, () -> StringEscapeUtils.UNESCAPE_JAVA.translate(null, null));
+ assertThrows(NullPointerException.class, () -> StringEscapeUtils.UNESCAPE_JAVA.translate("", null));
+ assertThrows(RuntimeException.class, () -> StringEscapeUtils.unescapeJava("\\u02-3"));
- assertEquals(expected, StringEscapeUtils.escapeJson(input));
+ assertUnescapeJava("", "");
+ assertUnescapeJava("test", "test");
+ assertUnescapeJava("\ntest\b", "\\ntest\\b");
+ assertUnescapeJava("\u123425foo\ntest\b", "\\u123425foo\\ntest\\b");
+ assertUnescapeJava("'\foo\teste\r", "\\'\\foo\\teste\\r");
+ assertUnescapeJava("", "\\");
+ //foo
+ assertUnescapeJava("lowercase Unicode", "\uABCDx", "\\uabcdx");
+ assertUnescapeJava("uppercase Unicode", "\uABCDx", "\\uABCDx");
+ assertUnescapeJava("Unicode as final character", "\uABCD", "\\uabcd");
}
@Test
@@ -570,4 +551,23 @@ public class StringEscapeUtilsTest extends AbstractLangTest {
assertEquals(expected, StringEscapeUtils.unescapeJson(input));
}
+
+ @Test
+ public void testUnescapeUnknownEntity() {
+ assertEquals("&zzzz;", StringEscapeUtils.unescapeHtml4("&zzzz;"));
+ }
+
+ /**
+ * Reverse of the above.
+ *
+ * @see <a href="https://issues.apache.org/jira/browse/LANG-729">LANG-729</a>
+ */
+ @Test
+ public void testUnescapeXmlSupplementaryCharacters() {
+ assertEquals("\uD84C\uDFB4", StringEscapeUtils.unescapeXml("𣎴"),
+ "Supplementary character must be represented using a single escape");
+
+ assertEquals("a b c \uD84C\uDFB4", StringEscapeUtils.unescapeXml("a b c 𣎴"),
+ "Supplementary characters mixed with basic characters should be decoded correctly");
+ }
}
diff --git a/src/test/java/org/apache/commons/lang3/StringUtilsContainsTest.java b/src/test/java/org/apache/commons/lang3/StringUtilsContainsTest.java
index b152a8df2..87c5548df 100644
--- a/src/test/java/org/apache/commons/lang3/StringUtilsContainsTest.java
+++ b/src/test/java/org/apache/commons/lang3/StringUtilsContainsTest.java
@@ -178,27 +178,6 @@ public class StringUtilsContainsTest extends AbstractLangTest {
assertTrue(StringUtils.containsAny("abc", "d", "abc"));
}
- @Test
- public void testContainsAnyIgnoreCase_StringStringArray() {
- assertFalse(StringUtils.containsAnyIgnoreCase(null, (String[]) null));
- assertFalse(StringUtils.containsAnyIgnoreCase(null, new String[0]));
- assertFalse(StringUtils.containsAnyIgnoreCase(null, new String[] { "hello" }));
- assertFalse(StringUtils.containsAnyIgnoreCase("", (String[]) null));
- assertFalse(StringUtils.containsAnyIgnoreCase("", new String[0]));
- assertFalse(StringUtils.containsAnyIgnoreCase("", new String[] { "hello" }));
- assertFalse(StringUtils.containsAnyIgnoreCase("hello, goodbye", (String[]) null));
- assertFalse(StringUtils.containsAnyIgnoreCase("hello, goodbye", new String[0]));
- assertTrue(StringUtils.containsAnyIgnoreCase("hello, goodbye", new String[]{"hello", "goodbye"}));
- assertTrue(StringUtils.containsAnyIgnoreCase("hello, goodbye", new String[]{"hello", "Goodbye"}));
- assertTrue(StringUtils.containsAnyIgnoreCase("hello, goodbye", new String[]{"Hello", "Goodbye"}));
- assertTrue(StringUtils.containsAnyIgnoreCase("hello, goodbye", new String[]{"Hello", null}));
- assertTrue(StringUtils.containsAnyIgnoreCase("hello, null", new String[] { "Hello", null }));
- // Javadoc examples:
- assertTrue(StringUtils.containsAnyIgnoreCase("abcd", "ab", null));
- assertTrue(StringUtils.containsAnyIgnoreCase("abcd", "ab", "cd"));
- assertTrue(StringUtils.containsAnyIgnoreCase("abc", "d", "abc"));
- }
-
/**
* See https://www.oracle.com/technical-resources/articles/javase/supplementary.html
*/
@@ -230,6 +209,27 @@ public class StringUtilsContainsTest extends AbstractLangTest {
assertFalse(StringUtils.containsAny(CharU20001, CharU20000));
}
+ @Test
+ public void testContainsAnyIgnoreCase_StringStringArray() {
+ assertFalse(StringUtils.containsAnyIgnoreCase(null, (String[]) null));
+ assertFalse(StringUtils.containsAnyIgnoreCase(null, new String[0]));
+ assertFalse(StringUtils.containsAnyIgnoreCase(null, new String[] { "hello" }));
+ assertFalse(StringUtils.containsAnyIgnoreCase("", (String[]) null));
+ assertFalse(StringUtils.containsAnyIgnoreCase("", new String[0]));
+ assertFalse(StringUtils.containsAnyIgnoreCase("", new String[] { "hello" }));
+ assertFalse(StringUtils.containsAnyIgnoreCase("hello, goodbye", (String[]) null));
+ assertFalse(StringUtils.containsAnyIgnoreCase("hello, goodbye", new String[0]));
+ assertTrue(StringUtils.containsAnyIgnoreCase("hello, goodbye", new String[]{"hello", "goodbye"}));
+ assertTrue(StringUtils.containsAnyIgnoreCase("hello, goodbye", new String[]{"hello", "Goodbye"}));
+ assertTrue(StringUtils.containsAnyIgnoreCase("hello, goodbye", new String[]{"Hello", "Goodbye"}));
+ assertTrue(StringUtils.containsAnyIgnoreCase("hello, goodbye", new String[]{"Hello", null}));
+ assertTrue(StringUtils.containsAnyIgnoreCase("hello, null", new String[] { "Hello", null }));
+ // Javadoc examples:
+ assertTrue(StringUtils.containsAnyIgnoreCase("abcd", "ab", null));
+ assertTrue(StringUtils.containsAnyIgnoreCase("abcd", "ab", "cd"));
+ assertTrue(StringUtils.containsAnyIgnoreCase("abc", "d", "abc"));
+ }
+
@DefaultLocale(language = "de", country = "DE")
@Test
public void testContainsIgnoreCase_LocaleIndependence() {
diff --git a/src/test/java/org/apache/commons/lang3/StringUtilsEmptyBlankTest.java b/src/test/java/org/apache/commons/lang3/StringUtilsEmptyBlankTest.java
index 68493989f..595eb6e21 100644
--- a/src/test/java/org/apache/commons/lang3/StringUtilsEmptyBlankTest.java
+++ b/src/test/java/org/apache/commons/lang3/StringUtilsEmptyBlankTest.java
@@ -29,45 +29,43 @@ import org.junit.jupiter.api.Test;
public class StringUtilsEmptyBlankTest extends AbstractLangTest {
@Test
- public void testIsEmpty() {
- assertTrue(StringUtils.isEmpty(null));
- assertTrue(StringUtils.isEmpty(""));
- assertFalse(StringUtils.isEmpty(" "));
- assertFalse(StringUtils.isEmpty("foo"));
- assertFalse(StringUtils.isEmpty(" foo "));
- }
-
- @Test
- public void testIsNotEmpty() {
- assertFalse(StringUtils.isNotEmpty(null));
- assertFalse(StringUtils.isNotEmpty(""));
- assertTrue(StringUtils.isNotEmpty(" "));
- assertTrue(StringUtils.isNotEmpty("foo"));
- assertTrue(StringUtils.isNotEmpty(" foo "));
+ public void testFirstNonBlank() {
+ assertNull(StringUtils.firstNonBlank());
+ assertNull(StringUtils.firstNonBlank((String[]) null));
+ assertNull(StringUtils.firstNonBlank(null, null, null));
+ assertNull(StringUtils.firstNonBlank(null, "", " "));
+ assertNull(StringUtils.firstNonBlank(null, null, " "));
+ assertEquals("zz", StringUtils.firstNonBlank(null, "zz"));
+ assertEquals("abc", StringUtils.firstNonBlank("abc"));
+ assertEquals("xyz", StringUtils.firstNonBlank(null, "xyz"));
+ assertEquals("xyz", StringUtils.firstNonBlank(null, "xyz", "abc"));
}
@Test
- public void testIsAnyEmpty() {
- assertTrue(StringUtils.isAnyEmpty((String) null));
- assertFalse(StringUtils.isAnyEmpty((String[]) null));
- assertTrue(StringUtils.isAnyEmpty(null, "foo"));
- assertTrue(StringUtils.isAnyEmpty("", "bar"));
- assertTrue(StringUtils.isAnyEmpty("bob", ""));
- assertTrue(StringUtils.isAnyEmpty(" bob ", null));
- assertFalse(StringUtils.isAnyEmpty(" ", "bar"));
- assertFalse(StringUtils.isAnyEmpty("foo", "bar"));
+ public void testFirstNonEmpty() {
+ assertNull(StringUtils.firstNonEmpty());
+ assertNull(StringUtils.firstNonEmpty((String[]) null));
+ assertNull(StringUtils.firstNonEmpty(null, null, null));
+ assertEquals(" ", StringUtils.firstNonEmpty(null, "", " "));
+ assertNull(StringUtils.firstNonEmpty(null, null, ""));
+ assertEquals("zz", StringUtils.firstNonEmpty(null, "zz"));
+ assertEquals("abc", StringUtils.firstNonEmpty("abc"));
+ assertEquals("xyz", StringUtils.firstNonEmpty(null, "xyz"));
+ assertEquals("xyz", StringUtils.firstNonEmpty(null, "xyz", "abc"));
}
@Test
- public void testIsNoneEmpty() {
- assertFalse(StringUtils.isNoneEmpty((String) null));
- assertTrue(StringUtils.isNoneEmpty((String[]) null));
- assertFalse(StringUtils.isNoneEmpty(null, "foo"));
- assertFalse(StringUtils.isNoneEmpty("", "bar"));
- assertFalse(StringUtils.isNoneEmpty("bob", ""));
- assertFalse(StringUtils.isNoneEmpty(" bob ", null));
- assertTrue(StringUtils.isNoneEmpty(" ", "bar"));
- assertTrue(StringUtils.isNoneEmpty("foo", "bar"));
+ public void testIsAllBlank() {
+ assertTrue(StringUtils.isAllBlank((String) null));
+ assertTrue(StringUtils.isAllBlank((String[]) null));
+ assertTrue(StringUtils.isAllBlank(null, null));
+ assertTrue(StringUtils.isAllBlank(null, " "));
+ assertFalse(StringUtils.isAllBlank(null, "foo"));
+ assertFalse(StringUtils.isAllBlank("", "bar"));
+ assertFalse(StringUtils.isAllBlank("bob", ""));
+ assertFalse(StringUtils.isAllBlank(" bob ", null));
+ assertFalse(StringUtils.isAllBlank(" ", "bar"));
+ assertFalse(StringUtils.isAllBlank("foo", "bar"));
}
@Test
@@ -85,24 +83,6 @@ public class StringUtilsEmptyBlankTest extends AbstractLangTest {
assertTrue(StringUtils.isAllEmpty("", null));
}
- @Test
- public void testIsBlank() {
- assertTrue(StringUtils.isBlank(null));
- assertTrue(StringUtils.isBlank(""));
- assertTrue(StringUtils.isBlank(StringUtilsTest.WHITESPACE));
- assertFalse(StringUtils.isBlank("foo"));
- assertFalse(StringUtils.isBlank(" foo "));
- }
-
- @Test
- public void testIsNotBlank() {
- assertFalse(StringUtils.isNotBlank(null));
- assertFalse(StringUtils.isNotBlank(""));
- assertFalse(StringUtils.isNotBlank(StringUtilsTest.WHITESPACE));
- assertTrue(StringUtils.isNotBlank("foo"));
- assertTrue(StringUtils.isNotBlank(" foo "));
- }
-
@Test
public void testIsAnyBlank() {
assertTrue(StringUtils.isAnyBlank((String) null));
@@ -116,6 +96,36 @@ public class StringUtilsEmptyBlankTest extends AbstractLangTest {
assertFalse(StringUtils.isAnyBlank("foo", "bar"));
}
+ @Test
+ public void testIsAnyEmpty() {
+ assertTrue(StringUtils.isAnyEmpty((String) null));
+ assertFalse(StringUtils.isAnyEmpty((String[]) null));
+ assertTrue(StringUtils.isAnyEmpty(null, "foo"));
+ assertTrue(StringUtils.isAnyEmpty("", "bar"));
+ assertTrue(StringUtils.isAnyEmpty("bob", ""));
+ assertTrue(StringUtils.isAnyEmpty(" bob ", null));
+ assertFalse(StringUtils.isAnyEmpty(" ", "bar"));
+ assertFalse(StringUtils.isAnyEmpty("foo", "bar"));
+ }
+
+ @Test
+ public void testIsBlank() {
+ assertTrue(StringUtils.isBlank(null));
+ assertTrue(StringUtils.isBlank(""));
+ assertTrue(StringUtils.isBlank(StringUtilsTest.WHITESPACE));
+ assertFalse(StringUtils.isBlank("foo"));
+ assertFalse(StringUtils.isBlank(" foo "));
+ }
+
+ @Test
+ public void testIsEmpty() {
+ assertTrue(StringUtils.isEmpty(null));
+ assertTrue(StringUtils.isEmpty(""));
+ assertFalse(StringUtils.isEmpty(" "));
+ assertFalse(StringUtils.isEmpty("foo"));
+ assertFalse(StringUtils.isEmpty(" foo "));
+ }
+
@Test
public void testIsNoneBlank() {
assertFalse(StringUtils.isNoneBlank((String) null));
@@ -130,42 +140,32 @@ public class StringUtilsEmptyBlankTest extends AbstractLangTest {
}
@Test
- public void testIsAllBlank() {
- assertTrue(StringUtils.isAllBlank((String) null));
- assertTrue(StringUtils.isAllBlank((String[]) null));
- assertTrue(StringUtils.isAllBlank(null, null));
- assertTrue(StringUtils.isAllBlank(null, " "));
- assertFalse(StringUtils.isAllBlank(null, "foo"));
- assertFalse(StringUtils.isAllBlank("", "bar"));
- assertFalse(StringUtils.isAllBlank("bob", ""));
- assertFalse(StringUtils.isAllBlank(" bob ", null));
- assertFalse(StringUtils.isAllBlank(" ", "bar"));
- assertFalse(StringUtils.isAllBlank("foo", "bar"));
+ public void testIsNoneEmpty() {
+ assertFalse(StringUtils.isNoneEmpty((String) null));
+ assertTrue(StringUtils.isNoneEmpty((String[]) null));
+ assertFalse(StringUtils.isNoneEmpty(null, "foo"));
+ assertFalse(StringUtils.isNoneEmpty("", "bar"));
+ assertFalse(StringUtils.isNoneEmpty("bob", ""));
+ assertFalse(StringUtils.isNoneEmpty(" bob ", null));
+ assertTrue(StringUtils.isNoneEmpty(" ", "bar"));
+ assertTrue(StringUtils.isNoneEmpty("foo", "bar"));
}
@Test
- public void testFirstNonBlank() {
- assertNull(StringUtils.firstNonBlank());
- assertNull(StringUtils.firstNonBlank((String[]) null));
- assertNull(StringUtils.firstNonBlank(null, null, null));
- assertNull(StringUtils.firstNonBlank(null, "", " "));
- assertNull(StringUtils.firstNonBlank(null, null, " "));
- assertEquals("zz", StringUtils.firstNonBlank(null, "zz"));
- assertEquals("abc", StringUtils.firstNonBlank("abc"));
- assertEquals("xyz", StringUtils.firstNonBlank(null, "xyz"));
- assertEquals("xyz", StringUtils.firstNonBlank(null, "xyz", "abc"));
+ public void testIsNotBlank() {
+ assertFalse(StringUtils.isNotBlank(null));
+ assertFalse(StringUtils.isNotBlank(""));
+ assertFalse(StringUtils.isNotBlank(StringUtilsTest.WHITESPACE));
+ assertTrue(StringUtils.isNotBlank("foo"));
+ assertTrue(StringUtils.isNotBlank(" foo "));
}
@Test
- public void testFirstNonEmpty() {
- assertNull(StringUtils.firstNonEmpty());
- assertNull(StringUtils.firstNonEmpty((String[]) null));
- assertNull(StringUtils.firstNonEmpty(null, null, null));
- assertEquals(" ", StringUtils.firstNonEmpty(null, "", " "));
- assertNull(StringUtils.firstNonEmpty(null, null, ""));
- assertEquals("zz", StringUtils.firstNonEmpty(null, "zz"));
- assertEquals("abc", StringUtils.firstNonEmpty("abc"));
- assertEquals("xyz", StringUtils.firstNonEmpty(null, "xyz"));
- assertEquals("xyz", StringUtils.firstNonEmpty(null, "xyz", "abc"));
+ public void testIsNotEmpty() {
+ assertFalse(StringUtils.isNotEmpty(null));
+ assertFalse(StringUtils.isNotEmpty(""));
+ assertTrue(StringUtils.isNotEmpty(" "));
+ assertTrue(StringUtils.isNotEmpty("foo"));
+ assertTrue(StringUtils.isNotEmpty(" foo "));
}
}
diff --git a/src/test/java/org/apache/commons/lang3/StringUtilsEqualsIndexOfTest.java b/src/test/java/org/apache/commons/lang3/StringUtilsEqualsIndexOfTest.java
index db36fd30e..c6c045ccc 100644
--- a/src/test/java/org/apache/commons/lang3/StringUtilsEqualsIndexOfTest.java
+++ b/src/test/java/org/apache/commons/lang3/StringUtilsEqualsIndexOfTest.java
@@ -34,14 +34,6 @@ import org.junit.jupiter.api.Test;
*/
public class StringUtilsEqualsIndexOfTest extends AbstractLangTest {
- private static final String BAR = "bar";
-
- private static final String FOO = "foo";
-
- private static final String FOOBAR = "foobar";
-
- private static final String[] FOOBAR_SUB_ARRAY = {"ob", "ba"};
-
// The purpose of this class is to test StringUtils#equals(CharSequence, CharSequence)
// with a CharSequence implementation whose equals(Object) override requires that the
// other object be an instance of CustomCharSequence, even though, as char sequences,
@@ -58,16 +50,6 @@ public class StringUtilsEqualsIndexOfTest extends AbstractLangTest {
return seq.charAt(index);
}
- @Override
- public int length() {
- return seq.length();
- }
-
- @Override
- public CharSequence subSequence(final int start, final int end) {
- return new CustomCharSequence(seq.subSequence(start, end));
- }
-
@Override
public boolean equals(final Object obj) {
if (!(obj instanceof CustomCharSequence)) {
@@ -82,12 +64,98 @@ public class StringUtilsEqualsIndexOfTest extends AbstractLangTest {
return seq.hashCode();
}
+ @Override
+ public int length() {
+ return seq.length();
+ }
+
+ @Override
+ public CharSequence subSequence(final int start, final int end) {
+ return new CustomCharSequence(seq.subSequence(start, end));
+ }
+
@Override
public String toString() {
return seq.toString();
}
}
+ private static final String BAR = "bar";
+
+ private static final String FOO = "foo";
+
+ private static final String FOOBAR = "foobar";
+
+ private static final String[] FOOBAR_SUB_ARRAY = {"ob", "ba"};
+
+ @Test
+ public void testCompare_StringString() {
+ assertEquals(0, StringUtils.compare(null, null));
+ assertTrue(StringUtils.compare(null, "a") < 0);
+ assertTrue(StringUtils.compare("a", null) > 0);
+ assertEquals(0, StringUtils.compare("abc", "abc"));
+ assertTrue(StringUtils.compare("a", "b") < 0);
+ assertTrue(StringUtils.compare("b", "a") > 0);
+ assertTrue(StringUtils.compare("a", "B") > 0);
+ assertTrue(StringUtils.compare("abc", "abd") < 0);
+ assertTrue(StringUtils.compare("ab", "abc") < 0);
+ assertTrue(StringUtils.compare("ab", "ab ") < 0);
+ assertTrue(StringUtils.compare("abc", "ab ") > 0);
+ }
+
+ @Test
+ public void testCompare_StringStringBoolean() {
+ assertEquals(0, StringUtils.compare(null, null, false));
+ assertTrue(StringUtils.compare(null, "a", true) < 0);
+ assertTrue(StringUtils.compare(null, "a", false) > 0);
+ assertTrue(StringUtils.compare("a", null, true) > 0);
+ assertTrue(StringUtils.compare("a", null, false) < 0);
+ assertEquals(0, StringUtils.compare("abc", "abc", false));
+ assertTrue(StringUtils.compare("a", "b", false) < 0);
+ assertTrue(StringUtils.compare("b", "a", false) > 0);
+ assertTrue(StringUtils.compare("a", "B", false) > 0);
+ assertTrue(StringUtils.compare("abc", "abd", false) < 0);
+ assertTrue(StringUtils.compare("ab", "abc", false) < 0);
+ assertTrue(StringUtils.compare("ab", "ab ", false) < 0);
+ assertTrue(StringUtils.compare("abc", "ab ", false) > 0);
+ }
+
+ @Test
+ public void testCompareIgnoreCase_StringString() {
+ assertEquals(0, StringUtils.compareIgnoreCase(null, null));
+ assertTrue(StringUtils.compareIgnoreCase(null, "a") < 0);
+ assertTrue(StringUtils.compareIgnoreCase("a", null) > 0);
+ assertEquals(0, StringUtils.compareIgnoreCase("abc", "abc"));
+ assertEquals(0, StringUtils.compareIgnoreCase("abc", "ABC"));
+ assertTrue(StringUtils.compareIgnoreCase("a", "b") < 0);
+ assertTrue(StringUtils.compareIgnoreCase("b", "a") > 0);
+ assertTrue(StringUtils.compareIgnoreCase("a", "B") < 0);
+ assertTrue(StringUtils.compareIgnoreCase("A", "b") < 0);
+ assertTrue(StringUtils.compareIgnoreCase("abc", "ABD") < 0);
+ assertTrue(StringUtils.compareIgnoreCase("ab", "ABC") < 0);
+ assertTrue(StringUtils.compareIgnoreCase("ab", "AB ") < 0);
+ assertTrue(StringUtils.compareIgnoreCase("abc", "AB ") > 0);
+ }
+
+ @Test
+ public void testCompareIgnoreCase_StringStringBoolean() {
+ assertEquals(0, StringUtils.compareIgnoreCase(null, null, false));
+ assertTrue(StringUtils.compareIgnoreCase(null, "a", true) < 0);
+ assertTrue(StringUtils.compareIgnoreCase(null, "a", false) > 0);
+ assertTrue(StringUtils.compareIgnoreCase("a", null, true) > 0);
+ assertTrue(StringUtils.compareIgnoreCase("a", null, false) < 0);
+ assertEquals(0, StringUtils.compareIgnoreCase("abc", "abc", false));
+ assertEquals(0, StringUtils.compareIgnoreCase("abc", "ABC", false));
+ assertTrue(StringUtils.compareIgnoreCase("a", "b", false) < 0);
+ assertTrue(StringUtils.compareIgnoreCase("b", "a", false) > 0);
+ assertTrue(StringUtils.compareIgnoreCase("a", "B", false) < 0);
+ assertTrue(StringUtils.compareIgnoreCase("A", "b", false) < 0);
+ assertTrue(StringUtils.compareIgnoreCase("abc", "ABD", false) < 0);
+ assertTrue(StringUtils.compareIgnoreCase("ab", "ABC", false) < 0);
+ assertTrue(StringUtils.compareIgnoreCase("ab", "AB ", false) < 0);
+ assertTrue(StringUtils.compareIgnoreCase("abc", "AB ", false) > 0);
+ }
+
@Test
public void testCustomCharSequence() {
assertThat(new CustomCharSequence(FOO), IsNot.<CharSequence>not(FOO));
@@ -112,32 +180,6 @@ public class StringUtilsEqualsIndexOfTest extends AbstractLangTest {
assertFalse(StringUtils.equals(foobarCs, fooCs));
}
- @Test
- public void testEqualsOnStrings() {
- assertTrue(StringUtils.equals(null, null));
- assertTrue(StringUtils.equals(FOO, FOO));
- assertTrue(StringUtils.equals(FOO, new String(new char[] { 'f', 'o', 'o' })));
- assertFalse(StringUtils.equals(FOO, new String(new char[] { 'f', 'O', 'O' })));
- assertFalse(StringUtils.equals(FOO, BAR));
- assertFalse(StringUtils.equals(FOO, null));
- assertFalse(StringUtils.equals(null, FOO));
- assertFalse(StringUtils.equals(FOO, FOOBAR));
- assertFalse(StringUtils.equals(FOOBAR, FOO));
- }
-
- @Test
- public void testEqualsIgnoreCase() {
- assertTrue(StringUtils.equalsIgnoreCase(null, null));
- assertTrue(StringUtils.equalsIgnoreCase(FOO, FOO));
- assertTrue(StringUtils.equalsIgnoreCase(FOO, new String(new char[] { 'f', 'o', 'o' })));
- assertTrue(StringUtils.equalsIgnoreCase(FOO, new String(new char[] { 'f', 'O', 'O' })));
- assertFalse(StringUtils.equalsIgnoreCase(FOO, BAR));
- assertFalse(StringUtils.equalsIgnoreCase(FOO, null));
- assertFalse(StringUtils.equalsIgnoreCase(null, FOO));
- assertTrue(StringUtils.equalsIgnoreCase("", ""));
- assertFalse(StringUtils.equalsIgnoreCase("abcd", "abcd "));
- }
-
@Test
public void testEqualsAny() {
assertFalse(StringUtils.equalsAny(FOO));
@@ -192,71 +234,29 @@ public class StringUtilsEqualsIndexOfTest extends AbstractLangTest {
}
@Test
- public void testCompare_StringString() {
- assertEquals(0, StringUtils.compare(null, null));
- assertTrue(StringUtils.compare(null, "a") < 0);
- assertTrue(StringUtils.compare("a", null) > 0);
- assertEquals(0, StringUtils.compare("abc", "abc"));
- assertTrue(StringUtils.compare("a", "b") < 0);
- assertTrue(StringUtils.compare("b", "a") > 0);
- assertTrue(StringUtils.compare("a", "B") > 0);
- assertTrue(StringUtils.compare("abc", "abd") < 0);
- assertTrue(StringUtils.compare("ab", "abc") < 0);
- assertTrue(StringUtils.compare("ab", "ab ") < 0);
- assertTrue(StringUtils.compare("abc", "ab ") > 0);
- }
-
- @Test
- public void testCompare_StringStringBoolean() {
- assertEquals(0, StringUtils.compare(null, null, false));
- assertTrue(StringUtils.compare(null, "a", true) < 0);
- assertTrue(StringUtils.compare(null, "a", false) > 0);
- assertTrue(StringUtils.compare("a", null, true) > 0);
- assertTrue(StringUtils.compare("a", null, false) < 0);
- assertEquals(0, StringUtils.compare("abc", "abc", false));
- assertTrue(StringUtils.compare("a", "b", false) < 0);
- assertTrue(StringUtils.compare("b", "a", false) > 0);
- assertTrue(StringUtils.compare("a", "B", false) > 0);
- assertTrue(StringUtils.compare("abc", "abd", false) < 0);
- assertTrue(StringUtils.compare("ab", "abc", false) < 0);
- assertTrue(StringUtils.compare("ab", "ab ", false) < 0);
- assertTrue(StringUtils.compare("abc", "ab ", false) > 0);
- }
-
- @Test
- public void testCompareIgnoreCase_StringString() {
- assertEquals(0, StringUtils.compareIgnoreCase(null, null));
- assertTrue(StringUtils.compareIgnoreCase(null, "a") < 0);
- assertTrue(StringUtils.compareIgnoreCase("a", null) > 0);
- assertEquals(0, StringUtils.compareIgnoreCase("abc", "abc"));
- assertEquals(0, StringUtils.compareIgnoreCase("abc", "ABC"));
- assertTrue(StringUtils.compareIgnoreCase("a", "b") < 0);
- assertTrue(StringUtils.compareIgnoreCase("b", "a") > 0);
- assertTrue(StringUtils.compareIgnoreCase("a", "B") < 0);
- assertTrue(StringUtils.compareIgnoreCase("A", "b") < 0);
- assertTrue(StringUtils.compareIgnoreCase("abc", "ABD") < 0);
- assertTrue(StringUtils.compareIgnoreCase("ab", "ABC") < 0);
- assertTrue(StringUtils.compareIgnoreCase("ab", "AB ") < 0);
- assertTrue(StringUtils.compareIgnoreCase("abc", "AB ") > 0);
+ public void testEqualsIgnoreCase() {
+ assertTrue(StringUtils.equalsIgnoreCase(null, null));
+ assertTrue(StringUtils.equalsIgnoreCase(FOO, FOO));
+ assertTrue(StringUtils.equalsIgnoreCase(FOO, new String(new char[] { 'f', 'o', 'o' })));
+ assertTrue(StringUtils.equalsIgnoreCase(FOO, new String(new char[] { 'f', 'O', 'O' })));
+ assertFalse(StringUtils.equalsIgnoreCase(FOO, BAR));
+ assertFalse(StringUtils.equalsIgnoreCase(FOO, null));
+ assertFalse(StringUtils.equalsIgnoreCase(null, FOO));
+ assertTrue(StringUtils.equalsIgnoreCase("", ""));
+ assertFalse(StringUtils.equalsIgnoreCase("abcd", "abcd "));
}
@Test
- public void testCompareIgnoreCase_StringStringBoolean() {
- assertEquals(0, StringUtils.compareIgnoreCase(null, null, false));
- assertTrue(StringUtils.compareIgnoreCase(null, "a", true) < 0);
- assertTrue(StringUtils.compareIgnoreCase(null, "a", false) > 0);
- assertTrue(StringUtils.compareIgnoreCase("a", null, true) > 0);
- assertTrue(StringUtils.compareIgnoreCase("a", null, false) < 0);
- assertEquals(0, StringUtils.compareIgnoreCase("abc", "abc", false));
- assertEquals(0, StringUtils.compareIgnoreCase("abc", "ABC", false));
- assertTrue(StringUtils.compareIgnoreCase("a", "b", false) < 0);
- assertTrue(StringUtils.compareIgnoreCase("b", "a", false) > 0);
- assertTrue(StringUtils.compareIgnoreCase("a", "B", false) < 0);
- assertTrue(StringUtils.compareIgnoreCase("A", "b", false) < 0);
- assertTrue(StringUtils.compareIgnoreCase("abc", "ABD", false) < 0);
- assertTrue(StringUtils.compareIgnoreCase("ab", "ABC", false) < 0);
- assertTrue(StringUtils.compareIgnoreCase("ab", "AB ", false) < 0);
- assertTrue(StringUtils.compareIgnoreCase("abc", "AB ", false) > 0);
+ public void testEqualsOnStrings() {
+ assertTrue(StringUtils.equals(null, null));
+ assertTrue(StringUtils.equals(FOO, FOO));
+ assertTrue(StringUtils.equals(FOO, new String(new char[] { 'f', 'o', 'o' })));
+ assertFalse(StringUtils.equals(FOO, new String(new char[] { 'f', 'O', 'O' })));
+ assertFalse(StringUtils.equals(FOO, BAR));
+ assertFalse(StringUtils.equals(FOO, null));
+ assertFalse(StringUtils.equals(null, FOO));
+ assertFalse(StringUtils.equals(FOO, FOOBAR));
+ assertFalse(StringUtils.equals(FOOBAR, FOO));
}
@Test
@@ -510,6 +510,32 @@ public class StringUtilsEqualsIndexOfTest extends AbstractLangTest {
assertEquals(-1, StringUtils.indexOfIgnoreCase("abc", "", 9));
}
+ @Test
+ public void testLANG1193() {
+ assertEquals(0, StringUtils.ordinalIndexOf("abc", "ab", 1));
+ }
+
+ @Test
+ // Non-overlapping test
+ public void testLANG1241_1() {
+ // 0 3 6
+ assertEquals(0, StringUtils.ordinalIndexOf("abaabaab", "ab", 1));
+ assertEquals(3, StringUtils.ordinalIndexOf("abaabaab", "ab", 2));
+ assertEquals(6, StringUtils.ordinalIndexOf("abaabaab", "ab", 3));
+ }
+
+ @Test
+ // Overlapping matching test
+ public void testLANG1241_2() {
+ // 0 2 4
+ assertEquals(0, StringUtils.ordinalIndexOf("abababa", "aba", 1));
+ assertEquals(2, StringUtils.ordinalIndexOf("abababa", "aba", 2));
+ assertEquals(4, StringUtils.ordinalIndexOf("abababa", "aba", 3));
+ assertEquals(0, StringUtils.ordinalIndexOf("abababab", "abab", 1));
+ assertEquals(2, StringUtils.ordinalIndexOf("abababab", "abab", 2));
+ assertEquals(4, StringUtils.ordinalIndexOf("abababab", "abab", 3));
+ }
+
@Test
public void testLastIndexOf_char() {
assertEquals(-1, StringUtils.lastIndexOf(null, ' '));
@@ -771,30 +797,4 @@ public class StringUtilsEqualsIndexOfTest extends AbstractLangTest {
assertEquals(4, StringUtils.ordinalIndexOf("abababab", "abab", 3));
assertEquals(-1, StringUtils.ordinalIndexOf("abababab", "abab", 4));
}
-
- @Test
- public void testLANG1193() {
- assertEquals(0, StringUtils.ordinalIndexOf("abc", "ab", 1));
- }
-
- @Test
- // Non-overlapping test
- public void testLANG1241_1() {
- // 0 3 6
- assertEquals(0, StringUtils.ordinalIndexOf("abaabaab", "ab", 1));
- assertEquals(3, StringUtils.ordinalIndexOf("abaabaab", "ab", 2));
- assertEquals(6, StringUtils.ordinalIndexOf("abaabaab", "ab", 3));
- }
-
- @Test
- // Overlapping matching test
- public void testLANG1241_2() {
- // 0 2 4
- assertEquals(0, StringUtils.ordinalIndexOf("abababa", "aba", 1));
- assertEquals(2, StringUtils.ordinalIndexOf("abababa", "aba", 2));
- assertEquals(4, StringUtils.ordinalIndexOf("abababa", "aba", 3));
- assertEquals(0, StringUtils.ordinalIndexOf("abababab", "abab", 1));
- assertEquals(2, StringUtils.ordinalIndexOf("abababab", "abab", 2));
- assertEquals(4, StringUtils.ordinalIndexOf("abababab", "abab", 3));
- }
}
diff --git a/src/test/java/org/apache/commons/lang3/StringUtilsIsMixedCaseTest.java b/src/test/java/org/apache/commons/lang3/StringUtilsIsMixedCaseTest.java
index c69af49d1..a23b7765a 100644
--- a/src/test/java/org/apache/commons/lang3/StringUtilsIsMixedCaseTest.java
+++ b/src/test/java/org/apache/commons/lang3/StringUtilsIsMixedCaseTest.java
@@ -40,14 +40,29 @@ public class StringUtilsIsMixedCaseTest {
public static final String Middle_MATCH = "at tHe Mid";
public static final String EARLY_MATCH = "At tHe beginning";
- @Benchmark
- public boolean newIsMixedCaseNoneMatch() {
- return StringUtils.isMixedCase(LOWER_CASE_LETTERS);
+ public static boolean oldIsMixedCase(final CharSequence cs) {
+ if (StringUtils.isEmpty(cs) || cs.length() == 1) {
+ return false;
+ }
+ boolean containsUppercase = false;
+ boolean containsLowercase = false;
+ final int sz = cs.length();
+ for (int i = 0; i < sz; i++) {
+ if (containsUppercase && containsLowercase) {
+ return true;
+ }
+ if (Character.isUpperCase(cs.charAt(i))) {
+ containsUppercase = true;
+ } else if (Character.isLowerCase(cs.charAt(i))) {
+ containsLowercase = true;
+ }
+ }
+ return containsUppercase && containsLowercase;
}
@Benchmark
- public boolean oldIsMixedCaseNoneMatch() {
- return oldIsMixedCase(LOWER_CASE_LETTERS);
+ public boolean newIsMixedCaseBeginningMatch() {
+ return StringUtils.isMixedCase(EARLY_MATCH);
}
@Benchmark
@@ -56,47 +71,32 @@ public class StringUtilsIsMixedCaseTest {
}
@Benchmark
- public boolean oldIsMixedCaseEndMatch() {
- return oldIsMixedCase(END_MATCH);
+ public boolean newIsMixedCaseMiddleMatch() {
+ return StringUtils.isMixedCase(Middle_MATCH);
}
@Benchmark
- public boolean newIsMixedCaseMiddleMatch() {
- return StringUtils.isMixedCase(Middle_MATCH);
+ public boolean newIsMixedCaseNoneMatch() {
+ return StringUtils.isMixedCase(LOWER_CASE_LETTERS);
}
@Benchmark
- public boolean oldIsMixedCaseMiddleMatch() {
- return oldIsMixedCase(Middle_MATCH);
+ public boolean oldIsMixedCaseBeginningMatch() {
+ return oldIsMixedCase(EARLY_MATCH);
}
@Benchmark
- public boolean newIsMixedCaseBeginningMatch() {
- return StringUtils.isMixedCase(EARLY_MATCH);
+ public boolean oldIsMixedCaseEndMatch() {
+ return oldIsMixedCase(END_MATCH);
}
@Benchmark
- public boolean oldIsMixedCaseBeginningMatch() {
- return oldIsMixedCase(EARLY_MATCH);
+ public boolean oldIsMixedCaseMiddleMatch() {
+ return oldIsMixedCase(Middle_MATCH);
}
- public static boolean oldIsMixedCase(final CharSequence cs) {
- if (StringUtils.isEmpty(cs) || cs.length() == 1) {
- return false;
- }
- boolean containsUppercase = false;
- boolean containsLowercase = false;
- final int sz = cs.length();
- for (int i = 0; i < sz; i++) {
- if (containsUppercase && containsLowercase) {
- return true;
- }
- if (Character.isUpperCase(cs.charAt(i))) {
- containsUppercase = true;
- } else if (Character.isLowerCase(cs.charAt(i))) {
- containsLowercase = true;
- }
- }
- return containsUppercase && containsLowercase;
+ @Benchmark
+ public boolean oldIsMixedCaseNoneMatch() {
+ return oldIsMixedCase(LOWER_CASE_LETTERS);
}
}
diff --git a/src/test/java/org/apache/commons/lang3/StringUtilsStartsEndsWithTest.java b/src/test/java/org/apache/commons/lang3/StringUtilsStartsEndsWithTest.java
index d1f68d57b..da2bb400d 100644
--- a/src/test/java/org/apache/commons/lang3/StringUtilsStartsEndsWithTest.java
+++ b/src/test/java/org/apache/commons/lang3/StringUtilsStartsEndsWithTest.java
@@ -34,72 +34,6 @@ public class StringUtilsStartsEndsWithTest extends AbstractLangTest {
private static final String FOOBAR = "FOOBAR";
- /**
- * Test StringUtils.startsWith()
- */
- @Test
- public void testStartsWith() {
- assertTrue(StringUtils.startsWith(null, null), "startsWith(null, null)");
- assertFalse(StringUtils.startsWith(FOOBAR, null), "startsWith(FOOBAR, null)");
- assertFalse(StringUtils.startsWith(null, FOO), "startsWith(null, FOO)");
- assertTrue(StringUtils.startsWith(FOOBAR, ""), "startsWith(FOOBAR, \"\")");
-
- assertTrue(StringUtils.startsWith(foobar, foo), "startsWith(foobar, foo)");
- assertTrue(StringUtils.startsWith(FOOBAR, FOO), "startsWith(FOOBAR, FOO)");
- assertFalse(StringUtils.startsWith(foobar, FOO), "startsWith(foobar, FOO)");
- assertFalse(StringUtils.startsWith(FOOBAR, foo), "startsWith(FOOBAR, foo)");
-
- assertFalse(StringUtils.startsWith(foo, foobar), "startsWith(foo, foobar)");
- assertFalse(StringUtils.startsWith(bar, foobar), "startsWith(foo, foobar)");
-
- assertFalse(StringUtils.startsWith(foobar, bar), "startsWith(foobar, bar)");
- assertFalse(StringUtils.startsWith(FOOBAR, BAR), "startsWith(FOOBAR, BAR)");
- assertFalse(StringUtils.startsWith(foobar, BAR), "startsWith(foobar, BAR)");
- assertFalse(StringUtils.startsWith(FOOBAR, bar), "startsWith(FOOBAR, bar)");
- }
-
- /**
- * Test StringUtils.testStartsWithIgnoreCase()
- */
- @Test
- public void testStartsWithIgnoreCase() {
- assertTrue(StringUtils.startsWithIgnoreCase(null, null), "startsWithIgnoreCase(null, null)");
- assertFalse(StringUtils.startsWithIgnoreCase(FOOBAR, null), "startsWithIgnoreCase(FOOBAR, null)");
- assertFalse(StringUtils.startsWithIgnoreCase(null, FOO), "startsWithIgnoreCase(null, FOO)");
- assertTrue(StringUtils.startsWithIgnoreCase(FOOBAR, ""), "startsWithIgnoreCase(FOOBAR, \"\")");
-
- assertTrue(StringUtils.startsWithIgnoreCase(foobar, foo), "startsWithIgnoreCase(foobar, foo)");
- assertTrue(StringUtils.startsWithIgnoreCase(FOOBAR, FOO), "startsWithIgnoreCase(FOOBAR, FOO)");
- assertTrue(StringUtils.startsWithIgnoreCase(foobar, FOO), "startsWithIgnoreCase(foobar, FOO)");
- assertTrue(StringUtils.startsWithIgnoreCase(FOOBAR, foo), "startsWithIgnoreCase(FOOBAR, foo)");
-
- assertFalse(StringUtils.startsWithIgnoreCase(foo, foobar), "startsWithIgnoreCase(foo, foobar)");
- assertFalse(StringUtils.startsWithIgnoreCase(bar, foobar), "startsWithIgnoreCase(foo, foobar)");
-
- assertFalse(StringUtils.startsWithIgnoreCase(foobar, bar), "startsWithIgnoreCase(foobar, bar)");
- assertFalse(StringUtils.startsWithIgnoreCase(FOOBAR, BAR), "startsWithIgnoreCase(FOOBAR, BAR)");
- assertFalse(StringUtils.startsWithIgnoreCase(foobar, BAR), "startsWithIgnoreCase(foobar, BAR)");
- assertFalse(StringUtils.startsWithIgnoreCase(FOOBAR, bar), "startsWithIgnoreCase(FOOBAR, bar)");
- }
-
- @Test
- public void testStartsWithAny() {
- assertFalse(StringUtils.startsWithAny(null, (String[]) null));
- assertFalse(StringUtils.startsWithAny(null, "abc"));
- assertFalse(StringUtils.startsWithAny("abcxyz", (String[]) null));
- assertFalse(StringUtils.startsWithAny("abcxyz"));
- assertTrue(StringUtils.startsWithAny("abcxyz", "abc"));
- assertTrue(StringUtils.startsWithAny("abcxyz", null, "xyz", "abc"));
- assertFalse(StringUtils.startsWithAny("abcxyz", null, "xyz", "abcd"));
- assertTrue(StringUtils.startsWithAny("abcxyz", ""));
- assertFalse(StringUtils.startsWithAny("abcxyz", null, "xyz", "ABCX"));
- assertFalse(StringUtils.startsWithAny("ABCXYZ", null, "xyz", "abc"));
-
- assertTrue(StringUtils.startsWithAny("abcxyz", new StringBuilder("xyz"), new StringBuffer("abc")), "StringUtils.startsWithAny(abcxyz, StringBuilder(xyz), StringBuffer(abc))");
- assertTrue(StringUtils.startsWithAny(new StringBuffer("abcxyz"), new StringBuilder("xyz"), new StringBuffer("abc")), "StringUtils.startsWithAny(StringBuffer(abcxyz), StringBuilder(xyz), StringBuffer(abc))");
- }
-
-
/**
* Test StringUtils.endsWith()
*/
@@ -131,6 +65,35 @@ public class StringUtilsStartsEndsWithTest extends AbstractLangTest {
"endsWith(\u03B1\u03B2\u03B3\u03B4, \u03B3\u0394)");
}
+ @Test
+ public void testEndsWithAny() {
+ assertFalse(StringUtils.endsWithAny(null, (String) null), "StringUtils.endsWithAny(null, null)");
+ assertFalse(StringUtils.endsWithAny(null, "abc"), "StringUtils.endsWithAny(null, new String[] {abc})");
+ assertFalse(StringUtils.endsWithAny("abcxyz", (String) null), "StringUtils.endsWithAny(abcxyz, null)");
+ assertTrue(StringUtils.endsWithAny("abcxyz", ""), "StringUtils.endsWithAny(abcxyz, new String[] {\"\"})");
+ assertTrue(StringUtils.endsWithAny("abcxyz", "xyz"), "StringUtils.endsWithAny(abcxyz, new String[] {xyz})");
+ assertTrue(StringUtils.endsWithAny("abcxyz", null, "xyz", "abc"), "StringUtils.endsWithAny(abcxyz, new String[] {null, xyz, abc})");
+ assertFalse(StringUtils.endsWithAny("defg", null, "xyz", "abc"), "StringUtils.endsWithAny(defg, new String[] {null, xyz, abc})");
+ assertTrue(StringUtils.endsWithAny("abcXYZ", "def", "XYZ"));
+ assertFalse(StringUtils.endsWithAny("abcXYZ", "def", "xyz"));
+ assertTrue(StringUtils.endsWithAny("abcXYZ", "def", "YZ"));
+
+ /*
+ * Type null of the last argument to method endsWithAny(CharSequence, CharSequence...)
+ * doesn't exactly match the vararg parameter type.
+ * Cast to CharSequence[] to confirm the non-varargs invocation,
+ * or pass individual arguments of type CharSequence for a varargs invocation.
+ *
+ * assertFalse(StringUtils.endsWithAny("abcXYZ", null)); // replace with specific types to avoid warning
+ */
+ assertFalse(StringUtils.endsWithAny("abcXYZ", (CharSequence) null));
+ assertFalse(StringUtils.endsWithAny("abcXYZ", (CharSequence[]) null));
+ assertTrue(StringUtils.endsWithAny("abcXYZ", ""));
+
+ assertTrue(StringUtils.endsWithAny("abcxyz", new StringBuilder("abc"), new StringBuffer("xyz")), "StringUtils.endsWithAny(abcxyz, StringBuilder(abc), StringBuffer(xyz))");
+ assertTrue(StringUtils.endsWithAny(new StringBuffer("abcxyz"), new StringBuilder("abc"), new StringBuffer("xyz")), "StringUtils.endsWithAny(StringBuffer(abcxyz), StringBuilder(abc), StringBuffer(xyz))");
+ }
+
/**
* Test StringUtils.endsWithIgnoreCase()
*/
@@ -167,33 +130,70 @@ public class StringUtilsStartsEndsWithTest extends AbstractLangTest {
"endsWith(\u03B1\u03B2\u03B3\u03B4, \u0393)");
}
+
+ /**
+ * Test StringUtils.startsWith()
+ */
@Test
- public void testEndsWithAny() {
- assertFalse(StringUtils.endsWithAny(null, (String) null), "StringUtils.endsWithAny(null, null)");
- assertFalse(StringUtils.endsWithAny(null, "abc"), "StringUtils.endsWithAny(null, new String[] {abc})");
- assertFalse(StringUtils.endsWithAny("abcxyz", (String) null), "StringUtils.endsWithAny(abcxyz, null)");
- assertTrue(StringUtils.endsWithAny("abcxyz", ""), "StringUtils.endsWithAny(abcxyz, new String[] {\"\"})");
- assertTrue(StringUtils.endsWithAny("abcxyz", "xyz"), "StringUtils.endsWithAny(abcxyz, new String[] {xyz})");
- assertTrue(StringUtils.endsWithAny("abcxyz", null, "xyz", "abc"), "StringUtils.endsWithAny(abcxyz, new String[] {null, xyz, abc})");
- assertFalse(StringUtils.endsWithAny("defg", null, "xyz", "abc"), "StringUtils.endsWithAny(defg, new String[] {null, xyz, abc})");
- assertTrue(StringUtils.endsWithAny("abcXYZ", "def", "XYZ"));
- assertFalse(StringUtils.endsWithAny("abcXYZ", "def", "xyz"));
- assertTrue(StringUtils.endsWithAny("abcXYZ", "def", "YZ"));
+ public void testStartsWith() {
+ assertTrue(StringUtils.startsWith(null, null), "startsWith(null, null)");
+ assertFalse(StringUtils.startsWith(FOOBAR, null), "startsWith(FOOBAR, null)");
+ assertFalse(StringUtils.startsWith(null, FOO), "startsWith(null, FOO)");
+ assertTrue(StringUtils.startsWith(FOOBAR, ""), "startsWith(FOOBAR, \"\")");
- /*
- * Type null of the last argument to method endsWithAny(CharSequence, CharSequence...)
- * doesn't exactly match the vararg parameter type.
- * Cast to CharSequence[] to confirm the non-varargs invocation,
- * or pass individual arguments of type CharSequence for a varargs invocation.
- *
- * assertFalse(StringUtils.endsWithAny("abcXYZ", null)); // replace with specific types to avoid warning
- */
- assertFalse(StringUtils.endsWithAny("abcXYZ", (CharSequence) null));
- assertFalse(StringUtils.endsWithAny("abcXYZ", (CharSequence[]) null));
- assertTrue(StringUtils.endsWithAny("abcXYZ", ""));
+ assertTrue(StringUtils.startsWith(foobar, foo), "startsWith(foobar, foo)");
+ assertTrue(StringUtils.startsWith(FOOBAR, FOO), "startsWith(FOOBAR, FOO)");
+ assertFalse(StringUtils.startsWith(foobar, FOO), "startsWith(foobar, FOO)");
+ assertFalse(StringUtils.startsWith(FOOBAR, foo), "startsWith(FOOBAR, foo)");
- assertTrue(StringUtils.endsWithAny("abcxyz", new StringBuilder("abc"), new StringBuffer("xyz")), "StringUtils.endsWithAny(abcxyz, StringBuilder(abc), StringBuffer(xyz))");
- assertTrue(StringUtils.endsWithAny(new StringBuffer("abcxyz"), new StringBuilder("abc"), new StringBuffer("xyz")), "StringUtils.endsWithAny(StringBuffer(abcxyz), StringBuilder(abc), StringBuffer(xyz))");
+ assertFalse(StringUtils.startsWith(foo, foobar), "startsWith(foo, foobar)");
+ assertFalse(StringUtils.startsWith(bar, foobar), "startsWith(foo, foobar)");
+
+ assertFalse(StringUtils.startsWith(foobar, bar), "startsWith(foobar, bar)");
+ assertFalse(StringUtils.startsWith(FOOBAR, BAR), "startsWith(FOOBAR, BAR)");
+ assertFalse(StringUtils.startsWith(foobar, BAR), "startsWith(foobar, BAR)");
+ assertFalse(StringUtils.startsWith(FOOBAR, bar), "startsWith(FOOBAR, bar)");
+ }
+
+ @Test
+ public void testStartsWithAny() {
+ assertFalse(StringUtils.startsWithAny(null, (String[]) null));
+ assertFalse(StringUtils.startsWithAny(null, "abc"));
+ assertFalse(StringUtils.startsWithAny("abcxyz", (String[]) null));
+ assertFalse(StringUtils.startsWithAny("abcxyz"));
+ assertTrue(StringUtils.startsWithAny("abcxyz", "abc"));
+ assertTrue(StringUtils.startsWithAny("abcxyz", null, "xyz", "abc"));
+ assertFalse(StringUtils.startsWithAny("abcxyz", null, "xyz", "abcd"));
+ assertTrue(StringUtils.startsWithAny("abcxyz", ""));
+ assertFalse(StringUtils.startsWithAny("abcxyz", null, "xyz", "ABCX"));
+ assertFalse(StringUtils.startsWithAny("ABCXYZ", null, "xyz", "abc"));
+
+ assertTrue(StringUtils.startsWithAny("abcxyz", new StringBuilder("xyz"), new StringBuffer("abc")), "StringUtils.startsWithAny(abcxyz, StringBuilder(xyz), StringBuffer(abc))");
+ assertTrue(StringUtils.startsWithAny(new StringBuffer("abcxyz"), new StringBuilder("xyz"), new StringBuffer("abc")), "StringUtils.startsWithAny(StringBuffer(abcxyz), StringBuilder(xyz), StringBuffer(abc))");
+ }
+
+ /**
+ * Test StringUtils.testStartsWithIgnoreCase()
+ */
+ @Test
+ public void testStartsWithIgnoreCase() {
+ assertTrue(StringUtils.startsWithIgnoreCase(null, null), "startsWithIgnoreCase(null, null)");
+ assertFalse(StringUtils.startsWithIgnoreCase(FOOBAR, null), "startsWithIgnoreCase(FOOBAR, null)");
+ assertFalse(StringUtils.startsWithIgnoreCase(null, FOO), "startsWithIgnoreCase(null, FOO)");
+ assertTrue(StringUtils.startsWithIgnoreCase(FOOBAR, ""), "startsWithIgnoreCase(FOOBAR, \"\")");
+
+ assertTrue(StringUtils.startsWithIgnoreCase(foobar, foo), "startsWithIgnoreCase(foobar, foo)");
+ assertTrue(StringUtils.startsWithIgnoreCase(FOOBAR, FOO), "startsWithIgnoreCase(FOOBAR, FOO)");
+ assertTrue(StringUtils.startsWithIgnoreCase(foobar, FOO), "startsWithIgnoreCase(foobar, FOO)");
+ assertTrue(StringUtils.startsWithIgnoreCase(FOOBAR, foo), "startsWithIgnoreCase(FOOBAR, foo)");
+
+ assertFalse(StringUtils.startsWithIgnoreCase(foo, foobar), "startsWithIgnoreCase(foo, foobar)");
+ assertFalse(StringUtils.startsWithIgnoreCase(bar, foobar), "startsWithIgnoreCase(foo, foobar)");
+
+ assertFalse(StringUtils.startsWithIgnoreCase(foobar, bar), "startsWithIgnoreCase(foobar, bar)");
+ assertFalse(StringUtils.startsWithIgnoreCase(FOOBAR, BAR), "startsWithIgnoreCase(FOOBAR, BAR)");
+ assertFalse(StringUtils.startsWithIgnoreCase(foobar, BAR), "startsWithIgnoreCase(foobar, BAR)");
+ assertFalse(StringUtils.startsWithIgnoreCase(FOOBAR, bar), "startsWithIgnoreCase(FOOBAR, bar)");
}
diff --git a/src/test/java/org/apache/commons/lang3/StringUtilsSubstringTest.java b/src/test/java/org/apache/commons/lang3/StringUtilsSubstringTest.java
index a6f6bf5d0..4bd87454b 100644
--- a/src/test/java/org/apache/commons/lang3/StringUtilsSubstringTest.java
+++ b/src/test/java/org/apache/commons/lang3/StringUtilsSubstringTest.java
@@ -33,6 +33,93 @@ public class StringUtilsSubstringTest extends AbstractLangTest {
private static final String SENTENCE = "foo bar baz";
+ @Test
+ public void testCountMatches_char() {
+ assertEquals(0, StringUtils.countMatches(null, 'D'));
+ assertEquals(5, StringUtils.countMatches("one long someone sentence of one", ' '));
+ assertEquals(6, StringUtils.countMatches("one long someone sentence of one", 'o'));
+ assertEquals(4, StringUtils.countMatches("oooooooooooo", "ooo"));
+ }
+
+ @Test
+ public void testCountMatches_String() {
+ assertEquals(0, StringUtils.countMatches(null, null));
+ assertEquals(0, StringUtils.countMatches("blah", null));
+ assertEquals(0, StringUtils.countMatches(null, "DD"));
+
+ assertEquals(0, StringUtils.countMatches("x", ""));
+ assertEquals(0, StringUtils.countMatches("", ""));
+
+ assertEquals(3,
+ StringUtils.countMatches("one long someone sentence of one", "one"));
+ assertEquals(0,
+ StringUtils.countMatches("one long someone sentence of one", "two"));
+ assertEquals(4,
+ StringUtils.countMatches("oooooooooooo", "ooo"));
+ assertEquals(0, StringUtils.countMatches(null, "?"));
+ assertEquals(0, StringUtils.countMatches("", "?"));
+ assertEquals(0, StringUtils.countMatches("abba", null));
+ assertEquals(0, StringUtils.countMatches("abba", ""));
+ assertEquals(2, StringUtils.countMatches("abba", "a"));
+ assertEquals(1, StringUtils.countMatches("abba", "ab"));
+ assertEquals(0, StringUtils.countMatches("abba", "xxx"));
+ assertEquals(1, StringUtils.countMatches("ababa", "aba"));
+ }
+
+ @Test
+ public void testLeft_String() {
+ assertSame(null, StringUtils.left(null, -1));
+ assertSame(null, StringUtils.left(null, 0));
+ assertSame(null, StringUtils.left(null, 2));
+
+ assertEquals("", StringUtils.left("", -1));
+ assertEquals("", StringUtils.left("", 0));
+ assertEquals("", StringUtils.left("", 2));
+
+ assertEquals("", StringUtils.left(FOOBAR, -1));
+ assertEquals("", StringUtils.left(FOOBAR, 0));
+ assertEquals(FOO, StringUtils.left(FOOBAR, 3));
+ assertSame(FOOBAR, StringUtils.left(FOOBAR, 80));
+ }
+
+ @Test
+ public void testMid_String() {
+ assertSame(null, StringUtils.mid(null, -1, 0));
+ assertSame(null, StringUtils.mid(null, 0, -1));
+ assertSame(null, StringUtils.mid(null, 3, 0));
+ assertSame(null, StringUtils.mid(null, 3, 2));
+
+ assertEquals("", StringUtils.mid("", 0, -1));
+ assertEquals("", StringUtils.mid("", 0, 0));
+ assertEquals("", StringUtils.mid("", 0, 2));
+
+ assertEquals("", StringUtils.mid(FOOBAR, 3, -1));
+ assertEquals("", StringUtils.mid(FOOBAR, 3, 0));
+ assertEquals("b", StringUtils.mid(FOOBAR, 3, 1));
+ assertEquals(FOO, StringUtils.mid(FOOBAR, 0, 3));
+ assertEquals(BAR, StringUtils.mid(FOOBAR, 3, 3));
+ assertEquals(FOOBAR, StringUtils.mid(FOOBAR, 0, 80));
+ assertEquals(BAR, StringUtils.mid(FOOBAR, 3, 80));
+ assertEquals("", StringUtils.mid(FOOBAR, 9, 3));
+ assertEquals(FOO, StringUtils.mid(FOOBAR, -1, 3));
+ }
+
+ @Test
+ public void testRight_String() {
+ assertSame(null, StringUtils.right(null, -1));
+ assertSame(null, StringUtils.right(null, 0));
+ assertSame(null, StringUtils.right(null, 2));
+
+ assertEquals("", StringUtils.right("", -1));
+ assertEquals("", StringUtils.right("", 0));
+ assertEquals("", StringUtils.right("", 2));
+
+ assertEquals("", StringUtils.right(FOOBAR, -1));
+ assertEquals("", StringUtils.right(FOOBAR, 0));
+ assertEquals(BAR, StringUtils.right(FOOBAR, 3));
+ assertSame(FOOBAR, StringUtils.right(FOOBAR, 80));
+ }
+
@Test
public void testSubstring_StringInt() {
assertNull(StringUtils.substring(null, 0));
@@ -73,57 +160,75 @@ public class StringUtilsSubstringTest extends AbstractLangTest {
}
@Test
- public void testLeft_String() {
- assertSame(null, StringUtils.left(null, -1));
- assertSame(null, StringUtils.left(null, 0));
- assertSame(null, StringUtils.left(null, 2));
-
- assertEquals("", StringUtils.left("", -1));
- assertEquals("", StringUtils.left("", 0));
- assertEquals("", StringUtils.left("", 2));
+ public void testSubstringAfter_StringInt() {
+ assertNull(StringUtils.substringAfter(null, 0));
+ assertNull(StringUtils.substringAfter(null, 'X'));
+ assertEquals("", StringUtils.substringAfter("", 0));
+ assertEquals("", StringUtils.substringAfter("", 'X'));
- assertEquals("", StringUtils.left(FOOBAR, -1));
- assertEquals("", StringUtils.left(FOOBAR, 0));
- assertEquals(FOO, StringUtils.left(FOOBAR, 3));
- assertSame(FOOBAR, StringUtils.left(FOOBAR, 80));
+ assertEquals("", StringUtils.substringAfter("foo", 0));
+ assertEquals("ot", StringUtils.substringAfter("foot", 'o'));
+ assertEquals("bc", StringUtils.substringAfter("abc", 'a'));
+ assertEquals("cba", StringUtils.substringAfter("abcba", 'b'));
+ assertEquals("", StringUtils.substringAfter("abc", 'c'));
+ assertEquals("", StringUtils.substringAfter("abc", 'd'));
}
@Test
- public void testRight_String() {
- assertSame(null, StringUtils.right(null, -1));
- assertSame(null, StringUtils.right(null, 0));
- assertSame(null, StringUtils.right(null, 2));
+ public void testSubstringAfter_StringString() {
+ assertEquals("barXXbaz", StringUtils.substringAfter("fooXXbarXXbaz", "XX"));
- assertEquals("", StringUtils.right("", -1));
- assertEquals("", StringUtils.right("", 0));
- assertEquals("", StringUtils.right("", 2));
+ assertNull(StringUtils.substringAfter(null, null));
+ assertNull(StringUtils.substringAfter(null, ""));
+ assertNull(StringUtils.substringAfter(null, "XX"));
+ assertEquals("", StringUtils.substringAfter("", null));
+ assertEquals("", StringUtils.substringAfter("", ""));
+ assertEquals("", StringUtils.substringAfter("", "XX"));
- assertEquals("", StringUtils.right(FOOBAR, -1));
- assertEquals("", StringUtils.right(FOOBAR, 0));
- assertEquals(BAR, StringUtils.right(FOOBAR, 3));
- assertSame(FOOBAR, StringUtils.right(FOOBAR, 80));
+ assertEquals("", StringUtils.substringAfter("foo", null));
+ assertEquals("ot", StringUtils.substringAfter("foot", "o"));
+ assertEquals("bc", StringUtils.substringAfter("abc", "a"));
+ assertEquals("cba", StringUtils.substringAfter("abcba", "b"));
+ assertEquals("", StringUtils.substringAfter("abc", "c"));
+ assertEquals("abc", StringUtils.substringAfter("abc", ""));
+ assertEquals("", StringUtils.substringAfter("abc", "d"));
}
@Test
- public void testMid_String() {
- assertSame(null, StringUtils.mid(null, -1, 0));
- assertSame(null, StringUtils.mid(null, 0, -1));
- assertSame(null, StringUtils.mid(null, 3, 0));
- assertSame(null, StringUtils.mid(null, 3, 2));
+ public void testSubstringAfterLast_StringInt() {
+ assertNull(StringUtils.substringAfterLast(null, 0));
+ assertNull(StringUtils.substringAfterLast(null, 'X'));
+ assertEquals("", StringUtils.substringAfterLast("", 0));
+ assertEquals("", StringUtils.substringAfterLast("", 'a'));
- assertEquals("", StringUtils.mid("", 0, -1));
- assertEquals("", StringUtils.mid("", 0, 0));
- assertEquals("", StringUtils.mid("", 0, 2));
+ assertEquals("", StringUtils.substringAfterLast("foo", 0));
+ assertEquals("", StringUtils.substringAfterLast("foo", 'b'));
+ assertEquals("t", StringUtils.substringAfterLast("foot", 'o'));
+ assertEquals("bc", StringUtils.substringAfterLast("abc", 'a'));
+ assertEquals("a", StringUtils.substringAfterLast("abcba", 'b'));
+ assertEquals("", StringUtils.substringAfterLast("abc", 'c'));
+ assertEquals("", StringUtils.substringAfterLast("", 'd'));
+ }
- assertEquals("", StringUtils.mid(FOOBAR, 3, -1));
- assertEquals("", StringUtils.mid(FOOBAR, 3, 0));
- assertEquals("b", StringUtils.mid(FOOBAR, 3, 1));
- assertEquals(FOO, StringUtils.mid(FOOBAR, 0, 3));
- assertEquals(BAR, StringUtils.mid(FOOBAR, 3, 3));
- assertEquals(FOOBAR, StringUtils.mid(FOOBAR, 0, 80));
- assertEquals(BAR, StringUtils.mid(FOOBAR, 3, 80));
- assertEquals("", StringUtils.mid(FOOBAR, 9, 3));
- assertEquals(FOO, StringUtils.mid(FOOBAR, -1, 3));
+ @Test
+ public void testSubstringAfterLast_StringString() {
+ assertEquals("baz", StringUtils.substringAfterLast("fooXXbarXXbaz", "XX"));
+
+ assertNull(StringUtils.substringAfterLast(null, null));
+ assertNull(StringUtils.substringAfterLast(null, ""));
+ assertNull(StringUtils.substringAfterLast(null, "XX"));
+ assertEquals("", StringUtils.substringAfterLast("", null));
+ assertEquals("", StringUtils.substringAfterLast("", ""));
+ assertEquals("", StringUtils.substringAfterLast("", "a"));
+
+ assertEquals("", StringUtils.substringAfterLast("foo", null));
+ assertEquals("", StringUtils.substringAfterLast("foo", "b"));
+ assertEquals("t", StringUtils.substringAfterLast("foot", "o"));
+ assertEquals("bc", StringUtils.substringAfterLast("abc", "a"));
+ assertEquals("a", StringUtils.substringAfterLast("abcba", "b"));
+ assertEquals("", StringUtils.substringAfterLast("abc", "c"));
+ assertEquals("", StringUtils.substringAfterLast("", "d"));
+ assertEquals("", StringUtils.substringAfterLast("abc", ""));
}
@Test
@@ -165,41 +270,6 @@ public class StringUtilsSubstringTest extends AbstractLangTest {
assertEquals("abc", StringUtils.substringBefore("abc", "X"));
}
- @Test
- public void testSubstringAfter_StringString() {
- assertEquals("barXXbaz", StringUtils.substringAfter("fooXXbarXXbaz", "XX"));
-
- assertNull(StringUtils.substringAfter(null, null));
- assertNull(StringUtils.substringAfter(null, ""));
- assertNull(StringUtils.substringAfter(null, "XX"));
- assertEquals("", StringUtils.substringAfter("", null));
- assertEquals("", StringUtils.substringAfter("", ""));
- assertEquals("", StringUtils.substringAfter("", "XX"));
-
- assertEquals("", StringUtils.substringAfter("foo", null));
- assertEquals("ot", StringUtils.substringAfter("foot", "o"));
- assertEquals("bc", StringUtils.substringAfter("abc", "a"));
- assertEquals("cba", StringUtils.substringAfter("abcba", "b"));
- assertEquals("", StringUtils.substringAfter("abc", "c"));
- assertEquals("abc", StringUtils.substringAfter("abc", ""));
- assertEquals("", StringUtils.substringAfter("abc", "d"));
- }
-
- @Test
- public void testSubstringAfter_StringInt() {
- assertNull(StringUtils.substringAfter(null, 0));
- assertNull(StringUtils.substringAfter(null, 'X'));
- assertEquals("", StringUtils.substringAfter("", 0));
- assertEquals("", StringUtils.substringAfter("", 'X'));
-
- assertEquals("", StringUtils.substringAfter("foo", 0));
- assertEquals("ot", StringUtils.substringAfter("foot", 'o'));
- assertEquals("bc", StringUtils.substringAfter("abc", 'a'));
- assertEquals("cba", StringUtils.substringAfter("abcba", 'b'));
- assertEquals("", StringUtils.substringAfter("abc", 'c'));
- assertEquals("", StringUtils.substringAfter("abc", 'd'));
- }
-
@Test
public void testSubstringBeforeLast_StringString() {
assertEquals("fooXXbar", StringUtils.substringBeforeLast("fooXXbarXXbaz", "XX"));
@@ -224,56 +294,19 @@ public class StringUtilsSubstringTest extends AbstractLangTest {
assertEquals("", StringUtils.substringBeforeLast("a", "a"));
}
- @Test
- public void testSubstringAfterLast_StringString() {
- assertEquals("baz", StringUtils.substringAfterLast("fooXXbarXXbaz", "XX"));
-
- assertNull(StringUtils.substringAfterLast(null, null));
- assertNull(StringUtils.substringAfterLast(null, ""));
- assertNull(StringUtils.substringAfterLast(null, "XX"));
- assertEquals("", StringUtils.substringAfterLast("", null));
- assertEquals("", StringUtils.substringAfterLast("", ""));
- assertEquals("", StringUtils.substringAfterLast("", "a"));
-
- assertEquals("", StringUtils.substringAfterLast("foo", null));
- assertEquals("", StringUtils.substringAfterLast("foo", "b"));
- assertEquals("t", StringUtils.substringAfterLast("foot", "o"));
- assertEquals("bc", StringUtils.substringAfterLast("abc", "a"));
- assertEquals("a", StringUtils.substringAfterLast("abcba", "b"));
- assertEquals("", StringUtils.substringAfterLast("abc", "c"));
- assertEquals("", StringUtils.substringAfterLast("", "d"));
- assertEquals("", StringUtils.substringAfterLast("abc", ""));
- }
-
- @Test
- public void testSubstringAfterLast_StringInt() {
- assertNull(StringUtils.substringAfterLast(null, 0));
- assertNull(StringUtils.substringAfterLast(null, 'X'));
- assertEquals("", StringUtils.substringAfterLast("", 0));
- assertEquals("", StringUtils.substringAfterLast("", 'a'));
-
- assertEquals("", StringUtils.substringAfterLast("foo", 0));
- assertEquals("", StringUtils.substringAfterLast("foo", 'b'));
- assertEquals("t", StringUtils.substringAfterLast("foot", 'o'));
- assertEquals("bc", StringUtils.substringAfterLast("abc", 'a'));
- assertEquals("a", StringUtils.substringAfterLast("abcba", 'b'));
- assertEquals("", StringUtils.substringAfterLast("abc", 'c'));
- assertEquals("", StringUtils.substringAfterLast("", 'd'));
- }
-
- @Test
- public void testSubstringBetween_StringString() {
- assertNull(StringUtils.substringBetween(null, "tag"));
- assertEquals("", StringUtils.substringBetween("", ""));
- assertNull(StringUtils.substringBetween("", "abc"));
- assertEquals("", StringUtils.substringBetween(" ", " "));
- assertNull(StringUtils.substringBetween("abc", null));
- assertEquals("", StringUtils.substringBetween("abc", ""));
- assertNull(StringUtils.substringBetween("abc", "a"));
- assertEquals("bc", StringUtils.substringBetween("abca", "a"));
- assertEquals("bc", StringUtils.substringBetween("abcabca", "a"));
- assertEquals("bar", StringUtils.substringBetween("\nbar\n", "\n"));
- }
+ @Test
+public void testSubstringBetween_StringString() {
+ assertNull(StringUtils.substringBetween(null, "tag"));
+ assertEquals("", StringUtils.substringBetween("", ""));
+ assertNull(StringUtils.substringBetween("", "abc"));
+ assertEquals("", StringUtils.substringBetween(" ", " "));
+ assertNull(StringUtils.substringBetween("abc", null));
+ assertEquals("", StringUtils.substringBetween("abc", ""));
+ assertNull(StringUtils.substringBetween("abc", "a"));
+ assertEquals("bc", StringUtils.substringBetween("abca", "a"));
+ assertEquals("bc", StringUtils.substringBetween("abcabca", "a"));
+ assertEquals("bar", StringUtils.substringBetween("\nbar\n", "\n"));
+}
@Test
public void testSubstringBetween_StringStringString() {
@@ -289,98 +322,65 @@ public class StringUtilsSubstringTest extends AbstractLangTest {
assertEquals("abc", StringUtils.substringBetween("yabczyabcz", "y", "z"));
}
- /**
- * Tests the substringsBetween method that returns a String Array of substrings.
- */
- @Test
- public void testSubstringsBetween_StringStringString() {
-
- String[] results = StringUtils.substringsBetween("[one], [two], [three]", "[", "]");
- assertEquals(3, results.length);
- assertEquals("one", results[0]);
- assertEquals("two", results[1]);
- assertEquals("three", results[2]);
-
- results = StringUtils.substringsBetween("[one], [two], three", "[", "]");
- assertEquals(2, results.length);
- assertEquals("one", results[0]);
- assertEquals("two", results[1]);
-
- results = StringUtils.substringsBetween("[one], [two], three]", "[", "]");
- assertEquals(2, results.length);
- assertEquals("one", results[0]);
- assertEquals("two", results[1]);
-
- results = StringUtils.substringsBetween("[one], two], three]", "[", "]");
- assertEquals(1, results.length);
- assertEquals("one", results[0]);
-
- results = StringUtils.substringsBetween("one], two], [three]", "[", "]");
- assertEquals(1, results.length);
- assertEquals("three", results[0]);
-
- // 'ab hello ba' will match, but 'ab non ba' won't
- // this is because the 'a' is shared between the two and can't be matched twice
- results = StringUtils.substringsBetween("aabhellobabnonba", "ab", "ba");
- assertEquals(1, results.length);
- assertEquals("hello", results[0]);
-
- results = StringUtils.substringsBetween("one, two, three", "[", "]");
- assertNull(results);
-
- results = StringUtils.substringsBetween("[one, two, three", "[", "]");
- assertNull(results);
-
- results = StringUtils.substringsBetween("one, two, three]", "[", "]");
- assertNull(results);
-
- results = StringUtils.substringsBetween("[one], [two], [three]", "[", null);
- assertNull(results);
-
- results = StringUtils.substringsBetween("[one], [two], [three]", null, "]");
- assertNull(results);
-
- results = StringUtils.substringsBetween("[one], [two], [three]", "", "");
- assertNull(results);
-
- results = StringUtils.substringsBetween(null, "[", "]");
- assertNull(results);
-
- results = StringUtils.substringsBetween("", "[", "]");
- assertEquals(0, results.length);
- }
-
- @Test
- public void testCountMatches_String() {
- assertEquals(0, StringUtils.countMatches(null, null));
- assertEquals(0, StringUtils.countMatches("blah", null));
- assertEquals(0, StringUtils.countMatches(null, "DD"));
-
- assertEquals(0, StringUtils.countMatches("x", ""));
- assertEquals(0, StringUtils.countMatches("", ""));
-
- assertEquals(3,
- StringUtils.countMatches("one long someone sentence of one", "one"));
- assertEquals(0,
- StringUtils.countMatches("one long someone sentence of one", "two"));
- assertEquals(4,
- StringUtils.countMatches("oooooooooooo", "ooo"));
- assertEquals(0, StringUtils.countMatches(null, "?"));
- assertEquals(0, StringUtils.countMatches("", "?"));
- assertEquals(0, StringUtils.countMatches("abba", null));
- assertEquals(0, StringUtils.countMatches("abba", ""));
- assertEquals(2, StringUtils.countMatches("abba", "a"));
- assertEquals(1, StringUtils.countMatches("abba", "ab"));
- assertEquals(0, StringUtils.countMatches("abba", "xxx"));
- assertEquals(1, StringUtils.countMatches("ababa", "aba"));
- }
-
- @Test
- public void testCountMatches_char() {
- assertEquals(0, StringUtils.countMatches(null, 'D'));
- assertEquals(5, StringUtils.countMatches("one long someone sentence of one", ' '));
- assertEquals(6, StringUtils.countMatches("one long someone sentence of one", 'o'));
- assertEquals(4, StringUtils.countMatches("oooooooooooo", "ooo"));
- }
+ /**
+ * Tests the substringsBetween method that returns a String Array of substrings.
+ */
+ @Test
+ public void testSubstringsBetween_StringStringString() {
+
+ String[] results = StringUtils.substringsBetween("[one], [two], [three]", "[", "]");
+ assertEquals(3, results.length);
+ assertEquals("one", results[0]);
+ assertEquals("two", results[1]);
+ assertEquals("three", results[2]);
+
+ results = StringUtils.substringsBetween("[one], [two], three", "[", "]");
+ assertEquals(2, results.length);
+ assertEquals("one", results[0]);
+ assertEquals("two", results[1]);
+
+ results = StringUtils.substringsBetween("[one], [two], three]", "[", "]");
+ assertEquals(2, results.length);
+ assertEquals("one", results[0]);
+ assertEquals("two", results[1]);
+
+ results = StringUtils.substringsBetween("[one], two], three]", "[", "]");
+ assertEquals(1, results.length);
+ assertEquals("one", results[0]);
+
+ results = StringUtils.substringsBetween("one], two], [three]", "[", "]");
+ assertEquals(1, results.length);
+ assertEquals("three", results[0]);
+
+ // 'ab hello ba' will match, but 'ab non ba' won't
+ // this is because the 'a' is shared between the two and can't be matched twice
+ results = StringUtils.substringsBetween("aabhellobabnonba", "ab", "ba");
+ assertEquals(1, results.length);
+ assertEquals("hello", results[0]);
+
+ results = StringUtils.substringsBetween("one, two, three", "[", "]");
+ assertNull(results);
+
+ results = StringUtils.substringsBetween("[one, two, three", "[", "]");
+ assertNull(results);
+
+ results = StringUtils.substringsBetween("one, two, three]", "[", "]");
+ assertNull(results);
+
+ results = StringUtils.substringsBetween("[one], [two], [three]", "[", null);
+ assertNull(results);
+
+ results = StringUtils.substringsBetween("[one], [two], [three]", null, "]");
+ assertNull(results);
+
+ results = StringUtils.substringsBetween("[one], [two], [three]", "", "");
+ assertNull(results);
+
+ results = StringUtils.substringsBetween(null, "[", "]");
+ assertNull(results);
+
+ results = StringUtils.substringsBetween("", "[", "]");
+ assertEquals(0, results.length);
+ }
}
diff --git a/src/test/java/org/apache/commons/lang3/StringUtilsTest.java b/src/test/java/org/apache/commons/lang3/StringUtilsTest.java
index 9b9f9a06b..3fe33ad5b 100644
--- a/src/test/java/org/apache/commons/lang3/StringUtilsTest.java
+++ b/src/test/java/org/apache/commons/lang3/StringUtilsTest.java
@@ -245,13 +245,6 @@ public class StringUtilsTest extends AbstractLangTest {
assertEquals(str.substring(2), res[1], msg);
}
- //Fixed LANG-1463
- @Test
- public void testAbbreviateMarkerWithEmptyString() {
- final String greaterThanMaxTest = "much too long text";
- assertEquals("much too long", StringUtils.abbreviate(greaterThanMaxTest, "", 13));
- }
-
@Test
public void testAbbreviate_StringInt() {
assertNull(StringUtils.abbreviate(null, 10));
@@ -382,6 +375,13 @@ public class StringUtilsTest extends AbstractLangTest {
assertAbbreviateWithAbbrevMarkerAndOffset("+ghijklmno", "+", Integer.MAX_VALUE, 10);
}
+ //Fixed LANG-1463
+ @Test
+ public void testAbbreviateMarkerWithEmptyString() {
+ final String greaterThanMaxTest = "much too long text";
+ assertEquals("much too long", StringUtils.abbreviate(greaterThanMaxTest, "", 13));
+ }
+
@Test
public void testAbbreviateMiddle() {
// javadoc examples
@@ -677,33 +677,6 @@ public class StringUtilsTest extends AbstractLangTest {
}
- @Test
- public void testGetIfBlank_StringStringSupplier() {
- assertEquals("NULL", StringUtils.getIfBlank(null, () -> "NULL"));
- assertEquals("NULL", StringUtils.getIfBlank("", () -> "NULL"));
- assertEquals("NULL", StringUtils.getIfBlank(" ", () -> "NULL"));
- assertEquals("abc", StringUtils.getIfBlank("abc", () -> "NULL"));
- assertNull(StringUtils.getIfBlank("", Suppliers.nul()));
- assertNull(StringUtils.defaultIfBlank("", (String) null));
- // Tests compatibility for the API return type
- final String s = StringUtils.getIfBlank("abc", () -> "NULL");
- assertEquals("abc", s);
- //Checking that default value supplied only on demand
- final MutableInt numberOfCalls = new MutableInt(0);
- final Supplier<String> countingDefaultSupplier = () -> {
- numberOfCalls.increment();
- return "NULL";
- };
- StringUtils.getIfBlank("abc", countingDefaultSupplier);
- assertEquals(0, numberOfCalls.getValue());
- StringUtils.getIfBlank("", countingDefaultSupplier);
- assertEquals(1, numberOfCalls.getValue());
- StringUtils.getIfBlank(" ", countingDefaultSupplier);
- assertEquals(2, numberOfCalls.getValue());
- StringUtils.getIfBlank(null, countingDefaultSupplier);
- assertEquals(3, numberOfCalls.getValue());
- }
-
@Test
public void testDefaultIfEmpty_CharBuffers() {
assertEquals("NULL", StringUtils.defaultIfEmpty(CharBuffer.wrap(""), CharBuffer.wrap("NULL")).toString());
@@ -714,7 +687,6 @@ public class StringUtilsTest extends AbstractLangTest {
assertEquals("abc", s.toString());
}
-
@Test
public void testDefaultIfEmpty_StringBuffers() {
assertEquals("NULL", StringUtils.defaultIfEmpty(new StringBuffer(""), new StringBuffer("NULL")).toString());
@@ -725,6 +697,7 @@ public class StringUtilsTest extends AbstractLangTest {
assertEquals("abc", s.toString());
}
+
@Test
public void testDefaultIfEmpty_StringBuilders() {
assertEquals("NULL", StringUtils.defaultIfEmpty(new StringBuilder(""), new StringBuilder("NULL")).toString());
@@ -746,31 +719,6 @@ public class StringUtilsTest extends AbstractLangTest {
assertEquals("abc", s);
}
- @Test
- public void testGetIfEmpty_StringStringSupplier() {
- assertEquals("NULL", StringUtils.getIfEmpty((String) null, () -> "NULL"));
- assertEquals("NULL", StringUtils.getIfEmpty("", () -> "NULL"));
- assertEquals("abc", StringUtils.getIfEmpty("abc", () -> "NULL"));
- assertNull(StringUtils.getIfEmpty("", Suppliers.nul()));
- assertNull(StringUtils.defaultIfEmpty("", (String) null));
- // Tests compatibility for the API return type
- final String s = StringUtils.getIfEmpty("abc", () -> "NULL");
- assertEquals("abc", s);
- //Checking that default value supplied only on demand
- final MutableInt numberOfCalls = new MutableInt(0);
- final Supplier<String> countingDefaultSupplier = () -> {
- numberOfCalls.increment();
- return "NULL";
- };
- StringUtils.getIfEmpty("abc", countingDefaultSupplier);
- assertEquals(0, numberOfCalls.getValue());
- StringUtils.getIfEmpty("", countingDefaultSupplier);
- assertEquals(1, numberOfCalls.getValue());
- StringUtils.getIfEmpty(null, countingDefaultSupplier);
- assertEquals(2, numberOfCalls.getValue());
- }
-
-
@Test
public void testDeleteWhitespace_String() {
assertNull(StringUtils.deleteWhitespace(null));
@@ -798,6 +746,7 @@ public class StringUtilsTest extends AbstractLangTest {
assertEquals("you are a robot", StringUtils.difference("i am a robot", "you are a robot"));
}
+
@Test
public void testDifferenceAt_StringArray() {
assertEquals(-1, StringUtils.indexOfDifference((String[]) null));
@@ -863,6 +812,41 @@ public class StringUtilsTest extends AbstractLangTest {
assertEquals("\\uDBFF\\uDFFD", StringEscapeUtils.escapeEcmaScript("\uDBFF\uDFFD")); //fail LANG-858
}
+ @Test
+ public void testGeorgianSample() {
+ final char[] arrayI = {
+ //Latin Small Letter dotless I
+ (char) 0x0131,
+ //Greek Capital Letter Theta
+ (char) 0x03F4
+ };
+ final char[] arrayJ = {
+ //Latin Capital Letter I with dot above
+ (char) 0x0130,
+ //Greek Theta Symbol
+ (char) 0x03D1
+ };
+ for (final char i : arrayI) {
+ for (final char j : arrayJ) {
+ final String si = String.valueOf(i);
+ final String sj = String.valueOf(j);
+ final boolean res1 = si.equalsIgnoreCase(sj);
+ final CharSequence ci = new StringBuilder(si);
+ final CharSequence cj = new StringBuilder(sj);
+ boolean res2 = StringUtils.startsWithIgnoreCase(ci, cj);
+ assertEquals(res1, res2, "si : " + si + " sj : " + sj);
+ res2 = StringUtils.endsWithIgnoreCase(ci, cj);
+ assertEquals(res1, res2, "si : " + si + " sj : " + sj);
+ res2 = StringUtils.compareIgnoreCase(ci.toString(), cj.toString()) == 0;
+ assertEquals(res1, res2, "si : " + si + " sj : " + sj);
+ res2 = StringUtils.indexOfIgnoreCase(ci.toString(), cj.toString()) == 0;
+ assertEquals(res1, res2, "si : " + si + " sj : " + sj);
+ res2 = StringUtils.lastIndexOfIgnoreCase(ci.toString(), cj.toString()) == 0;
+ assertEquals(res1, res2, "si : " + si + " sj : " + sj);
+ }
+ }
+ }
+
@Test
public void testGetBytes_Charset() {
assertEquals(ArrayUtils.EMPTY_BYTE_ARRAY, StringUtils.getBytes(null, (Charset) null));
@@ -942,6 +926,57 @@ public class StringUtilsTest extends AbstractLangTest {
assertThrows(IllegalArgumentException.class, () -> StringUtils.getFuzzyDistance(" ", "clear", null));
}
+ @Test
+ public void testGetIfBlank_StringStringSupplier() {
+ assertEquals("NULL", StringUtils.getIfBlank(null, () -> "NULL"));
+ assertEquals("NULL", StringUtils.getIfBlank("", () -> "NULL"));
+ assertEquals("NULL", StringUtils.getIfBlank(" ", () -> "NULL"));
+ assertEquals("abc", StringUtils.getIfBlank("abc", () -> "NULL"));
+ assertNull(StringUtils.getIfBlank("", Suppliers.nul()));
+ assertNull(StringUtils.defaultIfBlank("", (String) null));
+ // Tests compatibility for the API return type
+ final String s = StringUtils.getIfBlank("abc", () -> "NULL");
+ assertEquals("abc", s);
+ //Checking that default value supplied only on demand
+ final MutableInt numberOfCalls = new MutableInt(0);
+ final Supplier<String> countingDefaultSupplier = () -> {
+ numberOfCalls.increment();
+ return "NULL";
+ };
+ StringUtils.getIfBlank("abc", countingDefaultSupplier);
+ assertEquals(0, numberOfCalls.getValue());
+ StringUtils.getIfBlank("", countingDefaultSupplier);
+ assertEquals(1, numberOfCalls.getValue());
+ StringUtils.getIfBlank(" ", countingDefaultSupplier);
+ assertEquals(2, numberOfCalls.getValue());
+ StringUtils.getIfBlank(null, countingDefaultSupplier);
+ assertEquals(3, numberOfCalls.getValue());
+ }
+
+ @Test
+ public void testGetIfEmpty_StringStringSupplier() {
+ assertEquals("NULL", StringUtils.getIfEmpty((String) null, () -> "NULL"));
+ assertEquals("NULL", StringUtils.getIfEmpty("", () -> "NULL"));
+ assertEquals("abc", StringUtils.getIfEmpty("abc", () -> "NULL"));
+ assertNull(StringUtils.getIfEmpty("", Suppliers.nul()));
+ assertNull(StringUtils.defaultIfEmpty("", (String) null));
+ // Tests compatibility for the API return type
+ final String s = StringUtils.getIfEmpty("abc", () -> "NULL");
+ assertEquals("abc", s);
+ //Checking that default value supplied only on demand
+ final MutableInt numberOfCalls = new MutableInt(0);
+ final Supplier<String> countingDefaultSupplier = () -> {
+ numberOfCalls.increment();
+ return "NULL";
+ };
+ StringUtils.getIfEmpty("abc", countingDefaultSupplier);
+ assertEquals(0, numberOfCalls.getValue());
+ StringUtils.getIfEmpty("", countingDefaultSupplier);
+ assertEquals(1, numberOfCalls.getValue());
+ StringUtils.getIfEmpty(null, countingDefaultSupplier);
+ assertEquals(2, numberOfCalls.getValue());
+ }
+
@Test
public void testGetJaroWinklerDistance_NullNull() {
assertThrows(IllegalArgumentException.class, () -> StringUtils.getJaroWinklerDistance(null, null));
@@ -1147,16 +1182,6 @@ public class StringUtilsTest extends AbstractLangTest {
assertEquals("", StringUtils.join(MIXED_TYPE_LIST, '/', 2, 1));
}
- @Test
- public void testJoin_ArrayOfBytes() {
- assertNull(StringUtils.join((byte[]) null, ','));
- assertEquals("1;2", StringUtils.join(BYTE_PRIM_LIST, SEPARATOR_CHAR));
- assertEquals("2", StringUtils.join(BYTE_PRIM_LIST, SEPARATOR_CHAR, 1, 2));
- assertNull(StringUtils.join((byte[]) null, SEPARATOR_CHAR, 0, 1));
- assertEquals(StringUtils.EMPTY, StringUtils.join(BYTE_PRIM_LIST, SEPARATOR_CHAR, 0, 0));
- assertEquals(StringUtils.EMPTY, StringUtils.join(BYTE_PRIM_LIST, SEPARATOR_CHAR, 1, 0));
- }
-
@Test
public void testJoin_ArrayOfBooleans() {
@@ -1170,6 +1195,16 @@ public class StringUtilsTest extends AbstractLangTest {
assertEquals(StringUtils.EMPTY, StringUtils.join(ARRAY_FALSE_TRUE_FALSE, SEPARATOR_CHAR, 1, 0));
}
+ @Test
+ public void testJoin_ArrayOfBytes() {
+ assertNull(StringUtils.join((byte[]) null, ','));
+ assertEquals("1;2", StringUtils.join(BYTE_PRIM_LIST, SEPARATOR_CHAR));
+ assertEquals("2", StringUtils.join(BYTE_PRIM_LIST, SEPARATOR_CHAR, 1, 2));
+ assertNull(StringUtils.join((byte[]) null, SEPARATOR_CHAR, 0, 1));
+ assertEquals(StringUtils.EMPTY, StringUtils.join(BYTE_PRIM_LIST, SEPARATOR_CHAR, 0, 0));
+ assertEquals(StringUtils.EMPTY, StringUtils.join(BYTE_PRIM_LIST, SEPARATOR_CHAR, 1, 0));
+ }
+
@Test
public void testJoin_ArrayOfChars() {
assertNull(StringUtils.join((char[]) null, ','));
@@ -1315,6 +1350,16 @@ public class StringUtilsTest extends AbstractLangTest {
assertEquals("null", StringUtils.join(Arrays.asList(NULL_TO_STRING_LIST).iterator(), SEPARATOR));
}
+ @Test
+ public void testJoin_List_CharDelimiter() {
+ assertEquals("/", StringUtils.join(MIXED_STRING_LIST, '/', 0, MIXED_STRING_LIST.size() - 1));
+ assertEquals("foo", StringUtils.join(MIXED_TYPE_OBJECT_LIST, '/', 0, 1));
+ assertEquals("foo/2", StringUtils.join(MIXED_TYPE_OBJECT_LIST, '/', 0, 2));
+ assertEquals("2", StringUtils.join(MIXED_TYPE_OBJECT_LIST, '/', 1, 2));
+ assertEquals("", StringUtils.join(MIXED_TYPE_OBJECT_LIST, '/', 2, 1));
+ assertNull(null, StringUtils.join((List<?>) null, '/', 0, 1));
+ }
+
@Test
public void testJoin_List_EmptyDelimiter() {
assertNull(StringUtils.join((List<String>) null, null));
@@ -1329,16 +1374,6 @@ public class StringUtilsTest extends AbstractLangTest {
assertEquals("", StringUtils.join(MIXED_STRING_LIST, "", 0, MIXED_STRING_LIST.size()- 1));
}
- @Test
- public void testJoin_List_CharDelimiter() {
- assertEquals("/", StringUtils.join(MIXED_STRING_LIST, '/', 0, MIXED_STRING_LIST.size() - 1));
- assertEquals("foo", StringUtils.join(MIXED_TYPE_OBJECT_LIST, '/', 0, 1));
- assertEquals("foo/2", StringUtils.join(MIXED_TYPE_OBJECT_LIST, '/', 0, 2));
- assertEquals("2", StringUtils.join(MIXED_TYPE_OBJECT_LIST, '/', 1, 2));
- assertEquals("", StringUtils.join(MIXED_TYPE_OBJECT_LIST, '/', 2, 1));
- assertNull(null, StringUtils.join((List<?>) null, '/', 0, 1));
- }
-
@ParameterizedTest
@ValueSource(strings = {",", ";", Supplementary.CharU20000, Supplementary.CharU20001})
public void testJoin_List_NonEmptyDelimiter(final String delimiter) {
@@ -1373,15 +1408,6 @@ public class StringUtilsTest extends AbstractLangTest {
assertEquals("foo2", StringUtils.join(MIXED_TYPE_LIST));
}
- @Disabled
- @Test
- public void testLang1593() {
- final int[] arr = {1, 2, 3, 4, 5, 6, 7};
- final String expected = StringUtils.join(arr, '-');
- final String actual = StringUtils.join(arr, "-");
- assertEquals(expected, actual);
- }
-
@Test
public void testJoin_Objects() {
assertEquals("abc", StringUtils.join("a", "b", "c"));
@@ -1408,6 +1434,15 @@ public class StringUtilsTest extends AbstractLangTest {
assertThrows(IllegalArgumentException.class, () -> StringUtils.joinWith(",", (Object[]) null));
}
+ @Disabled
+ @Test
+ public void testLang1593() {
+ final int[] arr = {1, 2, 3, 4, 5, 6, 7};
+ final String expected = StringUtils.join(arr, '-');
+ final String actual = StringUtils.join(arr, "-");
+ assertEquals(expected, actual);
+ }
+
@Test
public void testLang623() {
assertEquals("t", StringUtils.replaceChars("\u00DE", '\u00DE', 't'));
@@ -1826,25 +1861,6 @@ public class StringUtilsTest extends AbstractLangTest {
assertEquals(StringUtils.removeStart("path", '\0'), "path");
}
- @Test
- public void testRemoveStartString() {
- // StringUtils.removeStart("", *) = ""
- assertNull(StringUtils.removeStart(null, null));
- assertNull(StringUtils.removeStart(null, ""));
- assertNull(StringUtils.removeStart(null, "a"));
-
- // StringUtils.removeStart(*, null) = *
- assertEquals(StringUtils.removeStart("", null), "");
- assertEquals(StringUtils.removeStart("", ""), "");
- assertEquals(StringUtils.removeStart("", "a"), "");
-
- // All others:
- assertEquals(StringUtils.removeStart("www.domain.com", "www."), "domain.com");
- assertEquals(StringUtils.removeStart("domain.com", "www."), "domain.com");
- assertEquals(StringUtils.removeStart("domain.com", ""), "domain.com");
- assertEquals(StringUtils.removeStart("domain.com", null), "domain.com");
- }
-
@Test
public void testRemoveStartIgnoreCase() {
// StringUtils.removeStart("", *) = ""
@@ -1867,6 +1883,25 @@ public class StringUtilsTest extends AbstractLangTest {
assertEquals(StringUtils.removeStartIgnoreCase("www.domain.com", "WWW."), "domain.com", "removeStartIgnoreCase(\"www.domain.com\", \"WWW.\")");
}
+ @Test
+ public void testRemoveStartString() {
+ // StringUtils.removeStart("", *) = ""
+ assertNull(StringUtils.removeStart(null, null));
+ assertNull(StringUtils.removeStart(null, ""));
+ assertNull(StringUtils.removeStart(null, "a"));
+
+ // StringUtils.removeStart(*, null) = *
+ assertEquals(StringUtils.removeStart("", null), "");
+ assertEquals(StringUtils.removeStart("", ""), "");
+ assertEquals(StringUtils.removeStart("", "a"), "");
+
+ // All others:
+ assertEquals(StringUtils.removeStart("www.domain.com", "www."), "domain.com");
+ assertEquals(StringUtils.removeStart("domain.com", "www."), "domain.com");
+ assertEquals(StringUtils.removeStart("domain.com", ""), "domain.com");
+ assertEquals(StringUtils.removeStart("domain.com", null), "domain.com");
+ }
+
@Test
public void testRepeat_CharInt() {
assertEquals("zzz", StringUtils.repeat('z', 3));
@@ -3011,6 +3046,46 @@ public class StringUtilsTest extends AbstractLangTest {
assertEquals(expectedString, StringUtils.toEncodedString(expectedBytes, Charset.forName(encoding)));
}
+ @Test
+ public void testToRootLowerCase() {
+ assertNull(StringUtils.toRootLowerCase(null));
+ assertEquals("a", StringUtils.toRootLowerCase("A"));
+ assertEquals("a", StringUtils.toRootLowerCase("a"));
+ final Locale TURKISH = Locale.forLanguageTag("tr");
+ // Sanity checks:
+ assertNotEquals("title", "TITLE".toLowerCase(TURKISH));
+ assertEquals("title", "TITLE".toLowerCase(Locale.ROOT));
+ assertEquals("title", StringUtils.toRootLowerCase("TITLE"));
+ // Make sure we are not using the default Locale:
+ final Locale defaultLocale = Locale.getDefault();
+ try {
+ Locale.setDefault(TURKISH);
+ assertEquals("title", StringUtils.toRootLowerCase("TITLE"));
+ } finally {
+ Locale.setDefault(defaultLocale);
+ }
+ }
+
+ @Test
+ public void testToRootUpperCase() {
+ assertNull(StringUtils.toRootUpperCase(null));
+ assertEquals("A", StringUtils.toRootUpperCase("a"));
+ assertEquals("A", StringUtils.toRootUpperCase("A"));
+ final Locale TURKISH = Locale.forLanguageTag("tr");
+ // Sanity checks:
+ assertNotEquals("TITLE", "title".toUpperCase(TURKISH));
+ assertEquals("TITLE", "title".toUpperCase(Locale.ROOT));
+ assertEquals("TITLE", StringUtils.toRootUpperCase("title"));
+ // Make sure we are not using the default Locale:
+ final Locale defaultLocale = Locale.getDefault();
+ try {
+ Locale.setDefault(TURKISH);
+ assertEquals("TITLE", StringUtils.toRootUpperCase("title"));
+ } finally {
+ Locale.setDefault(defaultLocale);
+ }
+ }
+
/**
* Tests {@link StringUtils#toString(byte[], String)}
*
@@ -3314,79 +3389,4 @@ public class StringUtilsTest extends AbstractLangTest {
assertSame("ab/ab", StringUtils.wrapIfMissing("ab/ab", "ab"));
assertSame("//x//", StringUtils.wrapIfMissing("//x//", "//"));
}
-
- @Test
- public void testToRootLowerCase() {
- assertNull(StringUtils.toRootLowerCase(null));
- assertEquals("a", StringUtils.toRootLowerCase("A"));
- assertEquals("a", StringUtils.toRootLowerCase("a"));
- final Locale TURKISH = Locale.forLanguageTag("tr");
- // Sanity checks:
- assertNotEquals("title", "TITLE".toLowerCase(TURKISH));
- assertEquals("title", "TITLE".toLowerCase(Locale.ROOT));
- assertEquals("title", StringUtils.toRootLowerCase("TITLE"));
- // Make sure we are not using the default Locale:
- final Locale defaultLocale = Locale.getDefault();
- try {
- Locale.setDefault(TURKISH);
- assertEquals("title", StringUtils.toRootLowerCase("TITLE"));
- } finally {
- Locale.setDefault(defaultLocale);
- }
- }
-
- @Test
- public void testToRootUpperCase() {
- assertNull(StringUtils.toRootUpperCase(null));
- assertEquals("A", StringUtils.toRootUpperCase("a"));
- assertEquals("A", StringUtils.toRootUpperCase("A"));
- final Locale TURKISH = Locale.forLanguageTag("tr");
- // Sanity checks:
- assertNotEquals("TITLE", "title".toUpperCase(TURKISH));
- assertEquals("TITLE", "title".toUpperCase(Locale.ROOT));
- assertEquals("TITLE", StringUtils.toRootUpperCase("title"));
- // Make sure we are not using the default Locale:
- final Locale defaultLocale = Locale.getDefault();
- try {
- Locale.setDefault(TURKISH);
- assertEquals("TITLE", StringUtils.toRootUpperCase("title"));
- } finally {
- Locale.setDefault(defaultLocale);
- }
- }
-
- @Test
- public void testGeorgianSample() {
- final char[] arrayI = {
- //Latin Small Letter dotless I
- (char) 0x0131,
- //Greek Capital Letter Theta
- (char) 0x03F4
- };
- final char[] arrayJ = {
- //Latin Capital Letter I with dot above
- (char) 0x0130,
- //Greek Theta Symbol
- (char) 0x03D1
- };
- for (final char i : arrayI) {
- for (final char j : arrayJ) {
- final String si = String.valueOf(i);
- final String sj = String.valueOf(j);
- final boolean res1 = si.equalsIgnoreCase(sj);
- final CharSequence ci = new StringBuilder(si);
- final CharSequence cj = new StringBuilder(sj);
- boolean res2 = StringUtils.startsWithIgnoreCase(ci, cj);
- assertEquals(res1, res2, "si : " + si + " sj : " + sj);
- res2 = StringUtils.endsWithIgnoreCase(ci, cj);
- assertEquals(res1, res2, "si : " + si + " sj : " + sj);
- res2 = StringUtils.compareIgnoreCase(ci.toString(), cj.toString()) == 0;
- assertEquals(res1, res2, "si : " + si + " sj : " + sj);
- res2 = StringUtils.indexOfIgnoreCase(ci.toString(), cj.toString()) == 0;
- assertEquals(res1, res2, "si : " + si + " sj : " + sj);
- res2 = StringUtils.lastIndexOfIgnoreCase(ci.toString(), cj.toString()) == 0;
- assertEquals(res1, res2, "si : " + si + " sj : " + sj);
- }
- }
- }
}
diff --git a/src/test/java/org/apache/commons/lang3/StringUtilsTrimStripTest.java b/src/test/java/org/apache/commons/lang3/StringUtilsTrimStripTest.java
index 79bff3f1e..cd7a8ca05 100644
--- a/src/test/java/org/apache/commons/lang3/StringUtilsTrimStripTest.java
+++ b/src/test/java/org/apache/commons/lang3/StringUtilsTrimStripTest.java
@@ -29,45 +29,6 @@ import org.junit.jupiter.api.Test;
public class StringUtilsTrimStripTest extends AbstractLangTest {
private static final String FOO = "foo";
- @Test
- public void testTrim() {
- assertEquals(FOO, StringUtils.trim(FOO + " "));
- assertEquals(FOO, StringUtils.trim(" " + FOO + " "));
- assertEquals(FOO, StringUtils.trim(" " + FOO));
- assertEquals(FOO, StringUtils.trim(FOO + ""));
- assertEquals("", StringUtils.trim(" \t\r\n\b "));
- assertEquals("", StringUtils.trim(StringUtilsTest.TRIMMABLE));
- assertEquals(StringUtilsTest.NON_TRIMMABLE, StringUtils.trim(StringUtilsTest.NON_TRIMMABLE));
- assertEquals("", StringUtils.trim(""));
- assertNull(StringUtils.trim(null));
- }
-
- @Test
- public void testTrimToNull() {
- assertEquals(FOO, StringUtils.trimToNull(FOO + " "));
- assertEquals(FOO, StringUtils.trimToNull(" " + FOO + " "));
- assertEquals(FOO, StringUtils.trimToNull(" " + FOO));
- assertEquals(FOO, StringUtils.trimToNull(FOO + ""));
- assertNull(StringUtils.trimToNull(" \t\r\n\b "));
- assertNull(StringUtils.trimToNull(StringUtilsTest.TRIMMABLE));
- assertEquals(StringUtilsTest.NON_TRIMMABLE, StringUtils.trimToNull(StringUtilsTest.NON_TRIMMABLE));
- assertNull(StringUtils.trimToNull(""));
- assertNull(StringUtils.trimToNull(null));
- }
-
- @Test
- public void testTrimToEmpty() {
- assertEquals(FOO, StringUtils.trimToEmpty(FOO + " "));
- assertEquals(FOO, StringUtils.trimToEmpty(" " + FOO + " "));
- assertEquals(FOO, StringUtils.trimToEmpty(" " + FOO));
- assertEquals(FOO, StringUtils.trimToEmpty(FOO + ""));
- assertEquals("", StringUtils.trimToEmpty(" \t\r\n\b "));
- assertEquals("", StringUtils.trimToEmpty(StringUtilsTest.TRIMMABLE));
- assertEquals(StringUtilsTest.NON_TRIMMABLE, StringUtils.trimToEmpty(StringUtilsTest.NON_TRIMMABLE));
- assertEquals("", StringUtils.trimToEmpty(""));
- assertEquals("", StringUtils.trimToEmpty(null));
- }
-
@Test
public void testStrip_String() {
assertNull(StringUtils.strip(null));
@@ -78,28 +39,6 @@ public class StringUtilsTrimStripTest extends AbstractLangTest {
StringUtils.strip(StringUtilsTest.WHITESPACE + StringUtilsTest.NON_WHITESPACE + StringUtilsTest.WHITESPACE));
}
- @Test
- public void testStripToNull_String() {
- assertNull(StringUtils.stripToNull(null));
- assertNull(StringUtils.stripToNull(""));
- assertNull(StringUtils.stripToNull(" "));
- assertNull(StringUtils.stripToNull(StringUtilsTest.WHITESPACE));
- assertEquals("ab c", StringUtils.stripToNull(" ab c "));
- assertEquals(StringUtilsTest.NON_WHITESPACE,
- StringUtils.stripToNull(StringUtilsTest.WHITESPACE + StringUtilsTest.NON_WHITESPACE + StringUtilsTest.WHITESPACE));
- }
-
- @Test
- public void testStripToEmpty_String() {
- assertEquals("", StringUtils.stripToEmpty(null));
- assertEquals("", StringUtils.stripToEmpty(""));
- assertEquals("", StringUtils.stripToEmpty(" "));
- assertEquals("", StringUtils.stripToEmpty(StringUtilsTest.WHITESPACE));
- assertEquals("ab c", StringUtils.stripToEmpty(" ab c "));
- assertEquals(StringUtilsTest.NON_WHITESPACE,
- StringUtils.stripToEmpty(StringUtilsTest.WHITESPACE + StringUtilsTest.NON_WHITESPACE + StringUtilsTest.WHITESPACE));
- }
-
@Test
public void testStrip_StringString() {
// null strip
@@ -133,35 +72,53 @@ public class StringUtilsTrimStripTest extends AbstractLangTest {
}
@Test
- public void testStripStart_StringString() {
- // null stripStart
- assertNull(StringUtils.stripStart(null, null));
- assertEquals("", StringUtils.stripStart("", null));
- assertEquals("", StringUtils.stripStart(" ", null));
- assertEquals("abc ", StringUtils.stripStart(" abc ", null));
- assertEquals(StringUtilsTest.NON_WHITESPACE + StringUtilsTest.WHITESPACE,
- StringUtils.stripStart(StringUtilsTest.WHITESPACE + StringUtilsTest.NON_WHITESPACE + StringUtilsTest.WHITESPACE, null));
+ public void testStripAccents() {
+ final String cue = "\u00C7\u00FA\u00EA";
+ assertEquals("Cue", StringUtils.stripAccents(cue), "Failed to strip accents from " + cue);
- // "" stripStart
- assertNull(StringUtils.stripStart(null, ""));
- assertEquals("", StringUtils.stripStart("", ""));
- assertEquals(" ", StringUtils.stripStart(" ", ""));
- assertEquals(" abc ", StringUtils.stripStart(" abc ", ""));
- assertEquals(StringUtilsTest.WHITESPACE, StringUtils.stripStart(StringUtilsTest.WHITESPACE, ""));
+ final String lots = "\u00C0\u00C1\u00C2\u00C3\u00C4\u00C5\u00C7\u00C8\u00C9" +
+ "\u00CA\u00CB\u00CC\u00CD\u00CE\u00CF\u00D1\u00D2\u00D3" +
+ "\u00D4\u00D5\u00D6\u00D9\u00DA\u00DB\u00DC\u00DD";
+ assertEquals("AAAAAACEEEEIIIINOOOOOUUUUY",
+ StringUtils.stripAccents(lots),
+ "Failed to strip accents from " + lots);
- // " " stripStart
- assertNull(StringUtils.stripStart(null, " "));
- assertEquals("", StringUtils.stripStart("", " "));
- assertEquals("", StringUtils.stripStart(" ", " "));
- assertEquals("abc ", StringUtils.stripStart(" abc ", " "));
+ assertNull(StringUtils.stripAccents(null), "Failed null safety");
+ assertEquals("", StringUtils.stripAccents(""), "Failed empty String");
+ assertEquals("control", StringUtils.stripAccents("control"), "Failed to handle non-accented text");
+ assertEquals("eclair", StringUtils.stripAccents("\u00E9clair"), "Failed to handle easy example");
+ assertEquals("ALOSZZCN aloszzcn", StringUtils.stripAccents("\u0104\u0141\u00D3\u015A\u017B\u0179\u0106\u0143 "
+ + "\u0105\u0142\u00F3\u015B\u017C\u017A\u0107\u0144"));
+ }
- // "ab" stripStart
- assertNull(StringUtils.stripStart(null, "ab"));
- assertEquals("", StringUtils.stripStart("", "ab"));
- assertEquals(" ", StringUtils.stripStart(" ", "ab"));
- assertEquals(" abc ", StringUtils.stripStart(" abc ", "ab"));
- assertEquals("cabab", StringUtils.stripStart("abcabab", "ab"));
- assertEquals(StringUtilsTest.WHITESPACE, StringUtils.stripStart(StringUtilsTest.WHITESPACE, ""));
+ @Test
+ @Disabled
+ public void testStripAccents_Korean() {
+ // LANG-1655
+ final String input = "잊지마 넌 흐린 어둠사이 왼손으로 그린 별 하나";
+ assertEquals(input, StringUtils.stripAccents(input), "Failed to handle non-accented text");
+
+ }
+
+ @Test
+ public void testStripAll() {
+ // test stripAll method, merely an array version of the above strip
+ final String[] empty = {};
+ final String[] fooSpace = { " "+FOO+" ", " "+FOO, FOO+" " };
+ final String[] fooDots = { ".."+FOO+"..", ".."+FOO, FOO+".." };
+ final String[] foo = { FOO, FOO, FOO };
+
+ assertNull(StringUtils.stripAll((String[]) null));
+ // Additional varargs tests
+ assertArrayEquals(empty, StringUtils.stripAll()); // empty array
+ assertArrayEquals(new String[]{null}, StringUtils.stripAll((String) null)); // == new String[]{null}
+
+ assertArrayEquals(empty, StringUtils.stripAll(empty));
+ assertArrayEquals(foo, StringUtils.stripAll(fooSpace));
+
+ assertNull(StringUtils.stripAll(null, null));
+ assertArrayEquals(foo, StringUtils.stripAll(fooSpace, null));
+ assertArrayEquals(foo, StringUtils.stripAll(fooDots, "."));
}
@Test
@@ -197,52 +154,95 @@ public class StringUtilsTrimStripTest extends AbstractLangTest {
}
@Test
- public void testStripAll() {
- // test stripAll method, merely an array version of the above strip
- final String[] empty = {};
- final String[] fooSpace = { " "+FOO+" ", " "+FOO, FOO+" " };
- final String[] fooDots = { ".."+FOO+"..", ".."+FOO, FOO+".." };
- final String[] foo = { FOO, FOO, FOO };
+ public void testStripStart_StringString() {
+ // null stripStart
+ assertNull(StringUtils.stripStart(null, null));
+ assertEquals("", StringUtils.stripStart("", null));
+ assertEquals("", StringUtils.stripStart(" ", null));
+ assertEquals("abc ", StringUtils.stripStart(" abc ", null));
+ assertEquals(StringUtilsTest.NON_WHITESPACE + StringUtilsTest.WHITESPACE,
+ StringUtils.stripStart(StringUtilsTest.WHITESPACE + StringUtilsTest.NON_WHITESPACE + StringUtilsTest.WHITESPACE, null));
- assertNull(StringUtils.stripAll((String[]) null));
- // Additional varargs tests
- assertArrayEquals(empty, StringUtils.stripAll()); // empty array
- assertArrayEquals(new String[]{null}, StringUtils.stripAll((String) null)); // == new String[]{null}
+ // "" stripStart
+ assertNull(StringUtils.stripStart(null, ""));
+ assertEquals("", StringUtils.stripStart("", ""));
+ assertEquals(" ", StringUtils.stripStart(" ", ""));
+ assertEquals(" abc ", StringUtils.stripStart(" abc ", ""));
+ assertEquals(StringUtilsTest.WHITESPACE, StringUtils.stripStart(StringUtilsTest.WHITESPACE, ""));
- assertArrayEquals(empty, StringUtils.stripAll(empty));
- assertArrayEquals(foo, StringUtils.stripAll(fooSpace));
+ // " " stripStart
+ assertNull(StringUtils.stripStart(null, " "));
+ assertEquals("", StringUtils.stripStart("", " "));
+ assertEquals("", StringUtils.stripStart(" ", " "));
+ assertEquals("abc ", StringUtils.stripStart(" abc ", " "));
- assertNull(StringUtils.stripAll(null, null));
- assertArrayEquals(foo, StringUtils.stripAll(fooSpace, null));
- assertArrayEquals(foo, StringUtils.stripAll(fooDots, "."));
+ // "ab" stripStart
+ assertNull(StringUtils.stripStart(null, "ab"));
+ assertEquals("", StringUtils.stripStart("", "ab"));
+ assertEquals(" ", StringUtils.stripStart(" ", "ab"));
+ assertEquals(" abc ", StringUtils.stripStart(" abc ", "ab"));
+ assertEquals("cabab", StringUtils.stripStart("abcabab", "ab"));
+ assertEquals(StringUtilsTest.WHITESPACE, StringUtils.stripStart(StringUtilsTest.WHITESPACE, ""));
}
@Test
- public void testStripAccents() {
- final String cue = "\u00C7\u00FA\u00EA";
- assertEquals("Cue", StringUtils.stripAccents(cue), "Failed to strip accents from " + cue);
+ public void testStripToEmpty_String() {
+ assertEquals("", StringUtils.stripToEmpty(null));
+ assertEquals("", StringUtils.stripToEmpty(""));
+ assertEquals("", StringUtils.stripToEmpty(" "));
+ assertEquals("", StringUtils.stripToEmpty(StringUtilsTest.WHITESPACE));
+ assertEquals("ab c", StringUtils.stripToEmpty(" ab c "));
+ assertEquals(StringUtilsTest.NON_WHITESPACE,
+ StringUtils.stripToEmpty(StringUtilsTest.WHITESPACE + StringUtilsTest.NON_WHITESPACE + StringUtilsTest.WHITESPACE));
+ }
- final String lots = "\u00C0\u00C1\u00C2\u00C3\u00C4\u00C5\u00C7\u00C8\u00C9" +
- "\u00CA\u00CB\u00CC\u00CD\u00CE\u00CF\u00D1\u00D2\u00D3" +
- "\u00D4\u00D5\u00D6\u00D9\u00DA\u00DB\u00DC\u00DD";
- assertEquals("AAAAAACEEEEIIIINOOOOOUUUUY",
- StringUtils.stripAccents(lots),
- "Failed to strip accents from " + lots);
+ @Test
+ public void testStripToNull_String() {
+ assertNull(StringUtils.stripToNull(null));
+ assertNull(StringUtils.stripToNull(""));
+ assertNull(StringUtils.stripToNull(" "));
+ assertNull(StringUtils.stripToNull(StringUtilsTest.WHITESPACE));
+ assertEquals("ab c", StringUtils.stripToNull(" ab c "));
+ assertEquals(StringUtilsTest.NON_WHITESPACE,
+ StringUtils.stripToNull(StringUtilsTest.WHITESPACE + StringUtilsTest.NON_WHITESPACE + StringUtilsTest.WHITESPACE));
+ }
- assertNull(StringUtils.stripAccents(null), "Failed null safety");
- assertEquals("", StringUtils.stripAccents(""), "Failed empty String");
- assertEquals("control", StringUtils.stripAccents("control"), "Failed to handle non-accented text");
- assertEquals("eclair", StringUtils.stripAccents("\u00E9clair"), "Failed to handle easy example");
- assertEquals("ALOSZZCN aloszzcn", StringUtils.stripAccents("\u0104\u0141\u00D3\u015A\u017B\u0179\u0106\u0143 "
- + "\u0105\u0142\u00F3\u015B\u017C\u017A\u0107\u0144"));
+ @Test
+ public void testTrim() {
+ assertEquals(FOO, StringUtils.trim(FOO + " "));
+ assertEquals(FOO, StringUtils.trim(" " + FOO + " "));
+ assertEquals(FOO, StringUtils.trim(" " + FOO));
+ assertEquals(FOO, StringUtils.trim(FOO + ""));
+ assertEquals("", StringUtils.trim(" \t\r\n\b "));
+ assertEquals("", StringUtils.trim(StringUtilsTest.TRIMMABLE));
+ assertEquals(StringUtilsTest.NON_TRIMMABLE, StringUtils.trim(StringUtilsTest.NON_TRIMMABLE));
+ assertEquals("", StringUtils.trim(""));
+ assertNull(StringUtils.trim(null));
}
@Test
- @Disabled
- public void testStripAccents_Korean() {
- // LANG-1655
- final String input = "잊지마 넌 흐린 어둠사이 왼손으로 그린 별 하나";
- assertEquals(input, StringUtils.stripAccents(input), "Failed to handle non-accented text");
+ public void testTrimToEmpty() {
+ assertEquals(FOO, StringUtils.trimToEmpty(FOO + " "));
+ assertEquals(FOO, StringUtils.trimToEmpty(" " + FOO + " "));
+ assertEquals(FOO, StringUtils.trimToEmpty(" " + FOO));
+ assertEquals(FOO, StringUtils.trimToEmpty(FOO + ""));
+ assertEquals("", StringUtils.trimToEmpty(" \t\r\n\b "));
+ assertEquals("", StringUtils.trimToEmpty(StringUtilsTest.TRIMMABLE));
+ assertEquals(StringUtilsTest.NON_TRIMMABLE, StringUtils.trimToEmpty(StringUtilsTest.NON_TRIMMABLE));
+ assertEquals("", StringUtils.trimToEmpty(""));
+ assertEquals("", StringUtils.trimToEmpty(null));
+ }
+ @Test
+ public void testTrimToNull() {
+ assertEquals(FOO, StringUtils.trimToNull(FOO + " "));
+ assertEquals(FOO, StringUtils.trimToNull(" " + FOO + " "));
+ assertEquals(FOO, StringUtils.trimToNull(" " + FOO));
+ assertEquals(FOO, StringUtils.trimToNull(FOO + ""));
+ assertNull(StringUtils.trimToNull(" \t\r\n\b "));
+ assertNull(StringUtils.trimToNull(StringUtilsTest.TRIMMABLE));
+ assertEquals(StringUtilsTest.NON_TRIMMABLE, StringUtils.trimToNull(StringUtilsTest.NON_TRIMMABLE));
+ assertNull(StringUtils.trimToNull(""));
+ assertNull(StringUtils.trimToNull(null));
}
}
diff --git a/src/test/java/org/apache/commons/lang3/SystemPropertiesTest.java b/src/test/java/org/apache/commons/lang3/SystemPropertiesTest.java
index 4a24724d0..a1b0d8e58 100644
--- a/src/test/java/org/apache/commons/lang3/SystemPropertiesTest.java
+++ b/src/test/java/org/apache/commons/lang3/SystemPropertiesTest.java
@@ -36,6 +36,22 @@ public class SystemPropertiesTest {
assertDoesNotThrow(SystemProperties::getAwtToolkit);
}
+ @Test
+ public void testGetBoolean() {
+ final String key = RandomStringUtils.random(10);
+ final String absentKey = RandomStringUtils.random(10);
+ assertNull(System.getProperty(absentKey));
+ try {
+ System.setProperty(key, Boolean.toString(Boolean.TRUE));
+ assertEquals(Boolean.TRUE, SystemProperties.getBoolean(key, () -> false));
+ assertEquals(Boolean.TRUE, SystemProperties.getBoolean(absentKey, () -> Boolean.TRUE));
+ assertEquals(false, SystemProperties.getBoolean(absentKey, () -> false));
+ assertEquals(false, SystemProperties.getBoolean(absentKey, null));
+ } finally {
+ System.clearProperty(key);
+ }
+ }
+
@Test
public void testGetFileEncoding() {
assertNotNull(SystemProperties.getFileEncoding());
@@ -46,6 +62,22 @@ public class SystemPropertiesTest {
assertNotNull(SystemProperties.getFileSeparator());
}
+ @Test
+ public void testGetInt() {
+ final String key = RandomStringUtils.random(10);
+ final String absentKey = RandomStringUtils.random(10);
+ assertNull(System.getProperty(absentKey));
+ try {
+ System.setProperty(key, Integer.toString(Integer.MAX_VALUE));
+ assertEquals(Integer.MAX_VALUE, SystemProperties.getInt(key, () -> 0));
+ assertEquals(Integer.MAX_VALUE, SystemProperties.getInt(absentKey, () -> Integer.MAX_VALUE));
+ assertEquals(0, SystemProperties.getInt(absentKey, () -> 0));
+ assertEquals(0, SystemProperties.getInt(absentKey, null));
+ } finally {
+ System.clearProperty(key);
+ }
+ }
+
@Test
public void testGetJavaAwtFonts() {
assertNull(SystemProperties.getJavaAwtFonts());
@@ -211,48 +243,6 @@ public class SystemPropertiesTest {
assertNotNull(SystemProperties.getLineSeparator());
}
- @Test
- public void testGetOsArch() {
- assertNotNull(SystemProperties.getOsArch());
- }
-
- @Test
- public void testGetOsName() {
- assertNotNull(SystemProperties.getOsName());
- }
-
- @Test
- public void testGetBoolean() {
- final String key = RandomStringUtils.random(10);
- final String absentKey = RandomStringUtils.random(10);
- assertNull(System.getProperty(absentKey));
- try {
- System.setProperty(key, Boolean.toString(Boolean.TRUE));
- assertEquals(Boolean.TRUE, SystemProperties.getBoolean(key, () -> false));
- assertEquals(Boolean.TRUE, SystemProperties.getBoolean(absentKey, () -> Boolean.TRUE));
- assertEquals(false, SystemProperties.getBoolean(absentKey, () -> false));
- assertEquals(false, SystemProperties.getBoolean(absentKey, null));
- } finally {
- System.clearProperty(key);
- }
- }
-
- @Test
- public void testGetInt() {
- final String key = RandomStringUtils.random(10);
- final String absentKey = RandomStringUtils.random(10);
- assertNull(System.getProperty(absentKey));
- try {
- System.setProperty(key, Integer.toString(Integer.MAX_VALUE));
- assertEquals(Integer.MAX_VALUE, SystemProperties.getInt(key, () -> 0));
- assertEquals(Integer.MAX_VALUE, SystemProperties.getInt(absentKey, () -> Integer.MAX_VALUE));
- assertEquals(0, SystemProperties.getInt(absentKey, () -> 0));
- assertEquals(0, SystemProperties.getInt(absentKey, null));
- } finally {
- System.clearProperty(key);
- }
- }
-
@Test
public void testGetLong() {
final String key = RandomStringUtils.random(10);
@@ -269,6 +259,16 @@ public class SystemPropertiesTest {
}
}
+ @Test
+ public void testGetOsArch() {
+ assertNotNull(SystemProperties.getOsArch());
+ }
+
+ @Test
+ public void testGetOsName() {
+ assertNotNull(SystemProperties.getOsName());
+ }
+
@Test
public void testGetOsVersion() {
diff --git a/src/test/java/org/apache/commons/lang3/SystemUtilsTest.java b/src/test/java/org/apache/commons/lang3/SystemUtilsTest.java
index 69fd9b9ba..61140d063 100644
--- a/src/test/java/org/apache/commons/lang3/SystemUtilsTest.java
+++ b/src/test/java/org/apache/commons/lang3/SystemUtilsTest.java
@@ -53,6 +53,28 @@ import org.junit.jupiter.api.Test;
*/
public class SystemUtilsTest extends AbstractLangTest {
+ /**
+ * Returns the value of the SystemUtils.IS_JAVA_X field for the versions >= 9.
+ */
+ private boolean getIS_JAVA(int version) throws Exception {
+ return SystemUtils.class.getField("IS_JAVA_" + version).getBoolean(null);
+ }
+
+ /**
+ * Returns the last supported version with the SystemUtils.IS_JAVA_X fields.
+ */
+ public int getLastSupportedJavaVersion() {
+ int lastSupportedVersion = 0;
+
+ for (Field field : SystemUtils.class.getFields()) {
+ if (field.getName().matches("IS_JAVA_\\d+")) {
+ lastSupportedVersion = Math.max(lastSupportedVersion, Integer.parseInt(field.getName().substring(8)));
+ }
+ }
+
+ return lastSupportedVersion;
+ }
+
@Test
@SuppressWarnings("deprecation")
public void test_IS_JAVA() throws Exception {
@@ -109,28 +131,6 @@ public class SystemUtilsTest extends AbstractLangTest {
}
}
- /**
- * Returns the value of the SystemUtils.IS_JAVA_X field for the versions >= 9.
- */
- private boolean getIS_JAVA(int version) throws Exception {
- return SystemUtils.class.getField("IS_JAVA_" + version).getBoolean(null);
- }
-
- /**
- * Returns the last supported version with the SystemUtils.IS_JAVA_X fields.
- */
- public int getLastSupportedJavaVersion() {
- int lastSupportedVersion = 0;
... 28234 lines suppressed ...
(commons-lang) 02/03: Sort main members
Posted by gg...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
ggregory pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/commons-lang.git
commit dc83c2820b96095f63d233475037ca7a9da2839f
Author: Gary Gregory <ga...@gmail.com>
AuthorDate: Fri Nov 3 11:25:53 2023 -0400
Sort main members
---
.../org/apache/commons/lang3/AnnotationUtils.java | 262 +-
.../java/org/apache/commons/lang3/ArchUtils.java | 76 +-
.../java/org/apache/commons/lang3/BitField.java | 212 +-
.../java/org/apache/commons/lang3/CharRange.java | 350 +-
.../java/org/apache/commons/lang3/CharSet.java | 30 +-
.../java/org/apache/commons/lang3/CharUtils.java | 378 +-
.../java/org/apache/commons/lang3/ClassUtils.java | 20 +-
.../java/org/apache/commons/lang3/Conversion.java | 1602 ++++-----
.../java/org/apache/commons/lang3/JavaVersion.java | 138 +-
.../java/org/apache/commons/lang3/LocaleUtils.java | 8 +-
.../commons/lang3/NotImplementedException.java | 24 +-
.../java/org/apache/commons/lang3/ObjectUtils.java | 42 +-
.../commons/lang3/SerializationException.java | 14 +-
.../java/org/apache/commons/lang3/Streams.java | 332 +-
.../apache/commons/lang3/StringEscapeUtils.java | 468 +--
.../java/org/apache/commons/lang3/Validate.java | 1494 ++++----
.../org/apache/commons/lang3/builder/Diff.java | 32 +-
.../apache/commons/lang3/builder/DiffBuilder.java | 260 +-
.../apache/commons/lang3/builder/DiffResult.java | 56 +-
.../commons/lang3/builder/EqualsBuilder.java | 1070 +++---
.../org/apache/commons/lang3/builder/IDKey.java | 18 +-
.../builder/MultilineRecursiveToStringStyle.java | 108 +-
.../lang3/builder/RecursiveToStringStyle.java | 36 +-
.../lang3/builder/ReflectionDiffBuilder.java | 86 +-
.../lang3/builder/StandardToStringStyle.java | 390 +-
.../commons/lang3/builder/ToStringBuilder.java | 68 +-
.../commons/lang3/builder/ToStringStyle.java | 3358 +++++++++---------
.../lang3/concurrent/AbstractCircuitBreaker.java | 154 +-
.../concurrent/AbstractConcurrentInitializer.java | 16 +-
.../lang3/concurrent/AtomicInitializer.java | 22 +-
.../lang3/concurrent/AtomicSafeInitializer.java | 28 +-
.../lang3/concurrent/BackgroundInitializer.java | 304 +-
.../lang3/concurrent/BasicThreadFactory.java | 334 +-
.../concurrent/CallableBackgroundInitializer.java | 26 +-
.../commons/lang3/concurrent/CircuitBreaker.java | 50 +-
.../lang3/concurrent/CircuitBreakingException.java | 14 +-
.../lang3/concurrent/ConcurrentException.java | 14 +-
.../concurrent/ConcurrentRuntimeException.java | 14 +-
.../commons/lang3/concurrent/ConcurrentUtils.java | 304 +-
.../lang3/concurrent/ConstantInitializer.java | 58 +-
.../lang3/concurrent/EventCountCircuitBreaker.java | 560 +--
.../commons/lang3/concurrent/FutureTasks.java | 8 +-
.../commons/lang3/concurrent/LazyInitializer.java | 16 +-
.../concurrent/MultiBackgroundInitializer.java | 338 +-
.../lang3/concurrent/ThresholdCircuitBreaker.java | 18 +-
.../commons/lang3/concurrent/TimedSemaphore.java | 232 +-
.../commons/lang3/event/EventListenerSupport.java | 228 +-
.../org/apache/commons/lang3/event/EventUtils.java | 98 +-
.../lang3/exception/CloneFailedException.java | 10 +-
.../lang3/exception/ContextedException.java | 74 +-
.../lang3/exception/ContextedRuntimeException.java | 74 +-
.../apache/commons/lang3/function/Consumers.java | 8 +-
.../apache/commons/lang3/function/Suppliers.java | 22 +-
.../apache/commons/lang3/function/TriFunction.java | 20 +-
.../org/apache/commons/lang3/math/Fraction.java | 808 ++---
.../apache/commons/lang3/math/IEEE754rUtils.java | 208 +-
.../org/apache/commons/lang3/math/NumberUtils.java | 2302 ++++++------
.../commons/lang3/mutable/MutableBoolean.java | 122 +-
.../apache/commons/lang3/mutable/MutableByte.java | 276 +-
.../commons/lang3/mutable/MutableDouble.java | 348 +-
.../apache/commons/lang3/mutable/MutableFloat.java | 350 +-
.../apache/commons/lang3/mutable/MutableInt.java | 274 +-
.../apache/commons/lang3/mutable/MutableLong.java | 276 +-
.../commons/lang3/mutable/MutableObject.java | 40 +-
.../apache/commons/lang3/mutable/MutableShort.java | 292 +-
.../commons/lang3/reflect/ConstructorUtils.java | 204 +-
.../apache/commons/lang3/reflect/FieldUtils.java | 608 ++--
.../commons/lang3/reflect/InheritanceUtils.java | 22 +-
.../apache/commons/lang3/reflect/MemberUtils.java | 278 +-
.../apache/commons/lang3/reflect/MethodUtils.java | 1490 ++++----
.../apache/commons/lang3/reflect/TypeLiteral.java | 10 +-
.../apache/commons/lang3/text/CompositeFormat.java | 28 +-
.../commons/lang3/text/ExtendedMessageFormat.java | 360 +-
.../commons/lang3/text/FormattableUtils.java | 80 +-
.../org/apache/commons/lang3/text/StrBuilder.java | 3738 ++++++++++----------
.../org/apache/commons/lang3/text/StrLookup.java | 132 +-
.../org/apache/commons/lang3/text/StrMatcher.java | 488 +--
.../apache/commons/lang3/text/StrSubstitutor.java | 994 +++---
.../apache/commons/lang3/text/StrTokenizer.java | 846 ++---
.../org/apache/commons/lang3/text/WordUtils.java | 1022 +++---
.../text/translate/CharSequenceTranslator.java | 42 +-
.../commons/lang3/text/translate/EntityArrays.java | 146 +-
.../lang3/text/translate/NumericEntityEscaper.java | 68 +-
.../lang3/text/translate/OctalUnescaper.java | 36 +-
.../lang3/text/translate/UnicodeEscaper.java | 94 +-
.../commons/lang3/time/AbstractFormatCache.java | 234 +-
.../apache/commons/lang3/time/DateFormatUtils.java | 18 +-
.../org/apache/commons/lang3/time/DateParser.java | 54 +-
.../org/apache/commons/lang3/time/DatePrinter.java | 124 +-
.../org/apache/commons/lang3/time/DateUtils.java | 2312 ++++++------
.../commons/lang3/time/DurationFormatUtils.java | 712 ++--
.../apache/commons/lang3/time/DurationUtils.java | 12 +-
.../apache/commons/lang3/time/FastDateFormat.java | 528 +--
.../apache/commons/lang3/time/FastDateParser.java | 1592 ++++-----
.../apache/commons/lang3/time/FastDatePrinter.java | 2370 ++++++-------
.../org/apache/commons/lang3/time/TimeZones.java | 8 +-
96 files changed, 18961 insertions(+), 18961 deletions(-)
diff --git a/src/main/java/org/apache/commons/lang3/AnnotationUtils.java b/src/main/java/org/apache/commons/lang3/AnnotationUtils.java
index 9d0571488..fcb579b1a 100644
--- a/src/main/java/org/apache/commons/lang3/AnnotationUtils.java
+++ b/src/main/java/org/apache/commons/lang3/AnnotationUtils.java
@@ -64,6 +64,17 @@ public class AnnotationUtils {
setArrayEnd("]");
}
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ protected void appendDetail(final StringBuffer buffer, final String fieldName, Object value) {
+ if (value instanceof Annotation) {
+ value = AnnotationUtils.toString((Annotation) value);
+ }
+ super.appendDetail(buffer, fieldName, value);
+ }
+
/**
* {@inheritDoc}
*/
@@ -76,27 +87,99 @@ public class AnnotationUtils {
// formatter:on
}
- /**
- * {@inheritDoc}
- */
- @Override
- protected void appendDetail(final StringBuffer buffer, final String fieldName, Object value) {
- if (value instanceof Annotation) {
- value = AnnotationUtils.toString((Annotation) value);
+ };
+
+ /**
+ * Helper method for comparing two arrays of annotations.
+ *
+ * @param a1 the first array
+ * @param a2 the second array
+ * @return a flag whether these arrays are equal
+ */
+ private static boolean annotationArrayMemberEquals(final Annotation[] a1, final Annotation[] a2) {
+ if (a1.length != a2.length) {
+ return false;
+ }
+ for (int i = 0; i < a1.length; i++) {
+ if (!equals(a1[i], a2[i])) {
+ return false;
}
- super.appendDetail(buffer, fieldName, value);
}
+ return true;
+ }
- };
+ /**
+ * Helper method for comparing two objects of an array type.
+ *
+ * @param componentType the component type of the array
+ * @param o1 the first object
+ * @param o2 the second object
+ * @return a flag whether these objects are equal
+ */
+ private static boolean arrayMemberEquals(final Class<?> componentType, final Object o1, final Object o2) {
+ if (componentType.isAnnotation()) {
+ return annotationArrayMemberEquals((Annotation[]) o1, (Annotation[]) o2);
+ }
+ if (componentType.equals(Byte.TYPE)) {
+ return Arrays.equals((byte[]) o1, (byte[]) o2);
+ }
+ if (componentType.equals(Short.TYPE)) {
+ return Arrays.equals((short[]) o1, (short[]) o2);
+ }
+ if (componentType.equals(Integer.TYPE)) {
+ return Arrays.equals((int[]) o1, (int[]) o2);
+ }
+ if (componentType.equals(Character.TYPE)) {
+ return Arrays.equals((char[]) o1, (char[]) o2);
+ }
+ if (componentType.equals(Long.TYPE)) {
+ return Arrays.equals((long[]) o1, (long[]) o2);
+ }
+ if (componentType.equals(Float.TYPE)) {
+ return Arrays.equals((float[]) o1, (float[]) o2);
+ }
+ if (componentType.equals(Double.TYPE)) {
+ return Arrays.equals((double[]) o1, (double[]) o2);
+ }
+ if (componentType.equals(Boolean.TYPE)) {
+ return Arrays.equals((boolean[]) o1, (boolean[]) o2);
+ }
+ return Arrays.equals((Object[]) o1, (Object[]) o2);
+ }
/**
- * {@link AnnotationUtils} instances should NOT be constructed in
- * standard programming. Instead, the class should be used statically.
+ * Helper method for generating a hash code for an array.
*
- * <p>This constructor is public to permit tools that require a JavaBean
- * instance to operate.</p>
+ * @param componentType the component type of the array
+ * @param o the array
+ * @return a hash code for the specified array
*/
- public AnnotationUtils() {
+ private static int arrayMemberHash(final Class<?> componentType, final Object o) {
+ if (componentType.equals(Byte.TYPE)) {
+ return Arrays.hashCode((byte[]) o);
+ }
+ if (componentType.equals(Short.TYPE)) {
+ return Arrays.hashCode((short[]) o);
+ }
+ if (componentType.equals(Integer.TYPE)) {
+ return Arrays.hashCode((int[]) o);
+ }
+ if (componentType.equals(Character.TYPE)) {
+ return Arrays.hashCode((char[]) o);
+ }
+ if (componentType.equals(Long.TYPE)) {
+ return Arrays.hashCode((long[]) o);
+ }
+ if (componentType.equals(Float.TYPE)) {
+ return Arrays.hashCode((float[]) o);
+ }
+ if (componentType.equals(Double.TYPE)) {
+ return Arrays.hashCode((double[]) o);
+ }
+ if (componentType.equals(Boolean.TYPE)) {
+ return Arrays.hashCode((boolean[]) o);
+ }
+ return Arrays.hashCode((Object[]) o);
}
/**
@@ -170,27 +253,23 @@ public class AnnotationUtils {
return result;
}
+ //besides modularity, this has the advantage of autoboxing primitives:
/**
- * Generate a string representation of an Annotation, as suggested by
- * {@link Annotation#toString()}.
+ * Helper method for generating a hash code for a member of an annotation.
*
- * @param a the annotation of which a string representation is desired
- * @return the standard string representation of an annotation, not
- * {@code null}
+ * @param name the name of the member
+ * @param value the value of the member
+ * @return a hash code for this member
*/
- public static String toString(final Annotation a) {
- final ToStringBuilder builder = new ToStringBuilder(a, TO_STRING_STYLE);
- for (final Method m : a.annotationType().getDeclaredMethods()) {
- if (m.getParameterTypes().length > 0) {
- continue; // wtf?
- }
- try {
- builder.append(m.getName(), m.invoke(a));
- } catch (final ReflectiveOperationException ex) {
- throw new UncheckedException(ex);
- }
+ private static int hashMember(final String name, final Object value) {
+ final int part1 = name.hashCode() * 127;
+ if (ObjectUtils.isArray(value)) {
+ return part1 ^ arrayMemberHash(value.getClass().getComponentType(), value);
}
- return builder.build();
+ if (value instanceof Annotation) {
+ return part1 ^ hashCode((Annotation) value);
+ }
+ return part1 ^ value.hashCode();
}
/**
@@ -215,25 +294,6 @@ public class AnnotationUtils {
|| String.class.equals(type) || Class.class.equals(type);
}
- //besides modularity, this has the advantage of autoboxing primitives:
- /**
- * Helper method for generating a hash code for a member of an annotation.
- *
- * @param name the name of the member
- * @param value the value of the member
- * @return a hash code for this member
- */
- private static int hashMember(final String name, final Object value) {
- final int part1 = name.hashCode() * 127;
- if (ObjectUtils.isArray(value)) {
- return part1 ^ arrayMemberHash(value.getClass().getComponentType(), value);
- }
- if (value instanceof Annotation) {
- return part1 ^ hashCode((Annotation) value);
- }
- return part1 ^ value.hashCode();
- }
-
/**
* Helper method for checking whether two objects of the given type are
* equal. This method is used to compare the parameters of two annotation
@@ -261,95 +321,35 @@ public class AnnotationUtils {
}
/**
- * Helper method for comparing two objects of an array type.
- *
- * @param componentType the component type of the array
- * @param o1 the first object
- * @param o2 the second object
- * @return a flag whether these objects are equal
- */
- private static boolean arrayMemberEquals(final Class<?> componentType, final Object o1, final Object o2) {
- if (componentType.isAnnotation()) {
- return annotationArrayMemberEquals((Annotation[]) o1, (Annotation[]) o2);
- }
- if (componentType.equals(Byte.TYPE)) {
- return Arrays.equals((byte[]) o1, (byte[]) o2);
- }
- if (componentType.equals(Short.TYPE)) {
- return Arrays.equals((short[]) o1, (short[]) o2);
- }
- if (componentType.equals(Integer.TYPE)) {
- return Arrays.equals((int[]) o1, (int[]) o2);
- }
- if (componentType.equals(Character.TYPE)) {
- return Arrays.equals((char[]) o1, (char[]) o2);
- }
- if (componentType.equals(Long.TYPE)) {
- return Arrays.equals((long[]) o1, (long[]) o2);
- }
- if (componentType.equals(Float.TYPE)) {
- return Arrays.equals((float[]) o1, (float[]) o2);
- }
- if (componentType.equals(Double.TYPE)) {
- return Arrays.equals((double[]) o1, (double[]) o2);
- }
- if (componentType.equals(Boolean.TYPE)) {
- return Arrays.equals((boolean[]) o1, (boolean[]) o2);
- }
- return Arrays.equals((Object[]) o1, (Object[]) o2);
- }
-
- /**
- * Helper method for comparing two arrays of annotations.
+ * Generate a string representation of an Annotation, as suggested by
+ * {@link Annotation#toString()}.
*
- * @param a1 the first array
- * @param a2 the second array
- * @return a flag whether these arrays are equal
+ * @param a the annotation of which a string representation is desired
+ * @return the standard string representation of an annotation, not
+ * {@code null}
*/
- private static boolean annotationArrayMemberEquals(final Annotation[] a1, final Annotation[] a2) {
- if (a1.length != a2.length) {
- return false;
- }
- for (int i = 0; i < a1.length; i++) {
- if (!equals(a1[i], a2[i])) {
- return false;
+ public static String toString(final Annotation a) {
+ final ToStringBuilder builder = new ToStringBuilder(a, TO_STRING_STYLE);
+ for (final Method m : a.annotationType().getDeclaredMethods()) {
+ if (m.getParameterTypes().length > 0) {
+ continue; // wtf?
+ }
+ try {
+ builder.append(m.getName(), m.invoke(a));
+ } catch (final ReflectiveOperationException ex) {
+ throw new UncheckedException(ex);
}
}
- return true;
+ return builder.build();
}
/**
- * Helper method for generating a hash code for an array.
+ * {@link AnnotationUtils} instances should NOT be constructed in
+ * standard programming. Instead, the class should be used statically.
*
- * @param componentType the component type of the array
- * @param o the array
- * @return a hash code for the specified array
+ * <p>This constructor is public to permit tools that require a JavaBean
+ * instance to operate.</p>
*/
- private static int arrayMemberHash(final Class<?> componentType, final Object o) {
- if (componentType.equals(Byte.TYPE)) {
- return Arrays.hashCode((byte[]) o);
- }
- if (componentType.equals(Short.TYPE)) {
- return Arrays.hashCode((short[]) o);
- }
- if (componentType.equals(Integer.TYPE)) {
- return Arrays.hashCode((int[]) o);
- }
- if (componentType.equals(Character.TYPE)) {
- return Arrays.hashCode((char[]) o);
- }
- if (componentType.equals(Long.TYPE)) {
- return Arrays.hashCode((long[]) o);
- }
- if (componentType.equals(Float.TYPE)) {
- return Arrays.hashCode((float[]) o);
- }
- if (componentType.equals(Double.TYPE)) {
- return Arrays.hashCode((double[]) o);
- }
- if (componentType.equals(Boolean.TYPE)) {
- return Arrays.hashCode((boolean[]) o);
- }
- return Arrays.hashCode((Object[]) o);
+ public AnnotationUtils() {
}
}
diff --git a/src/main/java/org/apache/commons/lang3/ArchUtils.java b/src/main/java/org/apache/commons/lang3/ArchUtils.java
index efc5b0a18..4bc325c5e 100644
--- a/src/main/java/org/apache/commons/lang3/ArchUtils.java
+++ b/src/main/java/org/apache/commons/lang3/ArchUtils.java
@@ -39,44 +39,6 @@ public class ArchUtils {
init();
}
- private static void init() {
- init_X86_32Bit();
- init_X86_64Bit();
- init_IA64_32Bit();
- init_IA64_64Bit();
- init_PPC_32Bit();
- init_PPC_64Bit();
- init_Aarch_64Bit();
- }
-
- private static void init_Aarch_64Bit() {
- addProcessors(new Processor(Processor.Arch.BIT_64, Processor.Type.AARCH_64), "aarch64");
- }
-
- private static void init_X86_32Bit() {
- addProcessors(new Processor(Processor.Arch.BIT_32, Processor.Type.X86), "x86", "i386", "i486", "i586", "i686", "pentium");
- }
-
- private static void init_X86_64Bit() {
- addProcessors(new Processor(Processor.Arch.BIT_64, Processor.Type.X86), "x86_64", "amd64", "em64t", "universal");
- }
-
- private static void init_IA64_32Bit() {
- addProcessors(new Processor(Processor.Arch.BIT_32, Processor.Type.IA_64), "ia64_32", "ia64n");
- }
-
- private static void init_IA64_64Bit() {
- addProcessors(new Processor(Processor.Arch.BIT_64, Processor.Type.IA_64), "ia64", "ia64w");
- }
-
- private static void init_PPC_32Bit() {
- addProcessors(new Processor(Processor.Arch.BIT_32, Processor.Type.PPC), "ppc", "power", "powerpc", "power_pc", "power_rs");
- }
-
- private static void init_PPC_64Bit() {
- addProcessors(new Processor(Processor.Arch.BIT_64, Processor.Type.PPC), "ppc64", "power64", "powerpc64", "power_pc64", "power_rs64");
- }
-
/**
* Adds the given {@link Processor} with the given key {@link String} to the map.
*
@@ -126,4 +88,42 @@ public class ArchUtils {
return ARCH_TO_PROCESSOR.get(value);
}
+ private static void init() {
+ init_X86_32Bit();
+ init_X86_64Bit();
+ init_IA64_32Bit();
+ init_IA64_64Bit();
+ init_PPC_32Bit();
+ init_PPC_64Bit();
+ init_Aarch_64Bit();
+ }
+
+ private static void init_Aarch_64Bit() {
+ addProcessors(new Processor(Processor.Arch.BIT_64, Processor.Type.AARCH_64), "aarch64");
+ }
+
+ private static void init_IA64_32Bit() {
+ addProcessors(new Processor(Processor.Arch.BIT_32, Processor.Type.IA_64), "ia64_32", "ia64n");
+ }
+
+ private static void init_IA64_64Bit() {
+ addProcessors(new Processor(Processor.Arch.BIT_64, Processor.Type.IA_64), "ia64", "ia64w");
+ }
+
+ private static void init_PPC_32Bit() {
+ addProcessors(new Processor(Processor.Arch.BIT_32, Processor.Type.PPC), "ppc", "power", "powerpc", "power_pc", "power_rs");
+ }
+
+ private static void init_PPC_64Bit() {
+ addProcessors(new Processor(Processor.Arch.BIT_64, Processor.Type.PPC), "ppc64", "power64", "powerpc64", "power_pc64", "power_rs64");
+ }
+
+ private static void init_X86_32Bit() {
+ addProcessors(new Processor(Processor.Arch.BIT_32, Processor.Type.X86), "x86", "i386", "i486", "i586", "i686", "pentium");
+ }
+
+ private static void init_X86_64Bit() {
+ addProcessors(new Processor(Processor.Arch.BIT_64, Processor.Type.X86), "x86_64", "amd64", "em64t", "universal");
+ }
+
}
diff --git a/src/main/java/org/apache/commons/lang3/BitField.java b/src/main/java/org/apache/commons/lang3/BitField.java
index a2d0ccbe3..03f6339a3 100644
--- a/src/main/java/org/apache/commons/lang3/BitField.java
+++ b/src/main/java/org/apache/commons/lang3/BitField.java
@@ -88,39 +88,40 @@ public class BitField {
}
/**
- * Obtains the value for the specified BitField, appropriately
- * shifted right.
- *
- * <p>Many users of a BitField will want to treat the specified
- * bits as an int value, and will not want to be aware that the
- * value is stored as a BitField (and so shifted left so many
- * bits).</p>
+ * Clears the bits.
*
- * @see #setValue(int,int)
- * @param holder the int data containing the bits we're interested
- * in
- * @return the selected bits, shifted right appropriately
+ * @param holder the int data containing the bits we're
+ * interested in
+ * @return the value of holder with the specified bits cleared
+ * (set to {@code 0})
*/
- public int getValue(final int holder) {
- return getRawValue(holder) >> shiftCount;
+ public int clear(final int holder) {
+ return holder & ~mask;
}
/**
- * Obtains the value for the specified BitField, appropriately
- * shifted right, as a short.
+ * Clears the bits.
*
- * <p>Many users of a BitField will want to treat the specified
- * bits as an int value, and will not want to be aware that the
- * value is stored as a BitField (and so shifted left so many
- * bits).</p>
+ * @param holder the byte data containing the bits we're
+ * interested in
+ *
+ * @return the value of holder with the specified bits cleared
+ * (set to {@code 0})
+ */
+ public byte clearByte(final byte holder) {
+ return (byte) clear(holder);
+ }
+
+ /**
+ * Clears the bits.
*
- * @see #setShortValue(short,short)
* @param holder the short data containing the bits we're
* interested in
- * @return the selected bits, shifted right appropriately
+ * @return the value of holder with the specified bits cleared
+ * (set to {@code 0})
*/
- public short getShortValue(final short holder) {
- return (short) getValue(holder);
+ public short clearShort(final short holder) {
+ return (short) clear(holder);
}
/**
@@ -146,20 +147,39 @@ public class BitField {
}
/**
- * Returns whether the field is set or not.
+ * Obtains the value for the specified BitField, appropriately
+ * shifted right, as a short.
*
- * <p>This is most commonly used for a single-bit field, which is
- * often used to represent a boolean value; the results of using
- * it for a multi-bit field is to determine whether *any* of its
- * bits are set.</p>
+ * <p>Many users of a BitField will want to treat the specified
+ * bits as an int value, and will not want to be aware that the
+ * value is stored as a BitField (and so shifted left so many
+ * bits).</p>
*
+ * @see #setShortValue(short,short)
+ * @param holder the short data containing the bits we're
+ * interested in
+ * @return the selected bits, shifted right appropriately
+ */
+ public short getShortValue(final short holder) {
+ return (short) getValue(holder);
+ }
+
+ /**
+ * Obtains the value for the specified BitField, appropriately
+ * shifted right.
+ *
+ * <p>Many users of a BitField will want to treat the specified
+ * bits as an int value, and will not want to be aware that the
+ * value is stored as a BitField (and so shifted left so many
+ * bits).</p>
+ *
+ * @see #setValue(int,int)
* @param holder the int data containing the bits we're interested
* in
- * @return {@code true} if any of the bits are set,
- * else {@code false}
+ * @return the selected bits, shifted right appropriately
*/
- public boolean isSet(final int holder) {
- return (holder & mask) != 0;
+ public int getValue(final int holder) {
+ return getRawValue(holder) >> shiftCount;
}
/**
@@ -179,80 +199,71 @@ public class BitField {
}
/**
- * Replaces the bits with new values.
+ * Returns whether the field is set or not.
*
- * @see #getValue(int)
- * @param holder the int data containing the bits we're
- * interested in
- * @param value the new value for the specified bits
- * @return the value of holder with the bits from the value
- * parameter replacing the old bits
- */
- public int setValue(final int holder, final int value) {
- return (holder & ~mask) | ((value << shiftCount) & mask);
- }
-
- /**
- * Replaces the bits with new values.
+ * <p>This is most commonly used for a single-bit field, which is
+ * often used to represent a boolean value; the results of using
+ * it for a multi-bit field is to determine whether *any* of its
+ * bits are set.</p>
*
- * @see #getShortValue(short)
- * @param holder the short data containing the bits we're
- * interested in
- * @param value the new value for the specified bits
- * @return the value of holder with the bits from the value
- * parameter replacing the old bits
+ * @param holder the int data containing the bits we're interested
+ * in
+ * @return {@code true} if any of the bits are set,
+ * else {@code false}
*/
- public short setShortValue(final short holder, final short value) {
- return (short) setValue(holder, value);
+ public boolean isSet(final int holder) {
+ return (holder & mask) != 0;
}
/**
- * Clears the bits.
+ * Sets the bits.
*
* @param holder the int data containing the bits we're
* interested in
- * @return the value of holder with the specified bits cleared
- * (set to {@code 0})
+ * @return the value of holder with the specified bits set
+ * to {@code 1}
*/
- public int clear(final int holder) {
- return holder & ~mask;
+ public int set(final int holder) {
+ return holder | mask;
}
/**
- * Clears the bits.
+ * Sets a boolean BitField.
*
- * @param holder the short data containing the bits we're
+ * @param holder the int data containing the bits we're
* interested in
- * @return the value of holder with the specified bits cleared
- * (set to {@code 0})
+ * @param flag indicating whether to set or clear the bits
+ * @return the value of holder with the specified bits set or
+ * cleared
*/
- public short clearShort(final short holder) {
- return (short) clear(holder);
+ public int setBoolean(final int holder, final boolean flag) {
+ return flag ? set(holder) : clear(holder);
}
/**
- * Clears the bits.
+ * Sets the bits.
*
* @param holder the byte data containing the bits we're
* interested in
*
- * @return the value of holder with the specified bits cleared
- * (set to {@code 0})
+ * @return the value of holder with the specified bits set
+ * to {@code 1}
*/
- public byte clearByte(final byte holder) {
- return (byte) clear(holder);
+ public byte setByte(final byte holder) {
+ return (byte) set(holder);
}
/**
- * Sets the bits.
+ * Sets a boolean BitField.
*
- * @param holder the int data containing the bits we're
+ * @param holder the byte data containing the bits we're
* interested in
- * @return the value of holder with the specified bits set
- * to {@code 1}
+ * @param flag indicating whether to set or clear the bits
+ * @return the value of holder with the specified bits set or
+ * cleared
*/
- public int set(final int holder) {
- return holder | mask;
+ public byte setByteBoolean(final byte holder, final boolean flag) {
+ return flag ? setByte(holder) : clearByte(holder);
}
/**
@@ -267,56 +278,45 @@ public class BitField {
return (short) set(holder);
}
- /**
- * Sets the bits.
- *
- * @param holder the byte data containing the bits we're
- * interested in
- *
- * @return the value of holder with the specified bits set
- * to {@code 1}
- */
- public byte setByte(final byte holder) {
- return (byte) set(holder);
- }
-
/**
* Sets a boolean BitField.
*
- * @param holder the int data containing the bits we're
+ * @param holder the short data containing the bits we're
* interested in
* @param flag indicating whether to set or clear the bits
* @return the value of holder with the specified bits set or
- * cleared
+ * cleared
*/
- public int setBoolean(final int holder, final boolean flag) {
- return flag ? set(holder) : clear(holder);
+ public short setShortBoolean(final short holder, final boolean flag) {
+ return flag ? setShort(holder) : clearShort(holder);
}
/**
- * Sets a boolean BitField.
+ * Replaces the bits with new values.
*
+ * @see #getShortValue(short)
* @param holder the short data containing the bits we're
* interested in
- * @param flag indicating whether to set or clear the bits
- * @return the value of holder with the specified bits set or
- * cleared
+ * @param value the new value for the specified bits
+ * @return the value of holder with the bits from the value
+ * parameter replacing the old bits
*/
- public short setShortBoolean(final short holder, final boolean flag) {
- return flag ? setShort(holder) : clearShort(holder);
+ public short setShortValue(final short holder, final short value) {
+ return (short) setValue(holder, value);
}
/**
- * Sets a boolean BitField.
+ * Replaces the bits with new values.
*
- * @param holder the byte data containing the bits we're
+ * @see #getValue(int)
+ * @param holder the int data containing the bits we're
* interested in
- * @param flag indicating whether to set or clear the bits
- * @return the value of holder with the specified bits set or
- * cleared
+ * @param value the new value for the specified bits
+ * @return the value of holder with the bits from the value
+ * parameter replacing the old bits
*/
- public byte setByteBoolean(final byte holder, final boolean flag) {
- return flag ? setByte(holder) : clearByte(holder);
+ public int setValue(final int holder, final int value) {
+ return (holder & ~mask) | ((value << shiftCount) & mask);
}
}
diff --git a/src/main/java/org/apache/commons/lang3/CharRange.java b/src/main/java/org/apache/commons/lang3/CharRange.java
index cf90e0950..ae593c219 100644
--- a/src/main/java/org/apache/commons/lang3/CharRange.java
+++ b/src/main/java/org/apache/commons/lang3/CharRange.java
@@ -34,52 +34,110 @@ import java.util.Objects;
final class CharRange implements Iterable<Character>, Serializable {
/**
- * Required for serialization support. Lang version 2.0.
- *
- * @see java.io.Serializable
+ * Character {@link Iterator}.
+ * <p>#NotThreadSafe#</p>
*/
- private static final long serialVersionUID = 8270183163158333422L;
+ private static final class CharacterIterator implements Iterator<Character> {
+ /** The current character */
+ private char current;
- /** The first character, inclusive, in the range. */
- private final char start;
+ private final CharRange range;
+ private boolean hasNext;
- /** The last character, inclusive, in the range. */
- private final char end;
+ /**
+ * Constructs a new iterator for the character range.
+ *
+ * @param r The character range
+ */
+ private CharacterIterator(final CharRange r) {
+ range = r;
+ hasNext = true;
- /** True if the range is everything except the characters specified. */
- private final boolean negated;
+ if (range.negated) {
+ if (range.start == 0) {
+ if (range.end == Character.MAX_VALUE) {
+ // This range is an empty set
+ hasNext = false;
+ } else {
+ current = (char) (range.end + 1);
+ }
+ } else {
+ current = 0;
+ }
+ } else {
+ current = range.start;
+ }
+ }
- /** Cached toString. */
- private transient String iToString;
+ /**
+ * Has the iterator not reached the end character yet?
+ *
+ * @return {@code true} if the iterator has yet to reach the character date
+ */
+ @Override
+ public boolean hasNext() {
+ return hasNext;
+ }
- /** Empty array. */
- static final CharRange[] EMPTY_ARRAY = {};
+ /**
+ * Returns the next character in the iteration
+ *
+ * @return {@link Character} for the next character
+ */
+ @Override
+ public Character next() {
+ if (!hasNext) {
+ throw new NoSuchElementException();
+ }
+ final char cur = current;
+ prepareNext();
+ return Character.valueOf(cur);
+ }
+
+ /**
+ * Prepares the next character in the range.
+ */
+ private void prepareNext() {
+ if (range.negated) {
+ if (current == Character.MAX_VALUE) {
+ hasNext = false;
+ } else if (current + 1 == range.start) {
+ if (range.end == Character.MAX_VALUE) {
+ hasNext = false;
+ } else {
+ current = (char) (range.end + 1);
+ }
+ } else {
+ current = (char) (current + 1);
+ }
+ } else if (current < range.end) {
+ current = (char) (current + 1);
+ } else {
+ hasNext = false;
+ }
+ }
+
+ /**
+ * Always throws UnsupportedOperationException.
+ *
+ * @throws UnsupportedOperationException Always thrown.
+ * @see java.util.Iterator#remove()
+ */
+ @Override
+ public void remove() {
+ throw new UnsupportedOperationException();
+ }
+ }
/**
- * Constructs a {@link CharRange} over a set of characters,
- * optionally negating the range.
- *
- * <p>A negated range includes everything except that defined by the
- * start and end characters.</p>
- *
- * <p>If start and end are in the wrong order, they are reversed.
- * Thus {@code a-e} is the same as {@code e-a}.</p>
+ * Required for serialization support. Lang version 2.0.
*
- * @param start first character, inclusive, in this range
- * @param end last character, inclusive, in this range
- * @param negated true to express everything except the range
+ * @see java.io.Serializable
*/
- private CharRange(char start, char end, final boolean negated) {
- if (start > end) {
- final char temp = start;
- start = end;
- end = temp;
- }
+ private static final long serialVersionUID = 8270183163158333422L;
- this.start = start;
- this.end = end;
- this.negated = negated;
- }
+ /** Empty array. */
+ static final CharRange[] EMPTY_ARRAY = {};
/**
* Constructs a {@link CharRange} over a single character.
@@ -93,32 +151,32 @@ final class CharRange implements Iterable<Character>, Serializable {
}
/**
- * Constructs a negated {@link CharRange} over a single character.
+ * Constructs a {@link CharRange} over a set of characters.
*
- * <p>A negated range includes everything except that defined by the
- * single character.</p>
+ * <p>If start and end are in the wrong order, they are reversed.
+ * Thus {@code a-e} is the same as {@code e-a}.</p>
*
- * @param ch only character in this range
+ * @param start first character, inclusive, in this range
+ * @param end last character, inclusive, in this range
* @return the new CharRange object
* @since 2.5
*/
- public static CharRange isNot(final char ch) {
- return new CharRange(ch, ch, true);
+ public static CharRange isIn(final char start, final char end) {
+ return new CharRange(start, end, false);
}
/**
- * Constructs a {@link CharRange} over a set of characters.
+ * Constructs a negated {@link CharRange} over a single character.
*
- * <p>If start and end are in the wrong order, they are reversed.
- * Thus {@code a-e} is the same as {@code e-a}.</p>
+ * <p>A negated range includes everything except that defined by the
+ * single character.</p>
*
- * @param start first character, inclusive, in this range
- * @param end last character, inclusive, in this range
+ * @param ch only character in this range
* @return the new CharRange object
* @since 2.5
*/
- public static CharRange isIn(final char start, final char end) {
- return new CharRange(start, end, false);
+ public static CharRange isNot(final char ch) {
+ return new CharRange(ch, ch, true);
}
/**
@@ -139,35 +197,42 @@ final class CharRange implements Iterable<Character>, Serializable {
return new CharRange(start, end, true);
}
- // Accessors
- /**
- * Gets the start character for this character range.
- *
- * @return the start char (inclusive)
- */
- public char getStart() {
- return this.start;
- }
+ /** The first character, inclusive, in the range. */
+ private final char start;
- /**
- * Gets the end character for this character range.
- *
- * @return the end char (inclusive)
- */
- public char getEnd() {
- return this.end;
- }
+ /** The last character, inclusive, in the range. */
+ private final char end;
+
+ /** True if the range is everything except the characters specified. */
+ private final boolean negated;
+
+ /** Cached toString. */
+ private transient String iToString;
/**
- * Is this {@link CharRange} negated.
+ * Constructs a {@link CharRange} over a set of characters,
+ * optionally negating the range.
*
* <p>A negated range includes everything except that defined by the
* start and end characters.</p>
*
- * @return {@code true} if negated
+ * <p>If start and end are in the wrong order, they are reversed.
+ * Thus {@code a-e} is the same as {@code e-a}.</p>
+ *
+ * @param start first character, inclusive, in this range
+ * @param end last character, inclusive, in this range
+ * @param negated true to express everything except the range
*/
- public boolean isNegated() {
- return negated;
+ private CharRange(char start, char end, final boolean negated) {
+ if (start > end) {
+ final char temp = start;
+ start = end;
+ end = temp;
+ }
+
+ this.start = start;
+ this.end = end;
+ this.negated = negated;
}
// Contains
@@ -223,6 +288,25 @@ final class CharRange implements Iterable<Character>, Serializable {
return start == other.start && end == other.end && negated == other.negated;
}
+ /**
+ * Gets the end character for this character range.
+ *
+ * @return the end char (inclusive)
+ */
+ public char getEnd() {
+ return this.end;
+ }
+
+ // Accessors
+ /**
+ * Gets the start character for this character range.
+ *
+ * @return the start char (inclusive)
+ */
+ public char getStart() {
+ return this.start;
+ }
+
/**
* Gets a hashCode compatible with the equals method.
*
@@ -234,25 +318,15 @@ final class CharRange implements Iterable<Character>, Serializable {
}
/**
- * Gets a string representation of the character range.
+ * Is this {@link CharRange} negated.
*
- * @return string representation of this range
+ * <p>A negated range includes everything except that defined by the
+ * start and end characters.</p>
+ *
+ * @return {@code true} if negated
*/
- @Override
- public String toString() {
- if (iToString == null) {
- final StringBuilder buf = new StringBuilder(4);
- if (isNegated()) {
- buf.append('^');
- }
- buf.append(start);
- if (start != end) {
- buf.append('-');
- buf.append(end);
- }
- iToString = buf.toString();
- }
- return iToString;
+ public boolean isNegated() {
+ return negated;
}
/**
@@ -268,98 +342,24 @@ final class CharRange implements Iterable<Character>, Serializable {
}
/**
- * Character {@link Iterator}.
- * <p>#NotThreadSafe#</p>
+ * Gets a string representation of the character range.
+ *
+ * @return string representation of this range
*/
- private static final class CharacterIterator implements Iterator<Character> {
- /** The current character */
- private char current;
-
- private final CharRange range;
- private boolean hasNext;
-
- /**
- * Constructs a new iterator for the character range.
- *
- * @param r The character range
- */
- private CharacterIterator(final CharRange r) {
- range = r;
- hasNext = true;
-
- if (range.negated) {
- if (range.start == 0) {
- if (range.end == Character.MAX_VALUE) {
- // This range is an empty set
- hasNext = false;
- } else {
- current = (char) (range.end + 1);
- }
- } else {
- current = 0;
- }
- } else {
- current = range.start;
- }
- }
-
- /**
- * Prepares the next character in the range.
- */
- private void prepareNext() {
- if (range.negated) {
- if (current == Character.MAX_VALUE) {
- hasNext = false;
- } else if (current + 1 == range.start) {
- if (range.end == Character.MAX_VALUE) {
- hasNext = false;
- } else {
- current = (char) (range.end + 1);
- }
- } else {
- current = (char) (current + 1);
- }
- } else if (current < range.end) {
- current = (char) (current + 1);
- } else {
- hasNext = false;
+ @Override
+ public String toString() {
+ if (iToString == null) {
+ final StringBuilder buf = new StringBuilder(4);
+ if (isNegated()) {
+ buf.append('^');
}
- }
-
- /**
- * Has the iterator not reached the end character yet?
- *
- * @return {@code true} if the iterator has yet to reach the character date
- */
- @Override
- public boolean hasNext() {
- return hasNext;
- }
-
- /**
- * Returns the next character in the iteration
- *
- * @return {@link Character} for the next character
- */
- @Override
- public Character next() {
- if (!hasNext) {
- throw new NoSuchElementException();
+ buf.append(start);
+ if (start != end) {
+ buf.append('-');
+ buf.append(end);
}
- final char cur = current;
- prepareNext();
- return Character.valueOf(cur);
- }
-
- /**
- * Always throws UnsupportedOperationException.
- *
- * @throws UnsupportedOperationException Always thrown.
- * @see java.util.Iterator#remove()
- */
- @Override
- public void remove() {
- throw new UnsupportedOperationException();
+ iToString = buf.toString();
}
+ return iToString;
}
}
diff --git a/src/main/java/org/apache/commons/lang3/CharSet.java b/src/main/java/org/apache/commons/lang3/CharSet.java
index a6b7bcbb5..80aa2ef17 100644
--- a/src/main/java/org/apache/commons/lang3/CharSet.java
+++ b/src/main/java/org/apache/commons/lang3/CharSet.java
@@ -88,9 +88,6 @@ public class CharSet implements Serializable {
COMMON.put("0-9", ASCII_NUMERIC);
}
- /** The set of CharRange objects. */
- private final Set<CharRange> set = Collections.synchronizedSet(new HashSet<>());
-
/**
* Factory method to create a new CharSet using a special syntax.
*
@@ -165,6 +162,9 @@ public class CharSet implements Serializable {
return new CharSet(setStrs);
}
+ /** The set of CharRange objects. */
+ private final Set<CharRange> set = Collections.synchronizedSet(new HashSet<>());
+
/**
* Constructs a new CharSet using the set syntax.
* Each string is merged in with the set.
@@ -210,18 +210,6 @@ public class CharSet implements Serializable {
}
}
- /**
- * Gets the internal set as an array of CharRange objects.
- *
- * @return an array of immutable CharRange objects
- * @since 2.0
- */
-// NOTE: This is no longer public as CharRange is no longer a public class.
-// It may be replaced when CharSet moves to Range.
- /*public*/ CharRange[] getCharRanges() {
- return set.toArray(CharRange.EMPTY_ARRAY);
- }
-
/**
* Does the {@link CharSet} contain the specified
* character {@code ch}.
@@ -259,6 +247,18 @@ public class CharSet implements Serializable {
return set.equals(other.set);
}
+ /**
+ * Gets the internal set as an array of CharRange objects.
+ *
+ * @return an array of immutable CharRange objects
+ * @since 2.0
+ */
+// NOTE: This is no longer public as CharRange is no longer a public class.
+// It may be replaced when CharSet moves to Range.
+ /*public*/ CharRange[] getCharRanges() {
+ return set.toArray(CharRange.EMPTY_ARRAY);
+ }
+
/**
* Gets a hash code compatible with the equals method.
*
diff --git a/src/main/java/org/apache/commons/lang3/CharUtils.java b/src/main/java/org/apache/commons/lang3/CharUtils.java
index 52b864d6e..b85366453 100644
--- a/src/main/java/org/apache/commons/lang3/CharUtils.java
+++ b/src/main/java/org/apache/commons/lang3/CharUtils.java
@@ -64,54 +64,169 @@ public class CharUtils {
}
/**
- * {@link CharUtils} instances should NOT be constructed in standard programming.
- * Instead, the class should be used as {@code CharUtils.toString('c');}.
+ * Compares two {@code char} values numerically. This is the same functionality as provided in Java 7.
*
- * <p>This constructor is public to permit tools that require a JavaBean instance
- * to operate.</p>
+ * @param x the first {@code char} to compare
+ * @param y the second {@code char} to compare
+ * @return the value {@code 0} if {@code x == y};
+ * a value less than {@code 0} if {@code x < y}; and
+ * a value greater than {@code 0} if {@code x > y}
+ * @since 3.4
*/
- public CharUtils() {
+ public static int compare(final char x, final char y) {
+ return x - y;
}
/**
- * Converts the character to a Character.
+ * Checks whether the character is ASCII 7 bit.
*
- * <p>For ASCII 7 bit characters, this uses a cache that will return the
- * same Character object each time.</p>
+ * <pre>
+ * CharUtils.isAscii('a') = true
+ * CharUtils.isAscii('A') = true
+ * CharUtils.isAscii('3') = true
+ * CharUtils.isAscii('-') = true
+ * CharUtils.isAscii('\n') = true
+ * CharUtils.isAscii('©') = false
+ * </pre>
+ *
+ * @param ch the character to check
+ * @return true if less than 128
+ */
+ public static boolean isAscii(final char ch) {
+ return ch < 128;
+ }
+
+ /**
+ * Checks whether the character is ASCII 7 bit alphabetic.
*
* <pre>
- * CharUtils.toCharacterObject(' ') = ' '
- * CharUtils.toCharacterObject('A') = 'A'
+ * CharUtils.isAsciiAlpha('a') = true
+ * CharUtils.isAsciiAlpha('A') = true
+ * CharUtils.isAsciiAlpha('3') = false
+ * CharUtils.isAsciiAlpha('-') = false
+ * CharUtils.isAsciiAlpha('\n') = false
+ * CharUtils.isAsciiAlpha('©') = false
* </pre>
*
- * @deprecated Java 5 introduced {@link Character#valueOf(char)} which caches chars 0 through 127.
- * @param ch the character to convert
- * @return a Character of the specified character
+ * @param ch the character to check
+ * @return true if between 65 and 90 or 97 and 122 inclusive
*/
- @Deprecated
- public static Character toCharacterObject(final char ch) {
- return Character.valueOf(ch);
+ public static boolean isAsciiAlpha(final char ch) {
+ return isAsciiAlphaUpper(ch) || isAsciiAlphaLower(ch);
}
/**
- * Converts the String to a Character using the first character, returning
- * null for empty Strings.
+ * Checks whether the character is ASCII 7 bit alphabetic lower case.
*
- * <p>For ASCII 7 bit characters, this uses a cache that will return the
- * same Character object each time.</p>
+ * <pre>
+ * CharUtils.isAsciiAlphaLower('a') = true
+ * CharUtils.isAsciiAlphaLower('A') = false
+ * CharUtils.isAsciiAlphaLower('3') = false
+ * CharUtils.isAsciiAlphaLower('-') = false
+ * CharUtils.isAsciiAlphaLower('\n') = false
+ * CharUtils.isAsciiAlphaLower('©') = false
+ * </pre>
+ *
+ * @param ch the character to check
+ * @return true if between 97 and 122 inclusive
+ */
+ public static boolean isAsciiAlphaLower(final char ch) {
+ return ch >= 'a' && ch <= 'z';
+ }
+
+ /**
+ * Checks whether the character is ASCII 7 bit numeric.
*
* <pre>
- * CharUtils.toCharacterObject(null) = null
- * CharUtils.toCharacterObject("") = null
- * CharUtils.toCharacterObject("A") = 'A'
- * CharUtils.toCharacterObject("BA") = 'B'
+ * CharUtils.isAsciiAlphanumeric('a') = true
+ * CharUtils.isAsciiAlphanumeric('A') = true
+ * CharUtils.isAsciiAlphanumeric('3') = true
+ * CharUtils.isAsciiAlphanumeric('-') = false
+ * CharUtils.isAsciiAlphanumeric('\n') = false
+ * CharUtils.isAsciiAlphanumeric('©') = false
* </pre>
*
- * @param str the character to convert
- * @return the Character value of the first letter of the String
+ * @param ch the character to check
+ * @return true if between 48 and 57 or 65 and 90 or 97 and 122 inclusive
*/
- public static Character toCharacterObject(final String str) {
- return StringUtils.isEmpty(str) ? null : Character.valueOf(str.charAt(0));
+ public static boolean isAsciiAlphanumeric(final char ch) {
+ return isAsciiAlpha(ch) || isAsciiNumeric(ch);
+ }
+
+ /**
+ * Checks whether the character is ASCII 7 bit alphabetic upper case.
+ *
+ * <pre>
+ * CharUtils.isAsciiAlphaUpper('a') = false
+ * CharUtils.isAsciiAlphaUpper('A') = true
+ * CharUtils.isAsciiAlphaUpper('3') = false
+ * CharUtils.isAsciiAlphaUpper('-') = false
+ * CharUtils.isAsciiAlphaUpper('\n') = false
+ * CharUtils.isAsciiAlphaUpper('©') = false
+ * </pre>
+ *
+ * @param ch the character to check
+ * @return true if between 65 and 90 inclusive
+ */
+ public static boolean isAsciiAlphaUpper(final char ch) {
+ return ch >= 'A' && ch <= 'Z';
+ }
+
+ /**
+ * Checks whether the character is ASCII 7 bit control.
+ *
+ * <pre>
+ * CharUtils.isAsciiControl('a') = false
+ * CharUtils.isAsciiControl('A') = false
+ * CharUtils.isAsciiControl('3') = false
+ * CharUtils.isAsciiControl('-') = false
+ * CharUtils.isAsciiControl('\n') = true
+ * CharUtils.isAsciiControl('©') = false
+ * </pre>
+ *
+ * @param ch the character to check
+ * @return true if less than 32 or equals 127
+ */
+ public static boolean isAsciiControl(final char ch) {
+ return ch < 32 || ch == 127;
+ }
+
+ /**
+ * Checks whether the character is ASCII 7 bit numeric.
+ *
+ * <pre>
+ * CharUtils.isAsciiNumeric('a') = false
+ * CharUtils.isAsciiNumeric('A') = false
+ * CharUtils.isAsciiNumeric('3') = true
+ * CharUtils.isAsciiNumeric('-') = false
+ * CharUtils.isAsciiNumeric('\n') = false
+ * CharUtils.isAsciiNumeric('©') = false
+ * </pre>
+ *
+ * @param ch the character to check
+ * @return true if between 48 and 57 inclusive
+ */
+ public static boolean isAsciiNumeric(final char ch) {
+ return ch >= '0' && ch <= '9';
+ }
+
+ /**
+ * Checks whether the character is ASCII 7 bit printable.
+ *
+ * <pre>
+ * CharUtils.isAsciiPrintable('a') = true
+ * CharUtils.isAsciiPrintable('A') = true
+ * CharUtils.isAsciiPrintable('3') = true
+ * CharUtils.isAsciiPrintable('-') = true
+ * CharUtils.isAsciiPrintable('\n') = false
+ * CharUtils.isAsciiPrintable('©') = false
+ * </pre>
+ *
+ * @param ch the character to check
+ * @return true if between 32 and 126 inclusive
+ */
+ public static boolean isAsciiPrintable(final char ch) {
+ return ch >= 32 && ch < 127;
}
/**
@@ -188,6 +303,47 @@ public class CharUtils {
return StringUtils.isEmpty(str) ? defaultValue : str.charAt(0);
}
+ /**
+ * Converts the character to a Character.
+ *
+ * <p>For ASCII 7 bit characters, this uses a cache that will return the
+ * same Character object each time.</p>
+ *
+ * <pre>
+ * CharUtils.toCharacterObject(' ') = ' '
+ * CharUtils.toCharacterObject('A') = 'A'
+ * </pre>
+ *
+ * @deprecated Java 5 introduced {@link Character#valueOf(char)} which caches chars 0 through 127.
+ * @param ch the character to convert
+ * @return a Character of the specified character
+ */
+ @Deprecated
+ public static Character toCharacterObject(final char ch) {
+ return Character.valueOf(ch);
+ }
+
+ /**
+ * Converts the String to a Character using the first character, returning
+ * null for empty Strings.
+ *
+ * <p>For ASCII 7 bit characters, this uses a cache that will return the
+ * same Character object each time.</p>
+ *
+ * <pre>
+ * CharUtils.toCharacterObject(null) = null
+ * CharUtils.toCharacterObject("") = null
+ * CharUtils.toCharacterObject("A") = 'A'
+ * CharUtils.toCharacterObject("BA") = 'B'
+ * </pre>
+ *
+ * @param str the character to convert
+ * @return the Character value of the first letter of the String
+ */
+ public static Character toCharacterObject(final String str) {
+ return StringUtils.isEmpty(str) ? null : Character.valueOf(str.charAt(0));
+ }
+
/**
* Converts the character to the Integer it represents, throwing an
* exception if the character is not numeric.
@@ -354,168 +510,12 @@ public class CharUtils {
}
/**
- * Checks whether the character is ASCII 7 bit.
- *
- * <pre>
- * CharUtils.isAscii('a') = true
- * CharUtils.isAscii('A') = true
- * CharUtils.isAscii('3') = true
- * CharUtils.isAscii('-') = true
- * CharUtils.isAscii('\n') = true
- * CharUtils.isAscii('©') = false
- * </pre>
- *
- * @param ch the character to check
- * @return true if less than 128
- */
- public static boolean isAscii(final char ch) {
- return ch < 128;
- }
-
- /**
- * Checks whether the character is ASCII 7 bit printable.
- *
- * <pre>
- * CharUtils.isAsciiPrintable('a') = true
- * CharUtils.isAsciiPrintable('A') = true
- * CharUtils.isAsciiPrintable('3') = true
- * CharUtils.isAsciiPrintable('-') = true
- * CharUtils.isAsciiPrintable('\n') = false
- * CharUtils.isAsciiPrintable('©') = false
- * </pre>
- *
- * @param ch the character to check
- * @return true if between 32 and 126 inclusive
- */
- public static boolean isAsciiPrintable(final char ch) {
- return ch >= 32 && ch < 127;
- }
-
- /**
- * Checks whether the character is ASCII 7 bit control.
- *
- * <pre>
- * CharUtils.isAsciiControl('a') = false
- * CharUtils.isAsciiControl('A') = false
- * CharUtils.isAsciiControl('3') = false
- * CharUtils.isAsciiControl('-') = false
- * CharUtils.isAsciiControl('\n') = true
- * CharUtils.isAsciiControl('©') = false
- * </pre>
- *
- * @param ch the character to check
- * @return true if less than 32 or equals 127
- */
- public static boolean isAsciiControl(final char ch) {
- return ch < 32 || ch == 127;
- }
-
- /**
- * Checks whether the character is ASCII 7 bit alphabetic.
- *
- * <pre>
- * CharUtils.isAsciiAlpha('a') = true
- * CharUtils.isAsciiAlpha('A') = true
- * CharUtils.isAsciiAlpha('3') = false
- * CharUtils.isAsciiAlpha('-') = false
- * CharUtils.isAsciiAlpha('\n') = false
- * CharUtils.isAsciiAlpha('©') = false
- * </pre>
- *
- * @param ch the character to check
- * @return true if between 65 and 90 or 97 and 122 inclusive
- */
- public static boolean isAsciiAlpha(final char ch) {
- return isAsciiAlphaUpper(ch) || isAsciiAlphaLower(ch);
- }
-
- /**
- * Checks whether the character is ASCII 7 bit alphabetic upper case.
- *
- * <pre>
- * CharUtils.isAsciiAlphaUpper('a') = false
- * CharUtils.isAsciiAlphaUpper('A') = true
- * CharUtils.isAsciiAlphaUpper('3') = false
- * CharUtils.isAsciiAlphaUpper('-') = false
- * CharUtils.isAsciiAlphaUpper('\n') = false
- * CharUtils.isAsciiAlphaUpper('©') = false
- * </pre>
- *
- * @param ch the character to check
- * @return true if between 65 and 90 inclusive
- */
- public static boolean isAsciiAlphaUpper(final char ch) {
- return ch >= 'A' && ch <= 'Z';
- }
-
- /**
- * Checks whether the character is ASCII 7 bit alphabetic lower case.
- *
- * <pre>
- * CharUtils.isAsciiAlphaLower('a') = true
- * CharUtils.isAsciiAlphaLower('A') = false
- * CharUtils.isAsciiAlphaLower('3') = false
- * CharUtils.isAsciiAlphaLower('-') = false
- * CharUtils.isAsciiAlphaLower('\n') = false
- * CharUtils.isAsciiAlphaLower('©') = false
- * </pre>
- *
- * @param ch the character to check
- * @return true if between 97 and 122 inclusive
- */
- public static boolean isAsciiAlphaLower(final char ch) {
- return ch >= 'a' && ch <= 'z';
- }
-
- /**
- * Checks whether the character is ASCII 7 bit numeric.
- *
- * <pre>
- * CharUtils.isAsciiNumeric('a') = false
- * CharUtils.isAsciiNumeric('A') = false
- * CharUtils.isAsciiNumeric('3') = true
- * CharUtils.isAsciiNumeric('-') = false
- * CharUtils.isAsciiNumeric('\n') = false
- * CharUtils.isAsciiNumeric('©') = false
- * </pre>
- *
- * @param ch the character to check
- * @return true if between 48 and 57 inclusive
- */
- public static boolean isAsciiNumeric(final char ch) {
- return ch >= '0' && ch <= '9';
- }
-
- /**
- * Checks whether the character is ASCII 7 bit numeric.
- *
- * <pre>
- * CharUtils.isAsciiAlphanumeric('a') = true
- * CharUtils.isAsciiAlphanumeric('A') = true
- * CharUtils.isAsciiAlphanumeric('3') = true
- * CharUtils.isAsciiAlphanumeric('-') = false
- * CharUtils.isAsciiAlphanumeric('\n') = false
- * CharUtils.isAsciiAlphanumeric('©') = false
- * </pre>
- *
- * @param ch the character to check
- * @return true if between 48 and 57 or 65 and 90 or 97 and 122 inclusive
- */
- public static boolean isAsciiAlphanumeric(final char ch) {
- return isAsciiAlpha(ch) || isAsciiNumeric(ch);
- }
-
- /**
- * Compares two {@code char} values numerically. This is the same functionality as provided in Java 7.
+ * {@link CharUtils} instances should NOT be constructed in standard programming.
+ * Instead, the class should be used as {@code CharUtils.toString('c');}.
*
- * @param x the first {@code char} to compare
- * @param y the second {@code char} to compare
- * @return the value {@code 0} if {@code x == y};
- * a value less than {@code 0} if {@code x < y}; and
- * a value greater than {@code 0} if {@code x > y}
- * @since 3.4
+ * <p>This constructor is public to permit tools that require a JavaBean instance
+ * to operate.</p>
*/
- public static int compare(final char x, final char y) {
- return x - y;
+ public CharUtils() {
}
}
diff --git a/src/main/java/org/apache/commons/lang3/ClassUtils.java b/src/main/java/org/apache/commons/lang3/ClassUtils.java
index 1d8396864..6ef65d7f0 100644
--- a/src/main/java/org/apache/commons/lang3/ClassUtils.java
+++ b/src/main/java/org/apache/commons/lang3/ClassUtils.java
@@ -1408,15 +1408,6 @@ public class ClassUtils {
return cls != null && cls.getEnclosingClass() != null;
}
- /**
- * Tests whether a {@link Class} is public.
- * @param cls Class to test.
- * @return {@code true} if {@code cls} is public.
- * @since 3.13.0
- */
- public static boolean isPublic(final Class<?> cls) {
- return Modifier.isPublic(cls.getModifiers());
- }
/**
* Returns whether the given {@code type} is a primitive or primitive wrapper ({@link Boolean}, {@link Byte},
* {@link Character}, {@link Short}, {@link Integer}, {@link Long}, {@link Double}, {@link Float}).
@@ -1432,7 +1423,6 @@ public class ClassUtils {
}
return type.isPrimitive() || isPrimitiveWrapper(type);
}
-
/**
* Returns whether the given {@code type} is a primitive wrapper ({@link Boolean}, {@link Byte}, {@link Character},
* {@link Short}, {@link Integer}, {@link Long}, {@link Double}, {@link Float}).
@@ -1446,6 +1436,16 @@ public class ClassUtils {
return wrapperPrimitiveMap.containsKey(type);
}
+ /**
+ * Tests whether a {@link Class} is public.
+ * @param cls Class to test.
+ * @return {@code true} if {@code cls} is public.
+ * @since 3.13.0
+ */
+ public static boolean isPublic(final Class<?> cls) {
+ return Modifier.isPublic(cls.getModifiers());
+ }
+
/**
* Converts the specified array of primitive Class objects to an array of its corresponding wrapper Class objects.
*
diff --git a/src/main/java/org/apache/commons/lang3/Conversion.java b/src/main/java/org/apache/commons/lang3/Conversion.java
index 89fb4966e..51a644fca 100644
--- a/src/main/java/org/apache/commons/lang3/Conversion.java
+++ b/src/main/java/org/apache/commons/lang3/Conversion.java
@@ -80,192 +80,105 @@ public class Conversion {
private static final boolean[] FFFF = {false, false, false, false};
/**
- * Converts a hexadecimal digit into an int using the default (Lsb0) bit ordering.
+ * Converts the first 4 bits of a binary (represented as boolean array) in big endian Msb0
+ * bit ordering to a hexadecimal digit.
*
* <p>
- * '1' is converted to 1
+ * (1, 0, 0, 0) is converted as follow: '8' (1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0) is converted
+ * to '4'
* </p>
*
- * @param hexDigit the hexadecimal digit to convert
- * @return an int equals to {@code hexDigit}
- * @throws IllegalArgumentException if {@code hexDigit} is not a hexadecimal digit
+ * @param src the binary to convert
+ * @return a hexadecimal digit representing the selected bits
+ * @throws IllegalArgumentException if {@code src} is empty
+ * @throws NullPointerException if {@code src} is {@code null}
*/
- public static int hexDigitToInt(final char hexDigit) {
- final int digit = Character.digit(hexDigit, 16);
- if (digit < 0) {
- throw new IllegalArgumentException("Cannot interpret '" + hexDigit + "' as a hexadecimal digit");
- }
- return digit;
+ public static char binaryBeMsb0ToHexDigit(final boolean[] src) {
+ return binaryBeMsb0ToHexDigit(src, 0);
}
/**
- * Converts a hexadecimal digit into an int using the Msb0 bit ordering.
+ * Converts a binary (represented as boolean array) in big endian Msb0 bit ordering to a
+ * hexadecimal digit.
*
* <p>
- * '1' is converted to 8
+ * (1, 0, 0, 0) with srcPos = 0 is converted as follow: '8' (1, 0, 0, 0, 0, 0, 0, 0,
+ * 0, 0, 0, 1, 0, 1, 0, 0) with srcPos = 2 is converted to '5'
* </p>
*
- * @param hexDigit the hexadecimal digit to convert
- * @return an int equals to {@code hexDigit}
- * @throws IllegalArgumentException if {@code hexDigit} is not a hexadecimal digit
+ * @param src the binary to convert
+ * @param srcPos the position of the lsb to start the conversion
+ * @return a hexadecimal digit representing the selected bits
+ * @throws IllegalArgumentException if {@code src} is empty
+ * @throws NullPointerException if {@code src} is {@code null}
+ * @throws IndexOutOfBoundsException if {@code srcPos} is outside the array.
*/
- public static int hexDigitMsb0ToInt(final char hexDigit) {
- switch (hexDigit) {
- case '0':
- return 0x0;
- case '1':
- return 0x8;
- case '2':
- return 0x4;
- case '3':
- return 0xC;
- case '4':
- return 0x2;
- case '5':
- return 0xA;
- case '6':
- return 0x6;
- case '7':
- return 0xE;
- case '8':
- return 0x1;
- case '9':
- return 0x9;
- case 'a':// fall through
- case 'A':
- return 0x5;
- case 'b':// fall through
- case 'B':
- return 0xD;
- case 'c':// fall through
- case 'C':
- return 0x3;
- case 'd':// fall through
- case 'D':
- return 0xB;
- case 'e':// fall through
- case 'E':
- return 0x7;
- case 'f':// fall through
- case 'F':
- return 0xF;
- default:
- throw new IllegalArgumentException("Cannot interpret '" + hexDigit + "' as a hexadecimal digit");
+ public static char binaryBeMsb0ToHexDigit(final boolean[] src, final int srcPos) {
+ // JDK 9: Objects.checkIndex(int index, int length)
+ if (Integer.compareUnsigned(srcPos, src.length) >= 0) {
+ // Throw the correct exception
+ if (src.length == 0) {
+ throw new IllegalArgumentException("Cannot convert an empty array.");
+ }
+ throw new IndexOutOfBoundsException(srcPos + " is not within array length " + src.length);
}
- }
-
- /**
- * Converts a hexadecimal digit into binary (represented as boolean array) using the default
- * (Lsb0) bit ordering.
- *
- * <p>
- * '1' is converted as follow: (1, 0, 0, 0)
- * </p>
- *
- * @param hexDigit the hexadecimal digit to convert
- * @return a boolean array with the binary representation of {@code hexDigit}
- * @throws IllegalArgumentException if {@code hexDigit} is not a hexadecimal digit
- */
- public static boolean[] hexDigitToBinary(final char hexDigit) {
- switch (hexDigit) {
- case '0':
- return FFFF.clone();
- case '1':
- return TFFF.clone();
- case '2':
- return FTFF.clone();
- case '3':
- return TTFF.clone();
- case '4':
- return FFTF.clone();
- case '5':
- return TFTF.clone();
- case '6':
- return FTTF.clone();
- case '7':
- return TTTF.clone();
- case '8':
- return FFFT.clone();
- case '9':
- return TFFT.clone();
- case 'a':// fall through
- case 'A':
- return FTFT.clone();
- case 'b':// fall through
- case 'B':
- return TTFT.clone();
- case 'c':// fall through
- case 'C':
- return FFTT.clone();
- case 'd':// fall through
- case 'D':
- return TFTT.clone();
- case 'e':// fall through
- case 'E':
- return FTTT.clone();
- case 'f':// fall through
- case 'F':
- return TTTT.clone();
- default:
- throw new IllegalArgumentException("Cannot interpret '" + hexDigit + "' as a hexadecimal digit");
+ // Little-endian bit 0 position
+ final int pos = src.length - 1 - srcPos;
+ if (3 <= pos && src[pos - 3]) {
+ if (src[pos - 2]) {
+ if (src[pos - 1]) {
+ return src[pos] ? 'f' : 'e';
+ }
+ return src[pos] ? 'd' : 'c';
+ }
+ if (src[pos - 1]) {
+ return src[pos] ? 'b' : 'a';
+ }
+ return src[pos] ? '9' : '8';
+ }
+ if (2 <= pos && src[pos - 2]) {
+ if (src[pos - 1]) {
+ return src[pos] ? '7' : '6';
+ }
+ return src[pos] ? '5' : '4';
+ }
+ if (1 <= pos && src[pos - 1]) {
+ return src[pos] ? '3' : '2';
}
+ return src[pos] ? '1' : '0';
}
/**
- * Converts a hexadecimal digit into binary (represented as boolean array) using the Msb0
- * bit ordering.
- *
- * <p>
- * '1' is converted as follow: (0, 0, 0, 1)
- * </p>
+ * Converts binary (represented as boolean array) into a byte using the default (little
+ * endian, Lsb0) byte and bit ordering.
*
- * @param hexDigit the hexadecimal digit to convert
- * @return a boolean array with the binary representation of {@code hexDigit}
- * @throws IllegalArgumentException if {@code hexDigit} is not a hexadecimal digit
+ * @param src the binary to convert
+ * @param srcPos the position in {@code src}, in boolean unit, from where to start the
+ * conversion
+ * @param dstInit initial value of the destination byte
+ * @param dstPos the position of the lsb, in bits, in the result byte
+ * @param nBools the number of booleans to convert
+ * @return a byte containing the selected bits
+ * @throws NullPointerException if {@code src} is {@code null}
+ * @throws IllegalArgumentException if {@code nBools-1+dstPos >= 8}
+ * @throws ArrayIndexOutOfBoundsException if {@code srcPos + nBools > src.length}
*/
- public static boolean[] hexDigitMsb0ToBinary(final char hexDigit) {
- switch (hexDigit) {
- case '0':
- return FFFF.clone();
- case '1':
- return FFFT.clone();
- case '2':
- return FFTF.clone();
- case '3':
- return FFTT.clone();
- case '4':
- return FTFF.clone();
- case '5':
- return FTFT.clone();
- case '6':
- return FTTF.clone();
- case '7':
- return FTTT.clone();
- case '8':
- return TFFF.clone();
- case '9':
- return TFFT.clone();
- case 'a':// fall through
- case 'A':
- return TFTF.clone();
- case 'b':// fall through
- case 'B':
- return TFTT.clone();
- case 'c':// fall through
- case 'C':
- return TTFF.clone();
- case 'd':// fall through
- case 'D':
- return TTFT.clone();
- case 'e':// fall through
- case 'E':
- return TTTF.clone();
- case 'f':// fall through
- case 'F':
- return TTTT.clone();
- default:
- throw new IllegalArgumentException("Cannot interpret '" + hexDigit + "' as a hexadecimal digit");
+ public static byte binaryToByte(final boolean[] src, final int srcPos, final byte dstInit, final int dstPos,
+ final int nBools) {
+ if (src.length == 0 && srcPos == 0 || 0 == nBools) {
+ return dstInit;
+ }
+ if (nBools - 1 + dstPos >= 8) {
+ throw new IllegalArgumentException("nBools-1+dstPos is greater or equal to than 8");
+ }
+ byte out = dstInit;
+ for (int i = 0; i < nBools; i++) {
+ final int shift = i + dstPos;
+ final int bits = (src[i + srcPos] ? 1 : 0) << shift;
+ final int mask = 0x1 << shift;
+ out = (byte) ((out & ~mask) | bits);
}
+ return out;
}
/**
@@ -393,249 +306,132 @@ public class Conversion {
}
/**
- * Converts the first 4 bits of a binary (represented as boolean array) in big endian Msb0
- * bit ordering to a hexadecimal digit.
- *
- * <p>
- * (1, 0, 0, 0) is converted as follow: '8' (1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0) is converted
- * to '4'
- * </p>
+ * Converts binary (represented as boolean array) into an int using the default (little
+ * endian, Lsb0) byte and bit ordering.
*
* @param src the binary to convert
- * @return a hexadecimal digit representing the selected bits
- * @throws IllegalArgumentException if {@code src} is empty
- * @throws NullPointerException if {@code src} is {@code null}
- */
- public static char binaryBeMsb0ToHexDigit(final boolean[] src) {
- return binaryBeMsb0ToHexDigit(src, 0);
- }
-
- /**
- * Converts a binary (represented as boolean array) in big endian Msb0 bit ordering to a
- * hexadecimal digit.
- *
- * <p>
- * (1, 0, 0, 0) with srcPos = 0 is converted as follow: '8' (1, 0, 0, 0, 0, 0, 0, 0,
- * 0, 0, 0, 1, 0, 1, 0, 0) with srcPos = 2 is converted to '5'
- * </p>
- *
- * @param src the binary to convert
- * @param srcPos the position of the lsb to start the conversion
- * @return a hexadecimal digit representing the selected bits
- * @throws IllegalArgumentException if {@code src} is empty
+ * @param srcPos the position in {@code src}, in boolean unit, from where to start the
+ * conversion
+ * @param dstInit initial value of the destination int
+ * @param dstPos the position of the lsb, in bits, in the result int
+ * @param nBools the number of booleans to convert
+ * @return an int containing the selected bits
* @throws NullPointerException if {@code src} is {@code null}
- * @throws IndexOutOfBoundsException if {@code srcPos} is outside the array.
+ * @throws IllegalArgumentException if {@code nBools-1+dstPos >= 32}
+ * @throws ArrayIndexOutOfBoundsException if {@code srcPos + nBools > src.length}
*/
- public static char binaryBeMsb0ToHexDigit(final boolean[] src, final int srcPos) {
- // JDK 9: Objects.checkIndex(int index, int length)
- if (Integer.compareUnsigned(srcPos, src.length) >= 0) {
- // Throw the correct exception
- if (src.length == 0) {
- throw new IllegalArgumentException("Cannot convert an empty array.");
- }
- throw new IndexOutOfBoundsException(srcPos + " is not within array length " + src.length);
- }
- // Little-endian bit 0 position
- final int pos = src.length - 1 - srcPos;
- if (3 <= pos && src[pos - 3]) {
- if (src[pos - 2]) {
- if (src[pos - 1]) {
- return src[pos] ? 'f' : 'e';
- }
- return src[pos] ? 'd' : 'c';
- }
- if (src[pos - 1]) {
- return src[pos] ? 'b' : 'a';
- }
- return src[pos] ? '9' : '8';
- }
- if (2 <= pos && src[pos - 2]) {
- if (src[pos - 1]) {
- return src[pos] ? '7' : '6';
- }
- return src[pos] ? '5' : '4';
- }
- if (1 <= pos && src[pos - 1]) {
- return src[pos] ? '3' : '2';
+ public static int binaryToInt(final boolean[] src, final int srcPos, final int dstInit, final int dstPos,
+ final int nBools) {
+ if (src.length == 0 && srcPos == 0 || 0 == nBools) {
+ return dstInit;
}
- return src[pos] ? '1' : '0';
- }
-
- /**
- * Converts the 4 lsb of an int to a hexadecimal digit.
- *
- * <p>
- * 0 returns '0'
- * </p>
- * <p>
- * 1 returns '1'
- * </p>
- * <p>
- * 10 returns 'A' and so on...
- * </p>
- *
- * @param nibble the 4 bits to convert
- * @return a hexadecimal digit representing the 4 lsb of {@code nibble}
- * @throws IllegalArgumentException if {@code nibble < 0} or {@code nibble > 15}
- */
- public static char intToHexDigit(final int nibble) {
- final char c = Character.forDigit(nibble, 16);
- if (c == Character.MIN_VALUE) {
- throw new IllegalArgumentException("nibble value not between 0 and 15: " + nibble);
+ if (nBools - 1 + dstPos >= 32) {
+ throw new IllegalArgumentException("nBools-1+dstPos is greater or equal to than 32");
}
- return c;
- }
-
- /**
- * Converts the 4 lsb of an int to a hexadecimal digit encoded using the Msb0 bit ordering.
- *
- * <p>
- * 0 returns '0'
- * </p>
- * <p>
- * 1 returns '8'
- * </p>
- * <p>
- * 10 returns '5' and so on...
- * </p>
- *
- * @param nibble the 4 bits to convert
- * @return a hexadecimal digit representing the 4 lsb of {@code nibble}
- * @throws IllegalArgumentException if {@code nibble < 0} or {@code nibble > 15}
- */
- public static char intToHexDigitMsb0(final int nibble) {
- switch (nibble) {
- case 0x0:
- return '0';
- case 0x1:
- return '8';
- case 0x2:
- return '4';
- case 0x3:
- return 'c';
- case 0x4:
- return '2';
- case 0x5:
- return 'a';
- case 0x6:
- return '6';
- case 0x7:
- return 'e';
- case 0x8:
- return '1';
- case 0x9:
- return '9';
- case 0xA:
- return '5';
- case 0xB:
- return 'd';
- case 0xC:
- return '3';
- case 0xD:
- return 'b';
- case 0xE:
- return '7';
- case 0xF:
- return 'f';
- default:
- throw new IllegalArgumentException("nibble value not between 0 and 15: " + nibble);
+ int out = dstInit;
+ for (int i = 0; i < nBools; i++) {
+ final int shift = i + dstPos;
+ final int bits = (src[i + srcPos] ? 1 : 0) << shift;
+ final int mask = 0x1 << shift;
+ out = (out & ~mask) | bits;
}
+ return out;
}
/**
- * Converts an array of int into a long using the default (little endian, Lsb0) byte and bit
- * ordering.
+ * Converts binary (represented as boolean array) into a long using the default (little
+ * endian, Lsb0) byte and bit ordering.
*
- * @param src the int array to convert
- * @param srcPos the position in {@code src}, in int unit, from where to start the
+ * @param src the binary to convert
+ * @param srcPos the position in {@code src}, in boolean unit, from where to start the
* conversion
* @param dstInit initial value of the destination long
* @param dstPos the position of the lsb, in bits, in the result long
- * @param nInts the number of ints to convert
+ * @param nBools the number of booleans to convert
* @return a long containing the selected bits
- * @throws IllegalArgumentException if {@code (nInts-1)*32+dstPos >= 64}
* @throws NullPointerException if {@code src} is {@code null}
- * @throws ArrayIndexOutOfBoundsException if {@code srcPos + nInts > src.length}
+ * @throws IllegalArgumentException if {@code nBools-1+dstPos >= 64}
+ * @throws ArrayIndexOutOfBoundsException if {@code srcPos + nBools > src.length}
*/
- public static long intArrayToLong(final int[] src, final int srcPos, final long dstInit, final int dstPos,
- final int nInts) {
- if (src.length == 0 && srcPos == 0 || 0 == nInts) {
+ public static long binaryToLong(final boolean[] src, final int srcPos, final long dstInit, final int dstPos,
+ final int nBools) {
+ if (src.length == 0 && srcPos == 0 || 0 == nBools) {
return dstInit;
}
- if ((nInts - 1) * 32 + dstPos >= 64) {
- throw new IllegalArgumentException("(nInts-1)*32+dstPos is greater or equal to than 64");
+ if (nBools - 1 + dstPos >= 64) {
+ throw new IllegalArgumentException("nBools-1+dstPos is greater or equal to than 64");
}
long out = dstInit;
- for (int i = 0; i < nInts; i++) {
- final int shift = i * 32 + dstPos;
- final long bits = (0xffffffffL & src[i + srcPos]) << shift;
- final long mask = 0xffffffffL << shift;
+ for (int i = 0; i < nBools; i++) {
+ final int shift = i + dstPos;
+ final long bits = (src[i + srcPos] ? 1L : 0) << shift;
+ final long mask = 0x1L << shift;
out = (out & ~mask) | bits;
}
return out;
}
/**
- * Converts an array of short into a long using the default (little endian, Lsb0) byte and
- * bit ordering.
+ * Converts binary (represented as boolean array) into a short using the default (little
+ * endian, Lsb0) byte and bit ordering.
*
- * @param src the short array to convert
- * @param srcPos the position in {@code src}, in short unit, from where to start the
+ * @param src the binary to convert
+ * @param srcPos the position in {@code src}, in boolean unit, from where to start the
* conversion
- * @param dstInit initial value of the destination long
- * @param dstPos the position of the lsb, in bits, in the result long
- * @param nShorts the number of shorts to convert
- * @return a long containing the selected bits
+ * @param dstInit initial value of the destination short
+ * @param dstPos the position of the lsb, in bits, in the result short
+ * @param nBools the number of booleans to convert
+ * @return a short containing the selected bits
* @throws NullPointerException if {@code src} is {@code null}
- * @throws IllegalArgumentException if {@code (nShorts-1)*16+dstPos >= 64}
- * @throws ArrayIndexOutOfBoundsException if {@code srcPos + nShorts > src.length}
+ * @throws IllegalArgumentException if {@code nBools-1+dstPos >= 16}
+ * @throws ArrayIndexOutOfBoundsException if {@code srcPos + nBools > src.length}
*/
- public static long shortArrayToLong(final short[] src, final int srcPos, final long dstInit, final int dstPos,
- final int nShorts) {
- if (src.length == 0 && srcPos == 0 || 0 == nShorts) {
+ public static short binaryToShort(final boolean[] src, final int srcPos, final short dstInit, final int dstPos,
+ final int nBools) {
+ if (src.length == 0 && srcPos == 0 || 0 == nBools) {
return dstInit;
}
- if ((nShorts - 1) * 16 + dstPos >= 64) {
- throw new IllegalArgumentException("(nShorts-1)*16+dstPos is greater or equal to than 64");
+ if (nBools - 1 + dstPos >= 16) {
+ throw new IllegalArgumentException("nBools-1+dstPos is greater or equal to than 16");
}
- long out = dstInit;
- for (int i = 0; i < nShorts; i++) {
- final int shift = i * 16 + dstPos;
- final long bits = (0xffffL & src[i + srcPos]) << shift;
- final long mask = 0xffffL << shift;
- out = (out & ~mask) | bits;
+ short out = dstInit;
+ for (int i = 0; i < nBools; i++) {
+ final int shift = i + dstPos;
+ final int bits = (src[i + srcPos] ? 1 : 0) << shift;
+ final int mask = 0x1 << shift;
+ out = (short) ((out & ~mask) | bits);
}
return out;
}
/**
- * Converts an array of short into an int using the default (little endian, Lsb0) byte and
- * bit ordering.
+ * Converts an array of byte into an int using the default (little endian, Lsb0) byte and bit
+ * ordering.
*
- * @param src the short array to convert
- * @param srcPos the position in {@code src}, in short unit, from where to start the
+ * @param src the byte array to convert
+ * @param srcPos the position in {@code src}, in byte unit, from where to start the
* conversion
* @param dstInit initial value of the destination int
* @param dstPos the position of the lsb, in bits, in the result int
- * @param nShorts the number of shorts to convert
+ * @param nBytes the number of bytes to convert
* @return an int containing the selected bits
* @throws NullPointerException if {@code src} is {@code null}
- * @throws IllegalArgumentException if {@code (nShorts-1)*16+dstPos >= 32}
- * @throws ArrayIndexOutOfBoundsException if {@code srcPos + nShorts > src.length}
+ * @throws IllegalArgumentException if {@code (nBytes-1)*8+dstPos >= 32}
+ * @throws ArrayIndexOutOfBoundsException if {@code srcPos + nBytes > src.length}
*/
- public static int shortArrayToInt(final short[] src, final int srcPos, final int dstInit, final int dstPos,
- final int nShorts) {
- if (src.length == 0 && srcPos == 0 || 0 == nShorts) {
+ public static int byteArrayToInt(final byte[] src, final int srcPos, final int dstInit, final int dstPos,
+ final int nBytes) {
+ if (src.length == 0 && srcPos == 0 || 0 == nBytes) {
return dstInit;
}
- if ((nShorts - 1) * 16 + dstPos >= 32) {
- throw new IllegalArgumentException("(nShorts-1)*16+dstPos is greater or equal to than 32");
+ if ((nBytes - 1) * 8 + dstPos >= 32) {
+ throw new IllegalArgumentException("(nBytes-1)*8+dstPos is greater or equal to than 32");
}
int out = dstInit;
- for (int i = 0; i < nShorts; i++) {
- final int shift = i * 16 + dstPos;
- final int bits = (0xffff & src[i + srcPos]) << shift;
- final int mask = 0xffff << shift;
+ for (int i = 0; i < nBytes; i++) {
+ final int shift = i * 8 + dstPos;
+ final int bits = (0xff & src[i + srcPos]) << shift;
+ final int mask = 0xff << shift;
out = (out & ~mask) | bits;
}
return out;
@@ -675,98 +471,339 @@ public class Conversion {
}
/**
- * Converts an array of byte into an int using the default (little endian, Lsb0) byte and bit
- * ordering.
+ * Converts an array of byte into a short using the default (little endian, Lsb0) byte and
+ * bit ordering.
*
* @param src the byte array to convert
* @param srcPos the position in {@code src}, in byte unit, from where to start the
* conversion
- * @param dstInit initial value of the destination int
- * @param dstPos the position of the lsb, in bits, in the result int
+ * @param dstInit initial value of the destination short
+ * @param dstPos the position of the lsb, in bits, in the result short
* @param nBytes the number of bytes to convert
- * @return an int containing the selected bits
+ * @return a short containing the selected bits
* @throws NullPointerException if {@code src} is {@code null}
- * @throws IllegalArgumentException if {@code (nBytes-1)*8+dstPos >= 32}
+ * @throws IllegalArgumentException if {@code (nBytes-1)*8+dstPos >= 16}
* @throws ArrayIndexOutOfBoundsException if {@code srcPos + nBytes > src.length}
*/
- public static int byteArrayToInt(final byte[] src, final int srcPos, final int dstInit, final int dstPos,
+ public static short byteArrayToShort(final byte[] src, final int srcPos, final short dstInit, final int dstPos,
final int nBytes) {
if (src.length == 0 && srcPos == 0 || 0 == nBytes) {
return dstInit;
}
- if ((nBytes - 1) * 8 + dstPos >= 32) {
- throw new IllegalArgumentException("(nBytes-1)*8+dstPos is greater or equal to than 32");
+ if ((nBytes - 1) * 8 + dstPos >= 16) {
+ throw new IllegalArgumentException("(nBytes-1)*8+dstPos is greater or equal to than 16");
}
- int out = dstInit;
+ short out = dstInit;
for (int i = 0; i < nBytes; i++) {
final int shift = i * 8 + dstPos;
final int bits = (0xff & src[i + srcPos]) << shift;
final int mask = 0xff << shift;
- out = (out & ~mask) | bits;
+ out = (short) ((out & ~mask) | bits);
}
return out;
}
/**
- * Converts an array of byte into a short using the default (little endian, Lsb0) byte and
+ * Converts bytes from an array into a UUID using the default (little endian, Lsb0) byte and
* bit ordering.
*
* @param src the byte array to convert
- * @param srcPos the position in {@code src}, in byte unit, from where to start the
- * conversion
- * @param dstInit initial value of the destination short
- * @param dstPos the position of the lsb, in bits, in the result short
- * @param nBytes the number of bytes to convert
- * @return a short containing the selected bits
+ * @param srcPos the position in {@code src} where to copy the result from
+ * @return a UUID
* @throws NullPointerException if {@code src} is {@code null}
- * @throws IllegalArgumentException if {@code (nBytes-1)*8+dstPos >= 16}
- * @throws ArrayIndexOutOfBoundsException if {@code srcPos + nBytes > src.length}
+ * @throws IllegalArgumentException if array does not contain at least 16 bytes beginning
+ * with {@code srcPos}
*/
- public static short byteArrayToShort(final byte[] src, final int srcPos, final short dstInit, final int dstPos,
- final int nBytes) {
- if (src.length == 0 && srcPos == 0 || 0 == nBytes) {
+ public static UUID byteArrayToUuid(final byte[] src, final int srcPos) {
+ if (src.length - srcPos < 16) {
+ throw new IllegalArgumentException("Need at least 16 bytes for UUID");
+ }
+ return new UUID(byteArrayToLong(src, srcPos, 0, 0, 8), byteArrayToLong(src, srcPos + 8, 0, 0, 8));
+ }
+
+ /**
+ * Converts a byte into an array of boolean using the default (little endian, Lsb0) byte and
+ * bit ordering.
+ *
+ * @param src the byte to convert
+ * @param srcPos the position in {@code src}, in bits, from where to start the conversion
+ * @param dst the destination array
+ * @param dstPos the position in {@code dst} where to copy the result
+ * @param nBools the number of booleans to copy to {@code dst}, must be smaller or equal to
+ * the width of the input (from srcPos to msb)
+ * @return {@code dst}
+ * @throws NullPointerException if {@code dst} is {@code null}
+ * @throws IllegalArgumentException if {@code nBools-1+srcPos >= 8}
+ * @throws ArrayIndexOutOfBoundsException if {@code dstPos + nBools > dst.length}
+ */
+ public static boolean[] byteToBinary(final byte src, final int srcPos, final boolean[] dst, final int dstPos,
+ final int nBools) {
+ if (0 == nBools) {
+ return dst;
+ }
+ if (nBools - 1 + srcPos >= 8) {
+ throw new IllegalArgumentException("nBools-1+srcPos is greater or equal to than 8");
+ }
+ for (int i = 0; i < nBools; i++) {
+ final int shift = i + srcPos;
+ dst[dstPos + i] = (0x1 & (src >> shift)) != 0;
+ }
+ return dst;
+ }
+
+ /**
+ * Converts a byte into an array of Char using the default (little endian, Lsb0) byte and
+ * bit ordering.
+ *
+ * @param src the byte to convert
+ * @param srcPos the position in {@code src}, in bits, from where to start the conversion
+ * @param dstInit the initial value for the result String
+ * @param dstPos the position in {@code dst} where to copy the result
+ * @param nHexs the number of Chars to copy to {@code dst}, must be smaller or equal to the
+ * width of the input (from srcPos to msb)
+ * @return {@code dst}
+ * @throws IllegalArgumentException if {@code (nHexs-1)*4+srcPos >= 8}
+ * @throws StringIndexOutOfBoundsException if {@code dst.init.length() < dstPos}
+ */
+ public static String byteToHex(final byte src, final int srcPos, final String dstInit, final int dstPos,
+ final int nHexs) {
+ if (0 == nHexs) {
return dstInit;
}
- if ((nBytes - 1) * 8 + dstPos >= 16) {
- throw new IllegalArgumentException("(nBytes-1)*8+dstPos is greater or equal to than 16");
+ if ((nHexs - 1) * 4 + srcPos >= 8) {
+ throw new IllegalArgumentException("(nHexs-1)*4+srcPos is greater or equal to than 8");
}
- short out = dstInit;
- for (int i = 0; i < nBytes; i++) {
- final int shift = i * 8 + dstPos;
- final int bits = (0xff & src[i + srcPos]) << shift;
- final int mask = 0xff << shift;
- out = (short) ((out & ~mask) | bits);
+ final StringBuilder sb = new StringBuilder(dstInit);
+ int append = sb.length();
+ for (int i = 0; i < nHexs; i++) {
+ final int shift = i * 4 + srcPos;
+ final int bits = 0xF & (src >> shift);
+ if (dstPos + i == append) {
+ ++append;
+ sb.append(intToHexDigit(bits));
+ } else {
+ sb.setCharAt(dstPos + i, intToHexDigit(bits));
+ }
}
- return out;
+ return sb.toString();
}
/**
- * Converts an array of Char into a long using the default (little endian, Lsb0) byte and
+ * Converts a hexadecimal digit into binary (represented as boolean array) using the Msb0
+ * bit ordering.
+ *
+ * <p>
+ * '1' is converted as follow: (0, 0, 0, 1)
+ * </p>
+ *
+ * @param hexDigit the hexadecimal digit to convert
+ * @return a boolean array with the binary representation of {@code hexDigit}
+ * @throws IllegalArgumentException if {@code hexDigit} is not a hexadecimal digit
+ */
+ public static boolean[] hexDigitMsb0ToBinary(final char hexDigit) {
+ switch (hexDigit) {
+ case '0':
+ return FFFF.clone();
+ case '1':
+ return FFFT.clone();
+ case '2':
+ return FFTF.clone();
+ case '3':
+ return FFTT.clone();
+ case '4':
+ return FTFF.clone();
+ case '5':
+ return FTFT.clone();
+ case '6':
+ return FTTF.clone();
+ case '7':
+ return FTTT.clone();
+ case '8':
+ return TFFF.clone();
+ case '9':
+ return TFFT.clone();
+ case 'a':// fall through
+ case 'A':
+ return TFTF.clone();
+ case 'b':// fall through
+ case 'B':
+ return TFTT.clone();
+ case 'c':// fall through
+ case 'C':
+ return TTFF.clone();
+ case 'd':// fall through
+ case 'D':
+ return TTFT.clone();
+ case 'e':// fall through
+ case 'E':
+ return TTTF.clone();
+ case 'f':// fall through
+ case 'F':
+ return TTTT.clone();
+ default:
+ throw new IllegalArgumentException("Cannot interpret '" + hexDigit + "' as a hexadecimal digit");
+ }
+ }
+
+ /**
+ * Converts a hexadecimal digit into an int using the Msb0 bit ordering.
+ *
+ * <p>
+ * '1' is converted to 8
+ * </p>
+ *
+ * @param hexDigit the hexadecimal digit to convert
+ * @return an int equals to {@code hexDigit}
+ * @throws IllegalArgumentException if {@code hexDigit} is not a hexadecimal digit
+ */
+ public static int hexDigitMsb0ToInt(final char hexDigit) {
+ switch (hexDigit) {
+ case '0':
+ return 0x0;
+ case '1':
+ return 0x8;
+ case '2':
+ return 0x4;
+ case '3':
+ return 0xC;
+ case '4':
+ return 0x2;
+ case '5':
+ return 0xA;
+ case '6':
+ return 0x6;
+ case '7':
+ return 0xE;
+ case '8':
+ return 0x1;
+ case '9':
+ return 0x9;
+ case 'a':// fall through
+ case 'A':
+ return 0x5;
+ case 'b':// fall through
+ case 'B':
+ return 0xD;
+ case 'c':// fall through
+ case 'C':
+ return 0x3;
+ case 'd':// fall through
+ case 'D':
+ return 0xB;
+ case 'e':// fall through
+ case 'E':
+ return 0x7;
+ case 'f':// fall through
+ case 'F':
+ return 0xF;
+ default:
+ throw new IllegalArgumentException("Cannot interpret '" + hexDigit + "' as a hexadecimal digit");
+ }
+ }
+
+ /**
+ * Converts a hexadecimal digit into binary (represented as boolean array) using the default
+ * (Lsb0) bit ordering.
+ *
+ * <p>
+ * '1' is converted as follow: (1, 0, 0, 0)
+ * </p>
+ *
+ * @param hexDigit the hexadecimal digit to convert
+ * @return a boolean array with the binary representation of {@code hexDigit}
+ * @throws IllegalArgumentException if {@code hexDigit} is not a hexadecimal digit
+ */
+ public static boolean[] hexDigitToBinary(final char hexDigit) {
+ switch (hexDigit) {
+ case '0':
+ return FFFF.clone();
+ case '1':
+ return TFFF.clone();
+ case '2':
+ return FTFF.clone();
+ case '3':
+ return TTFF.clone();
+ case '4':
+ return FFTF.clone();
+ case '5':
+ return TFTF.clone();
+ case '6':
+ return FTTF.clone();
+ case '7':
+ return TTTF.clone();
+ case '8':
+ return FFFT.clone();
+ case '9':
+ return TFFT.clone();
+ case 'a':// fall through
+ case 'A':
+ return FTFT.clone();
+ case 'b':// fall through
+ case 'B':
+ return TTFT.clone();
+ case 'c':// fall through
+ case 'C':
+ return FFTT.clone();
+ case 'd':// fall through
+ case 'D':
+ return TFTT.clone();
+ case 'e':// fall through
+ case 'E':
+ return FTTT.clone();
+ case 'f':// fall through
+ case 'F':
+ return TTTT.clone();
+ default:
+ throw new IllegalArgumentException("Cannot interpret '" + hexDigit + "' as a hexadecimal digit");
+ }
+ }
+
+ /**
+ * Converts a hexadecimal digit into an int using the default (Lsb0) bit ordering.
+ *
+ * <p>
+ * '1' is converted to 1
+ * </p>
+ *
+ * @param hexDigit the hexadecimal digit to convert
+ * @return an int equals to {@code hexDigit}
+ * @throws IllegalArgumentException if {@code hexDigit} is not a hexadecimal digit
+ */
+ public static int hexDigitToInt(final char hexDigit) {
+ final int digit = Character.digit(hexDigit, 16);
+ if (digit < 0) {
+ throw new IllegalArgumentException("Cannot interpret '" + hexDigit + "' as a hexadecimal digit");
+ }
+ return digit;
+ }
+
+ /**
+ * Converts an array of Char into a byte using the default (little endian, Lsb0) byte and
* bit ordering.
*
* @param src the hexadecimal string to convert
* @param srcPos the position in {@code src}, in Char unit, from where to start the
* conversion
- * @param dstInit initial value of the destination long
- * @param dstPos the position of the lsb, in bits, in the result long
+ * @param dstInit initial value of the destination byte
+ * @param dstPos the position of the lsb, in bits, in the result byte
* @param nHex the number of Chars to convert
- * @return a long containing the selected bits
- * @throws IllegalArgumentException if {@code (nHexs-1)*4+dstPos >= 64}
+ * @return a byte containing the selected bits
+ * @throws IllegalArgumentException if {@code (nHexs-1)*4+dstPos >= 8}
*/
- public static long hexToLong(final String src, final int srcPos, final long dstInit, final int dstPos,
+ public static byte hexToByte(final String src, final int srcPos, final byte dstInit, final int dstPos,
final int nHex) {
if (0 == nHex) {
return dstInit;
}
- if ((nHex - 1) * 4 + dstPos >= 64) {
- throw new IllegalArgumentException("(nHexs-1)*4+dstPos is greater or equal to than 64");
+ if ((nHex - 1) * 4 + dstPos >= 8) {
+ throw new IllegalArgumentException("(nHexs-1)*4+dstPos is greater or equal to than 8");
}
- long out = dstInit;
+ byte out = dstInit;
for (int i = 0; i < nHex; i++) {
final int shift = i * 4 + dstPos;
- final long bits = (0xfL & hexDigitToInt(src.charAt(i + srcPos))) << shift;
- final long mask = 0xfL << shift;
- out = (out & ~mask) | bits;
+ final int bits = (0xf & hexDigitToInt(src.charAt(i + srcPos))) << shift;
+ final int mask = 0xf << shift;
+ out = (byte) ((out & ~mask) | bits);
}
return out;
}
@@ -802,315 +839,126 @@ public class Conversion {
}
/**
- * Converts an array of Char into a short using the default (little endian, Lsb0) byte and
+ * Converts an array of Char into a long using the default (little endian, Lsb0) byte and
* bit ordering.
*
* @param src the hexadecimal string to convert
* @param srcPos the position in {@code src}, in Char unit, from where to start the
* conversion
- * @param dstInit initial value of the destination short
- * @param dstPos the position of the lsb, in bits, in the result short
+ * @param dstInit initial value of the destination long
+ * @param dstPos the position of the lsb, in bits, in the result long
* @param nHex the number of Chars to convert
- * @return a short containing the selected bits
- * @throws IllegalArgumentException if {@code (nHexs-1)*4+dstPos >= 16}
+ * @return a long containing the selected bits
+ * @throws IllegalArgumentException if {@code (nHexs-1)*4+dstPos >= 64}
*/
- public static short hexToShort(final String src, final int srcPos, final short dstInit, final int dstPos,
+ public static long hexToLong(final String src, final int srcPos, final long dstInit, final int dstPos,
final int nHex) {
if (0 == nHex) {
return dstInit;
}
- if ((nHex - 1) * 4 + dstPos >= 16) {
- throw new IllegalArgumentException("(nHexs-1)*4+dstPos is greater or equal to than 16");
+ if ((nHex - 1) * 4 + dstPos >= 64) {
+ throw new IllegalArgumentException("(nHexs-1)*4+dstPos is greater or equal to than 64");
}
- short out = dstInit;
+ long out = dstInit;
for (int i = 0; i < nHex; i++) {
final int shift = i * 4 + dstPos;
- final int bits = (0xf & hexDigitToInt(src.charAt(i + srcPos))) << shift;
- final int mask = 0xf << shift;
- out = (short) ((out & ~mask) | bits);
+ final long bits = (0xfL & hexDigitToInt(src.charAt(i + srcPos))) << shift;
+ final long mask = 0xfL << shift;
+ out = (out & ~mask) | bits;
}
return out;
}
/**
- * Converts an array of Char into a byte using the default (little endian, Lsb0) byte and
+ * Converts an array of Char into a short using the default (little endian, Lsb0) byte and
* bit ordering.
*
* @param src the hexadecimal string to convert
* @param srcPos the position in {@code src}, in Char unit, from where to start the
* conversion
- * @param dstInit initial value of the destination byte
- * @param dstPos the position of the lsb, in bits, in the result byte
+ * @param dstInit initial value of the destination short
+ * @param dstPos the position of the lsb, in bits, in the result short
* @param nHex the number of Chars to convert
- * @return a byte containing the selected bits
- * @throws IllegalArgumentException if {@code (nHexs-1)*4+dstPos >= 8}
+ * @return a short containing the selected bits
+ * @throws IllegalArgumentException if {@code (nHexs-1)*4+dstPos >= 16}
*/
- public static byte hexToByte(final String src, final int srcPos, final byte dstInit, final int dstPos,
+ public static short hexToShort(final String src, final int srcPos, final short dstInit, final int dstPos,
final int nHex) {
if (0 == nHex) {
return dstInit;
}
- if ((nHex - 1) * 4 + dstPos >= 8) {
- throw new IllegalArgumentException("(nHexs-1)*4+dstPos is greater or equal to than 8");
+ if ((nHex - 1) * 4 + dstPos >= 16) {
+ throw new IllegalArgumentException("(nHexs-1)*4+dstPos is greater or equal to than 16");
}
- byte out = dstInit;
+ short out = dstInit;
for (int i = 0; i < nHex; i++) {
final int shift = i * 4 + dstPos;
final int bits = (0xf & hexDigitToInt(src.charAt(i + srcPos))) << shift;
final int mask = 0xf << shift;
- out = (byte) ((out & ~mask) | bits);
+ out = (short) ((out & ~mask) | bits);
}
return out;
}
/**
- * Converts binary (represented as boolean array) into a long using the default (little
- * endian, Lsb0) byte and bit ordering.
+ * Converts an array of int into a long using the default (little endian, Lsb0) byte and bit
+ * ordering.
*
- * @param src the binary to convert
- * @param srcPos the position in {@code src}, in boolean unit, from where to start the
+ * @param src the int array to convert
+ * @param srcPos the position in {@code src}, in int unit, from where to start the
* conversion
* @param dstInit initial value of the destination long
* @param dstPos the position of the lsb, in bits, in the result long
- * @param nBools the number of booleans to convert
+ * @param nInts the number of ints to convert
* @return a long containing the selected bits
+ * @throws IllegalArgumentException if {@code (nInts-1)*32+dstPos >= 64}
* @throws NullPointerException if {@code src} is {@code null}
- * @throws IllegalArgumentException if {@code nBools-1+dstPos >= 64}
- * @throws ArrayIndexOutOfBoundsException if {@code srcPos + nBools > src.length}
- */
- public static long binaryToLong(final boolean[] src, final int srcPos, final long dstInit, final int dstPos,
- final int nBools) {
- if (src.length == 0 && srcPos == 0 || 0 == nBools) {
- return dstInit;
- }
- if (nBools - 1 + dstPos >= 64) {
- throw new IllegalArgumentException("nBools-1+dstPos is greater or equal to than 64");
- }
- long out = dstInit;
- for (int i = 0; i < nBools; i++) {
- final int shift = i + dstPos;
- final long bits = (src[i + srcPos] ? 1L : 0) << shift;
- final long mask = 0x1L << shift;
- out = (out & ~mask) | bits;
- }
- return out;
- }
-
- /**
- * Converts binary (represented as boolean array) into an int using the default (little
- * endian, Lsb0) byte and bit ordering.
- *
- * @param src the binary to convert
- * @param srcPos the position in {@code src}, in boolean unit, from where to start the
- * conversion
- * @param dstInit initial value of the destination int
- * @param dstPos the position of the lsb, in bits, in the result int
- * @param nBools the number of booleans to convert
- * @return an int containing the selected bits
- * @throws NullPointerException if {@code src} is {@code null}
- * @throws IllegalArgumentException if {@code nBools-1+dstPos >= 32}
- * @throws ArrayIndexOutOfBoundsException if {@code srcPos + nBools > src.length}
- */
- public static int binaryToInt(final boolean[] src, final int srcPos, final int dstInit, final int dstPos,
- final int nBools) {
- if (src.length == 0 && srcPos == 0 || 0 == nBools) {
- return dstInit;
- }
- if (nBools - 1 + dstPos >= 32) {
- throw new IllegalArgumentException("nBools-1+dstPos is greater or equal to than 32");
- }
- int out = dstInit;
- for (int i = 0; i < nBools; i++) {
- final int shift = i + dstPos;
- final int bits = (src[i + srcPos] ? 1 : 0) << shift;
- final int mask = 0x1 << shift;
- out = (out & ~mask) | bits;
- }
- return out;
- }
-
- /**
- * Converts binary (represented as boolean array) into a short using the default (little
- * endian, Lsb0) byte and bit ordering.
- *
- * @param src the binary to convert
- * @param srcPos the position in {@code src}, in boolean unit, from where to start the
- * conversion
- * @param dstInit initial value of the destination short
- * @param dstPos the position of the lsb, in bits, in the result short
- * @param nBools the number of booleans to convert
- * @return a short containing the selected bits
- * @throws NullPointerException if {@code src} is {@code null}
- * @throws IllegalArgumentException if {@code nBools-1+dstPos >= 16}
- * @throws ArrayIndexOutOfBoundsException if {@code srcPos + nBools > src.length}
- */
- public static short binaryToShort(final boolean[] src, final int srcPos, final short dstInit, final int dstPos,
- final int nBools) {
- if (src.length == 0 && srcPos == 0 || 0 == nBools) {
- return dstInit;
- }
- if (nBools - 1 + dstPos >= 16) {
- throw new IllegalArgumentException("nBools-1+dstPos is greater or equal to than 16");
- }
- short out = dstInit;
- for (int i = 0; i < nBools; i++) {
- final int shift = i + dstPos;
- final int bits = (src[i + srcPos] ? 1 : 0) << shift;
- final int mask = 0x1 << shift;
- out = (short) ((out & ~mask) | bits);
- }
- return out;
- }
-
- /**
- * Converts binary (represented as boolean array) into a byte using the default (little
- * endian, Lsb0) byte and bit ordering.
- *
- * @param src the binary to convert
- * @param srcPos the position in {@code src}, in boolean unit, from where to start the
- * conversion
- * @param dstInit initial value of the destination byte
- * @param dstPos the position of the lsb, in bits, in the result byte
- * @param nBools the number of booleans to convert
- * @return a byte containing the selected bits
- * @throws NullPointerException if {@code src} is {@code null}
- * @throws IllegalArgumentException if {@code nBools-1+dstPos >= 8}
- * @throws ArrayIndexOutOfBoundsException if {@code srcPos + nBools > src.length}
- */
- public static byte binaryToByte(final boolean[] src, final int srcPos, final byte dstInit, final int dstPos,
- final int nBools) {
- if (src.length == 0 && srcPos == 0 || 0 == nBools) {
- return dstInit;
- }
- if (nBools - 1 + dstPos >= 8) {
- throw new IllegalArgumentException("nBools-1+dstPos is greater or equal to than 8");
- }
- byte out = dstInit;
- for (int i = 0; i < nBools; i++) {
- final int shift = i + dstPos;
- final int bits = (src[i + srcPos] ? 1 : 0) << shift;
- final int mask = 0x1 << shift;
- out = (byte) ((out & ~mask) | bits);
- }
- return out;
- }
-
- /**
- * Converts a long into an array of int using the default (little endian, Lsb0) byte and bit
- * ordering.
- *
- * @param src the long to convert
- * @param srcPos the position in {@code src}, in bits, from where to start the conversion
- * @param dst the destination array
- * @param dstPos the position in {@code dst} where to copy the result
- * @param nInts the number of ints to copy to {@code dst}, must be smaller or equal to the
- * width of the input (from srcPos to msb)
- * @return {@code dst}
- * @throws NullPointerException if {@code dst} is {@code null} and {@code nInts > 0}
- * @throws IllegalArgumentException if {@code (nInts-1)*32+srcPos >= 64}
- * @throws ArrayIndexOutOfBoundsException if {@code dstPos + nInts > dst.length}
- */
- public static int[] longToIntArray(final long src, final int srcPos, final int[] dst, final int dstPos,
- final int nInts) {
- if (0 == nInts) {
- return dst;
- }
- if ((nInts - 1) * 32 + srcPos >= 64) {
- throw new IllegalArgumentException("(nInts-1)*32+srcPos is greater or equal to than 64");
- }
- for (int i = 0; i < nInts; i++) {
- final int shift = i * 32 + srcPos;
- dst[dstPos + i] = (int) (0xffffffff & (src >> shift));
- }
- return dst;
- }
-
- /**
- * Converts a long into an array of short using the default (little endian, Lsb0) byte and
- * bit ordering.
- *
- * @param src the long to convert
- * @param srcPos the position in {@code src}, in bits, from where to start the conversion
- * @param dst the destination array
- * @param dstPos the position in {@code dst} where to copy the result
- * @param nShorts the number of shorts to copy to {@code dst}, must be smaller or equal to
- * the width of the input (from srcPos to msb)
- * @return {@code dst}
- * @throws NullPointerException if {@code dst} is {@code null}
- * @throws IllegalArgumentException if {@code (nShorts-1)*16+srcPos >= 64}
- * @throws ArrayIndexOutOfBoundsException if {@code dstPos + nShorts > dst.length}
- */
- public static short[] longToShortArray(final long src, final int srcPos, final short[] dst, final int dstPos,
- final int nShorts) {
- if (0 == nShorts) {
- return dst;
- }
- if ((nShorts - 1) * 16 + srcPos >= 64) {
- throw new IllegalArgumentException("(nShorts-1)*16+srcPos is greater or equal to than 64");
- }
- for (int i = 0; i < nShorts; i++) {
- final int shift = i * 16 + srcPos;
- dst[dstPos + i] = (short) (0xffff & (src >> shift));
- }
- return dst;
- }
-
- /**
- * Converts an int into an array of short using the default (little endian, Lsb0) byte and
- * bit ordering.
- *
- * @param src the int to convert
- * @param srcPos the position in {@code src}, in bits, from where to start the conversion
- * @param dst the destination array
- * @param dstPos the position in {@code dst} where to copy the result
- * @param nShorts the number of shorts to copy to {@code dst}, must be smaller or equal to
- * the width of the input (from srcPos to msb)
- * @return {@code dst}
- * @throws NullPointerException if {@code dst} is {@code null}
- * @throws IllegalArgumentException if {@code (nShorts-1)*16+srcPos >= 32}
- * @throws ArrayIndexOutOfBoundsException if {@code dstPos + nShorts > dst.length}
+ * @throws ArrayIndexOutOfBoundsException if {@code srcPos + nInts > src.length}
*/
- public static short[] intToShortArray(final int src, final int srcPos, final short[] dst, final int dstPos,
- final int nShorts) {
- if (0 == nShorts) {
- return dst;
+ public static long intArrayToLong(final int[] src, final int srcPos, final long dstInit, final int dstPos,
+ final int nInts) {
+ if (src.length == 0 && srcPos == 0 || 0 == nInts) {
+ return dstInit;
}
- if ((nShorts - 1) * 16 + srcPos >= 32) {
- throw new IllegalArgumentException("(nShorts-1)*16+srcPos is greater or equal to than 32");
+ if ((nInts - 1) * 32 + dstPos >= 64) {
+ throw new IllegalArgumentException("(nInts-1)*32+dstPos is greater or equal to than 64");
}
- for (int i = 0; i < nShorts; i++) {
- final int shift = i * 16 + srcPos;
- dst[dstPos + i] = (short) (0xffff & (src >> shift));
+ long out = dstInit;
+ for (int i = 0; i < nInts; i++) {
+ final int shift = i * 32 + dstPos;
+ final long bits = (0xffffffffL & src[i + srcPos]) << shift;
+ final long mask = 0xffffffffL << shift;
+ out = (out & ~mask) | bits;
}
- return dst;
+ return out;
}
/**
- * Converts a long into an array of byte using the default (little endian, Lsb0) byte and
+ * Converts an int into an array of boolean using the default (little endian, Lsb0) byte and
* bit ordering.
*
- * @param src the long to convert
+ * @param src the int to convert
* @param srcPos the position in {@code src}, in bits, from where to start the conversion
* @param dst the destination array
* @param dstPos the position in {@code dst} where to copy the result
- * @param nBytes the number of bytes to copy to {@code dst}, must be smaller or equal to the
- * width of the input (from srcPos to msb)
+ * @param nBools the number of booleans to copy to {@code dst}, must be smaller or equal to
+ * the width of the input (from srcPos to msb)
* @return {@code dst}
* @throws NullPointerException if {@code dst} is {@code null}
- * @throws IllegalArgumentException if {@code (nBytes-1)*8+srcPos >= 64}
- * @throws ArrayIndexOutOfBoundsException if {@code dstPos + nBytes > dst.length}
+ * @throws IllegalArgumentException if {@code nBools-1+srcPos >= 32}
+ * @throws ArrayIndexOutOfBoundsException if {@code dstPos + nBools > dst.length}
*/
- public static byte[] longToByteArray(final long src, final int srcPos, final byte[] dst, final int dstPos,
- final int nBytes) {
- if (0 == nBytes) {
+ public static boolean[] intToBinary(final int src, final int srcPos, final boolean[] dst, final int dstPos,
+ final int nBools) {
+ if (0 == nBools) {
return dst;
}
- if ((nBytes - 1) * 8 + srcPos >= 64) {
- throw new IllegalArgumentException("(nBytes-1)*8+srcPos is greater or equal to than 64");
+ if (nBools - 1 + srcPos >= 32) {
+ throw new IllegalArgumentException("nBools-1+srcPos is greater or equal to than 32");
}
- for (int i = 0; i < nBytes; i++) {
- final int shift = i * 8 + srcPos;
- dst[dstPos + i] = (byte) (0xff & (src >> shift));
+ for (int i = 0; i < nBools; i++) {
+ final int shift = i + srcPos;
+ dst[dstPos + i] = (0x1 & (src >> shift)) != 0;
}
return dst;
}
@@ -1146,62 +994,32 @@ public class Conversion {
}
/**
- * Converts a short into an array of byte using the default (little endian, Lsb0) byte and
- * bit ordering.
- *
- * @param src the short to convert
- * @param srcPos the position in {@code src}, in bits, from where to start the conversion
- * @param dst the destination array
- * @param dstPos the position in {@code dst} where to copy the result
- * @param nBytes the number of bytes to copy to {@code dst}, must be smaller or equal to the
- * width of the input (from srcPos to msb)
- * @return {@code dst}
- * @throws NullPointerException if {@code dst} is {@code null}
- * @throws IllegalArgumentException if {@code (nBytes-1)*8+srcPos >= 16}
- * @throws ArrayIndexOutOfBoundsException if {@code dstPos + nBytes > dst.length}
- */
- public static byte[] shortToByteArray(final short src, final int srcPos, final byte[] dst, final int dstPos,
- final int nBytes) {
- if (0 == nBytes) {
- return dst;
- }
- if ((nBytes - 1) * 8 + srcPos >= 16) {
- throw new IllegalArgumentException("(nBytes-1)*8+srcPos is greater or equal to than 16");
- }
- for (int i = 0; i < nBytes; i++) {
- final int shift = i * 8 + srcPos;
- dst[dstPos + i] = (byte) (0xff & (src >> shift));
- }
- return dst;
- }
-
- /**
- * Converts a long into an array of Char using the default (little endian, Lsb0) byte and
- * bit ordering.
+ * Converts an int into an array of Char using the default (little endian, Lsb0) byte and bit
+ * ordering.
*
- * @param src the long to convert
+ * @param src the int to convert
* @param srcPos the position in {@code src}, in bits, from where to start the conversion
* @param dstInit the initial value for the result String
* @param dstPos the position in {@code dst} where to copy the result
* @param nHexs the number of Chars to copy to {@code dst}, must be smaller or equal to the
* width of the input (from srcPos to msb)
* @return {@code dst}
- * @throws IllegalArgumentException if {@code (nHexs-1)*4+srcPos >= 64}
+ * @throws IllegalArgumentException if {@code (nHexs-1)*4+srcPos >= 32}
* @throws StringIndexOutOfBoundsException if {@code dst.init.length() < dstPos}
*/
- public static String longToHex(final long src, final int srcPos, final String dstInit, final int dstPos,
+ public static String intToHex(final int src, final int srcPos, final String dstInit, final int dstPos,
final int nHexs) {
if (0 == nHexs) {
return dstInit;
}
- if ((nHexs - 1) * 4 + srcPos >= 64) {
- throw new IllegalArgumentException("(nHexs-1)*4+srcPos is greater or equal to than 64");
+ if ((nHexs - 1) * 4 + srcPos >= 32) {
+ throw new IllegalArgumentException("(nHexs-1)*4+srcPos is greater or equal to than 32");
}
final StringBuilder sb = new StringBuilder(dstInit);
int append = sb.length();
for (int i = 0; i < nHexs; i++) {
final int shift = i * 4 + srcPos;
- final int bits = (int) (0xF & (src >> shift));
+ final int bits = 0xF & (src >> shift);
if (dstPos + i == append) {
++append;
sb.append(intToHexDigit(bits));
@@ -1213,106 +1031,203 @@ public class Conversion {
}
/**
- * Converts an int into an array of Char using the default (little endian, Lsb0) byte and bit
- * ordering.
+ * Converts the 4 lsb of an int to a hexadecimal digit.
+ *
+ * <p>
+ * 0 returns '0'
+ * </p>
+ * <p>
+ * 1 returns '1'
+ * </p>
+ * <p>
+ * 10 returns 'A' and so on...
+ * </p>
+ *
+ * @param nibble the 4 bits to convert
+ * @return a hexadecimal digit representing the 4 lsb of {@code nibble}
+ * @throws IllegalArgumentException if {@code nibble < 0} or {@code nibble > 15}
+ */
+ public static char intToHexDigit(final int nibble) {
+ final char c = Character.forDigit(nibble, 16);
+ if (c == Character.MIN_VALUE) {
+ throw new IllegalArgumentException("nibble value not between 0 and 15: " + nibble);
+ }
+ return c;
+ }
+
+ /**
+ * Converts the 4 lsb of an int to a hexadecimal digit encoded using the Msb0 bit ordering.
+ *
+ * <p>
+ * 0 returns '0'
+ * </p>
+ * <p>
+ * 1 returns '8'
+ * </p>
+ * <p>
+ * 10 returns '5' and so on...
+ * </p>
+ *
+ * @param nibble the 4 bits to convert
+ * @return a hexadecimal digit representing the 4 lsb of {@code nibble}
+ * @throws IllegalArgumentException if {@code nibble < 0} or {@code nibble > 15}
+ */
+ public static char intToHexDigitMsb0(final int nibble) {
+ switch (nibble) {
+ case 0x0:
+ return '0';
+ case 0x1:
+ return '8';
+ case 0x2:
+ return '4';
+ case 0x3:
+ return 'c';
+ case 0x4:
+ return '2';
+ case 0x5:
+ return 'a';
+ case 0x6:
+ return '6';
+ case 0x7:
+ return 'e';
+ case 0x8:
+ return '1';
+ case 0x9:
+ return '9';
+ case 0xA:
+ return '5';
+ case 0xB:
+ return 'd';
+ case 0xC:
+ return '3';
+ case 0xD:
+ return 'b';
+ case 0xE:
+ return '7';
+ case 0xF:
+ return 'f';
+ default:
+ throw new IllegalArgumentException("nibble value not between 0 and 15: " + nibble);
+ }
+ }
+
+ /**
+ * Converts an int into an array of short using the default (little endian, Lsb0) byte and
+ * bit ordering.
*
* @param src the int to convert
* @param srcPos the position in {@code src}, in bits, from where to start the conversion
- * @param dstInit the initial value for the result String
+ * @param dst the destination array
* @param dstPos the position in {@code dst} where to copy the result
- * @param nHexs the number of Chars to copy to {@code dst}, must be smaller or equal to the
- * width of the input (from srcPos to msb)
+ * @param nShorts the number of shorts to copy to {@code dst}, must be smaller or equal to
+ * the width of the input (from srcPos to msb)
* @return {@code dst}
- * @throws IllegalArgumentException if {@code (nHexs-1)*4+srcPos >= 32}
- * @throws StringIndexOutOfBoundsException if {@code dst.init.length() < dstPos}
+ * @throws NullPointerException if {@code dst} is {@code null}
+ * @throws IllegalArgumentException if {@code (nShorts-1)*16+srcPos >= 32}
+ * @throws ArrayIndexOutOfBoundsException if {@code dstPos + nShorts > dst.length}
*/
- public static String intToHex(final int src, final int srcPos, final String dstInit, final int dstPos,
- final int nHexs) {
- if (0 == nHexs) {
- return dstInit;
+ public static short[] intToShortArray(final int src, final int srcPos, final short[] dst, final int dstPos,
+ final int nShorts) {
+ if (0 == nShorts) {
+ return dst;
}
- if ((nHexs - 1) * 4 + srcPos >= 32) {
- throw new IllegalArgumentException("(nHexs-1)*4+srcPos is greater or equal to than 32");
+ if ((nShorts - 1) * 16 + srcPos >= 32) {
+ throw new IllegalArgumentException("(nShorts-1)*16+srcPos is greater or equal to than 32");
}
- final StringBuilder sb = new StringBuilder(dstInit);
- int append = sb.length();
- for (int i = 0; i < nHexs; i++) {
- final int shift = i * 4 + srcPos;
- final int bits = 0xF & (src >> shift);
- if (dstPos + i == append) {
- ++append;
- sb.append(intToHexDigit(bits));
- } else {
- sb.setCharAt(dstPos + i, intToHexDigit(bits));
- }
+ for (int i = 0; i < nShorts; i++) {
+ final int shift = i * 16 + srcPos;
+ dst[dstPos + i] = (short) (0xffff & (src >> shift));
}
- return sb.toString();
+ return dst;
}
/**
- * Converts a short into an array of Char using the default (little endian, Lsb0) byte and
+ * Converts a long into an array of boolean using the default (little endian, Lsb0) byte and
* bit ordering.
*
- * @param src the short to convert
+ * @param src the long to convert
+ * @param srcPos the position in {@code src}, in bits, from where to start the conversion
+ * @param dst the destination array
+ * @param dstPos the position in {@code dst} where to copy the result
+ * @param nBools the number of booleans to copy to {@code dst}, must be smaller or equal to
+ * the width of the input (from srcPos to msb)
+ * @return {@code dst}
+ * @throws NullPointerException if {@code dst} is {@code null}
+ * @throws IllegalArgumentException if {@code nBools-1+srcPos >= 64}
+ * @throws ArrayIndexOutOfBoundsException if {@code dstPos + nBools > dst.length}
+ */
+ public static boolean[] longToBinary(final long src, final int srcPos, final boolean[] dst, final int dstPos,
+ final int nBools) {
+ if (0 == nBools) {
+ return dst;
+ }
+ if (nBools - 1 + srcPos >= 64) {
+ throw new IllegalArgumentException("nBools-1+srcPos is greater or equal to than 64");
+ }
+ for (int i = 0; i < nBools; i++) {
+ final int shift = i + srcPos;
+ dst[dstPos + i] = (0x1 & (src >> shift)) != 0;
+ }
+ return dst;
+ }
+
+ /**
+ * Converts a long into an array of byte using the default (little endian, Lsb0) byte and
+ * bit ordering.
+ *
+ * @param src the long to convert
* @param srcPos the position in {@code src}, in bits, from where to start the conversion
- * @param dstInit the initial value for the result String
+ * @param dst the destination array
* @param dstPos the position in {@code dst} where to copy the result
- * @param nHexs the number of Chars to copy to {@code dst}, must be smaller or equal to the
+ * @param nBytes the number of bytes to copy to {@code dst}, must be smaller or equal to the
* width of the input (from srcPos to msb)
* @return {@code dst}
- * @throws IllegalArgumentException if {@code (nHexs-1)*4+srcPos >= 16}
- * @throws StringIndexOutOfBoundsException if {@code dst.init.length() < dstPos}
+ * @throws NullPointerException if {@code dst} is {@code null}
+ * @throws IllegalArgumentException if {@code (nBytes-1)*8+srcPos >= 64}
+ * @throws ArrayIndexOutOfBoundsException if {@code dstPos + nBytes > dst.length}
*/
- public static String shortToHex(final short src, final int srcPos, final String dstInit, final int dstPos,
- final int nHexs) {
- if (0 == nHexs) {
- return dstInit;
+ public static byte[] longToByteArray(final long src, final int srcPos, final byte[] dst, final int dstPos,
+ final int nBytes) {
+ if (0 == nBytes) {
+ return dst;
}
- if ((nHexs - 1) * 4 + srcPos >= 16) {
- throw new IllegalArgumentException("(nHexs-1)*4+srcPos is greater or equal to than 16");
+ if ((nBytes - 1) * 8 + srcPos >= 64) {
+ throw new IllegalArgumentException("(nBytes-1)*8+srcPos is greater or equal to than 64");
}
- final StringBuilder sb = new StringBuilder(dstInit);
- int append = sb.length();
- for (int i = 0; i < nHexs; i++) {
- final int shift = i * 4 + srcPos;
- final int bits = 0xF & (src >> shift);
- if (dstPos + i == append) {
- ++append;
- sb.append(intToHexDigit(bits));
- } else {
- sb.setCharAt(dstPos + i, intToHexDigit(bits));
- }
+ for (int i = 0; i < nBytes; i++) {
+ final int shift = i * 8 + srcPos;
+ dst[dstPos + i] = (byte) (0xff & (src >> shift));
}
- return sb.toString();
+ return dst;
}
/**
- * Converts a byte into an array of Char using the default (little endian, Lsb0) byte and
+ * Converts a long into an array of Char using the default (little endian, Lsb0) byte and
* bit ordering.
*
- * @param src the byte to convert
+ * @param src the long to convert
* @param srcPos the position in {@code src}, in bits, from where to start the conversion
* @param dstInit the initial value for the result String
* @param dstPos the position in {@code dst} where to copy the result
* @param nHexs the number of Chars to copy to {@code dst}, must be smaller or equal to the
* width of the input (from srcPos to msb)
* @return {@code dst}
- * @throws IllegalArgumentException if {@code (nHexs-1)*4+srcPos >= 8}
+ * @throws IllegalArgumentException if {@code (nHexs-1)*4+srcPos >= 64}
* @throws StringIndexOutOfBoundsException if {@code dst.init.length() < dstPos}
*/
- public static String byteToHex(final byte src, final int srcPos, final String dstInit, final int dstPos,
+ public static String longToHex(final long src, final int srcPos, final String dstInit, final int dstPos,
final int nHexs) {
if (0 == nHexs) {
return dstInit;
}
- if ((nHexs - 1) * 4 + srcPos >= 8) {
- throw new IllegalArgumentException("(nHexs-1)*4+srcPos is greater or equal to than 8");
+ if ((nHexs - 1) * 4 + srcPos >= 64) {
+ throw new IllegalArgumentException("(nHexs-1)*4+srcPos is greater or equal to than 64");
}
final StringBuilder sb = new StringBuilder(dstInit);
int append = sb.length();
for (int i = 0; i < nHexs; i++) {
final int shift = i * 4 + srcPos;
- final int bits = 0xF & (src >> shift);
+ final int bits = (int) (0xF & (src >> shift));
if (dstPos + i == append) {
++append;
sb.append(intToHexDigit(bits));
@@ -1324,65 +1239,131 @@ public class Conversion {
}
/**
- * Converts a long into an array of boolean using the default (little endian, Lsb0) byte and
- * bit ordering.
+ * Converts a long into an array of int using the default (little endian, Lsb0) byte and bit
+ * ordering.
*
* @param src the long to convert
* @param srcPos the position in {@code src}, in bits, from where to start the conversion
* @param dst the destination array
* @param dstPos the position in {@code dst} where to copy the result
- * @param nBools the number of booleans to copy to {@code dst}, must be smaller or equal to
- * the width of the input (from srcPos to msb)
+ * @param nInts the number of ints to copy to {@code dst}, must be smaller or equal to the
+ * width of the input (from srcPos to msb)
* @return {@code dst}
- * @throws NullPointerException if {@code dst} is {@code null}
- * @throws IllegalArgumentException if {@code nBools-1+srcPos >= 64}
- * @throws ArrayIndexOutOfBoundsException if {@code dstPos + nBools > dst.length}
+ * @throws NullPointerException if {@code dst} is {@code null} and {@code nInts > 0}
+ * @throws IllegalArgumentException if {@code (nInts-1)*32+srcPos >= 64}
+ * @throws ArrayIndexOutOfBoundsException if {@code dstPos + nInts > dst.length}
*/
- public static boolean[] longToBinary(final long src, final int srcPos, final boolean[] dst, final int dstPos,
- final int nBools) {
- if (0 == nBools) {
+ public static int[] longToIntArray(final long src, final int srcPos, final int[] dst, final int dstPos,
+ final int nInts) {
+ if (0 == nInts) {
return dst;
}
- if (nBools - 1 + srcPos >= 64) {
- throw new IllegalArgumentException("nBools-1+srcPos is greater or equal to than 64");
+ if ((nInts - 1) * 32 + srcPos >= 64) {
+ throw new IllegalArgumentException("(nInts-1)*32+srcPos is greater or equal to than 64");
}
- for (int i = 0; i < nBools; i++) {
- final int shift = i + srcPos;
- dst[dstPos + i] = (0x1 & (src >> shift)) != 0;
+ for (int i = 0; i < nInts; i++) {
+ final int shift = i * 32 + srcPos;
+ dst[dstPos + i] = (int) (0xffffffff & (src >> shift));
}
return dst;
}
/**
- * Converts an int into an array of boolean using the default (little endian, Lsb0) byte and
+ * Converts a long into an array of short using the default (little endian, Lsb0) byte and
* bit ordering.
*
- * @param src the int to convert
+ * @param src the long to convert
* @param srcPos the position in {@code src}, in bits, from where to start the conversion
* @param dst the destination array
* @param dstPos the position in {@code dst} where to copy the result
- * @param nBools the number of booleans to copy to {@code dst}, must be smaller or equal to
+ * @param nShorts the number of shorts to copy to {@code dst}, must be smaller or equal to
* the width of the input (from srcPos to msb)
* @return {@code dst}
* @throws NullPointerException if {@code dst} is {@code null}
- * @throws IllegalArgumentException if {@code nBools-1+srcPos >= 32}
- * @throws ArrayIndexOutOfBoundsException if {@code dstPos + nBools > dst.length}
+ * @throws IllegalArgumentException if {@code (nShorts-1)*16+srcPos >= 64}
+ * @throws ArrayIndexOutOfBoundsException if {@code dstPos + nShorts > dst.length}
*/
- public static boolean[] intToBinary(final int src, final int srcPos, final boolean[] dst, final int dstPos,
- final int nBools) {
- if (0 == nBools) {
+ public static short[] longToShortArray(final long src, final int srcPos, final short[] dst, final int dstPos,
+ final int nShorts) {
+ if (0 == nShorts) {
return dst;
}
- if (nBools - 1 + srcPos >= 32) {
- throw new IllegalArgumentException("nBools-1+srcPos is greater or equal to than 32");
+ if ((nShorts - 1) * 16 + srcPos >= 64) {
+ throw new IllegalArgumentException("(nShorts-1)*16+srcPos is greater or equal to than 64");
}
- for (int i = 0; i < nBools; i++) {
- final int shift = i + srcPos;
- dst[dstPos + i] = (0x1 & (src >> shift)) != 0;
+ for (int i = 0; i < nShorts; i++) {
+ final int shift = i * 16 + srcPos;
+ dst[dstPos + i] = (short) (0xffff & (src >> shift));
}
return dst;
}
+ /**
+ * Converts an array of short into an int using the default (little endian, Lsb0) byte and
+ * bit ordering.
+ *
+ * @param src the short array to convert
+ * @param srcPos the position in {@code src}, in short unit, from where to start the
+ * conversion
+ * @param dstInit initial value of the destination int
+ * @param dstPos the position of the lsb, in bits, in the result int
+ * @param nShorts the number of shorts to convert
+ * @return an int containing the selected bits
+ * @throws NullPointerException if {@code src} is {@code null}
+ * @throws IllegalArgumentException if {@code (nShorts-1)*16+dstPos >= 32}
+ * @throws ArrayIndexOutOfBoundsException if {@code srcPos + nShorts > src.length}
+ */
+ public static int shortArrayToInt(final short[] src, final int srcPos, final int dstInit, final int dstPos,
+ final int nShorts) {
+ if (src.length == 0 && srcPos == 0 || 0 == nShorts) {
+ return dstInit;
+ }
+ if ((nShorts - 1) * 16 + dstPos >= 32) {
+ throw new IllegalArgumentException("(nShorts-1)*16+dstPos is greater or equal to than 32");
+ }
+ int out = dstInit;
+ for (int i = 0; i < nShorts; i++) {
+ final int shift = i * 16 + dstPos;
+ final int bits = (0xffff & src[i + srcPos]) << shift;
+ final int mask = 0xffff << shift;
+ out = (out & ~mask) | bits;
+ }
+ return out;
+ }
+
+ /**
+ * Converts an array of short into a long using the default (little endian, Lsb0) byte and
+ * bit ordering.
+ *
+ * @param src the short array to convert
+ * @param srcPos the position in {@code src}, in short unit, from where to start the
+ * conversion
+ * @param dstInit initial value of the destination long
+ * @param dstPos the position of the lsb, in bits, in the result long
+ * @param nShorts the number of shorts to convert
+ * @return a long containing the selected bits
+ * @throws NullPointerException if {@code src} is {@code null}
+ * @throws IllegalArgumentException if {@code (nShorts-1)*16+dstPos >= 64}
+ * @throws ArrayIndexOutOfBoundsException if {@code srcPos + nShorts > src.length}
+ */
+ public static long shortArrayToLong(final short[] src, final int srcPos, final long dstInit, final int dstPos,
+ final int nShorts) {
+ if (src.length == 0 && srcPos == 0 || 0 == nShorts) {
+ return dstInit;
+ }
+ if ((nShorts - 1) * 16 + dstPos >= 64) {
+ throw new IllegalArgumentException("(nShorts-1)*16+dstPos is greater or equal to than 64");
+ }
+ long out = dstInit;
+ for (int i = 0; i < nShorts; i++) {
+ final int shift = i * 16 + dstPos;
+ final long bits = (0xffffL & src[i + srcPos]) << shift;
+ final long mask = 0xffffL << shift;
+ out = (out & ~mask) | bits;
+ }
+ return out;
+ }
+
/**
* Converts a short into an array of boolean using the default (little endian, Lsb0) byte
* and bit ordering.
@@ -1415,35 +1396,72 @@ public class Conversion {
}
/**
- * Converts a byte into an array of boolean using the default (little endian, Lsb0) byte and
+ * Converts a short into an array of byte using the default (little endian, Lsb0) byte and
* bit ordering.
*
- * @param src the byte to convert
+ * @param src the short to convert
* @param srcPos the position in {@code src}, in bits, from where to start the conversion
* @param dst the destination array
* @param dstPos the position in {@code dst} where to copy the result
- * @param nBools the number of booleans to copy to {@code dst}, must be smaller or equal to
- * the width of the input (from srcPos to msb)
+ * @param nBytes the number of bytes to copy to {@code dst}, must be smaller or equal to the
+ * width of the input (from srcPos to msb)
* @return {@code dst}
* @throws NullPointerException if {@code dst} is {@code null}
- * @throws IllegalArgumentException if {@code nBools-1+srcPos >= 8}
- * @throws ArrayIndexOutOfBoundsException if {@code dstPos + nBools > dst.length}
+ * @throws IllegalArgumentException if {@code (nBytes-1)*8+srcPos >= 16}
+ * @throws ArrayIndexOutOfBoundsException if {@code dstPos + nBytes > dst.length}
*/
- public static boolean[] byteToBinary(final byte src, final int srcPos, final boolean[] dst, final int dstPos,
- final int nBools) {
- if (0 == nBools) {
+ public static byte[] shortToByteArray(final short src, final int srcPos, final byte[] dst, final int dstPos,
+ final int nBytes) {
+ if (0 == nBytes) {
return dst;
}
- if (nBools - 1 + srcPos >= 8) {
- throw new IllegalArgumentException("nBools-1+srcPos is greater or equal to than 8");
+ if ((nBytes - 1) * 8 + srcPos >= 16) {
+ throw new IllegalArgumentException("(nBytes-1)*8+srcPos is greater or equal to than 16");
}
- for (int i = 0; i < nBools; i++) {
- final int shift = i + srcPos;
- dst[dstPos + i] = (0x1 & (src >> shift)) != 0;
+ for (int i = 0; i < nBytes; i++) {
+ final int shift = i * 8 + srcPos;
+ dst[dstPos + i] = (byte) (0xff & (src >> shift));
}
return dst;
}
+ /**
+ * Converts a short into an array of Char using the default (little endian, Lsb0) byte and
+ * bit ordering.
+ *
+ * @param src the short to convert
+ * @param srcPos the position in {@code src}, in bits, from where to start the conversion
+ * @param dstInit the initial value for the result String
+ * @param dstPos the position in {@code dst} where to copy the result
+ * @param nHexs the number of Chars to copy to {@code dst}, must be smaller or equal to the
+ * width of the input (from srcPos to msb)
+ * @return {@code dst}
+ * @throws IllegalArgumentException if {@code (nHexs-1)*4+srcPos >= 16}
+ * @throws StringIndexOutOfBoundsException if {@code dst.init.length() < dstPos}
+ */
+ public static String shortToHex(final short src, final int srcPos, final String dstInit, final int dstPos,
+ final int nHexs) {
+ if (0 == nHexs) {
+ return dstInit;
+ }
+ if ((nHexs - 1) * 4 + srcPos >= 16) {
+ throw new IllegalArgumentException("(nHexs-1)*4+srcPos is greater or equal to than 16");
+ }
+ final StringBuilder sb = new StringBuilder(dstInit);
+ int append = sb.length();
+ for (int i = 0; i < nHexs; i++) {
+ final int shift = i * 4 + srcPos;
+ final int bits = 0xF & (src >> shift);
+ if (dstPos + i == append) {
+ ++append;
+ sb.append(intToHexDigit(bits));
+ } else {
+ sb.setCharAt(dstPos + i, intToHexDigit(bits));
+ }
+ }
+ return sb.toString();
+ }
+
/**
* Converts UUID into an array of byte using the default (little endian, Lsb0) byte and bit
* ordering.
@@ -1471,22 +1489,4 @@ public class Conversion {
}
return dst;
}
-
- /**
- * Converts bytes from an array into a UUID using the default (little endian, Lsb0) byte and
- * bit ordering.
- *
- * @param src the byte array to convert
- * @param srcPos the position in {@code src} where to copy the result from
- * @return a UUID
- * @throws NullPointerException if {@code src} is {@code null}
- * @throws IllegalArgumentException if array does not contain at least 16 bytes beginning
- * with {@code srcPos}
- */
- public static UUID byteArrayToUuid(final byte[] src, final int srcPos) {
- if (src.length - srcPos < 16) {
- throw new IllegalArgumentException("Need at least 16 bytes for UUID");
- }
- return new UUID(byteArrayToLong(src, srcPos, 0, 0, 8), byteArrayToLong(src, srcPos + 8, 0, 0, 8));
- }
}
diff --git a/src/main/java/org/apache/commons/lang3/JavaVersion.java b/src/main/java/org/apache/commons/lang3/JavaVersion.java
index d5deb6c2b..a0b828429 100644
--- a/src/main/java/org/apache/commons/lang3/JavaVersion.java
+++ b/src/main/java/org/apache/commons/lang3/JavaVersion.java
@@ -176,68 +176,6 @@ public enum JavaVersion {
*/
JAVA_RECENT(maxVersion(), Float.toString(maxVersion()));
- /**
- * The float value.
- */
- private final float value;
-
- /**
- * The standard name.
- */
- private final String name;
-
- /**
- * Constructor.
- *
- * @param value the float value
- * @param name the standard name, not null
- */
- JavaVersion(final float value, final String name) {
- this.value = value;
- this.name = name;
- }
-
- /**
- * Whether this version of Java is at least the version of Java passed in.
- *
- * <p>For example:<br>
- * {@code myVersion.atLeast(JavaVersion.JAVA_1_4)}</p>
- *
- * @param requiredVersion the version to check against, not null
- * @return true if this version is equal to or greater than the specified version
- */
- public boolean atLeast(final JavaVersion requiredVersion) {
- return this.value >= requiredVersion.value;
- }
-
- /**
- * Whether this version of Java is at most the version of Java passed in.
- *
- * <p>For example:<br>
- * {@code myVersion.atMost(JavaVersion.JAVA_1_4)}</p>
- *
- * @param requiredVersion the version to check against, not null
- * @return true if this version is equal to or greater than the specified version
- * @since 3.9
- */
- public boolean atMost(final JavaVersion requiredVersion) {
- return this.value <= requiredVersion.value;
- }
-
- /**
- * Transforms the given string with a Java version number to the
- * corresponding constant of this enumeration class. This method is used
- * internally.
- *
- * @param versionStr the Java version as string
- * @return the corresponding enumeration constant or <b>null</b> if the
- * version is unknown
- */
- // helper for static importing
- static JavaVersion getJavaVersion(final String versionStr) {
- return get(versionStr);
- }
-
/**
* Transforms the given string with a Java version number to the
* corresponding constant of this enumeration class. This method is used
@@ -312,15 +250,17 @@ public enum JavaVersion {
}
/**
- * The string value is overridden to return the standard name.
- *
- * <p>For example, {@code "1.5"}.</p>
+ * Transforms the given string with a Java version number to the
+ * corresponding constant of this enumeration class. This method is used
+ * internally.
*
- * @return the name, not null
+ * @param versionStr the Java version as string
+ * @return the corresponding enumeration constant or <b>null</b> if the
+ * version is unknown
*/
- @Override
- public String toString() {
- return name;
+ // helper for static importing
+ static JavaVersion getJavaVersion(final String versionStr) {
+ return get(versionStr);
}
/**
@@ -350,4 +290,64 @@ public enum JavaVersion {
}
return defaultReturnValue;
}
+
+ /**
+ * The float value.
+ */
+ private final float value;
+
+ /**
+ * The standard name.
+ */
+ private final String name;
+
+ /**
+ * Constructor.
+ *
+ * @param value the float value
+ * @param name the standard name, not null
+ */
+ JavaVersion(final float value, final String name) {
+ this.value = value;
+ this.name = name;
+ }
+
+ /**
+ * Whether this version of Java is at least the version of Java passed in.
+ *
+ * <p>For example:<br>
+ * {@code myVersion.atLeast(JavaVersion.JAVA_1_4)}</p>
+ *
+ * @param requiredVersion the version to check against, not null
+ * @return true if this version is equal to or greater than the specified version
+ */
+ public boolean atLeast(final JavaVersion requiredVersion) {
+ return this.value >= requiredVersion.value;
+ }
+
+ /**
+ * Whether this version of Java is at most the version of Java passed in.
+ *
+ * <p>For example:<br>
+ * {@code myVersion.atMost(JavaVersion.JAVA_1_4)}</p>
+ *
+ * @param requiredVersion the version to check against, not null
+ * @return true if this version is equal to or greater than the specified version
+ * @since 3.9
+ */
+ public boolean atMost(final JavaVersion requiredVersion) {
+ return this.value <= requiredVersion.value;
+ }
+
+ /**
+ * The string value is overridden to return the standard name.
+ *
+ * <p>For example, {@code "1.5"}.</p>
+ *
+ * @return the name, not null
+ */
+ @Override
+ public String toString() {
+ return name;
+ }
}
diff --git a/src/main/java/org/apache/commons/lang3/LocaleUtils.java b/src/main/java/org/apache/commons/lang3/LocaleUtils.java
index 0e65b8425..93f81685b 100644
--- a/src/main/java/org/apache/commons/lang3/LocaleUtils.java
+++ b/src/main/java/org/apache/commons/lang3/LocaleUtils.java
@@ -39,10 +39,6 @@ import java.util.stream.Collectors;
*/
public class LocaleUtils {
- private static final char UNDERSCORE = '_';
- private static final String UNDETERMINED = "und";
- private static final char DASH = '-';
-
// class to avoid synchronization (Init on demand)
static class SyncAvoid {
/** Unmodifiable list of available locales. */
@@ -56,6 +52,10 @@ public class LocaleUtils {
AVAILABLE_LOCALE_SET = Collections.unmodifiableSet(new HashSet<>(list));
}
}
+ private static final char UNDERSCORE = '_';
+ private static final String UNDETERMINED = "und";
+
+ private static final char DASH = '-';
/** Concurrent map of language locales by country. */
private static final ConcurrentMap<String, List<Locale>> cLanguagesByCountry =
diff --git a/src/main/java/org/apache/commons/lang3/NotImplementedException.java b/src/main/java/org/apache/commons/lang3/NotImplementedException.java
index 783b8a259..7317a4071 100644
--- a/src/main/java/org/apache/commons/lang3/NotImplementedException.java
+++ b/src/main/java/org/apache/commons/lang3/NotImplementedException.java
@@ -69,11 +69,13 @@ public class NotImplementedException extends UnsupportedOperationException {
/**
* Constructs a NotImplementedException.
*
- * @param cause cause of the exception
+ * @param message description of the exception
+ * @param code code indicating a resource for more information regarding the lack of implementation
* @since 3.2
*/
- public NotImplementedException(final Throwable cause) {
- this(cause, null);
+ public NotImplementedException(final String message, final String code) {
+ super(message);
+ this.code = code;
}
/**
@@ -91,11 +93,12 @@ public class NotImplementedException extends UnsupportedOperationException {
* Constructs a NotImplementedException.
*
* @param message description of the exception
+ * @param cause cause of the exception
* @param code code indicating a resource for more information regarding the lack of implementation
* @since 3.2
*/
- public NotImplementedException(final String message, final String code) {
- super(message);
+ public NotImplementedException(final String message, final Throwable cause, final String code) {
+ super(message, cause);
this.code = code;
}
@@ -103,24 +106,21 @@ public class NotImplementedException extends UnsupportedOperationException {
* Constructs a NotImplementedException.
*
* @param cause cause of the exception
- * @param code code indicating a resource for more information regarding the lack of implementation
* @since 3.2
*/
- public NotImplementedException(final Throwable cause, final String code) {
- super(cause);
- this.code = code;
+ public NotImplementedException(final Throwable cause) {
+ this(cause, null);
}
/**
* Constructs a NotImplementedException.
*
- * @param message description of the exception
* @param cause cause of the exception
* @param code code indicating a resource for more information regarding the lack of implementation
* @since 3.2
*/
- public NotImplementedException(final String message, final Throwable cause, final String code) {
- super(message, cause);
+ public NotImplementedException(final Throwable cause, final String code) {
+ super(cause);
this.code = code;
}
diff --git a/src/main/java/org/apache/commons/lang3/ObjectUtils.java b/src/main/java/org/apache/commons/lang3/ObjectUtils.java
index 2e5a6c4db..67d6d2cf9 100644
--- a/src/main/java/org/apache/commons/lang3/ObjectUtils.java
+++ b/src/main/java/org/apache/commons/lang3/ObjectUtils.java
@@ -1334,52 +1334,52 @@ public class ObjectUtils {
}
/**
- * Gets the {@code toString} of an {@link Object} returning
+ * Gets the {@code toString} of an {@link Supplier}'s {@link Supplier#get()} returning
* a specified text if {@code null} input.
*
* <pre>
- * ObjectUtils.toString(obj, () -> expensive())
+ * ObjectUtils.toString(() -> obj, () -> expensive())
* </pre>
* <pre>
- * ObjectUtils.toString(null, () -> expensive()) = result of expensive()
- * ObjectUtils.toString(null, () -> expensive()) = result of expensive()
- * ObjectUtils.toString("", () -> expensive()) = ""
- * ObjectUtils.toString("bat", () -> expensive()) = "bat"
- * ObjectUtils.toString(Boolean.TRUE, () -> expensive()) = "true"
+ * ObjectUtils.toString(() -> null, () -> expensive()) = result of expensive()
+ * ObjectUtils.toString(() -> null, () -> expensive()) = result of expensive()
+ * ObjectUtils.toString(() -> "", () -> expensive()) = ""
+ * ObjectUtils.toString(() -> "bat", () -> expensive()) = "bat"
+ * ObjectUtils.toString(() -> Boolean.TRUE, () -> expensive()) = "true"
* </pre>
*
- * @param <T> the obj type (used to provide better source compatibility in 3.14.0).
* @param obj the Object to {@code toString}, may be null
* @param supplier the Supplier of String used on {@code null} input, may be null
* @return the passed in Object's toString, or {@code nullStr} if {@code null} input
- * @since 3.11
+ * @since 3.14.0
*/
- public static <T> String toString(final T obj, final Supplier<String> supplier) {
- return obj == null ? Suppliers.get(supplier) : obj.toString();
+ public static String toString(final Supplier<Object> obj, final Supplier<String> supplier) {
+ return obj == null ? Suppliers.get(supplier) : toString(obj.get(), supplier);
}
/**
- * Gets the {@code toString} of an {@link Supplier}'s {@link Supplier#get()} returning
+ * Gets the {@code toString} of an {@link Object} returning
* a specified text if {@code null} input.
*
* <pre>
- * ObjectUtils.toString(() -> obj, () -> expensive())
+ * ObjectUtils.toString(obj, () -> expensive())
* </pre>
* <pre>
- * ObjectUtils.toString(() -> null, () -> expensive()) = result of expensive()
- * ObjectUtils.toString(() -> null, () -> expensive()) = result of expensive()
- * ObjectUtils.toString(() -> "", () -> expensive()) = ""
- * ObjectUtils.toString(() -> "bat", () -> expensive()) = "bat"
- * ObjectUtils.toString(() -> Boolean.TRUE, () -> expensive()) = "true"
+ * ObjectUtils.toString(null, () -> expensive()) = result of expensive()
+ * ObjectUtils.toString(null, () -> expensive()) = result of expensive()
+ * ObjectUtils.toString("", () -> expensive()) = ""
+ * ObjectUtils.toString("bat", () -> expensive()) = "bat"
+ * ObjectUtils.toString(Boolean.TRUE, () -> expensive()) = "true"
* </pre>
*
+ * @param <T> the obj type (used to provide better source compatibility in 3.14.0).
* @param obj the Object to {@code toString}, may be null
* @param supplier the Supplier of String used on {@code null} input, may be null
* @return the passed in Object's toString, or {@code nullStr} if {@code null} input
- * @since 3.14.0
+ * @since 3.11
*/
- public static String toString(final Supplier<Object> obj, final Supplier<String> supplier) {
- return obj == null ? Suppliers.get(supplier) : toString(obj.get(), supplier);
+ public static <T> String toString(final T obj, final Supplier<String> supplier) {
+ return obj == null ? Suppliers.get(supplier) : obj.toString();
}
/**
diff --git a/src/main/java/org/apache/commons/lang3/SerializationException.java b/src/main/java/org/apache/commons/lang3/SerializationException.java
index c68787312..a51ecf6fc 100644
--- a/src/main/java/org/apache/commons/lang3/SerializationException.java
+++ b/src/main/java/org/apache/commons/lang3/SerializationException.java
@@ -52,25 +52,25 @@ public class SerializationException extends RuntimeException {
/**
* Constructs a new {@link SerializationException} with specified
- * nested {@link Throwable}.
+ * detail message and nested {@link Throwable}.
*
+ * @param msg The error message.
* @param cause The {@link Exception} or {@link Error}
* that caused this exception to be thrown.
*/
- public SerializationException(final Throwable cause) {
- super(cause);
+ public SerializationException(final String msg, final Throwable cause) {
+ super(msg, cause);
}
/**
* Constructs a new {@link SerializationException} with specified
- * detail message and nested {@link Throwable}.
+ * nested {@link Throwable}.
*
- * @param msg The error message.
* @param cause The {@link Exception} or {@link Error}
* that caused this exception to be thrown.
*/
- public SerializationException(final String msg, final Throwable cause) {
- super(msg, cause);
+ public SerializationException(final Throwable cause) {
+ super(cause);
}
}
diff --git a/src/main/java/org/apache/commons/lang3/Streams.java b/src/main/java/org/apache/commons/lang3/Streams.java
index 2a9201d75..84ffef643 100644
--- a/src/main/java/org/apache/commons/lang3/Streams.java
+++ b/src/main/java/org/apache/commons/lang3/Streams.java
@@ -66,6 +66,55 @@ import org.apache.commons.lang3.Functions.FailablePredicate;
@Deprecated
public class Streams {
+ /**
+ * A Collector type for arrays.
+ *
+ * @param <O> The array type.
+ * @deprecated Use {@link org.apache.commons.lang3.stream.Streams.ArrayCollector}.
+ */
+ @Deprecated
+ public static class ArrayCollector<O> implements Collector<O, List<O>, O[]> {
+ private static final Set<Characteristics> characteristics = Collections.emptySet();
+ private final Class<O> elementType;
+
+ /**
+ * Constructs a new instance for the given element type.
+ *
+ * @param elementType The element type.
+ */
+ public ArrayCollector(final Class<O> elementType) {
+ this.elementType = elementType;
+ }
+
+ @Override
+ public BiConsumer<List<O>, O> accumulator() {
+ return List::add;
+ }
+
+ @Override
+ public Set<Characteristics> characteristics() {
+ return characteristics;
+ }
+
+ @Override
+ public BinaryOperator<List<O>> combiner() {
+ return (left, right) -> {
+ left.addAll(right);
+ return left;
+ };
+ }
+
+ @Override
+ public Function<List<O>, O[]> finisher() {
+ return list -> list.toArray(ArrayUtils.newInstance(elementType, list.size()));
+ }
+
+ @Override
+ public Supplier<List<O>> supplier() {
+ return ArrayList::new;
+ }
+ }
+
/**
* A reduced, and simplified version of a {@link Stream} with
* failable method signatures.
@@ -87,66 +136,66 @@ public class Streams {
}
/**
- * Throws IllegalStateException if this stream is already terminated.
+ * Returns whether all elements of this stream match the provided predicate.
+ * May not evaluate the predicate on all elements if not necessary for
+ * determining the result. If the stream is empty then {@code true} is
+ * returned and the predicate is not evaluated.
*
- * @throws IllegalStateException if this stream is already terminated.
- */
- protected void assertNotTerminated() {
- if (terminated) {
- throw new IllegalStateException("This stream is already terminated.");
- }
- }
-
- /**
- * Marks this stream as terminated.
+ * <p>
+ * This is a short-circuiting terminal operation.
+ * </p>
*
- * @throws IllegalStateException if this stream is already terminated.
+ * <p>
+ * Note
+ * This method evaluates the <em>universal quantification</em> of the
+ * predicate over the elements of the stream (for all x P(x)). If the
+ * stream is empty, the quantification is said to be <em>vacuously
+ * satisfied</em> and is always {@code true} (regardless of P(x)).
+ * </p>
+ *
+ * @param predicate A non-interfering, stateless predicate to apply to
+ * elements of this stream
+ * @return {@code true} If either all elements of the stream match the
+ * provided predicate or the stream is empty, otherwise {@code false}.
*/
- protected void makeTerminated() {
+ public boolean allMatch(final FailablePredicate<O, ?> predicate) {
assertNotTerminated();
- terminated = true;
+ return stream().allMatch(Functions.asPredicate(predicate));
}
/**
- * Returns a FailableStream consisting of the elements of this stream that match
- * the given FailablePredicate.
+ * Returns whether any elements of this stream match the provided
+ * predicate. May not evaluate the predicate on all elements if not
+ * necessary for determining the result. If the stream is empty then
+ * {@code false} is returned and the predicate is not evaluated.
*
* <p>
- * This is an intermediate operation.
+ * This is a short-circuiting terminal operation.
* </p>
*
- * @param predicate a non-interfering, stateless predicate to apply to each
- * element to determine if it should be included.
- * @return the new stream
+ * Note
+ * This method evaluates the <em>existential quantification</em> of the
+ * predicate over the elements of the stream (for some x P(x)).
+ *
+ * @param predicate A non-interfering, stateless predicate to apply to
+ * elements of this stream
+ * @return {@code true} if any elements of the stream match the provided
+ * predicate, otherwise {@code false}
*/
- public FailableStream<O> filter(final FailablePredicate<O, ?> predicate){
+ public boolean anyMatch(final FailablePredicate<O, ?> predicate) {
assertNotTerminated();
- stream = stream.filter(Functions.asPredicate(predicate));
- return this;
+ return stream().anyMatch(Functions.asPredicate(predicate));
}
/**
- * Performs an action for each element of this stream.
- *
- * <p>
- * This is an intermediate operation.
- * </p>
- *
- * <p>
- * The behavior of this operation is explicitly nondeterministic.
- * For parallel stream pipelines, this operation does <em>not</em>
- * guarantee to respect the encounter order of the stream, as doing so
- * would sacrifice the benefit of parallelism. For any given element, the
- * action may be performed at whatever time and in whatever thread the
- * library chooses. If the action accesses shared state, it is
- * responsible for providing the required synchronization.
- * </p>
+ * Throws IllegalStateException if this stream is already terminated.
*
- * @param action a non-interfering action to perform on the elements
+ * @throws IllegalStateException if this stream is already terminated.
*/
- public void forEach(final FailableConsumer<O, ?> action) {
- makeTerminated();
- stream().forEach(Functions.asConsumer(action));
+ protected void assertNotTerminated() {
+ if (terminated) {
+ throw new IllegalStateException("This stream is already terminated.");
+ }
}
/**
@@ -271,6 +320,75 @@ public class Streams {
return stream().collect(supplier, accumulator, combiner);
}
+ /**
+ * Returns a FailableStream consisting of the elements of this stream that match
+ * the given FailablePredicate.
+ *
+ * <p>
+ * This is an intermediate operation.
+ * </p>
+ *
+ * @param predicate a non-interfering, stateless predicate to apply to each
+ * element to determine if it should be included.
+ * @return the new stream
+ */
+ public FailableStream<O> filter(final FailablePredicate<O, ?> predicate){
+ assertNotTerminated();
+ stream = stream.filter(Functions.asPredicate(predicate));
+ return this;
+ }
+
+ /**
+ * Performs an action for each element of this stream.
+ *
+ * <p>
+ * This is an intermediate operation.
+ * </p>
+ *
+ * <p>
+ * The behavior of this operation is explicitly nondeterministic.
+ * For parallel stream pipelines, this operation does <em>not</em>
+ * guarantee to respect the encounter order of the stream, as doing so
+ * would sacrifice the benefit of parallelism. For any given element, the
+ * action may be performed at whatever time and in whatever thread the
+ * library chooses. If the action accesses shared state, it is
+ * responsible for providing the required synchronization.
+ * </p>
+ *
+ * @param action a non-interfering action to perform on the elements
+ */
+ public void forEach(final FailableConsumer<O, ?> action) {
+ makeTerminated();
+ stream().forEach(Functions.asConsumer(action));
+ }
+
+ /**
+ * Marks this stream as terminated.
+ *
+ * @throws IllegalStateException if this stream is already terminated.
+ */
+ protected void makeTerminated() {
+ assertNotTerminated();
+ terminated = true;
+ }
+
+ /**
+ * Returns a stream consisting of the results of applying the given
+ * function to the elements of this stream.
+ *
+ * <p>
+ * This is an intermediate operation.
+ * </p>
+ *
+ * @param <R> The element type of the new stream
+ * @param mapper A non-interfering, stateless function to apply to each element
+ * @return the new stream
+ */
+ public <R> FailableStream<R> map(final FailableFunction<O, R, ?> mapper) {
+ assertNotTerminated();
+ return new FailableStream<>(stream.map(Functions.asFunction(mapper)));
+ }
+
/**
* Performs a reduction on the elements of this stream, using the provided
* identity value and an associative accumulation function, and returns
@@ -325,23 +443,6 @@ public class Streams {
return stream().reduce(identity, accumulator);
}
- /**
- * Returns a stream consisting of the results of applying the given
- * function to the elements of this stream.
- *
- * <p>
- * This is an intermediate operation.
- * </p>
- *
- * @param <R> The element type of the new stream
- * @param mapper A non-interfering, stateless function to apply to each element
- * @return the new stream
- */
- public <R> FailableStream<R> map(final FailableFunction<O, R, ?> mapper) {
- assertNotTerminated();
- return new FailableStream<>(stream.map(Functions.asFunction(mapper)));
- }
-
/**
* Converts the FailableStream into an equivalent stream.
* @return A stream, which will return the same elements, which this FailableStream would return.
@@ -349,62 +450,10 @@ public class Streams {
public Stream<O> stream() {
return stream;
}
-
- /**
- * Returns whether all elements of this stream match the provided predicate.
- * May not evaluate the predicate on all elements if not necessary for
- * determining the result. If the stream is empty then {@code true} is
- * returned and the predicate is not evaluated.
- *
- * <p>
- * This is a short-circuiting terminal operation.
- * </p>
- *
- * <p>
- * Note
- * This method evaluates the <em>universal quantification</em> of the
- * predicate over the elements of the stream (for all x P(x)). If the
- * stream is empty, the quantification is said to be <em>vacuously
- * satisfied</em> and is always {@code true} (regardless of P(x)).
- * </p>
- *
- * @param predicate A non-interfering, stateless predicate to apply to
- * elements of this stream
- * @return {@code true} If either all elements of the stream match the
- * provided predicate or the stream is empty, otherwise {@code false}.
- */
- public boolean allMatch(final FailablePredicate<O, ?> predicate) {
- assertNotTerminated();
- return stream().allMatch(Functions.asPredicate(predicate));
- }
-
- /**
- * Returns whether any elements of this stream match the provided
- * predicate. May not evaluate the predicate on all elements if not
- * necessary for determining the result. If the stream is empty then
- * {@code false} is returned and the predicate is not evaluated.
- *
- * <p>
- * This is a short-circuiting terminal operation.
- * </p>
- *
- * Note
- * This method evaluates the <em>existential quantification</em> of the
- * predicate over the elements of the stream (for some x P(x)).
- *
- * @param predicate A non-interfering, stateless predicate to apply to
- * elements of this stream
- * @return {@code true} if any elements of the stream match the provided
- * predicate, otherwise {@code false}
- */
- public boolean anyMatch(final FailablePredicate<O, ?> predicate) {
- assertNotTerminated();
- return stream().anyMatch(Functions.asPredicate(predicate));
- }
}
/**
- * Converts the given {@link Stream stream} into a {@link FailableStream}.
+ * Converts the given {@link Collection} into a {@link FailableStream}.
* This is basically a simplified, reduced version of the {@link Stream}
* class, with the same underlying element stream, except that failable
* objects, like {@link FailablePredicate}, {@link FailableFunction}, or
@@ -441,12 +490,12 @@ public class Streams {
* @return The {@link FailableStream}, which has been created by
* converting the stream.
*/
- public static <O> FailableStream<O> stream(final Stream<O> stream) {
- return new FailableStream<>(stream);
+ public static <O> FailableStream<O> stream(final Collection<O> stream) {
+ return stream(stream.stream());
}
/**
- * Converts the given {@link Collection} into a {@link FailableStream}.
+ * Converts the given {@link Stream stream} into a {@link FailableStream}.
* This is basically a simplified, reduced version of the {@link Stream}
* class, with the same underlying element stream, except that failable
* objects, like {@link FailablePredicate}, {@link FailableFunction}, or
@@ -483,57 +532,8 @@ public class Streams {
* @return The {@link FailableStream}, which has been created by
* converting the stream.
*/
- public static <O> FailableStream<O> stream(final Collection<O> stream) {
- return stream(stream.stream());
- }
-
- /**
- * A Collector type for arrays.
- *
- * @param <O> The array type.
- * @deprecated Use {@link org.apache.commons.lang3.stream.Streams.ArrayCollector}.
- */
- @Deprecated
- public static class ArrayCollector<O> implements Collector<O, List<O>, O[]> {
- private static final Set<Characteristics> characteristics = Collections.emptySet();
- private final Class<O> elementType;
-
- /**
- * Constructs a new instance for the given element type.
- *
- * @param elementType The element type.
- */
- public ArrayCollector(final Class<O> elementType) {
- this.elementType = elementType;
- }
-
- @Override
- public Supplier<List<O>> supplier() {
- return ArrayList::new;
- }
-
- @Override
- public BiConsumer<List<O>, O> accumulator() {
- return List::add;
- }
-
- @Override
- public BinaryOperator<List<O>> combiner() {
- return (left, right) -> {
- left.addAll(right);
- return left;
- };
- }
-
- @Override
- public Function<List<O>, O[]> finisher() {
- return list -> list.toArray(ArrayUtils.newInstance(elementType, list.size()));
- }
-
- @Override
- public Set<Characteristics> characteristics() {
- return characteristics;
- }
+ public static <O> FailableStream<O> stream(final Stream<O> stream) {
+ return new FailableStream<>(stream);
}
/**
diff --git a/src/main/java/org/apache/commons/lang3/StringEscapeUtils.java b/src/main/java/org/apache/commons/lang3/StringEscapeUtils.java
index 2aee2ca52..96bba1866 100644
--- a/src/main/java/org/apache/commons/lang3/StringEscapeUtils.java
+++ b/src/main/java/org/apache/commons/lang3/StringEscapeUtils.java
@@ -45,6 +45,66 @@ public class StringEscapeUtils {
/* ESCAPE TRANSLATORS */
+ // TODO: Create a parent class - 'SinglePassTranslator' ?
+ // It would handle the index checking + length returning,
+ // and could also have an optimization check method.
+ static class CsvEscaper extends CharSequenceTranslator {
+
+ private static final char CSV_DELIMITER = ',';
+ private static final char CSV_QUOTE = '"';
+ private static final String CSV_QUOTE_STR = String.valueOf(CSV_QUOTE);
+ private static final char[] CSV_SEARCH_CHARS = { CSV_DELIMITER, CSV_QUOTE, CharUtils.CR, CharUtils.LF };
+
+ @Override
+ public int translate(final CharSequence input, final int index, final Writer out) throws IOException {
+
+ if (index != 0) {
+ throw new IllegalStateException("CsvEscaper should never reach the [1] index");
+ }
+
+ if (StringUtils.containsNone(input.toString(), CSV_SEARCH_CHARS)) {
+ out.write(input.toString());
+ } else {
+ out.write(CSV_QUOTE);
+ out.write(StringUtils.replace(input.toString(), CSV_QUOTE_STR, CSV_QUOTE_STR + CSV_QUOTE_STR));
+ out.write(CSV_QUOTE);
+ }
+ return Character.codePointCount(input, 0, input.length());
+ }
+ }
+
+ static class CsvUnescaper extends CharSequenceTranslator {
+
+ private static final char CSV_DELIMITER = ',';
+ private static final char CSV_QUOTE = '"';
+ private static final String CSV_QUOTE_STR = String.valueOf(CSV_QUOTE);
+ private static final char[] CSV_SEARCH_CHARS = {CSV_DELIMITER, CSV_QUOTE, CharUtils.CR, CharUtils.LF};
+
+ @Override
+ public int translate(final CharSequence input, final int index, final Writer out) throws IOException {
+
+ if (index != 0) {
+ throw new IllegalStateException("CsvUnescaper should never reach the [1] index");
+ }
+
+ if ( input.charAt(0) != CSV_QUOTE || input.charAt(input.length() - 1) != CSV_QUOTE ) {
+ out.write(input.toString());
+ return Character.codePointCount(input, 0, input.length());
+ }
+
+ // strip quotes
+ final String quoteless = input.subSequence(1, input.length() - 1).toString();
+
+ if ( StringUtils.containsAny(quoteless, CSV_SEARCH_CHARS) ) {
+ // deal with escaped quotes; ie) ""
+ out.write(StringUtils.replace(quoteless, CSV_QUOTE_STR + CSV_QUOTE_STR, CSV_QUOTE_STR));
+ } else {
+ out.write(input.toString());
+ }
+ return Character.codePointCount(input, 0, input.length());
+ }
+ }
+
/**
* Translator object for escaping Java.
*
@@ -236,6 +296,8 @@ public class StringEscapeUtils {
new LookupTranslator(EntityArrays.HTML40_EXTENDED_ESCAPE())
);
+ /* UNESCAPE TRANSLATORS */
+
/**
* Translator object for escaping individual Comma Separated Values.
*
@@ -247,36 +309,6 @@ public class StringEscapeUtils {
*/
public static final CharSequenceTranslator ESCAPE_CSV = new CsvEscaper();
- // TODO: Create a parent class - 'SinglePassTranslator' ?
- // It would handle the index checking + length returning,
- // and could also have an optimization check method.
- static class CsvEscaper extends CharSequenceTranslator {
-
- private static final char CSV_DELIMITER = ',';
- private static final char CSV_QUOTE = '"';
- private static final String CSV_QUOTE_STR = String.valueOf(CSV_QUOTE);
- private static final char[] CSV_SEARCH_CHARS = { CSV_DELIMITER, CSV_QUOTE, CharUtils.CR, CharUtils.LF };
-
- @Override
- public int translate(final CharSequence input, final int index, final Writer out) throws IOException {
-
- if (index != 0) {
- throw new IllegalStateException("CsvEscaper should never reach the [1] index");
- }
-
- if (StringUtils.containsNone(input.toString(), CSV_SEARCH_CHARS)) {
- out.write(input.toString());
- } else {
- out.write(CSV_QUOTE);
- out.write(StringUtils.replace(input.toString(), CSV_QUOTE_STR, CSV_QUOTE_STR + CSV_QUOTE_STR));
- out.write(CSV_QUOTE);
- }
- return Character.codePointCount(input, 0, input.length());
- }
- }
-
- /* UNESCAPE TRANSLATORS */
-
/**
* Translator object for unescaping escaped Java.
*
@@ -383,75 +415,30 @@ public class StringEscapeUtils {
*/
public static final CharSequenceTranslator UNESCAPE_CSV = new CsvUnescaper();
- static class CsvUnescaper extends CharSequenceTranslator {
-
- private static final char CSV_DELIMITER = ',';
- private static final char CSV_QUOTE = '"';
- private static final String CSV_QUOTE_STR = String.valueOf(CSV_QUOTE);
- private static final char[] CSV_SEARCH_CHARS = {CSV_DELIMITER, CSV_QUOTE, CharUtils.CR, CharUtils.LF};
-
- @Override
- public int translate(final CharSequence input, final int index, final Writer out) throws IOException {
-
- if (index != 0) {
- throw new IllegalStateException("CsvUnescaper should never reach the [1] index");
- }
-
- if ( input.charAt(0) != CSV_QUOTE || input.charAt(input.length() - 1) != CSV_QUOTE ) {
- out.write(input.toString());
- return Character.codePointCount(input, 0, input.length());
- }
-
- // strip quotes
- final String quoteless = input.subSequence(1, input.length() - 1).toString();
-
- if ( StringUtils.containsAny(quoteless, CSV_SEARCH_CHARS) ) {
- // deal with escaped quotes; ie) ""
- out.write(StringUtils.replace(quoteless, CSV_QUOTE_STR + CSV_QUOTE_STR, CSV_QUOTE_STR));
- } else {
- out.write(input.toString());
- }
- return Character.codePointCount(input, 0, input.length());
- }
- }
-
/* Helper functions */
/**
- * {@link StringEscapeUtils} instances should NOT be constructed in
- * standard programming.
- *
- * <p>Instead, the class should be used as:</p>
- * <pre>StringEscapeUtils.escapeJava("foo");</pre>
- *
- * <p>This constructor is public to permit tools that require a JavaBean
- * instance to operate.</p>
- */
- public StringEscapeUtils() {
- }
-
- /**
- * Escapes the characters in a {@link String} using Java String rules.
+ * Returns a {@link String} value for a CSV column enclosed in double quotes,
+ * if required.
*
- * <p>Deals correctly with quotes and control-chars (tab, backslash, cr, ff, etc.) </p>
+ * <p>If the value contains a comma, newline or double quote, then the
+ * String value is returned enclosed in double quotes.</p>
*
- * <p>So a tab becomes the characters {@code '\\'} and
- * {@code 't'}.</p>
+ * <p>Any double quote characters in the value are escaped with another double quote.</p>
*
- * <p>The only difference between Java strings and JavaScript strings
- * is that in JavaScript, a single quote and forward-slash (/) are escaped.</p>
+ * <p>If the value does not contain a comma, newline or double quote, then the
+ * String value is returned unchanged.</p>
*
- * <p>Example:</p>
- * <pre>
- * input string: He didn't say, "Stop!"
- * output string: He didn't say, \"Stop!\"
- * </pre>
+ * see <a href="https://en.wikipedia.org/wiki/Comma-separated_values">Wikipedia</a> and
+ * <a href="https://datatracker.ietf.org/doc/html/rfc4180">RFC 4180</a>.
*
- * @param input String to escape values in, may be null
- * @return String with escaped values, {@code null} if null string input
+ * @param input the input CSV column String, may be null
+ * @return the input String, enclosed in double quotes if the value contains a comma,
+ * newline or double quote, {@code null} if null string input
+ * @since 2.4
*/
- public static final String escapeJava(final String input) {
- return ESCAPE_JAVA.translate(input);
+ public static final String escapeCsv(final String input) {
+ return ESCAPE_CSV.translate(input);
}
/**
@@ -483,78 +470,16 @@ public class StringEscapeUtils {
}
/**
- * Escapes the characters in a {@link String} using Json String rules.
- * <p>Escapes any values it finds into their Json String form.
- * Deals correctly with quotes and control-chars (tab, backslash, cr, ff, etc.) </p>
- *
- * <p>So a tab becomes the characters {@code '\\'} and
- * {@code 't'}.</p>
- *
- * <p>The only difference between Java strings and Json strings
- * is that in Json, forward-slash (/) is escaped.</p>
- *
- * <p>See https://www.ietf.org/rfc/rfc4627.txt for further details.</p>
- *
- * <p>Example:</p>
- * <pre>
- * input string: He didn't say, "Stop!"
- * output string: He didn't say, \"Stop!\"
- * </pre>
- *
- * @param input String to escape values in, may be null
- * @return String with escaped values, {@code null} if null string input
- *
- * @since 3.2
- */
- public static final String escapeJson(final String input) {
- return ESCAPE_JSON.translate(input);
- }
-
- /**
- * Unescapes any Java literals found in the {@link String}.
- * For example, it will turn a sequence of {@code '\'} and
- * {@code 'n'} into a newline character, unless the {@code '\'}
- * is preceded by another {@code '\'}.
- *
- * @param input the {@link String} to unescape, may be null
- * @return a new unescaped {@link String}, {@code null} if null string input
- */
- public static final String unescapeJava(final String input) {
- return UNESCAPE_JAVA.translate(input);
- }
-
- /**
- * Unescapes any EcmaScript literals found in the {@link String}.
- *
- * <p>For example, it will turn a sequence of {@code '\'} and {@code 'n'}
- * into a newline character, unless the {@code '\'} is preceded by another
- * {@code '\'}.</p>
+ * Escapes the characters in a {@link String} using HTML entities.
+ * <p>Supports only the HTML 3.0 entities.</p>
*
- * @see #unescapeJava(String)
- * @param input the {@link String} to unescape, may be null
- * @return A new unescaped {@link String}, {@code null} if null string input
+ * @param input the {@link String} to escape, may be null
+ * @return a new escaped {@link String}, {@code null} if null string input
*
* @since 3.0
*/
- public static final String unescapeEcmaScript(final String input) {
- return UNESCAPE_ECMASCRIPT.translate(input);
- }
-
- /**
- * Unescapes any Json literals found in the {@link String}.
- *
- * <p>For example, it will turn a sequence of {@code '\'} and {@code 'n'}
- * into a newline character, unless the {@code '\'} is preceded by another
- * {@code '\'}.</p>
- *
- * @see #unescapeJava(String)
- * @param input the {@link String} to unescape, may be null
- * @return A new unescaped {@link String}, {@code null} if null string input
- *
- * @since 3.2
- */
- public static final String unescapeJson(final String input) {
- return UNESCAPE_JSON.translate(input);
+ public static final String escapeHtml3(final String input) {
+ return ESCAPE_HTML3.translate(input);
}
/**
@@ -589,51 +514,55 @@ public class StringEscapeUtils {
}
/**
- * Escapes the characters in a {@link String} using HTML entities.
- * <p>Supports only the HTML 3.0 entities.</p>
+ * Escapes the characters in a {@link String} using Java String rules.
*
- * @param input the {@link String} to escape, may be null
- * @return a new escaped {@link String}, {@code null} if null string input
+ * <p>Deals correctly with quotes and control-chars (tab, backslash, cr, ff, etc.) </p>
*
- * @since 3.0
+ * <p>So a tab becomes the characters {@code '\\'} and
+ * {@code 't'}.</p>
+ *
+ * <p>The only difference between Java strings and JavaScript strings
+ * is that in JavaScript, a single quote and forward-slash (/) are escaped.</p>
+ *
+ * <p>Example:</p>
+ * <pre>
+ * input string: He didn't say, "Stop!"
+ * output string: He didn't say, \"Stop!\"
+ * </pre>
+ *
+ * @param input String to escape values in, may be null
+ * @return String with escaped values, {@code null} if null string input
*/
- public static final String escapeHtml3(final String input) {
- return ESCAPE_HTML3.translate(input);
+ public static final String escapeJava(final String input) {
+ return ESCAPE_JAVA.translate(input);
}
/**
- * Unescapes a string containing entity escapes to a string
- * containing the actual Unicode characters corresponding to the
- * escapes. Supports HTML 4.0 entities.
+ * Escapes the characters in a {@link String} using Json String rules.
+ * <p>Escapes any values it finds into their Json String form.
+ * Deals correctly with quotes and control-chars (tab, backslash, cr, ff, etc.) </p>
*
- * <p>For example, the string {@code "<Français>"}
- * will become {@code "<Français>"}</p>
+ * <p>So a tab becomes the characters {@code '\\'} and
+ * {@code 't'}.</p>
*
- * <p>If an entity is unrecognized, it is left alone, and inserted
- * verbatim into the result string. e.g. {@code ">&zzzz;x"} will
- * become {@code ">&zzzz;x"}.</p>
+ * <p>The only difference between Java strings and Json strings
+ * is that in Json, forward-slash (/) is escaped.</p>
*
- * @param input the {@link String} to unescape, may be null
- * @return a new unescaped {@link String}, {@code null} if null string input
+ * <p>See https://www.ietf.org/rfc/rfc4627.txt for further details.</p>
*
- * @since 3.0
- */
- public static final String unescapeHtml4(final String input) {
- return UNESCAPE_HTML4.translate(input);
- }
-
- /**
- * Unescapes a string containing entity escapes to a string
- * containing the actual Unicode characters corresponding to the
- * escapes. Supports only HTML 3.0 entities.
+ * <p>Example:</p>
+ * <pre>
+ * input string: He didn't say, "Stop!"
+ * output string: He didn't say, \"Stop!\"
+ * </pre>
*
- * @param input the {@link String} to unescape, may be null
- * @return a new unescaped {@link String}, {@code null} if null string input
+ * @param input String to escape values in, may be null
+ * @return String with escaped values, {@code null} if null string input
*
- * @since 3.0
+ * @since 3.2
*/
- public static final String unescapeHtml3(final String input) {
- return UNESCAPE_HTML3.translate(input);
+ public static final String escapeJson(final String input) {
+ return ESCAPE_JSON.translate(input);
}
/**
@@ -724,74 +653,145 @@ public class StringEscapeUtils {
}
/**
- * Unescapes a string containing XML entity escapes to a string
- * containing the actual Unicode characters corresponding to the
- * escapes.
+ * Returns a {@link String} value for an unescaped CSV column.
*
- * <p>Supports only the five basic XML entities (gt, lt, quot, amp, apos).
- * Does not support DTDs or external entities.</p>
+ * <p>If the value is enclosed in double quotes, and contains a comma, newline
+ * or double quote, then quotes are removed.
+ * </p>
*
- * <p>Note that numerical \\u Unicode codes are unescaped to their respective
- * Unicode characters. This may change in future releases.</p>
+ * <p>Any double quote escaped characters (a pair of double quotes) are unescaped
+ * to just one double quote.</p>
*
+ * <p>If the value is not enclosed in double quotes, or is and does not contain a
+ * comma, newline or double quote, then the String value is returned unchanged.</p>
+ *
+ * see <a href="https://en.wikipedia.org/wiki/Comma-separated_values">Wikipedia</a> and
+ * <a href="https://datatracker.ietf.org/doc/html/rfc4180">RFC 4180</a>.
+ *
+ * @param input the input CSV column String, may be null
+ * @return the input String, with enclosing double quotes removed and embedded double
+ * quotes unescaped, {@code null} if null string input
+ * @since 2.4
+ */
+ public static final String unescapeCsv(final String input) {
+ return UNESCAPE_CSV.translate(input);
+ }
+
+ /**
+ * Unescapes any EcmaScript literals found in the {@link String}.
+ *
+ * <p>For example, it will turn a sequence of {@code '\'} and {@code 'n'}
+ * into a newline character, unless the {@code '\'} is preceded by another
+ * {@code '\'}.</p>
+ *
+ * @see #unescapeJava(String)
* @param input the {@link String} to unescape, may be null
- * @return a new unescaped {@link String}, {@code null} if null string input
- * @see #escapeXml(String)
- * @see #escapeXml10(String)
- * @see #escapeXml11(String)
+ * @return A new unescaped {@link String}, {@code null} if null string input
+ *
+ * @since 3.0
*/
- public static final String unescapeXml(final String input) {
- return UNESCAPE_XML.translate(input);
+ public static final String unescapeEcmaScript(final String input) {
+ return UNESCAPE_ECMASCRIPT.translate(input);
}
+ /**
+ * Unescapes a string containing entity escapes to a string
+ * containing the actual Unicode characters corresponding to the
+ * escapes. Supports only HTML 3.0 entities.
+ *
+ * @param input the {@link String} to unescape, may be null
+ * @return a new unescaped {@link String}, {@code null} if null string input
+ *
+ * @since 3.0
+ */
+ public static final String unescapeHtml3(final String input) {
+ return UNESCAPE_HTML3.translate(input);
+ }
/**
- * Returns a {@link String} value for a CSV column enclosed in double quotes,
- * if required.
+ * Unescapes a string containing entity escapes to a string
+ * containing the actual Unicode characters corresponding to the
+ * escapes. Supports HTML 4.0 entities.
*
- * <p>If the value contains a comma, newline or double quote, then the
- * String value is returned enclosed in double quotes.</p>
+ * <p>For example, the string {@code "<Français>"}
+ * will become {@code "<Français>"}</p>
*
- * <p>Any double quote characters in the value are escaped with another double quote.</p>
+ * <p>If an entity is unrecognized, it is left alone, and inserted
+ * verbatim into the result string. e.g. {@code ">&zzzz;x"} will
+ * become {@code ">&zzzz;x"}.</p>
*
- * <p>If the value does not contain a comma, newline or double quote, then the
- * String value is returned unchanged.</p>
+ * @param input the {@link String} to unescape, may be null
+ * @return a new unescaped {@link String}, {@code null} if null string input
*
- * see <a href="https://en.wikipedia.org/wiki/Comma-separated_values">Wikipedia</a> and
- * <a href="https://datatracker.ietf.org/doc/html/rfc4180">RFC 4180</a>.
+ * @since 3.0
+ */
+ public static final String unescapeHtml4(final String input) {
+ return UNESCAPE_HTML4.translate(input);
+ }
+
+ /**
+ * Unescapes any Java literals found in the {@link String}.
+ * For example, it will turn a sequence of {@code '\'} and
+ * {@code 'n'} into a newline character, unless the {@code '\'}
+ * is preceded by another {@code '\'}.
*
- * @param input the input CSV column String, may be null
- * @return the input String, enclosed in double quotes if the value contains a comma,
- * newline or double quote, {@code null} if null string input
- * @since 2.4
+ * @param input the {@link String} to unescape, may be null
+ * @return a new unescaped {@link String}, {@code null} if null string input
*/
- public static final String escapeCsv(final String input) {
- return ESCAPE_CSV.translate(input);
+ public static final String unescapeJava(final String input) {
+ return UNESCAPE_JAVA.translate(input);
}
/**
- * Returns a {@link String} value for an unescaped CSV column.
+ * Unescapes any Json literals found in the {@link String}.
*
- * <p>If the value is enclosed in double quotes, and contains a comma, newline
- * or double quote, then quotes are removed.
- * </p>
+ * <p>For example, it will turn a sequence of {@code '\'} and {@code 'n'}
+ * into a newline character, unless the {@code '\'} is preceded by another
+ * {@code '\'}.</p>
*
- * <p>Any double quote escaped characters (a pair of double quotes) are unescaped
- * to just one double quote.</p>
+ * @see #unescapeJava(String)
+ * @param input the {@link String} to unescape, may be null
+ * @return A new unescaped {@link String}, {@code null} if null string input
*
- * <p>If the value is not enclosed in double quotes, or is and does not contain a
- * comma, newline or double quote, then the String value is returned unchanged.</p>
+ * @since 3.2
+ */
+ public static final String unescapeJson(final String input) {
+ return UNESCAPE_JSON.translate(input);
+ }
+
+
+ /**
+ * Unescapes a string containing XML entity escapes to a string
+ * containing the actual Unicode characters corresponding to the
+ * escapes.
*
- * see <a href="https://en.wikipedia.org/wiki/Comma-separated_values">Wikipedia</a> and
- * <a href="https://datatracker.ietf.org/doc/html/rfc4180">RFC 4180</a>.
+ * <p>Supports only the five basic XML entities (gt, lt, quot, amp, apos).
+ * Does not support DTDs or external entities.</p>
*
- * @param input the input CSV column String, may be null
- * @return the input String, with enclosing double quotes removed and embedded double
- * quotes unescaped, {@code null} if null string input
- * @since 2.4
+ * <p>Note that numerical \\u Unicode codes are unescaped to their respective
+ * Unicode characters. This may change in future releases.</p>
+ *
+ * @param input the {@link String} to unescape, may be null
+ * @return a new unescaped {@link String}, {@code null} if null string input
+ * @see #escapeXml(String)
+ * @see #escapeXml10(String)
+ * @see #escapeXml11(String)
*/
- public static final String unescapeCsv(final String input) {
- return UNESCAPE_CSV.translate(input);
+ public static final String unescapeXml(final String input) {
+ return UNESCAPE_XML.translate(input);
+ }
+
+ /**
+ * {@link StringEscapeUtils} instances should NOT be constructed in
+ * standard programming.
+ *
+ * <p>Instead, the class should be used as:</p>
+ * <pre>StringEscapeUtils.escapeJava("foo");</pre>
+ *
+ * <p>This constructor is public to permit tools that require a JavaBean
+ * instance to operate.</p>
+ */
+ public StringEscapeUtils() {
}
}
diff --git a/src/main/java/org/apache/commons/lang3/Validate.java b/src/main/java/org/apache/commons/lang3/Validate.java
index c0e37d7b0..5950bd003 100644
--- a/src/main/java/org/apache/commons/lang3/Validate.java
+++ b/src/main/java/org/apache/commons/lang3/Validate.java
@@ -78,434 +78,568 @@ public class Validate {
private static final String DEFAULT_IS_INSTANCE_OF_EX_MESSAGE = "Expected type: %s, actual: %s";
/**
- * Constructor. This class should not normally be instantiated.
+ * Validate that the specified primitive value falls between the two
+ * exclusive values specified; otherwise, throws an exception.
+ *
+ * <pre>Validate.exclusiveBetween(0.1, 2.1, 1.1);</pre>
+ *
+ * @param start the exclusive start value
+ * @param end the exclusive end value
+ * @param value the value to validate
+ * @throws IllegalArgumentException if the value falls out of the boundaries
+ * @since 3.3
*/
- public Validate() {
+ @SuppressWarnings("boxing")
+ public static void exclusiveBetween(final double start, final double end, final double value) {
+ // TODO when breaking BC, consider returning value
+ if (value <= start || value >= end) {
+ throw new IllegalArgumentException(String.format(DEFAULT_EXCLUSIVE_BETWEEN_EX_MESSAGE, value, start, end));
+ }
}
/**
- * Validate that the argument condition is {@code true}; otherwise
- * throwing an exception with the specified message. This method is useful when
- * validating according to an arbitrary boolean expression, such as validating a
- * primitive number or using your own custom validation expression.
+ * Validate that the specified primitive value falls between the two
+ * exclusive values specified; otherwise, throws an exception with the
+ * specified message.
*
- * <pre>Validate.isTrue(i > 0.0, "The value must be greater than zero: %d", i);</pre>
+ * <pre>Validate.exclusiveBetween(0.1, 2.1, 1.1, "Not in range");</pre>
*
- * <p>For performance reasons, the long value is passed as a separate parameter and
- * appended to the exception message only in the case of an error.</p>
+ * @param start the exclusive start value
+ * @param end the exclusive end value
+ * @param value the value to validate
+ * @param message the exception message if invalid, not null
+ * @throws IllegalArgumentException if the value falls outside the boundaries
+ * @since 3.3
+ */
+ public static void exclusiveBetween(final double start, final double end, final double value, final String message) {
+ // TODO when breaking BC, consider returning value
+ if (value <= start || value >= end) {
+ throw new IllegalArgumentException(message);
+ }
+ }
+
+ /**
+ * Validate that the specified primitive value falls between the two
+ * exclusive values specified; otherwise, throws an exception.
*
- * @param expression the boolean expression to check
- * @param message the {@link String#format(String, Object...)} exception message if invalid, not null
- * @param value the value to append to the message when invalid
- * @throws IllegalArgumentException if expression is {@code false}
- * @see #isTrue(boolean)
- * @see #isTrue(boolean, String, double)
- * @see #isTrue(boolean, String, Object...)
+ * <pre>Validate.exclusiveBetween(0, 2, 1);</pre>
+ *
+ * @param start the exclusive start value
+ * @param end the exclusive end value
+ * @param value the value to validate
+ * @throws IllegalArgumentException if the value falls out of the boundaries
+ * @since 3.3
*/
- public static void isTrue(final boolean expression, final String message, final long value) {
- if (!expression) {
- throw new IllegalArgumentException(String.format(message, Long.valueOf(value)));
+ @SuppressWarnings("boxing")
+ public static void exclusiveBetween(final long start, final long end, final long value) {
+ // TODO when breaking BC, consider returning value
+ if (value <= start || value >= end) {
+ throw new IllegalArgumentException(String.format(DEFAULT_EXCLUSIVE_BETWEEN_EX_MESSAGE, value, start, end));
}
}
/**
- * Validate that the argument condition is {@code true}; otherwise
- * throwing an exception with the specified message. This method is useful when
- * validating according to an arbitrary boolean expression, such as validating a
- * primitive number or using your own custom validation expression.
+ * Validate that the specified primitive value falls between the two
+ * exclusive values specified; otherwise, throws an exception with the
+ * specified message.
*
- * <pre>Validate.isTrue(d > 0.0, "The value must be greater than zero: %s", d);</pre>
+ * <pre>Validate.exclusiveBetween(0, 2, 1, "Not in range");</pre>
*
- * <p>For performance reasons, the double value is passed as a separate parameter and
- * appended to the exception message only in the case of an error.</p>
+ * @param start the exclusive start value
+ * @param end the exclusive end value
+ * @param value the value to validate
+ * @param message the exception message if invalid, not null
+ * @throws IllegalArgumentException if the value falls outside the boundaries
+ * @since 3.3
+ */
+ public static void exclusiveBetween(final long start, final long end, final long value, final String message) {
+ // TODO when breaking BC, consider returning value
+ if (value <= start || value >= end) {
+ throw new IllegalArgumentException(message);
+ }
+ }
+
+ /**
+ * Validate that the specified argument object fall between the two
+ * exclusive values specified; otherwise, throws an exception.
*
- * @param expression the boolean expression to check
- * @param message the {@link String#format(String, Object...)} exception message if invalid, not null
- * @param value the value to append to the message when invalid
- * @throws IllegalArgumentException if expression is {@code false}
- * @see #isTrue(boolean)
- * @see #isTrue(boolean, String, long)
- * @see #isTrue(boolean, String, Object...)
+ * <pre>Validate.exclusiveBetween(0, 2, 1);</pre>
+ *
+ * @param <T> the type of the argument object
+ * @param start the exclusive start value, not null
+ * @param end the exclusive end value, not null
+ * @param value the object to validate, not null
+ * @throws IllegalArgumentException if the value falls outside the boundaries
+ * @see #exclusiveBetween(Object, Object, Comparable, String, Object...)
+ * @since 3.0
*/
- public static void isTrue(final boolean expression, final String message, final double value) {
- if (!expression) {
- throw new IllegalArgumentException(String.format(message, Double.valueOf(value)));
+ public static <T> void exclusiveBetween(final T start, final T end, final Comparable<T> value) {
+ // TODO when breaking BC, consider returning value
+ if (value.compareTo(start) <= 0 || value.compareTo(end) >= 0) {
+ throw new IllegalArgumentException(String.format(DEFAULT_EXCLUSIVE_BETWEEN_EX_MESSAGE, value, start, end));
}
}
/**
- * Validate that the argument condition is {@code true}; otherwise
- * throwing an exception with the specified message. This method is useful when
- * validating according to an arbitrary boolean expression, such as validating a
- * primitive number or using your own custom validation expression.
+ * Validate that the specified argument object fall between the two
+ * exclusive values specified; otherwise, throws an exception with the
+ * specified message.
*
- * <pre>
- * Validate.isTrue(i >= min && i <= max, "The value must be between %d and %d", min, max);</pre>
+ * <pre>Validate.exclusiveBetween(0, 2, 1, "Not in boundaries");</pre>
*
- * @param expression the boolean expression to check
+ * @param <T> the type of the argument object
+ * @param start the exclusive start value, not null
+ * @param end the exclusive end value, not null
+ * @param value the object to validate, not null
* @param message the {@link String#format(String, Object...)} exception message if invalid, not null
* @param values the optional values for the formatted exception message, null array not recommended
- * @throws IllegalArgumentException if expression is {@code false}
- * @see #isTrue(boolean)
- * @see #isTrue(boolean, String, long)
- * @see #isTrue(boolean, String, double)
+ * @throws IllegalArgumentException if the value falls outside the boundaries
+ * @see #exclusiveBetween(Object, Object, Comparable)
+ * @since 3.0
*/
- public static void isTrue(final boolean expression, final String message, final Object... values) {
- if (!expression) {
+ public static <T> void exclusiveBetween(final T start, final T end, final Comparable<T> value, final String message, final Object... values) {
+ // TODO when breaking BC, consider returning value
+ if (value.compareTo(start) <= 0 || value.compareTo(end) >= 0) {
throw new IllegalArgumentException(getMessage(message, values));
}
}
/**
- * Validate that the argument condition is {@code true}; otherwise
- * throwing an exception. This method is useful when validating according
- * to an arbitrary boolean expression, such as validating a
- * primitive number or using your own custom validation expression.
+ * Validates that the specified argument is not infinite or Not-a-Number (NaN);
+ * otherwise throwing an exception.
*
- * <pre>
- * Validate.isTrue(i > 0);
- * Validate.isTrue(myObject.isOk());</pre>
+ * <pre>Validate.finite(myDouble);</pre>
*
- * <p>The message of the exception is "The validated expression is
- * false".</p>
+ * <p>The message of the exception is "The value is invalid: %f".</p>
*
- * @param expression the boolean expression to check
- * @throws IllegalArgumentException if expression is {@code false}
- * @see #isTrue(boolean, String, long)
- * @see #isTrue(boolean, String, double)
- * @see #isTrue(boolean, String, Object...)
+ * @param value the value to validate
+ * @throws IllegalArgumentException if the value is infinite or Not-a-Number (NaN)
+ * @see #finite(double, String, Object...)
+ * @since 3.5
*/
- public static void isTrue(final boolean expression) {
- if (!expression) {
- throw new IllegalArgumentException(DEFAULT_IS_TRUE_EX_MESSAGE);
+ public static void finite(final double value) {
+ finite(value, DEFAULT_FINITE_EX_MESSAGE, value);
+ }
+
+ /**
+ * Validates that the specified argument is not infinite or Not-a-Number (NaN);
+ * otherwise throwing an exception with the specified message.
+ *
+ * <pre>Validate.finite(myDouble, "The argument must contain a numeric value");</pre>
+ *
+ * @param value the value to validate
+ * @param message the {@link String#format(String, Object...)} exception message if invalid, not null
+ * @param values the optional values for the formatted exception message
+ * @throws IllegalArgumentException if the value is infinite or Not-a-Number (NaN)
+ * @see #finite(double)
+ * @since 3.5
+ */
+ public static void finite(final double value, final String message, final Object... values) {
+ if (Double.isNaN(value) || Double.isInfinite(value)) {
+ throw new IllegalArgumentException(getMessage(message, values));
}
}
/**
- * Validate that the specified argument is not {@code null};
- * otherwise throwing an exception.
+ * Gets the message using {@link String#format(String, Object...) String.format(message, values)}
+ * if the values are not empty, otherwise return the message unformatted.
+ * This method exists to allow validation methods declaring a String message and varargs parameters
+ * to be used without any message parameters when the message contains special characters,
+ * e.g. {@code Validate.isTrue(false, "%Failed%")}.
*
- * <pre>Validate.notNull(myObject, "The object must not be null");</pre>
+ * @param message the {@link String#format(String, Object...)} exception message if invalid, not null
+ * @param values the optional values for the formatted message
+ * @return formatted message using {@link String#format(String, Object...) String.format(message, values)}
+ * if the values are not empty, otherwise return the unformatted message.
+ */
+ private static String getMessage(final String message, final Object... values) {
+ return ArrayUtils.isEmpty(values) ? message : String.format(message, values);
+ }
+
+ /**
+ * Validate that the specified primitive value falls between the two
+ * inclusive values specified; otherwise, throws an exception.
*
- * <p>The message of the exception is "The validated object is
- * null".
+ * <pre>Validate.inclusiveBetween(0.1, 2.1, 1.1);</pre>
*
- * @param <T> the object type
- * @param object the object to check
- * @return the validated object (never {@code null} for method chaining)
- * @throws NullPointerException if the object is {@code null}
- * @see #notNull(Object, String, Object...)
- * @deprecated Use {@link Objects#requireNonNull(Object)}.
+ * @param start the inclusive start value
+ * @param end the inclusive end value
+ * @param value the value to validate
+ * @throws IllegalArgumentException if the value falls outside the boundaries (inclusive)
+ * @since 3.3
*/
- @Deprecated
- public static <T> T notNull(final T object) {
- return notNull(object, DEFAULT_IS_NULL_EX_MESSAGE);
+ @SuppressWarnings("boxing")
+ public static void inclusiveBetween(final double start, final double end, final double value) {
+ // TODO when breaking BC, consider returning value
+ if (value < start || value > end) {
+ throw new IllegalArgumentException(String.format(DEFAULT_INCLUSIVE_BETWEEN_EX_MESSAGE, value, start, end));
+ }
}
/**
- * Validate that the specified argument is not {@code null};
- * otherwise throwing an exception with the specified message.
+ * Validate that the specified primitive value falls between the two
+ * inclusive values specified; otherwise, throws an exception with the
+ * specified message.
*
- * <pre>Validate.notNull(myObject, "The object must not be null");</pre>
+ * <pre>Validate.inclusiveBetween(0.1, 2.1, 1.1, "Not in range");</pre>
*
- * @param <T> the object type
- * @param object the object to check
- * @param message the {@link String#format(String, Object...)} exception message if invalid, not null
- * @param values the optional values for the formatted exception message
- * @return the validated object (never {@code null} for method chaining)
- * @throws NullPointerException if the object is {@code null}
- * @see Objects#requireNonNull(Object)
+ * @param start the inclusive start value
+ * @param end the inclusive end value
+ * @param value the value to validate
+ * @param message the exception message if invalid, not null
+ * @throws IllegalArgumentException if the value falls outside the boundaries
+ * @since 3.3
*/
- public static <T> T notNull(final T object, final String message, final Object... values) {
- return Objects.requireNonNull(object, toSupplier(message, values));
+ public static void inclusiveBetween(final double start, final double end, final double value, final String message) {
+ // TODO when breaking BC, consider returning value
+ if (value < start || value > end) {
+ throw new IllegalArgumentException(message);
+ }
}
- private static Supplier<String> toSupplier(final String message, final Object... values) {
- return () -> getMessage(message, values);
+ /**
+ * Validate that the specified primitive value falls between the two
+ * inclusive values specified; otherwise, throws an exception.
+ *
+ * <pre>Validate.inclusiveBetween(0, 2, 1);</pre>
+ *
+ * @param start the inclusive start value
+ * @param end the inclusive end value
+ * @param value the value to validate
+ * @throws IllegalArgumentException if the value falls outside the boundaries (inclusive)
+ * @since 3.3
+ */
+ @SuppressWarnings("boxing")
+ public static void inclusiveBetween(final long start, final long end, final long value) {
+ // TODO when breaking BC, consider returning value
+ if (value < start || value > end) {
+ throw new IllegalArgumentException(String.format(DEFAULT_INCLUSIVE_BETWEEN_EX_MESSAGE, value, start, end));
+ }
}
/**
- * <p>Validate that the specified argument array is neither {@code null}
- * nor a length of zero (no elements); otherwise throwing an exception
- * with the specified message.
+ * Validate that the specified primitive value falls between the two
+ * inclusive values specified; otherwise, throws an exception with the
+ * specified message.
*
- * <pre>Validate.notEmpty(myArray, "The array must not be empty");</pre>
+ * <pre>Validate.inclusiveBetween(0, 2, 1, "Not in range");</pre>
*
- * @param <T> the array type
- * @param array the array to check, validated not null by this method
+ * @param start the inclusive start value
+ * @param end the inclusive end value
+ * @param value the value to validate
+ * @param message the exception message if invalid, not null
+ * @throws IllegalArgumentException if the value falls outside the boundaries
+ * @since 3.3
+ */
+ public static void inclusiveBetween(final long start, final long end, final long value, final String message) {
+ // TODO when breaking BC, consider returning value
+ if (value < start || value > end) {
+ throw new IllegalArgumentException(message);
+ }
+ }
+
+ /**
+ * Validate that the specified argument object fall between the two
+ * inclusive values specified; otherwise, throws an exception.
+ *
+ * <pre>Validate.inclusiveBetween(0, 2, 1);</pre>
+ *
+ * @param <T> the type of the argument object
+ * @param start the inclusive start value, not null
+ * @param end the inclusive end value, not null
+ * @param value the object to validate, not null
+ * @throws IllegalArgumentException if the value falls outside the boundaries
+ * @see #inclusiveBetween(Object, Object, Comparable, String, Object...)
+ * @since 3.0
+ */
+ public static <T> void inclusiveBetween(final T start, final T end, final Comparable<T> value) {
+ // TODO when breaking BC, consider returning value
+ if (value.compareTo(start) < 0 || value.compareTo(end) > 0) {
+ throw new IllegalArgumentException(String.format(DEFAULT_INCLUSIVE_BETWEEN_EX_MESSAGE, value, start, end));
+ }
+ }
+
+ /**
+ * Validate that the specified argument object fall between the two
+ * inclusive values specified; otherwise, throws an exception with the
+ * specified message.
+ *
+ * <pre>Validate.inclusiveBetween(0, 2, 1, "Not in boundaries");</pre>
+ *
+ * @param <T> the type of the argument object
+ * @param start the inclusive start value, not null
+ * @param end the inclusive end value, not null
+ * @param value the object to validate, not null
* @param message the {@link String#format(String, Object...)} exception message if invalid, not null
* @param values the optional values for the formatted exception message, null array not recommended
- * @return the validated array (never {@code null} method for chaining)
- * @throws NullPointerException if the array is {@code null}
- * @throws IllegalArgumentException if the array is empty
- * @see #notEmpty(Object[])
+ * @throws IllegalArgumentException if the value falls outside the boundaries
+ * @see #inclusiveBetween(Object, Object, Comparable)
+ * @since 3.0
*/
- public static <T> T[] notEmpty(final T[] array, final String message, final Object... values) {
- Objects.requireNonNull(array, toSupplier(message, values));
- if (array.length == 0) {
+ public static <T> void inclusiveBetween(final T start, final T end, final Comparable<T> value, final String message, final Object... values) {
+ // TODO when breaking BC, consider returning value
+ if (value.compareTo(start) < 0 || value.compareTo(end) > 0) {
throw new IllegalArgumentException(getMessage(message, values));
}
- return array;
}
/**
- * <p>Validate that the specified argument array is neither {@code null}
- * nor a length of zero (no elements); otherwise throwing an exception.
+ * Validates that the argument can be converted to the specified class, if not, throws an exception.
*
- * <pre>Validate.notEmpty(myArray);</pre>
+ * <p>This method is useful when validating that there will be no casting errors.</p>
*
- * <p>The message in the exception is "The validated array is
- * empty".
+ * <pre>Validate.isAssignableFrom(SuperClass.class, object.getClass());</pre>
*
- * @param <T> the array type
- * @param array the array to check, validated not null by this method
- * @return the validated array (never {@code null} method for chaining)
- * @throws NullPointerException if the array is {@code null}
- * @throws IllegalArgumentException if the array is empty
- * @see #notEmpty(Object[], String, Object...)
+ * <p>The message format of the exception is "Cannot assign {type} to {superType}"</p>
+ *
+ * @param superType the class must be validated against, not null
+ * @param type the class to check, not null
+ * @throws IllegalArgumentException if type argument is not assignable to the specified superType
+ * @see #isAssignableFrom(Class, Class, String, Object...)
+ * @since 3.0
*/
- public static <T> T[] notEmpty(final T[] array) {
- return notEmpty(array, DEFAULT_NOT_EMPTY_ARRAY_EX_MESSAGE);
+ public static void isAssignableFrom(final Class<?> superType, final Class<?> type) {
+ // TODO when breaking BC, consider returning type
+ if (type == null || superType == null || !superType.isAssignableFrom(type)) {
+ throw new IllegalArgumentException(
+ String.format(DEFAULT_IS_ASSIGNABLE_EX_MESSAGE, ClassUtils.getName(type, "null type"), ClassUtils.getName(superType, "null type")));
+ }
}
/**
- * <p>Validate that the specified argument collection is neither {@code null}
- * nor a size of zero (no elements); otherwise throwing an exception
- * with the specified message.
+ * Validates that the argument can be converted to the specified class, if not throws an exception.
*
- * <pre>Validate.notEmpty(myCollection, "The collection must not be empty");</pre>
+ * <p>This method is useful when validating if there will be no casting errors.</p>
*
- * @param <T> the collection type
- * @param collection the collection to check, validated not null by this method
+ * <pre>Validate.isAssignableFrom(SuperClass.class, object.getClass());</pre>
+ *
+ * <p>The message of the exception is "The validated object can not be converted to the"
+ * followed by the name of the class and "class"</p>
+ *
+ * @param superType the class must be validated against, not null
+ * @param type the class to check, not null
* @param message the {@link String#format(String, Object...)} exception message if invalid, not null
* @param values the optional values for the formatted exception message, null array not recommended
- * @return the validated collection (never {@code null} method for chaining)
- * @throws NullPointerException if the collection is {@code null}
- * @throws IllegalArgumentException if the collection is empty
- * @see #notEmpty(Object[])
+ * @throws IllegalArgumentException if argument can not be converted to the specified class
+ * @see #isAssignableFrom(Class, Class)
*/
- public static <T extends Collection<?>> T notEmpty(final T collection, final String message, final Object... values) {
- Objects.requireNonNull(collection, toSupplier(message, values));
- if (collection.isEmpty()) {
+ public static void isAssignableFrom(final Class<?> superType, final Class<?> type, final String message, final Object... values) {
+ // TODO when breaking BC, consider returning type
+ if (!superType.isAssignableFrom(type)) {
throw new IllegalArgumentException(getMessage(message, values));
}
- return collection;
}
/**
- * <p>Validate that the specified argument collection is neither {@code null}
- * nor a size of zero (no elements); otherwise throwing an exception.
+ * Validates that the argument is an instance of the specified class, if not throws an exception.
*
- * <pre>Validate.notEmpty(myCollection);</pre>
+ * <p>This method is useful when validating according to an arbitrary class</p>
*
- * <p>The message in the exception is "The validated collection is
- * empty".
+ * <pre>Validate.isInstanceOf(OkClass.class, object);</pre>
*
- * @param <T> the collection type
- * @param collection the collection to check, validated not null by this method
- * @return the validated collection (never {@code null} method for chaining)
- * @throws NullPointerException if the collection is {@code null}
- * @throws IllegalArgumentException if the collection is empty
- * @see #notEmpty(Collection, String, Object...)
+ * <p>The message of the exception is "Expected type: {type}, actual: {obj_type}"</p>
+ *
+ * @param type the class the object must be validated against, not null
+ * @param obj the object to check, null throws an exception
+ * @throws IllegalArgumentException if argument is not of specified class
+ * @see #isInstanceOf(Class, Object, String, Object...)
+ * @since 3.0
*/
- public static <T extends Collection<?>> T notEmpty(final T collection) {
- return notEmpty(collection, DEFAULT_NOT_EMPTY_COLLECTION_EX_MESSAGE);
+ public static void isInstanceOf(final Class<?> type, final Object obj) {
+ // TODO when breaking BC, consider returning obj
+ if (!type.isInstance(obj)) {
+ throw new IllegalArgumentException(String.format(DEFAULT_IS_INSTANCE_OF_EX_MESSAGE, type.getName(), ClassUtils.getName(obj, "null")));
+ }
}
/**
- * Validate that the specified argument map is neither {@code null}
- * nor a size of zero (no elements); otherwise throwing an exception
- * with the specified message.
+ * Validate that the argument is an instance of the specified class; otherwise
+ * throwing an exception with the specified message. This method is useful when
+ * validating according to an arbitrary class
*
- * <pre>Validate.notEmpty(myMap, "The map must not be empty");</pre>
+ * <pre>Validate.isInstanceOf(OkClass.class, object, "Wrong class, object is of class %s",
+ * object.getClass().getName());</pre>
*
- * @param <T> the map type
- * @param map the map to check, validated not null by this method
+ * @param type the class the object must be validated against, not null
+ * @param obj the object to check, null throws an exception
* @param message the {@link String#format(String, Object...)} exception message if invalid, not null
* @param values the optional values for the formatted exception message, null array not recommended
- * @return the validated map (never {@code null} method for chaining)
- * @throws NullPointerException if the map is {@code null}
- * @throws IllegalArgumentException if the map is empty
- * @see #notEmpty(Object[])
+ * @throws IllegalArgumentException if argument is not of specified class
+ * @see #isInstanceOf(Class, Object)
+ * @since 3.0
*/
- public static <T extends Map<?, ?>> T notEmpty(final T map, final String message, final Object... values) {
- Objects.requireNonNull(map, toSupplier(message, values));
- if (map.isEmpty()) {
+ public static void isInstanceOf(final Class<?> type, final Object obj, final String message, final Object... values) {
+ // TODO when breaking BC, consider returning obj
+ if (!type.isInstance(obj)) {
throw new IllegalArgumentException(getMessage(message, values));
}
- return map;
}
/**
- * <p>Validate that the specified argument map is neither {@code null}
- * nor a size of zero (no elements); otherwise throwing an exception.
+ * Validate that the argument condition is {@code true}; otherwise
+ * throwing an exception. This method is useful when validating according
+ * to an arbitrary boolean expression, such as validating a
+ * primitive number or using your own custom validation expression.
*
- * <pre>Validate.notEmpty(myMap);</pre>
+ * <pre>
+ * Validate.isTrue(i > 0);
+ * Validate.isTrue(myObject.isOk());</pre>
*
- * <p>The message in the exception is "The validated map is
- * empty".
+ * <p>The message of the exception is "The validated expression is
+ * false".</p>
*
- * @param <T> the map type
- * @param map the map to check, validated not null by this method
- * @return the validated map (never {@code null} method for chaining)
- * @throws NullPointerException if the map is {@code null}
- * @throws IllegalArgumentException if the map is empty
- * @see #notEmpty(Map, String, Object...)
+ * @param expression the boolean expression to check
+ * @throws IllegalArgumentException if expression is {@code false}
+ * @see #isTrue(boolean, String, long)
+ * @see #isTrue(boolean, String, double)
+ * @see #isTrue(boolean, String, Object...)
*/
- public static <T extends Map<?, ?>> T notEmpty(final T map) {
- return notEmpty(map, DEFAULT_NOT_EMPTY_MAP_EX_MESSAGE);
+ public static void isTrue(final boolean expression) {
+ if (!expression) {
+ throw new IllegalArgumentException(DEFAULT_IS_TRUE_EX_MESSAGE);
+ }
}
/**
- * Validate that the specified argument character sequence is
- * neither {@code null} nor a length of zero (no characters);
- * otherwise throwing an exception with the specified message.
+ * Validate that the argument condition is {@code true}; otherwise
+ * throwing an exception with the specified message. This method is useful when
+ * validating according to an arbitrary boolean expression, such as validating a
+ * primitive number or using your own custom validation expression.
*
- * <pre>Validate.notEmpty(myString, "The string must not be empty");</pre>
+ * <pre>Validate.isTrue(d > 0.0, "The value must be greater than zero: %s", d);</pre>
*
- * @param <T> the character sequence type
- * @param chars the character sequence to check, validated not null by this method
+ * <p>For performance reasons, the double value is passed as a separate parameter and
+ * appended to the exception message only in the case of an error.</p>
+ *
+ * @param expression the boolean expression to check
* @param message the {@link String#format(String, Object...)} exception message if invalid, not null
- * @param values the optional values for the formatted exception message, null array not recommended
- * @return the validated character sequence (never {@code null} method for chaining)
- * @throws NullPointerException if the character sequence is {@code null}
- * @throws IllegalArgumentException if the character sequence is empty
- * @see #notEmpty(CharSequence)
+ * @param value the value to append to the message when invalid
+ * @throws IllegalArgumentException if expression is {@code false}
+ * @see #isTrue(boolean)
+ * @see #isTrue(boolean, String, long)
+ * @see #isTrue(boolean, String, Object...)
*/
- public static <T extends CharSequence> T notEmpty(final T chars, final String message, final Object... values) {
- Objects.requireNonNull(chars, toSupplier(message, values));
- if (chars.length() == 0) {
- throw new IllegalArgumentException(getMessage(message, values));
+ public static void isTrue(final boolean expression, final String message, final double value) {
+ if (!expression) {
+ throw new IllegalArgumentException(String.format(message, Double.valueOf(value)));
}
- return chars;
}
/**
- * <p>Validate that the specified argument character sequence is
- * neither {@code null} nor a length of zero (no characters);
- * otherwise throwing an exception with the specified message.
+ * Validate that the argument condition is {@code true}; otherwise
+ * throwing an exception with the specified message. This method is useful when
+ * validating according to an arbitrary boolean expression, such as validating a
+ * primitive number or using your own custom validation expression.
*
- * <pre>Validate.notEmpty(myString);</pre>
+ * <pre>Validate.isTrue(i > 0.0, "The value must be greater than zero: %d", i);</pre>
*
- * <p>The message in the exception is "The validated
- * character sequence is empty".
+ * <p>For performance reasons, the long value is passed as a separate parameter and
+ * appended to the exception message only in the case of an error.</p>
*
- * @param <T> the character sequence type
- * @param chars the character sequence to check, validated not null by this method
- * @return the validated character sequence (never {@code null} method for chaining)
- * @throws NullPointerException if the character sequence is {@code null}
- * @throws IllegalArgumentException if the character sequence is empty
- * @see #notEmpty(CharSequence, String, Object...)
+ * @param expression the boolean expression to check
+ * @param message the {@link String#format(String, Object...)} exception message if invalid, not null
+ * @param value the value to append to the message when invalid
+ * @throws IllegalArgumentException if expression is {@code false}
+ * @see #isTrue(boolean)
+ * @see #isTrue(boolean, String, double)
+ * @see #isTrue(boolean, String, Object...)
*/
- public static <T extends CharSequence> T notEmpty(final T chars) {
- return notEmpty(chars, DEFAULT_NOT_EMPTY_CHAR_SEQUENCE_EX_MESSAGE);
+ public static void isTrue(final boolean expression, final String message, final long value) {
+ if (!expression) {
+ throw new IllegalArgumentException(String.format(message, Long.valueOf(value)));
+ }
}
/**
- * Validate that the specified argument character sequence is
- * neither {@code null}, a length of zero (no characters), empty
- * nor whitespace; otherwise throwing an exception with the specified
- * message.
+ * Validate that the argument condition is {@code true}; otherwise
+ * throwing an exception with the specified message. This method is useful when
+ * validating according to an arbitrary boolean expression, such as validating a
+ * primitive number or using your own custom validation expression.
*
- * <pre>Validate.notBlank(myString, "The string must not be blank");</pre>
+ * <pre>
+ * Validate.isTrue(i >= min && i <= max, "The value must be between %d and %d", min, max);</pre>
*
- * @param <T> the character sequence type
- * @param chars the character sequence to check, validated not null by this method
+ * @param expression the boolean expression to check
* @param message the {@link String#format(String, Object...)} exception message if invalid, not null
* @param values the optional values for the formatted exception message, null array not recommended
- * @return the validated character sequence (never {@code null} method for chaining)
- * @throws NullPointerException if the character sequence is {@code null}
- * @throws IllegalArgumentException if the character sequence is blank
- * @see #notBlank(CharSequence)
- * @since 3.0
+ * @throws IllegalArgumentException if expression is {@code false}
+ * @see #isTrue(boolean)
+ * @see #isTrue(boolean, String, long)
+ * @see #isTrue(boolean, String, double)
*/
- public static <T extends CharSequence> T notBlank(final T chars, final String message, final Object... values) {
- Objects.requireNonNull(chars, toSupplier(message, values));
- if (StringUtils.isBlank(chars)) {
+ public static void isTrue(final boolean expression, final String message, final Object... values) {
+ if (!expression) {
throw new IllegalArgumentException(getMessage(message, values));
}
- return chars;
}
/**
- * <p>Validate that the specified argument character sequence is
- * neither {@code null}, a length of zero (no characters), empty
- * nor whitespace; otherwise throwing an exception.
+ * Validate that the specified argument character sequence matches the specified regular
+ * expression pattern; otherwise throwing an exception.
*
- * <pre>Validate.notBlank(myString);</pre>
+ * <pre>Validate.matchesPattern("hi", "[a-z]*");</pre>
*
- * <p>The message in the exception is "The validated character
- * sequence is blank".
+ * <p>The syntax of the pattern is the one used in the {@link Pattern} class.</p>
*
- * @param <T> the character sequence type
- * @param chars the character sequence to check, validated not null by this method
- * @return the validated character sequence (never {@code null} method for chaining)
- * @throws NullPointerException if the character sequence is {@code null}
- * @throws IllegalArgumentException if the character sequence is blank
- * @see #notBlank(CharSequence, String, Object...)
+ * @param input the character sequence to validate, not null
+ * @param pattern the regular expression pattern, not null
+ * @throws IllegalArgumentException if the character sequence does not match the pattern
+ * @see #matchesPattern(CharSequence, String, String, Object...)
* @since 3.0
*/
- public static <T extends CharSequence> T notBlank(final T chars) {
- return notBlank(chars, DEFAULT_NOT_BLANK_EX_MESSAGE);
+ public static void matchesPattern(final CharSequence input, final String pattern) {
+ // TODO when breaking BC, consider returning input
+ if (!Pattern.matches(pattern, input)) {
+ throw new IllegalArgumentException(String.format(DEFAULT_MATCHES_PATTERN_EX, input, pattern));
+ }
}
/**
- * Validate that the specified argument array is neither
- * {@code null} nor contains any elements that are {@code null};
- * otherwise throwing an exception with the specified message.
- *
- * <pre>Validate.noNullElements(myArray, "The array contain null at position %d");</pre>
+ * Validate that the specified argument character sequence matches the specified regular
+ * expression pattern; otherwise throwing an exception with the specified message.
*
- * <p>If the array is {@code null}, then the message in the exception
- * is "The validated object is null".
+ * <pre>Validate.matchesPattern("hi", "[a-z]*", "%s does not match %s", "hi" "[a-z]*");</pre>
*
- * <p>If the array has a {@code null} element, then the iteration
- * index of the invalid element is appended to the {@code values}
- * argument.</p>
+ * <p>The syntax of the pattern is the one used in the {@link Pattern} class.</p>
*
- * @param <T> the array type
- * @param array the array to check, validated not null by this method
+ * @param input the character sequence to validate, not null
+ * @param pattern the regular expression pattern, not null
* @param message the {@link String#format(String, Object...)} exception message if invalid, not null
* @param values the optional values for the formatted exception message, null array not recommended
- * @return the validated array (never {@code null} method for chaining)
- * @throws NullPointerException if the array is {@code null}
- * @throws IllegalArgumentException if an element is {@code null}
- * @see #noNullElements(Object[])
+ * @throws IllegalArgumentException if the character sequence does not match the pattern
+ * @see #matchesPattern(CharSequence, String)
+ * @since 3.0
*/
- public static <T> T[] noNullElements(final T[] array, final String message, final Object... values) {
- Objects.requireNonNull(array, "array");
- for (int i = 0; i < array.length; i++) {
- if (array[i] == null) {
- final Object[] values2 = ArrayUtils.add(values, Integer.valueOf(i));
- throw new IllegalArgumentException(getMessage(message, values2));
- }
+ public static void matchesPattern(final CharSequence input, final String pattern, final String message, final Object... values) {
+ // TODO when breaking BC, consider returning input
+ if (!Pattern.matches(pattern, input)) {
+ throw new IllegalArgumentException(getMessage(message, values));
}
- return array;
}
/**
- * Validate that the specified argument array is neither
+ * Validate that the specified argument iterable is neither
* {@code null} nor contains any elements that are {@code null};
* otherwise throwing an exception.
*
- * <pre>Validate.noNullElements(myArray);</pre>
+ * <pre>Validate.noNullElements(myCollection);</pre>
*
- * <p>If the array is {@code null}, then the message in the exception
- * is "The validated object is null".</p>
+ * <p>If the iterable is {@code null}, then the message in the exception
+ * is "The validated object is null".
*
* <p>If the array has a {@code null} element, then the message in the
- * exception is "The validated array contains null element at index:
+ * exception is "The validated iterable contains null element at index:
* " followed by the index.</p>
*
- * @param <T> the array type
- * @param array the array to check, validated not null by this method
- * @return the validated array (never {@code null} method for chaining)
+ * @param <T> the iterable type
+ * @param iterable the iterable to check, validated not null by this method
+ * @return the validated iterable (never {@code null} method for chaining)
* @throws NullPointerException if the array is {@code null}
* @throws IllegalArgumentException if an element is {@code null}
- * @see #noNullElements(Object[], String, Object...)
+ * @see #noNullElements(Iterable, String, Object...)
*/
- public static <T> T[] noNullElements(final T[] array) {
- return noNullElements(array, DEFAULT_NO_NULL_ELEMENTS_ARRAY_EX_MESSAGE);
+ public static <T extends Iterable<?>> T noNullElements(final T iterable) {
+ return noNullElements(iterable, DEFAULT_NO_NULL_ELEMENTS_COLLECTION_EX_MESSAGE);
}
/**
@@ -544,278 +678,287 @@ public class Validate {
}
/**
- * Validate that the specified argument iterable is neither
+ * Validate that the specified argument array is neither
* {@code null} nor contains any elements that are {@code null};
* otherwise throwing an exception.
*
- * <pre>Validate.noNullElements(myCollection);</pre>
+ * <pre>Validate.noNullElements(myArray);</pre>
*
- * <p>If the iterable is {@code null}, then the message in the exception
- * is "The validated object is null".
+ * <p>If the array is {@code null}, then the message in the exception
+ * is "The validated object is null".</p>
*
* <p>If the array has a {@code null} element, then the message in the
- * exception is "The validated iterable contains null element at index:
+ * exception is "The validated array contains null element at index:
* " followed by the index.</p>
*
- * @param <T> the iterable type
- * @param iterable the iterable to check, validated not null by this method
- * @return the validated iterable (never {@code null} method for chaining)
+ * @param <T> the array type
+ * @param array the array to check, validated not null by this method
+ * @return the validated array (never {@code null} method for chaining)
* @throws NullPointerException if the array is {@code null}
* @throws IllegalArgumentException if an element is {@code null}
- * @see #noNullElements(Iterable, String, Object...)
+ * @see #noNullElements(Object[], String, Object...)
*/
- public static <T extends Iterable<?>> T noNullElements(final T iterable) {
- return noNullElements(iterable, DEFAULT_NO_NULL_ELEMENTS_COLLECTION_EX_MESSAGE);
+ public static <T> T[] noNullElements(final T[] array) {
+ return noNullElements(array, DEFAULT_NO_NULL_ELEMENTS_ARRAY_EX_MESSAGE);
}
/**
- * Validates that the index is within the bounds of the argument
- * array; otherwise throwing an exception with the specified message.
+ * Validate that the specified argument array is neither
+ * {@code null} nor contains any elements that are {@code null};
+ * otherwise throwing an exception with the specified message.
*
- * <pre>Validate.validIndex(myArray, 2, "The array index is invalid: ");</pre>
+ * <pre>Validate.noNullElements(myArray, "The array contain null at position %d");</pre>
*
- * <p>If the array is {@code null}, then the message of the exception
- * is "The validated object is null".</p>
+ * <p>If the array is {@code null}, then the message in the exception
+ * is "The validated object is null".
+ *
+ * <p>If the array has a {@code null} element, then the iteration
+ * index of the invalid element is appended to the {@code values}
+ * argument.</p>
*
* @param <T> the array type
* @param array the array to check, validated not null by this method
- * @param index the index to check
* @param message the {@link String#format(String, Object...)} exception message if invalid, not null
* @param values the optional values for the formatted exception message, null array not recommended
- * @return the validated array (never {@code null} for method chaining)
+ * @return the validated array (never {@code null} method for chaining)
* @throws NullPointerException if the array is {@code null}
- * @throws IndexOutOfBoundsException if the index is invalid
- * @see #validIndex(Object[], int)
- * @since 3.0
+ * @throws IllegalArgumentException if an element is {@code null}
+ * @see #noNullElements(Object[])
*/
- public static <T> T[] validIndex(final T[] array, final int index, final String message, final Object... values) {
+ public static <T> T[] noNullElements(final T[] array, final String message, final Object... values) {
Objects.requireNonNull(array, "array");
- if (index < 0 || index >= array.length) {
- throw new IndexOutOfBoundsException(getMessage(message, values));
+ for (int i = 0; i < array.length; i++) {
+ if (array[i] == null) {
+ final Object[] values2 = ArrayUtils.add(values, Integer.valueOf(i));
+ throw new IllegalArgumentException(getMessage(message, values2));
+ }
}
return array;
}
/**
- * Validates that the index is within the bounds of the argument
- * array; otherwise throwing an exception.
- *
- * <pre>Validate.validIndex(myArray, 2);</pre>
+ * <p>Validate that the specified argument character sequence is
+ * neither {@code null}, a length of zero (no characters), empty
+ * nor whitespace; otherwise throwing an exception.
*
- * <p>If the array is {@code null}, then the message of the exception
- * is "The validated object is null".</p>
+ * <pre>Validate.notBlank(myString);</pre>
*
- * <p>If the index is invalid, then the message of the exception is
- * "The validated array index is invalid: " followed by the
- * index.</p>
+ * <p>The message in the exception is "The validated character
+ * sequence is blank".
*
- * @param <T> the array type
- * @param array the array to check, validated not null by this method
- * @param index the index to check
- * @return the validated array (never {@code null} for method chaining)
- * @throws NullPointerException if the array is {@code null}
- * @throws IndexOutOfBoundsException if the index is invalid
- * @see #validIndex(Object[], int, String, Object...)
+ * @param <T> the character sequence type
+ * @param chars the character sequence to check, validated not null by this method
+ * @return the validated character sequence (never {@code null} method for chaining)
+ * @throws NullPointerException if the character sequence is {@code null}
+ * @throws IllegalArgumentException if the character sequence is blank
+ * @see #notBlank(CharSequence, String, Object...)
* @since 3.0
*/
- public static <T> T[] validIndex(final T[] array, final int index) {
- return validIndex(array, index, DEFAULT_VALID_INDEX_ARRAY_EX_MESSAGE, Integer.valueOf(index));
+ public static <T extends CharSequence> T notBlank(final T chars) {
+ return notBlank(chars, DEFAULT_NOT_BLANK_EX_MESSAGE);
}
/**
- * Validates that the index is within the bounds of the argument
- * collection; otherwise throwing an exception with the specified message.
- *
- * <pre>Validate.validIndex(myCollection, 2, "The collection index is invalid: ");</pre>
+ * Validate that the specified argument character sequence is
+ * neither {@code null}, a length of zero (no characters), empty
+ * nor whitespace; otherwise throwing an exception with the specified
+ * message.
*
- * <p>If the collection is {@code null}, then the message of the
- * exception is "The validated object is null".</p>
+ * <pre>Validate.notBlank(myString, "The string must not be blank");</pre>
*
- * @param <T> the collection type
- * @param collection the collection to check, validated not null by this method
- * @param index the index to check
+ * @param <T> the character sequence type
+ * @param chars the character sequence to check, validated not null by this method
* @param message the {@link String#format(String, Object...)} exception message if invalid, not null
* @param values the optional values for the formatted exception message, null array not recommended
- * @return the validated collection (never {@code null} for chaining)
- * @throws NullPointerException if the collection is {@code null}
- * @throws IndexOutOfBoundsException if the index is invalid
- * @see #validIndex(Collection, int)
+ * @return the validated character sequence (never {@code null} method for chaining)
+ * @throws NullPointerException if the character sequence is {@code null}
+ * @throws IllegalArgumentException if the character sequence is blank
+ * @see #notBlank(CharSequence)
* @since 3.0
*/
- public static <T extends Collection<?>> T validIndex(final T collection, final int index, final String message, final Object... values) {
- Objects.requireNonNull(collection, "collection");
- if (index < 0 || index >= collection.size()) {
- throw new IndexOutOfBoundsException(getMessage(message, values));
+ public static <T extends CharSequence> T notBlank(final T chars, final String message, final Object... values) {
+ Objects.requireNonNull(chars, toSupplier(message, values));
+ if (StringUtils.isBlank(chars)) {
+ throw new IllegalArgumentException(getMessage(message, values));
}
- return collection;
+ return chars;
}
/**
- * Validates that the index is within the bounds of the argument
- * collection; otherwise throwing an exception.
+ * <p>Validate that the specified argument collection is neither {@code null}
+ * nor a size of zero (no elements); otherwise throwing an exception.
*
- * <pre>Validate.validIndex(myCollection, 2);</pre>
+ * <pre>Validate.notEmpty(myCollection);</pre>
*
- * <p>If the index is invalid, then the message of the exception
- * is "The validated collection index is invalid: "
- * followed by the index.</p>
+ * <p>The message in the exception is "The validated collection is
+ * empty".
*
* @param <T> the collection type
* @param collection the collection to check, validated not null by this method
- * @param index the index to check
- * @return the validated collection (never {@code null} for method chaining)
+ * @return the validated collection (never {@code null} method for chaining)
* @throws NullPointerException if the collection is {@code null}
- * @throws IndexOutOfBoundsException if the index is invalid
- * @see #validIndex(Collection, int, String, Object...)
- * @since 3.0
+ * @throws IllegalArgumentException if the collection is empty
+ * @see #notEmpty(Collection, String, Object...)
*/
- public static <T extends Collection<?>> T validIndex(final T collection, final int index) {
- return validIndex(collection, index, DEFAULT_VALID_INDEX_COLLECTION_EX_MESSAGE, Integer.valueOf(index));
+ public static <T extends Collection<?>> T notEmpty(final T collection) {
+ return notEmpty(collection, DEFAULT_NOT_EMPTY_COLLECTION_EX_MESSAGE);
}
/**
- * Validates that the index is within the bounds of the argument
- * character sequence; otherwise throwing an exception with the
- * specified message.
+ * <p>Validate that the specified argument map is neither {@code null}
+ * nor a size of zero (no elements); otherwise throwing an exception.
*
- * <pre>Validate.validIndex(myStr, 2, "The string index is invalid: ");</pre>
+ * <pre>Validate.notEmpty(myMap);</pre>
*
- * <p>If the character sequence is {@code null}, then the message
- * of the exception is "The validated object is null".</p>
+ * <p>The message in the exception is "The validated map is
+ * empty".
*
- * @param <T> the character sequence type
- * @param chars the character sequence to check, validated not null by this method
- * @param index the index to check
- * @param message the {@link String#format(String, Object...)} exception message if invalid, not null
- * @param values the optional values for the formatted exception message, null array not recommended
- * @return the validated character sequence (never {@code null} for method chaining)
- * @throws NullPointerException if the character sequence is {@code null}
- * @throws IndexOutOfBoundsException if the index is invalid
- * @see #validIndex(CharSequence, int)
- * @since 3.0
+ * @param <T> the map type
+ * @param map the map to check, validated not null by this method
+ * @return the validated map (never {@code null} method for chaining)
+ * @throws NullPointerException if the map is {@code null}
+ * @throws IllegalArgumentException if the map is empty
+ * @see #notEmpty(Map, String, Object...)
*/
- public static <T extends CharSequence> T validIndex(final T chars, final int index, final String message, final Object... values) {
- Objects.requireNonNull(chars, "chars");
- if (index < 0 || index >= chars.length()) {
- throw new IndexOutOfBoundsException(getMessage(message, values));
- }
- return chars;
+ public static <T extends Map<?, ?>> T notEmpty(final T map) {
+ return notEmpty(map, DEFAULT_NOT_EMPTY_MAP_EX_MESSAGE);
}
/**
- * Validates that the index is within the bounds of the argument
- * character sequence; otherwise throwing an exception.
- *
- * <pre>Validate.validIndex(myStr, 2);</pre>
+ * <p>Validate that the specified argument character sequence is
+ * neither {@code null} nor a length of zero (no characters);
+ * otherwise throwing an exception with the specified message.
*
- * <p>If the character sequence is {@code null}, then the message
- * of the exception is "The validated object is
- * null".</p>
+ * <pre>Validate.notEmpty(myString);</pre>
*
- * <p>If the index is invalid, then the message of the exception
- * is "The validated character sequence index is invalid: "
- * followed by the index.</p>
+ * <p>The message in the exception is "The validated
+ * character sequence is empty".
*
* @param <T> the character sequence type
* @param chars the character sequence to check, validated not null by this method
- * @param index the index to check
- * @return the validated character sequence (never {@code null} for method chaining)
+ * @return the validated character sequence (never {@code null} method for chaining)
* @throws NullPointerException if the character sequence is {@code null}
- * @throws IndexOutOfBoundsException if the index is invalid
- * @see #validIndex(CharSequence, int, String, Object...)
- * @since 3.0
+ * @throws IllegalArgumentException if the character sequence is empty
+ * @see #notEmpty(CharSequence, String, Object...)
*/
- public static <T extends CharSequence> T validIndex(final T chars, final int index) {
- return validIndex(chars, index, DEFAULT_VALID_INDEX_CHAR_SEQUENCE_EX_MESSAGE, Integer.valueOf(index));
+ public static <T extends CharSequence> T notEmpty(final T chars) {
+ return notEmpty(chars, DEFAULT_NOT_EMPTY_CHAR_SEQUENCE_EX_MESSAGE);
}
/**
- * Validate that the stateful condition is {@code true}; otherwise
- * throwing an exception. This method is useful when validating according
- * to an arbitrary boolean expression, such as validating a
- * primitive number or using your own custom validation expression.
+ * <p>Validate that the specified argument collection is neither {@code null}
+ * nor a size of zero (no elements); otherwise throwing an exception
+ * with the specified message.
*
- * <pre>
- * Validate.validState(field > 0);
- * Validate.validState(this.isOk());</pre>
+ * <pre>Validate.notEmpty(myCollection, "The collection must not be empty");</pre>
*
- * <p>The message of the exception is "The validated state is
- * false".</p>
+ * @param <T> the collection type
+ * @param collection the collection to check, validated not null by this method
+ * @param message the {@link String#format(String, Object...)} exception message if invalid, not null
+ * @param values the optional values for the formatted exception message, null array not recommended
+ * @return the validated collection (never {@code null} method for chaining)
+ * @throws NullPointerException if the collection is {@code null}
+ * @throws IllegalArgumentException if the collection is empty
+ * @see #notEmpty(Object[])
+ */
+ public static <T extends Collection<?>> T notEmpty(final T collection, final String message, final Object... values) {
+ Objects.requireNonNull(collection, toSupplier(message, values));
+ if (collection.isEmpty()) {
+ throw new IllegalArgumentException(getMessage(message, values));
+ }
+ return collection;
+ }
+
+ /**
+ * Validate that the specified argument map is neither {@code null}
+ * nor a size of zero (no elements); otherwise throwing an exception
+ * with the specified message.
*
- * @param expression the boolean expression to check
- * @throws IllegalStateException if expression is {@code false}
- * @see #validState(boolean, String, Object...)
- * @since 3.0
+ * <pre>Validate.notEmpty(myMap, "The map must not be empty");</pre>
+ *
+ * @param <T> the map type
+ * @param map the map to check, validated not null by this method
+ * @param message the {@link String#format(String, Object...)} exception message if invalid, not null
+ * @param values the optional values for the formatted exception message, null array not recommended
+ * @return the validated map (never {@code null} method for chaining)
+ * @throws NullPointerException if the map is {@code null}
+ * @throws IllegalArgumentException if the map is empty
+ * @see #notEmpty(Object[])
*/
- public static void validState(final boolean expression) {
- if (!expression) {
- throw new IllegalStateException(DEFAULT_VALID_STATE_EX_MESSAGE);
+ public static <T extends Map<?, ?>> T notEmpty(final T map, final String message, final Object... values) {
+ Objects.requireNonNull(map, toSupplier(message, values));
+ if (map.isEmpty()) {
+ throw new IllegalArgumentException(getMessage(message, values));
}
+ return map;
}
/**
- * Validate that the stateful condition is {@code true}; otherwise
- * throwing an exception with the specified message. This method is useful when
- * validating according to an arbitrary boolean expression, such as validating a
- * primitive number or using your own custom validation expression.
+ * Validate that the specified argument character sequence is
+ * neither {@code null} nor a length of zero (no characters);
+ * otherwise throwing an exception with the specified message.
*
- * <pre>Validate.validState(this.isOk(), "The state is not OK: %s", myObject);</pre>
+ * <pre>Validate.notEmpty(myString, "The string must not be empty");</pre>
*
- * @param expression the boolean expression to check
+ * @param <T> the character sequence type
+ * @param chars the character sequence to check, validated not null by this method
* @param message the {@link String#format(String, Object...)} exception message if invalid, not null
* @param values the optional values for the formatted exception message, null array not recommended
- * @throws IllegalStateException if expression is {@code false}
- * @see #validState(boolean)
- * @since 3.0
+ * @return the validated character sequence (never {@code null} method for chaining)
+ * @throws NullPointerException if the character sequence is {@code null}
+ * @throws IllegalArgumentException if the character sequence is empty
+ * @see #notEmpty(CharSequence)
*/
- public static void validState(final boolean expression, final String message, final Object... values) {
- if (!expression) {
- throw new IllegalStateException(getMessage(message, values));
+ public static <T extends CharSequence> T notEmpty(final T chars, final String message, final Object... values) {
+ Objects.requireNonNull(chars, toSupplier(message, values));
+ if (chars.length() == 0) {
+ throw new IllegalArgumentException(getMessage(message, values));
}
+ return chars;
}
/**
- * Validate that the specified argument character sequence matches the specified regular
- * expression pattern; otherwise throwing an exception.
+ * <p>Validate that the specified argument array is neither {@code null}
+ * nor a length of zero (no elements); otherwise throwing an exception.
*
- * <pre>Validate.matchesPattern("hi", "[a-z]*");</pre>
+ * <pre>Validate.notEmpty(myArray);</pre>
*
- * <p>The syntax of the pattern is the one used in the {@link Pattern} class.</p>
+ * <p>The message in the exception is "The validated array is
+ * empty".
*
- * @param input the character sequence to validate, not null
- * @param pattern the regular expression pattern, not null
- * @throws IllegalArgumentException if the character sequence does not match the pattern
- * @see #matchesPattern(CharSequence, String, String, Object...)
- * @since 3.0
+ * @param <T> the array type
+ * @param array the array to check, validated not null by this method
+ * @return the validated array (never {@code null} method for chaining)
+ * @throws NullPointerException if the array is {@code null}
+ * @throws IllegalArgumentException if the array is empty
+ * @see #notEmpty(Object[], String, Object...)
*/
- public static void matchesPattern(final CharSequence input, final String pattern) {
- // TODO when breaking BC, consider returning input
- if (!Pattern.matches(pattern, input)) {
- throw new IllegalArgumentException(String.format(DEFAULT_MATCHES_PATTERN_EX, input, pattern));
- }
+ public static <T> T[] notEmpty(final T[] array) {
+ return notEmpty(array, DEFAULT_NOT_EMPTY_ARRAY_EX_MESSAGE);
}
/**
- * Validate that the specified argument character sequence matches the specified regular
- * expression pattern; otherwise throwing an exception with the specified message.
- *
- * <pre>Validate.matchesPattern("hi", "[a-z]*", "%s does not match %s", "hi" "[a-z]*");</pre>
+ * <p>Validate that the specified argument array is neither {@code null}
+ * nor a length of zero (no elements); otherwise throwing an exception
+ * with the specified message.
*
- * <p>The syntax of the pattern is the one used in the {@link Pattern} class.</p>
+ * <pre>Validate.notEmpty(myArray, "The array must not be empty");</pre>
*
- * @param input the character sequence to validate, not null
- * @param pattern the regular expression pattern, not null
+ * @param <T> the array type
+ * @param array the array to check, validated not null by this method
* @param message the {@link String#format(String, Object...)} exception message if invalid, not null
* @param values the optional values for the formatted exception message, null array not recommended
- * @throws IllegalArgumentException if the character sequence does not match the pattern
- * @see #matchesPattern(CharSequence, String)
- * @since 3.0
+ * @return the validated array (never {@code null} method for chaining)
+ * @throws NullPointerException if the array is {@code null}
+ * @throws IllegalArgumentException if the array is empty
+ * @see #notEmpty(Object[])
*/
- public static void matchesPattern(final CharSequence input, final String pattern, final String message, final Object... values) {
- // TODO when breaking BC, consider returning input
- if (!Pattern.matches(pattern, input)) {
+ public static <T> T[] notEmpty(final T[] array, final String message, final Object... values) {
+ Objects.requireNonNull(array, toSupplier(message, values));
+ if (array.length == 0) {
throw new IllegalArgumentException(getMessage(message, values));
}
+ return array;
}
/**
@@ -856,400 +999,257 @@ public class Validate {
}
/**
- * Validates that the specified argument is not infinite or Not-a-Number (NaN);
+ * Validate that the specified argument is not {@code null};
* otherwise throwing an exception.
*
- * <pre>Validate.finite(myDouble);</pre>
+ * <pre>Validate.notNull(myObject, "The object must not be null");</pre>
*
- * <p>The message of the exception is "The value is invalid: %f".</p>
+ * <p>The message of the exception is "The validated object is
+ * null".
*
- * @param value the value to validate
- * @throws IllegalArgumentException if the value is infinite or Not-a-Number (NaN)
- * @see #finite(double, String, Object...)
- * @since 3.5
+ * @param <T> the object type
+ * @param object the object to check
+ * @return the validated object (never {@code null} for method chaining)
+ * @throws NullPointerException if the object is {@code null}
+ * @see #notNull(Object, String, Object...)
+ * @deprecated Use {@link Objects#requireNonNull(Object)}.
*/
- public static void finite(final double value) {
- finite(value, DEFAULT_FINITE_EX_MESSAGE, value);
+ @Deprecated
+ public static <T> T notNull(final T object) {
+ return notNull(object, DEFAULT_IS_NULL_EX_MESSAGE);
}
/**
- * Validates that the specified argument is not infinite or Not-a-Number (NaN);
+ * Validate that the specified argument is not {@code null};
* otherwise throwing an exception with the specified message.
*
- * <pre>Validate.finite(myDouble, "The argument must contain a numeric value");</pre>
+ * <pre>Validate.notNull(myObject, "The object must not be null");</pre>
*
- * @param value the value to validate
+ * @param <T> the object type
+ * @param object the object to check
* @param message the {@link String#format(String, Object...)} exception message if invalid, not null
* @param values the optional values for the formatted exception message
- * @throws IllegalArgumentException if the value is infinite or Not-a-Number (NaN)
- * @see #finite(double)
- * @since 3.5
- */
- public static void finite(final double value, final String message, final Object... values) {
- if (Double.isNaN(value) || Double.isInfinite(value)) {
- throw new IllegalArgumentException(getMessage(message, values));
- }
- }
-
- /**
- * Validate that the specified argument object fall between the two
- * inclusive values specified; otherwise, throws an exception.
- *
- * <pre>Validate.inclusiveBetween(0, 2, 1);</pre>
- *
- * @param <T> the type of the argument object
- * @param start the inclusive start value, not null
- * @param end the inclusive end value, not null
- * @param value the object to validate, not null
- * @throws IllegalArgumentException if the value falls outside the boundaries
- * @see #inclusiveBetween(Object, Object, Comparable, String, Object...)
- * @since 3.0
- */
- public static <T> void inclusiveBetween(final T start, final T end, final Comparable<T> value) {
- // TODO when breaking BC, consider returning value
- if (value.compareTo(start) < 0 || value.compareTo(end) > 0) {
- throw new IllegalArgumentException(String.format(DEFAULT_INCLUSIVE_BETWEEN_EX_MESSAGE, value, start, end));
- }
- }
-
- /**
- * Validate that the specified argument object fall between the two
- * inclusive values specified; otherwise, throws an exception with the
- * specified message.
- *
- * <pre>Validate.inclusiveBetween(0, 2, 1, "Not in boundaries");</pre>
- *
- * @param <T> the type of the argument object
- * @param start the inclusive start value, not null
- * @param end the inclusive end value, not null
- * @param value the object to validate, not null
- * @param message the {@link String#format(String, Object...)} exception message if invalid, not null
- * @param values the optional values for the formatted exception message, null array not recommended
- * @throws IllegalArgumentException if the value falls outside the boundaries
- * @see #inclusiveBetween(Object, Object, Comparable)
- * @since 3.0
- */
- public static <T> void inclusiveBetween(final T start, final T end, final Comparable<T> value, final String message, final Object... values) {
- // TODO when breaking BC, consider returning value
- if (value.compareTo(start) < 0 || value.compareTo(end) > 0) {
- throw new IllegalArgumentException(getMessage(message, values));
- }
- }
-
- /**
- * Validate that the specified primitive value falls between the two
- * inclusive values specified; otherwise, throws an exception.
- *
- * <pre>Validate.inclusiveBetween(0, 2, 1);</pre>
- *
- * @param start the inclusive start value
- * @param end the inclusive end value
- * @param value the value to validate
- * @throws IllegalArgumentException if the value falls outside the boundaries (inclusive)
- * @since 3.3
- */
- @SuppressWarnings("boxing")
- public static void inclusiveBetween(final long start, final long end, final long value) {
- // TODO when breaking BC, consider returning value
- if (value < start || value > end) {
- throw new IllegalArgumentException(String.format(DEFAULT_INCLUSIVE_BETWEEN_EX_MESSAGE, value, start, end));
- }
- }
-
- /**
- * Validate that the specified primitive value falls between the two
- * inclusive values specified; otherwise, throws an exception with the
- * specified message.
- *
- * <pre>Validate.inclusiveBetween(0, 2, 1, "Not in range");</pre>
- *
- * @param start the inclusive start value
- * @param end the inclusive end value
- * @param value the value to validate
- * @param message the exception message if invalid, not null
- * @throws IllegalArgumentException if the value falls outside the boundaries
- * @since 3.3
- */
- public static void inclusiveBetween(final long start, final long end, final long value, final String message) {
- // TODO when breaking BC, consider returning value
- if (value < start || value > end) {
- throw new IllegalArgumentException(message);
- }
- }
-
- /**
- * Validate that the specified primitive value falls between the two
- * inclusive values specified; otherwise, throws an exception.
- *
- * <pre>Validate.inclusiveBetween(0.1, 2.1, 1.1);</pre>
- *
- * @param start the inclusive start value
- * @param end the inclusive end value
- * @param value the value to validate
- * @throws IllegalArgumentException if the value falls outside the boundaries (inclusive)
- * @since 3.3
- */
- @SuppressWarnings("boxing")
- public static void inclusiveBetween(final double start, final double end, final double value) {
- // TODO when breaking BC, consider returning value
- if (value < start || value > end) {
- throw new IllegalArgumentException(String.format(DEFAULT_INCLUSIVE_BETWEEN_EX_MESSAGE, value, start, end));
- }
- }
-
- /**
- * Validate that the specified primitive value falls between the two
- * inclusive values specified; otherwise, throws an exception with the
- * specified message.
- *
- * <pre>Validate.inclusiveBetween(0.1, 2.1, 1.1, "Not in range");</pre>
- *
- * @param start the inclusive start value
- * @param end the inclusive end value
- * @param value the value to validate
- * @param message the exception message if invalid, not null
- * @throws IllegalArgumentException if the value falls outside the boundaries
- * @since 3.3
+ * @return the validated object (never {@code null} for method chaining)
+ * @throws NullPointerException if the object is {@code null}
+ * @see Objects#requireNonNull(Object)
*/
- public static void inclusiveBetween(final double start, final double end, final double value, final String message) {
- // TODO when breaking BC, consider returning value
- if (value < start || value > end) {
- throw new IllegalArgumentException(message);
- }
+ public static <T> T notNull(final T object, final String message, final Object... values) {
+ return Objects.requireNonNull(object, toSupplier(message, values));
}
- /**
- * Validate that the specified argument object fall between the two
- * exclusive values specified; otherwise, throws an exception.
- *
- * <pre>Validate.exclusiveBetween(0, 2, 1);</pre>
- *
- * @param <T> the type of the argument object
- * @param start the exclusive start value, not null
- * @param end the exclusive end value, not null
- * @param value the object to validate, not null
- * @throws IllegalArgumentException if the value falls outside the boundaries
- * @see #exclusiveBetween(Object, Object, Comparable, String, Object...)
- * @since 3.0
- */
- public static <T> void exclusiveBetween(final T start, final T end, final Comparable<T> value) {
- // TODO when breaking BC, consider returning value
- if (value.compareTo(start) <= 0 || value.compareTo(end) >= 0) {
- throw new IllegalArgumentException(String.format(DEFAULT_EXCLUSIVE_BETWEEN_EX_MESSAGE, value, start, end));
- }
+ private static Supplier<String> toSupplier(final String message, final Object... values) {
+ return () -> getMessage(message, values);
}
/**
- * Validate that the specified argument object fall between the two
- * exclusive values specified; otherwise, throws an exception with the
- * specified message.
- *
- * <pre>Validate.exclusiveBetween(0, 2, 1, "Not in boundaries");</pre>
+ * Validates that the index is within the bounds of the argument
+ * collection; otherwise throwing an exception.
*
- * @param <T> the type of the argument object
- * @param start the exclusive start value, not null
- * @param end the exclusive end value, not null
- * @param value the object to validate, not null
- * @param message the {@link String#format(String, Object...)} exception message if invalid, not null
- * @param values the optional values for the formatted exception message, null array not recommended
- * @throws IllegalArgumentException if the value falls outside the boundaries
- * @see #exclusiveBetween(Object, Object, Comparable)
- * @since 3.0
- */
- public static <T> void exclusiveBetween(final T start, final T end, final Comparable<T> value, final String message, final Object... values) {
- // TODO when breaking BC, consider returning value
- if (value.compareTo(start) <= 0 || value.compareTo(end) >= 0) {
- throw new IllegalArgumentException(getMessage(message, values));
- }
- }
-
- /**
- * Validate that the specified primitive value falls between the two
- * exclusive values specified; otherwise, throws an exception.
+ * <pre>Validate.validIndex(myCollection, 2);</pre>
*
- * <pre>Validate.exclusiveBetween(0, 2, 1);</pre>
+ * <p>If the index is invalid, then the message of the exception
+ * is "The validated collection index is invalid: "
+ * followed by the index.</p>
*
- * @param start the exclusive start value
- * @param end the exclusive end value
- * @param value the value to validate
- * @throws IllegalArgumentException if the value falls out of the boundaries
- * @since 3.3
+ * @param <T> the collection type
+ * @param collection the collection to check, validated not null by this method
+ * @param index the index to check
+ * @return the validated collection (never {@code null} for method chaining)
+ * @throws NullPointerException if the collection is {@code null}
+ * @throws IndexOutOfBoundsException if the index is invalid
+ * @see #validIndex(Collection, int, String, Object...)
+ * @since 3.0
*/
- @SuppressWarnings("boxing")
- public static void exclusiveBetween(final long start, final long end, final long value) {
- // TODO when breaking BC, consider returning value
- if (value <= start || value >= end) {
- throw new IllegalArgumentException(String.format(DEFAULT_EXCLUSIVE_BETWEEN_EX_MESSAGE, value, start, end));
- }
+ public static <T extends Collection<?>> T validIndex(final T collection, final int index) {
+ return validIndex(collection, index, DEFAULT_VALID_INDEX_COLLECTION_EX_MESSAGE, Integer.valueOf(index));
}
/**
- * Validate that the specified primitive value falls between the two
- * exclusive values specified; otherwise, throws an exception with the
- * specified message.
+ * Validates that the index is within the bounds of the argument
+ * character sequence; otherwise throwing an exception.
*
- * <pre>Validate.exclusiveBetween(0, 2, 1, "Not in range");</pre>
+ * <pre>Validate.validIndex(myStr, 2);</pre>
*
- * @param start the exclusive start value
- * @param end the exclusive end value
- * @param value the value to validate
- * @param message the exception message if invalid, not null
- * @throws IllegalArgumentException if the value falls outside the boundaries
- * @since 3.3
+ * <p>If the character sequence is {@code null}, then the message
+ * of the exception is "The validated object is
+ * null".</p>
+ *
+ * <p>If the index is invalid, then the message of the exception
+ * is "The validated character sequence index is invalid: "
+ * followed by the index.</p>
+ *
+ * @param <T> the character sequence type
+ * @param chars the character sequence to check, validated not null by this method
+ * @param index the index to check
+ * @return the validated character sequence (never {@code null} for method chaining)
+ * @throws NullPointerException if the character sequence is {@code null}
+ * @throws IndexOutOfBoundsException if the index is invalid
+ * @see #validIndex(CharSequence, int, String, Object...)
+ * @since 3.0
*/
- public static void exclusiveBetween(final long start, final long end, final long value, final String message) {
- // TODO when breaking BC, consider returning value
- if (value <= start || value >= end) {
- throw new IllegalArgumentException(message);
- }
+ public static <T extends CharSequence> T validIndex(final T chars, final int index) {
+ return validIndex(chars, index, DEFAULT_VALID_INDEX_CHAR_SEQUENCE_EX_MESSAGE, Integer.valueOf(index));
}
/**
- * Validate that the specified primitive value falls between the two
- * exclusive values specified; otherwise, throws an exception.
+ * Validates that the index is within the bounds of the argument
+ * collection; otherwise throwing an exception with the specified message.
*
- * <pre>Validate.exclusiveBetween(0.1, 2.1, 1.1);</pre>
+ * <pre>Validate.validIndex(myCollection, 2, "The collection index is invalid: ");</pre>
*
- * @param start the exclusive start value
- * @param end the exclusive end value
- * @param value the value to validate
- * @throws IllegalArgumentException if the value falls out of the boundaries
- * @since 3.3
+ * <p>If the collection is {@code null}, then the message of the
+ * exception is "The validated object is null".</p>
+ *
+ * @param <T> the collection type
+ * @param collection the collection to check, validated not null by this method
+ * @param index the index to check
+ * @param message the {@link String#format(String, Object...)} exception message if invalid, not null
+ * @param values the optional values for the formatted exception message, null array not recommended
+ * @return the validated collection (never {@code null} for chaining)
+ * @throws NullPointerException if the collection is {@code null}
+ * @throws IndexOutOfBoundsException if the index is invalid
+ * @see #validIndex(Collection, int)
+ * @since 3.0
*/
- @SuppressWarnings("boxing")
- public static void exclusiveBetween(final double start, final double end, final double value) {
- // TODO when breaking BC, consider returning value
- if (value <= start || value >= end) {
- throw new IllegalArgumentException(String.format(DEFAULT_EXCLUSIVE_BETWEEN_EX_MESSAGE, value, start, end));
+ public static <T extends Collection<?>> T validIndex(final T collection, final int index, final String message, final Object... values) {
+ Objects.requireNonNull(collection, "collection");
+ if (index < 0 || index >= collection.size()) {
+ throw new IndexOutOfBoundsException(getMessage(message, values));
}
+ return collection;
}
/**
- * Validate that the specified primitive value falls between the two
- * exclusive values specified; otherwise, throws an exception with the
+ * Validates that the index is within the bounds of the argument
+ * character sequence; otherwise throwing an exception with the
* specified message.
*
- * <pre>Validate.exclusiveBetween(0.1, 2.1, 1.1, "Not in range");</pre>
+ * <pre>Validate.validIndex(myStr, 2, "The string index is invalid: ");</pre>
*
- * @param start the exclusive start value
- * @param end the exclusive end value
- * @param value the value to validate
- * @param message the exception message if invalid, not null
- * @throws IllegalArgumentException if the value falls outside the boundaries
- * @since 3.3
+ * <p>If the character sequence is {@code null}, then the message
+ * of the exception is "The validated object is null".</p>
+ *
+ * @param <T> the character sequence type
+ * @param chars the character sequence to check, validated not null by this method
+ * @param index the index to check
+ * @param message the {@link String#format(String, Object...)} exception message if invalid, not null
+ * @param values the optional values for the formatted exception message, null array not recommended
+ * @return the validated character sequence (never {@code null} for method chaining)
+ * @throws NullPointerException if the character sequence is {@code null}
+ * @throws IndexOutOfBoundsException if the index is invalid
+ * @see #validIndex(CharSequence, int)
+ * @since 3.0
*/
- public static void exclusiveBetween(final double start, final double end, final double value, final String message) {
- // TODO when breaking BC, consider returning value
- if (value <= start || value >= end) {
- throw new IllegalArgumentException(message);
+ public static <T extends CharSequence> T validIndex(final T chars, final int index, final String message, final Object... values) {
+ Objects.requireNonNull(chars, "chars");
+ if (index < 0 || index >= chars.length()) {
+ throw new IndexOutOfBoundsException(getMessage(message, values));
}
+ return chars;
}
/**
- * Validates that the argument is an instance of the specified class, if not throws an exception.
+ * Validates that the index is within the bounds of the argument
+ * array; otherwise throwing an exception.
*
- * <p>This method is useful when validating according to an arbitrary class</p>
+ * <pre>Validate.validIndex(myArray, 2);</pre>
*
- * <pre>Validate.isInstanceOf(OkClass.class, object);</pre>
+ * <p>If the array is {@code null}, then the message of the exception
+ * is "The validated object is null".</p>
*
- * <p>The message of the exception is "Expected type: {type}, actual: {obj_type}"</p>
+ * <p>If the index is invalid, then the message of the exception is
+ * "The validated array index is invalid: " followed by the
+ * index.</p>
*
- * @param type the class the object must be validated against, not null
- * @param obj the object to check, null throws an exception
- * @throws IllegalArgumentException if argument is not of specified class
- * @see #isInstanceOf(Class, Object, String, Object...)
+ * @param <T> the array type
+ * @param array the array to check, validated not null by this method
+ * @param index the index to check
+ * @return the validated array (never {@code null} for method chaining)
+ * @throws NullPointerException if the array is {@code null}
+ * @throws IndexOutOfBoundsException if the index is invalid
+ * @see #validIndex(Object[], int, String, Object...)
* @since 3.0
*/
- public static void isInstanceOf(final Class<?> type, final Object obj) {
- // TODO when breaking BC, consider returning obj
- if (!type.isInstance(obj)) {
- throw new IllegalArgumentException(String.format(DEFAULT_IS_INSTANCE_OF_EX_MESSAGE, type.getName(), ClassUtils.getName(obj, "null")));
- }
+ public static <T> T[] validIndex(final T[] array, final int index) {
+ return validIndex(array, index, DEFAULT_VALID_INDEX_ARRAY_EX_MESSAGE, Integer.valueOf(index));
}
/**
- * Validate that the argument is an instance of the specified class; otherwise
- * throwing an exception with the specified message. This method is useful when
- * validating according to an arbitrary class
+ * Validates that the index is within the bounds of the argument
+ * array; otherwise throwing an exception with the specified message.
*
- * <pre>Validate.isInstanceOf(OkClass.class, object, "Wrong class, object is of class %s",
- * object.getClass().getName());</pre>
+ * <pre>Validate.validIndex(myArray, 2, "The array index is invalid: ");</pre>
*
- * @param type the class the object must be validated against, not null
- * @param obj the object to check, null throws an exception
+ * <p>If the array is {@code null}, then the message of the exception
+ * is "The validated object is null".</p>
+ *
+ * @param <T> the array type
+ * @param array the array to check, validated not null by this method
+ * @param index the index to check
* @param message the {@link String#format(String, Object...)} exception message if invalid, not null
* @param values the optional values for the formatted exception message, null array not recommended
- * @throws IllegalArgumentException if argument is not of specified class
- * @see #isInstanceOf(Class, Object)
+ * @return the validated array (never {@code null} for method chaining)
+ * @throws NullPointerException if the array is {@code null}
+ * @throws IndexOutOfBoundsException if the index is invalid
+ * @see #validIndex(Object[], int)
* @since 3.0
*/
- public static void isInstanceOf(final Class<?> type, final Object obj, final String message, final Object... values) {
- // TODO when breaking BC, consider returning obj
- if (!type.isInstance(obj)) {
- throw new IllegalArgumentException(getMessage(message, values));
+ public static <T> T[] validIndex(final T[] array, final int index, final String message, final Object... values) {
+ Objects.requireNonNull(array, "array");
+ if (index < 0 || index >= array.length) {
+ throw new IndexOutOfBoundsException(getMessage(message, values));
}
+ return array;
}
/**
- * Validates that the argument can be converted to the specified class, if not, throws an exception.
- *
- * <p>This method is useful when validating that there will be no casting errors.</p>
+ * Validate that the stateful condition is {@code true}; otherwise
+ * throwing an exception. This method is useful when validating according
+ * to an arbitrary boolean expression, such as validating a
+ * primitive number or using your own custom validation expression.
*
- * <pre>Validate.isAssignableFrom(SuperClass.class, object.getClass());</pre>
+ * <pre>
+ * Validate.validState(field > 0);
+ * Validate.validState(this.isOk());</pre>
*
- * <p>The message format of the exception is "Cannot assign {type} to {superType}"</p>
+ * <p>The message of the exception is "The validated state is
+ * false".</p>
*
- * @param superType the class must be validated against, not null
- * @param type the class to check, not null
- * @throws IllegalArgumentException if type argument is not assignable to the specified superType
- * @see #isAssignableFrom(Class, Class, String, Object...)
+ * @param expression the boolean expression to check
+ * @throws IllegalStateException if expression is {@code false}
+ * @see #validState(boolean, String, Object...)
* @since 3.0
*/
- public static void isAssignableFrom(final Class<?> superType, final Class<?> type) {
- // TODO when breaking BC, consider returning type
- if (type == null || superType == null || !superType.isAssignableFrom(type)) {
- throw new IllegalArgumentException(
- String.format(DEFAULT_IS_ASSIGNABLE_EX_MESSAGE, ClassUtils.getName(type, "null type"), ClassUtils.getName(superType, "null type")));
+ public static void validState(final boolean expression) {
+ if (!expression) {
+ throw new IllegalStateException(DEFAULT_VALID_STATE_EX_MESSAGE);
}
}
/**
- * Validates that the argument can be converted to the specified class, if not throws an exception.
- *
- * <p>This method is useful when validating if there will be no casting errors.</p>
- *
- * <pre>Validate.isAssignableFrom(SuperClass.class, object.getClass());</pre>
+ * Validate that the stateful condition is {@code true}; otherwise
+ * throwing an exception with the specified message. This method is useful when
+ * validating according to an arbitrary boolean expression, such as validating a
+ * primitive number or using your own custom validation expression.
*
- * <p>The message of the exception is "The validated object can not be converted to the"
- * followed by the name of the class and "class"</p>
+ * <pre>Validate.validState(this.isOk(), "The state is not OK: %s", myObject);</pre>
*
- * @param superType the class must be validated against, not null
- * @param type the class to check, not null
+ * @param expression the boolean expression to check
* @param message the {@link String#format(String, Object...)} exception message if invalid, not null
* @param values the optional values for the formatted exception message, null array not recommended
- * @throws IllegalArgumentException if argument can not be converted to the specified class
- * @see #isAssignableFrom(Class, Class)
+ * @throws IllegalStateException if expression is {@code false}
+ * @see #validState(boolean)
+ * @since 3.0
*/
- public static void isAssignableFrom(final Class<?> superType, final Class<?> type, final String message, final Object... values) {
- // TODO when breaking BC, consider returning type
- if (!superType.isAssignableFrom(type)) {
- throw new IllegalArgumentException(getMessage(message, values));
+ public static void validState(final boolean expression, final String message, final Object... values) {
+ if (!expression) {
+ throw new IllegalStateException(getMessage(message, values));
}
}
/**
- * Gets the message using {@link String#format(String, Object...) String.format(message, values)}
- * if the values are not empty, otherwise return the message unformatted.
- * This method exists to allow validation methods declaring a String message and varargs parameters
- * to be used without any message parameters when the message contains special characters,
- * e.g. {@code Validate.isTrue(false, "%Failed%")}.
- *
- * @param message the {@link String#format(String, Object...)} exception message if invalid, not null
- * @param values the optional values for the formatted message
- * @return formatted message using {@link String#format(String, Object...) String.format(message, values)}
- * if the values are not empty, otherwise return the unformatted message.
+ * Constructor. This class should not normally be instantiated.
*/
- private static String getMessage(final String message, final Object... values) {
- return ArrayUtils.isEmpty(values) ? message : String.format(message, values);
+ public Validate() {
}
}
diff --git a/src/main/java/org/apache/commons/lang3/builder/Diff.java b/src/main/java/org/apache/commons/lang3/builder/Diff.java
index 763cd9ae0..334b1c051 100644
--- a/src/main/java/org/apache/commons/lang3/builder/Diff.java
+++ b/src/main/java/org/apache/commons/lang3/builder/Diff.java
@@ -60,6 +60,15 @@ public abstract class Diff<T> extends Pair<T, T> {
this.fieldName = fieldName;
}
+ /**
+ * Gets the name of the field.
+ *
+ * @return the field name
+ */
+ public final String getFieldName() {
+ return fieldName;
+ }
+
/**
* Gets the type of the field.
*
@@ -70,12 +79,15 @@ public abstract class Diff<T> extends Pair<T, T> {
}
/**
- * Gets the name of the field.
+ * Throws {@link UnsupportedOperationException}.
*
- * @return the field name
+ * @param value
+ * ignored
+ * @return nothing
*/
- public final String getFieldName() {
- return fieldName;
+ @Override
+ public final T setValue(final T value) {
+ throw new UnsupportedOperationException("Cannot alter Diff object.");
}
/**
@@ -92,16 +104,4 @@ public abstract class Diff<T> extends Pair<T, T> {
public final String toString() {
return String.format("[%s: %s, %s]", fieldName, getLeft(), getRight());
}
-
- /**
- * Throws {@link UnsupportedOperationException}.
- *
- * @param value
- * ignored
- * @return nothing
- */
- @Override
- public final T setValue(final T value) {
- throw new UnsupportedOperationException("Cannot alter Diff object.");
- }
}
diff --git a/src/main/java/org/apache/commons/lang3/builder/DiffBuilder.java b/src/main/java/org/apache/commons/lang3/builder/DiffBuilder.java
index 4d481c565..1bacfd846 100644
--- a/src/main/java/org/apache/commons/lang3/builder/DiffBuilder.java
+++ b/src/main/java/org/apache/commons/lang3/builder/DiffBuilder.java
@@ -85,6 +85,11 @@ public class DiffBuilder<T> implements Builder<DiffResult<T>> {
* {@link DiffResult} when {@link #build()} is executed.
* </p>
*
+ * <p>
+ * This delegates to {@link #DiffBuilder(Object, Object, ToStringStyle, boolean)}
+ * with the testTriviallyEqual flag enabled.
+ * </p>
+ *
* @param lhs
* {@code this} object
* @param rhs
@@ -92,29 +97,13 @@ public class DiffBuilder<T> implements Builder<DiffResult<T>> {
* @param style
* the style will use when outputting the objects, {@code null}
* uses the default
- * @param testTriviallyEqual
- * If true, this will test if lhs and rhs are the same or equal.
- * All of the append(fieldName, lhs, rhs) methods will abort
- * without creating a field {@link Diff} if the trivially equal
- * test is enabled and returns true. The result of this test
- * is never changed throughout the life of this {@link DiffBuilder}.
* @throws NullPointerException
* if {@code lhs} or {@code rhs} is {@code null}
- * @since 3.4
*/
public DiffBuilder(final T lhs, final T rhs,
- final ToStringStyle style, final boolean testTriviallyEqual) {
-
- Objects.requireNonNull(lhs, "lhs");
- Objects.requireNonNull(rhs, "rhs");
-
- this.diffs = new ArrayList<>();
- this.left = lhs;
- this.right = rhs;
- this.style = style;
+ final ToStringStyle style) {
- // Don't compare any fields if objects equal
- this.objectsTriviallyEqual = testTriviallyEqual && Objects.equals(lhs, rhs);
+ this(lhs, rhs, style, true);
}
/**
@@ -126,11 +115,6 @@ public class DiffBuilder<T> implements Builder<DiffResult<T>> {
* {@link DiffResult} when {@link #build()} is executed.
* </p>
*
- * <p>
- * This delegates to {@link #DiffBuilder(Object, Object, ToStringStyle, boolean)}
- * with the testTriviallyEqual flag enabled.
- * </p>
- *
* @param lhs
* {@code this} object
* @param rhs
@@ -138,13 +122,29 @@ public class DiffBuilder<T> implements Builder<DiffResult<T>> {
* @param style
* the style will use when outputting the objects, {@code null}
* uses the default
+ * @param testTriviallyEqual
+ * If true, this will test if lhs and rhs are the same or equal.
+ * All of the append(fieldName, lhs, rhs) methods will abort
+ * without creating a field {@link Diff} if the trivially equal
+ * test is enabled and returns true. The result of this test
+ * is never changed throughout the life of this {@link DiffBuilder}.
* @throws NullPointerException
* if {@code lhs} or {@code rhs} is {@code null}
+ * @since 3.4
*/
public DiffBuilder(final T lhs, final T rhs,
- final ToStringStyle style) {
+ final ToStringStyle style, final boolean testTriviallyEqual) {
- this(lhs, rhs, style, true);
+ Objects.requireNonNull(lhs, "lhs");
+ Objects.requireNonNull(rhs, "rhs");
+
+ this.diffs = new ArrayList<>();
+ this.left = lhs;
+ this.right = rhs;
+ this.style = style;
+
+ // Don't compare any fields if objects equal
+ this.objectsTriviallyEqual = testTriviallyEqual && Objects.equals(lhs, rhs);
}
/**
@@ -373,6 +373,49 @@ public class DiffBuilder<T> implements Builder<DiffResult<T>> {
return this;
}
+ /**
+ * Append diffs from another {@link DiffResult}.
+ *
+ * <p>
+ * This method is useful if you want to compare properties which are
+ * themselves Diffable and would like to know which specific part of
+ * it is different.
+ * </p>
+ *
+ * <pre>
+ * public class Person implements Diffable<Person> {
+ * String name;
+ * Address address; // implements Diffable<Address>
+ *
+ * ...
+ *
+ * public DiffResult diff(Person obj) {
+ * return new DiffBuilder(this, obj, ToStringStyle.SHORT_PREFIX_STYLE)
+ * .append("name", this.name, obj.name)
+ * .append("address", this.address.diff(obj.address))
+ * .build();
+ * }
+ * }
+ * </pre>
+ *
+ * @param fieldName
+ * the field name
+ * @param diffResult
+ * the {@link DiffResult} to append
+ * @return this
+ * @throws NullPointerException if field name is {@code null} or diffResult is {@code null}
+ * @since 3.5
+ */
+ public DiffBuilder<T> append(final String fieldName, final DiffResult<T> diffResult) {
+ validateFieldNameNotNull(fieldName);
+ Objects.requireNonNull(diffResult, "diffResult");
+ if (objectsTriviallyEqual) {
+ return this;
+ }
+ diffResult.getDiffs().forEach(diff -> append(fieldName + "." + diff.getFieldName(), diff.getLeft(), diff.getRight()));
+ return this;
+ }
+
/**
* Test if two {@code double}s are equal.
*
@@ -677,82 +720,6 @@ public class DiffBuilder<T> implements Builder<DiffResult<T>> {
return this;
}
- /**
- * Test if two {@code short}s are equal.
- *
- * @param fieldName
- * the field name
- * @param lhs
- * the left-hand {@code short}
- * @param rhs
- * the right-hand {@code short}
- * @return this
- * @throws NullPointerException
- * if field name is {@code null}
- */
- public DiffBuilder<T> append(final String fieldName, final short lhs,
- final short rhs) {
- validateFieldNameNotNull(fieldName);
-
- if (objectsTriviallyEqual) {
- return this;
- }
- if (lhs != rhs) {
- diffs.add(new Diff<Short>(fieldName) {
- private static final long serialVersionUID = 1L;
-
- @Override
- public Short getLeft() {
- return Short.valueOf(lhs);
- }
-
- @Override
- public Short getRight() {
- return Short.valueOf(rhs);
- }
- });
- }
- return this;
- }
-
- /**
- * Test if two {@code short[]}s are equal.
- *
- * @param fieldName
- * the field name
- * @param lhs
- * the left-hand {@code short[]}
- * @param rhs
- * the right-hand {@code short[]}
- * @return this
- * @throws NullPointerException
- * if field name is {@code null}
- */
- public DiffBuilder<T> append(final String fieldName, final short[] lhs,
- final short[] rhs) {
- validateFieldNameNotNull(fieldName);
-
- if (objectsTriviallyEqual) {
- return this;
- }
- if (!Arrays.equals(lhs, rhs)) {
- diffs.add(new Diff<Short[]>(fieldName) {
- private static final long serialVersionUID = 1L;
-
- @Override
- public Short[] getLeft() {
- return ArrayUtils.toObject(lhs);
- }
-
- @Override
- public Short[] getRight() {
- return ArrayUtils.toObject(rhs);
- }
- });
- }
- return this;
- }
-
/**
* Test if two {@link Objects}s are equal.
*
@@ -875,45 +842,78 @@ public class DiffBuilder<T> implements Builder<DiffResult<T>> {
}
/**
- * Append diffs from another {@link DiffResult}.
- *
- * <p>
- * This method is useful if you want to compare properties which are
- * themselves Diffable and would like to know which specific part of
- * it is different.
- * </p>
- *
- * <pre>
- * public class Person implements Diffable<Person> {
- * String name;
- * Address address; // implements Diffable<Address>
- *
- * ...
+ * Test if two {@code short}s are equal.
*
- * public DiffResult diff(Person obj) {
- * return new DiffBuilder(this, obj, ToStringStyle.SHORT_PREFIX_STYLE)
- * .append("name", this.name, obj.name)
- * .append("address", this.address.diff(obj.address))
- * .build();
- * }
- * }
- * </pre>
+ * @param fieldName
+ * the field name
+ * @param lhs
+ * the left-hand {@code short}
+ * @param rhs
+ * the right-hand {@code short}
+ * @return this
+ * @throws NullPointerException
+ * if field name is {@code null}
+ */
+ public DiffBuilder<T> append(final String fieldName, final short lhs,
+ final short rhs) {
+ validateFieldNameNotNull(fieldName);
+
+ if (objectsTriviallyEqual) {
+ return this;
+ }
+ if (lhs != rhs) {
+ diffs.add(new Diff<Short>(fieldName) {
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public Short getLeft() {
+ return Short.valueOf(lhs);
+ }
+
+ @Override
+ public Short getRight() {
+ return Short.valueOf(rhs);
+ }
+ });
+ }
+ return this;
+ }
+
+ /**
+ * Test if two {@code short[]}s are equal.
*
* @param fieldName
* the field name
- * @param diffResult
- * the {@link DiffResult} to append
+ * @param lhs
+ * the left-hand {@code short[]}
+ * @param rhs
+ * the right-hand {@code short[]}
* @return this
- * @throws NullPointerException if field name is {@code null} or diffResult is {@code null}
- * @since 3.5
+ * @throws NullPointerException
+ * if field name is {@code null}
*/
- public DiffBuilder<T> append(final String fieldName, final DiffResult<T> diffResult) {
+ public DiffBuilder<T> append(final String fieldName, final short[] lhs,
+ final short[] rhs) {
validateFieldNameNotNull(fieldName);
- Objects.requireNonNull(diffResult, "diffResult");
+
if (objectsTriviallyEqual) {
return this;
}
- diffResult.getDiffs().forEach(diff -> append(fieldName + "." + diff.getFieldName(), diff.getLeft(), diff.getRight()));
+ if (!Arrays.equals(lhs, rhs)) {
+ diffs.add(new Diff<Short[]>(fieldName) {
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public Short[] getLeft() {
+ return ArrayUtils.toObject(lhs);
+ }
+
+ @Override
+ public Short[] getRight() {
+ return ArrayUtils.toObject(rhs);
+ }
+ });
+ }
return this;
}
diff --git a/src/main/java/org/apache/commons/lang3/builder/DiffResult.java b/src/main/java/org/apache/commons/lang3/builder/DiffResult.java
index a5c2d1053..c4c920d9e 100644
--- a/src/main/java/org/apache/commons/lang3/builder/DiffResult.java
+++ b/src/main/java/org/apache/commons/lang3/builder/DiffResult.java
@@ -84,42 +84,42 @@ public class DiffResult<T> implements Iterable<Diff<?>> {
}
/**
- * Returns the object the right object has been compared to.
+ * Returns an unmodifiable list of {@link Diff}s. The list may be empty if
+ * there were no differences between the objects.
*
- * @return the left object of the diff
- * @since 3.10
+ * @return an unmodifiable list of {@link Diff}s
*/
- public T getLeft() {
- return this.lhs;
+ public List<Diff<?>> getDiffs() {
+ return Collections.unmodifiableList(diffList);
}
/**
- * Returns the object the left object has been compared to.
+ * Returns the object the right object has been compared to.
*
- * @return the right object of the diff
+ * @return the left object of the diff
* @since 3.10
*/
- public T getRight() {
- return this.rhs;
+ public T getLeft() {
+ return this.lhs;
}
/**
- * Returns an unmodifiable list of {@link Diff}s. The list may be empty if
- * there were no differences between the objects.
+ * Returns the number of differences between the two objects.
*
- * @return an unmodifiable list of {@link Diff}s
+ * @return the number of differences
*/
- public List<Diff<?>> getDiffs() {
- return Collections.unmodifiableList(diffList);
+ public int getNumberOfDiffs() {
+ return diffList.size();
}
/**
- * Returns the number of differences between the two objects.
+ * Returns the object the left object has been compared to.
*
- * @return the number of differences
+ * @return the right object of the diff
+ * @since 3.10
*/
- public int getNumberOfDiffs() {
- return diffList.size();
+ public T getRight() {
+ return this.rhs;
}
/**
@@ -131,6 +131,16 @@ public class DiffResult<T> implements Iterable<Diff<?>> {
return style;
}
+ /**
+ * Returns an iterator over the {@link Diff} objects contained in this list.
+ *
+ * @return the iterator
+ */
+ @Override
+ public Iterator<Diff<?>> iterator() {
+ return diffList.iterator();
+ }
+
/**
* Builds a {@link String} description of the differences contained within
* this {@link DiffResult}. A {@link ToStringBuilder} is used for each object
@@ -189,14 +199,4 @@ public class DiffResult<T> implements Iterable<Diff<?>> {
return String.format("%s %s %s", lhsBuilder.build(), DIFFERS_STRING, rhsBuilder.build());
}
-
- /**
- * Returns an iterator over the {@link Diff} objects contained in this list.
- *
- * @return the iterator
- */
- @Override
- public Iterator<Diff<?>> iterator() {
- return diffList.iterator();
- }
}
diff --git a/src/main/java/org/apache/commons/lang3/builder/EqualsBuilder.java b/src/main/java/org/apache/commons/lang3/builder/EqualsBuilder.java
index 5b7d393e7..e5c4d33e4 100644
--- a/src/main/java/org/apache/commons/lang3/builder/EqualsBuilder.java
+++ b/src/main/java/org/apache/commons/lang3/builder/EqualsBuilder.java
@@ -112,17 +112,6 @@ public class EqualsBuilder implements Builder<Boolean> {
* to disambiguate the duplicate ids.
*/
- /**
- * Returns the registry of object pairs being traversed by the reflection
- * methods in the current thread.
- *
- * @return Set the registry of objects being traversed
- * @since 3.0
- */
- static Set<Pair<IDKey, IDKey>> getRegistry() {
- return REGISTRY.get();
- }
-
/**
* Converters value pair into a register pair.
*
@@ -137,6 +126,17 @@ public class EqualsBuilder implements Builder<Boolean> {
return Pair.of(left, right);
}
+ /**
+ * Returns the registry of object pairs being traversed by the reflection
+ * methods in the current thread.
+ *
+ * @return Set the registry of objects being traversed
+ * @since 3.0
+ */
+ static Set<Pair<IDKey, IDKey>> getRegistry() {
+ return REGISTRY.get();
+ }
+
/**
* Returns {@code true} if the registry contains the given object pair.
* Used by the reflection methods to avoid infinite loops.
@@ -157,133 +157,6 @@ public class EqualsBuilder implements Builder<Boolean> {
&& (registry.contains(pair) || registry.contains(swappedPair));
}
- /**
- * Registers the given object pair.
- * Used by the reflection methods to avoid infinite loops.
- *
- * @param lhs {@code this} object to register
- * @param rhs the other object to register
- */
- private static void register(final Object lhs, final Object rhs) {
- Set<Pair<IDKey, IDKey>> registry = getRegistry();
- if (registry == null) {
- registry = new HashSet<>();
- REGISTRY.set(registry);
- }
- final Pair<IDKey, IDKey> pair = getRegisterPair(lhs, rhs);
- registry.add(pair);
- }
-
- /**
- * Unregisters the given object pair.
- *
- * <p>
- * Used by the reflection methods to avoid infinite loops.
- *
- * @param lhs {@code this} object to unregister
- * @param rhs the other object to unregister
- * @since 3.0
- */
- private static void unregister(final Object lhs, final Object rhs) {
- final Set<Pair<IDKey, IDKey>> registry = getRegistry();
- if (registry != null) {
- registry.remove(getRegisterPair(lhs, rhs));
- if (registry.isEmpty()) {
- REGISTRY.remove();
- }
- }
- }
-
- /**
- * If the fields tested are equals.
- * The default value is {@code true}.
- */
- private boolean isEquals = true;
-
- private boolean testTransients;
- private boolean testRecursive;
- private List<Class<?>> bypassReflectionClasses;
- private Class<?> reflectUpToClass;
- private String[] excludeFields;
-
- /**
- * Constructor for EqualsBuilder.
- *
- * <p>Starts off assuming that equals is {@code true}.</p>
- * @see Object#equals(Object)
- */
- public EqualsBuilder() {
- // set up default classes to bypass reflection for
- bypassReflectionClasses = new ArrayList<>(1);
- bypassReflectionClasses.add(String.class); //hashCode field being lazy but not transient
- }
-
- /**
- * Sets whether to include transient fields when reflectively comparing objects.
- * @param testTransients whether to test transient fields
- * @return this
- * @since 3.6
- */
- public EqualsBuilder setTestTransients(final boolean testTransients) {
- this.testTransients = testTransients;
- return this;
- }
-
- /**
- * Sets whether to test fields recursively, instead of using their equals method, when reflectively comparing objects.
- * String objects, which cache a hash value, are automatically excluded from recursive testing.
- * You may specify other exceptions by calling {@link #setBypassReflectionClasses(List)}.
- * @param testRecursive whether to do a recursive test
- * @return this
- * @see #setBypassReflectionClasses(List)
- * @since 3.6
- */
- public EqualsBuilder setTestRecursive(final boolean testRecursive) {
- this.testRecursive = testRecursive;
- return this;
- }
-
- /**
- * Sets {@link Class}es whose instances should be compared by calling their {@code equals}
- * although being in recursive mode. So the fields of theses classes will not be compared recursively by reflection.
- *
- * <p>Here you should name classes having non-transient fields which are cache fields being set lazily.<br>
- * Prominent example being {@link String} class with its hash code cache field. Due to the importance
- * of the {@link String} class, it is included in the default bypasses classes. Usually, if you use
- * your own set of classes here, remember to include {@link String} class, too.</p>
- * @param bypassReflectionClasses classes to bypass reflection test
- * @return this
- * @see #setTestRecursive(boolean)
- * @since 3.8
- */
- public EqualsBuilder setBypassReflectionClasses(final List<Class<?>> bypassReflectionClasses) {
- this.bypassReflectionClasses = bypassReflectionClasses;
- return this;
- }
-
- /**
- * Sets the superclass to reflect up to at reflective tests.
- * @param reflectUpToClass the super class to reflect up to
- * @return this
- * @since 3.6
- */
- public EqualsBuilder setReflectUpToClass(final Class<?> reflectUpToClass) {
- this.reflectUpToClass = reflectUpToClass;
- return this;
- }
-
- /**
- * Sets field names to be excluded by reflection tests.
- * @param excludeFields the fields to exclude
- * @return this
- * @since 3.6
- */
- public EqualsBuilder setExcludeFields(final String... excludeFields) {
- this.excludeFields = excludeFields;
- return this;
- }
-
-
/**
* This method uses reflection to determine if the two {@link Object}s
* are equal.
@@ -294,20 +167,21 @@ public class EqualsBuilder implements Builder<Boolean> {
* not as efficient as testing explicitly. Non-primitive fields are compared using
* {@code equals()}.</p>
*
- * <p>Transient members will be not be tested, as they are likely derived
- * fields, and not part of the value of the Object.</p>
+ * <p>If the TestTransients parameter is set to {@code true}, transient
+ * members will be tested, otherwise they are ignored, as they are likely
+ * derived fields, and not part of the value of the {@link Object}.</p>
*
* <p>Static fields will not be tested. Superclass fields will be included.</p>
*
* @param lhs {@code this} object
* @param rhs the other object
- * @param excludeFields Collection of String field names to exclude from testing
+ * @param testTransients whether to include transient fields
* @return {@code true} if the two Objects have tested equals.
*
* @see EqualsExclude
*/
- public static boolean reflectionEquals(final Object lhs, final Object rhs, final Collection<String> excludeFields) {
- return reflectionEquals(lhs, rhs, ReflectionToStringBuilder.toNoNullStringArray(excludeFields));
+ public static boolean reflectionEquals(final Object lhs, final Object rhs, final boolean testTransients) {
+ return reflectionEquals(lhs, rhs, testTransients, null);
}
/**
@@ -320,20 +194,47 @@ public class EqualsBuilder implements Builder<Boolean> {
* not as efficient as testing explicitly. Non-primitive fields are compared using
* {@code equals()}.</p>
*
- * <p>Transient members will be not be tested, as they are likely derived
- * fields, and not part of the value of the Object.</p>
+ * <p>If the testTransients parameter is set to {@code true}, transient
+ * members will be tested, otherwise they are ignored, as they are likely
+ * derived fields, and not part of the value of the {@link Object}.</p>
*
- * <p>Static fields will not be tested. Superclass fields will be included.</p>
+ * <p>Static fields will not be included. Superclass fields will be appended
+ * up to and including the specified superclass. A null superclass is treated
+ * as java.lang.Object.</p>
+ *
+ * <p>If the testRecursive parameter is set to {@code true}, non primitive
+ * (and non primitive wrapper) field types will be compared by
+ * {@link EqualsBuilder} recursively instead of invoking their
+ * {@code equals()} method. Leading to a deep reflection equals test.
*
* @param lhs {@code this} object
* @param rhs the other object
+ * @param testTransients whether to include transient fields
+ * @param reflectUpToClass the superclass to reflect up to (inclusive),
+ * may be {@code null}
+ * @param testRecursive whether to call reflection equals on non-primitive
+ * fields recursively.
* @param excludeFields array of field names to exclude from testing
* @return {@code true} if the two Objects have tested equals.
*
* @see EqualsExclude
+ * @since 3.6
*/
- public static boolean reflectionEquals(final Object lhs, final Object rhs, final String... excludeFields) {
- return reflectionEquals(lhs, rhs, false, null, excludeFields);
+ public static boolean reflectionEquals(final Object lhs, final Object rhs, final boolean testTransients, final Class<?> reflectUpToClass,
+ final boolean testRecursive, final String... excludeFields) {
+ if (lhs == rhs) {
+ return true;
+ }
+ if (lhs == null || rhs == null) {
+ return false;
+ }
+ return new EqualsBuilder()
+ .setExcludeFields(excludeFields)
+ .setReflectUpToClass(reflectUpToClass)
+ .setTestTransients(testTransients)
+ .setTestRecursive(testRecursive)
+ .reflectionAppend(lhs, rhs)
+ .isEquals();
}
/**
@@ -346,21 +247,28 @@ public class EqualsBuilder implements Builder<Boolean> {
* not as efficient as testing explicitly. Non-primitive fields are compared using
* {@code equals()}.</p>
*
- * <p>If the TestTransients parameter is set to {@code true}, transient
+ * <p>If the testTransients parameter is set to {@code true}, transient
* members will be tested, otherwise they are ignored, as they are likely
* derived fields, and not part of the value of the {@link Object}.</p>
*
- * <p>Static fields will not be tested. Superclass fields will be included.</p>
+ * <p>Static fields will not be included. Superclass fields will be appended
+ * up to and including the specified superclass. A null superclass is treated
+ * as java.lang.Object.</p>
*
* @param lhs {@code this} object
* @param rhs the other object
* @param testTransients whether to include transient fields
+ * @param reflectUpToClass the superclass to reflect up to (inclusive),
+ * may be {@code null}
+ * @param excludeFields array of field names to exclude from testing
* @return {@code true} if the two Objects have tested equals.
*
* @see EqualsExclude
+ * @since 2.0
*/
- public static boolean reflectionEquals(final Object lhs, final Object rhs, final boolean testTransients) {
- return reflectionEquals(lhs, rhs, testTransients, null);
+ public static boolean reflectionEquals(final Object lhs, final Object rhs, final boolean testTransients, final Class<?> reflectUpToClass,
+ final String... excludeFields) {
+ return reflectionEquals(lhs, rhs, testTransients, reflectUpToClass, false, excludeFields);
}
/**
@@ -373,30 +281,21 @@ public class EqualsBuilder implements Builder<Boolean> {
* not as efficient as testing explicitly. Non-primitive fields are compared using
* {@code equals()}.</p>
*
- * <p>If the testTransients parameter is set to {@code true}, transient
- * members will be tested, otherwise they are ignored, as they are likely
- * derived fields, and not part of the value of the {@link Object}.</p>
+ * <p>Transient members will be not be tested, as they are likely derived
+ * fields, and not part of the value of the Object.</p>
*
- * <p>Static fields will not be included. Superclass fields will be appended
- * up to and including the specified superclass. A null superclass is treated
- * as java.lang.Object.</p>
+ * <p>Static fields will not be tested. Superclass fields will be included.</p>
*
* @param lhs {@code this} object
* @param rhs the other object
- * @param testTransients whether to include transient fields
- * @param reflectUpToClass the superclass to reflect up to (inclusive),
- * may be {@code null}
- * @param excludeFields array of field names to exclude from testing
+ * @param excludeFields Collection of String field names to exclude from testing
* @return {@code true} if the two Objects have tested equals.
*
* @see EqualsExclude
- * @since 2.0
*/
- public static boolean reflectionEquals(final Object lhs, final Object rhs, final boolean testTransients, final Class<?> reflectUpToClass,
- final String... excludeFields) {
- return reflectionEquals(lhs, rhs, testTransients, reflectUpToClass, false, excludeFields);
+ public static boolean reflectionEquals(final Object lhs, final Object rhs, final Collection<String> excludeFields) {
+ return reflectionEquals(lhs, rhs, ReflectionToStringBuilder.toNoNullStringArray(excludeFields));
}
-
/**
* This method uses reflection to determine if the two {@link Object}s
* are equal.
@@ -407,201 +306,111 @@ public class EqualsBuilder implements Builder<Boolean> {
* not as efficient as testing explicitly. Non-primitive fields are compared using
* {@code equals()}.</p>
*
- * <p>If the testTransients parameter is set to {@code true}, transient
- * members will be tested, otherwise they are ignored, as they are likely
- * derived fields, and not part of the value of the {@link Object}.</p>
- *
- * <p>Static fields will not be included. Superclass fields will be appended
- * up to and including the specified superclass. A null superclass is treated
- * as java.lang.Object.</p>
+ * <p>Transient members will be not be tested, as they are likely derived
+ * fields, and not part of the value of the Object.</p>
*
- * <p>If the testRecursive parameter is set to {@code true}, non primitive
- * (and non primitive wrapper) field types will be compared by
- * {@link EqualsBuilder} recursively instead of invoking their
- * {@code equals()} method. Leading to a deep reflection equals test.
+ * <p>Static fields will not be tested. Superclass fields will be included.</p>
*
* @param lhs {@code this} object
* @param rhs the other object
- * @param testTransients whether to include transient fields
- * @param reflectUpToClass the superclass to reflect up to (inclusive),
- * may be {@code null}
- * @param testRecursive whether to call reflection equals on non-primitive
- * fields recursively.
* @param excludeFields array of field names to exclude from testing
* @return {@code true} if the two Objects have tested equals.
*
* @see EqualsExclude
- * @since 3.6
*/
- public static boolean reflectionEquals(final Object lhs, final Object rhs, final boolean testTransients, final Class<?> reflectUpToClass,
- final boolean testRecursive, final String... excludeFields) {
- if (lhs == rhs) {
- return true;
- }
- if (lhs == null || rhs == null) {
- return false;
- }
- return new EqualsBuilder()
- .setExcludeFields(excludeFields)
- .setReflectUpToClass(reflectUpToClass)
- .setTestTransients(testTransients)
- .setTestRecursive(testRecursive)
- .reflectionAppend(lhs, rhs)
- .isEquals();
+ public static boolean reflectionEquals(final Object lhs, final Object rhs, final String... excludeFields) {
+ return reflectionEquals(lhs, rhs, false, null, excludeFields);
}
-
/**
- * Tests if two {@code objects} by using reflection.
- *
- * <p>It uses {@code AccessibleObject.setAccessible} to gain access to private
- * fields. This means that it will throw a security exception if run under
- * a security manager, if the permissions are not set up correctly. It is also
- * not as efficient as testing explicitly. Non-primitive fields are compared using
- * {@code equals()}.</p>
- *
- * <p>If the testTransients field is set to {@code true}, transient
- * members will be tested, otherwise they are ignored, as they are likely
- * derived fields, and not part of the value of the {@link Object}.</p>
- *
- * <p>Static fields will not be included. Superclass fields will be appended
- * up to and including the specified superclass in field {@code reflectUpToClass}.
- * A null superclass is treated as java.lang.Object.</p>
+ * Registers the given object pair.
+ * Used by the reflection methods to avoid infinite loops.
*
- * <p>Field names listed in field {@code excludeFields} will be ignored.</p>
+ * @param lhs {@code this} object to register
+ * @param rhs the other object to register
+ */
+ private static void register(final Object lhs, final Object rhs) {
+ Set<Pair<IDKey, IDKey>> registry = getRegistry();
+ if (registry == null) {
+ registry = new HashSet<>();
+ REGISTRY.set(registry);
+ }
+ final Pair<IDKey, IDKey> pair = getRegisterPair(lhs, rhs);
+ registry.add(pair);
+ }
+ /**
+ * Unregisters the given object pair.
*
- * <p>If either class of the compared objects is contained in
- * {@code bypassReflectionClasses}, both objects are compared by calling
- * the equals method of the left-hand object with the right-hand object as an argument.</p>
+ * <p>
+ * Used by the reflection methods to avoid infinite loops.
*
- * @param lhs the left-hand object
- * @param rhs the right-hand object
- * @return this
+ * @param lhs {@code this} object to unregister
+ * @param rhs the other object to unregister
+ * @since 3.0
*/
- public EqualsBuilder reflectionAppend(final Object lhs, final Object rhs) {
- if (!isEquals) {
- return this;
- }
- if (lhs == rhs) {
- return this;
- }
- if (lhs == null || rhs == null) {
- isEquals = false;
- return this;
- }
-
- // Find the leaf class since there may be transients in the leaf
- // class or in classes between the leaf and root.
- // If we are not testing transients or a subclass has no ivars,
- // then a subclass can test equals to a superclass.
- final Class<?> lhsClass = lhs.getClass();
- final Class<?> rhsClass = rhs.getClass();
- Class<?> testClass;
- if (lhsClass.isInstance(rhs)) {
- testClass = lhsClass;
- if (!rhsClass.isInstance(lhs)) {
- // rhsClass is a subclass of lhsClass
- testClass = rhsClass;
- }
- } else if (rhsClass.isInstance(lhs)) {
- testClass = rhsClass;
- if (!lhsClass.isInstance(rhs)) {
- // lhsClass is a subclass of rhsClass
- testClass = lhsClass;
+ private static void unregister(final Object lhs, final Object rhs) {
+ final Set<Pair<IDKey, IDKey>> registry = getRegistry();
+ if (registry != null) {
+ registry.remove(getRegisterPair(lhs, rhs));
+ if (registry.isEmpty()) {
+ REGISTRY.remove();
}
- } else {
- // The two classes are not related.
- isEquals = false;
- return this;
}
-
- try {
- if (testClass.isArray()) {
- append(lhs, rhs);
- } else //If either class is being excluded, call normal object equals method on lhsClass.
- if (bypassReflectionClasses != null
- && (bypassReflectionClasses.contains(lhsClass) || bypassReflectionClasses.contains(rhsClass))) {
- isEquals = lhs.equals(rhs);
- } else {
- reflectionAppend(lhs, rhs, testClass);
- while (testClass.getSuperclass() != null && testClass != reflectUpToClass) {
- testClass = testClass.getSuperclass();
- reflectionAppend(lhs, rhs, testClass);
- }
- }
- } catch (final IllegalArgumentException e) {
- // In this case, we tried to test a subclass vs. a superclass and
- // the subclass has ivars or the ivars are transient and
- // we are testing transients.
- // If a subclass has ivars that we are trying to test them, we get an
- // exception and we know that the objects are not equal.
- isEquals = false;
- }
- return this;
}
-
/**
- * Appends the fields and values defined by the given object of the
- * given Class.
- *
- * @param lhs the left-hand object
- * @param rhs the right-hand object
- * @param clazz the class to append details of
+ * If the fields tested are equals.
+ * The default value is {@code true}.
*/
- private void reflectionAppend(
- final Object lhs,
- final Object rhs,
- final Class<?> clazz) {
+ private boolean isEquals = true;
- if (isRegistered(lhs, rhs)) {
- return;
- }
+ private boolean testTransients;
- try {
- register(lhs, rhs);
- final Field[] fields = clazz.getDeclaredFields();
- AccessibleObject.setAccessible(fields, true);
- for (int i = 0; i < fields.length && isEquals; i++) {
- final Field field = fields[i];
- if (!ArrayUtils.contains(excludeFields, field.getName())
- && !field.getName().contains("$")
- && (testTransients || !Modifier.isTransient(field.getModifiers()))
- && !Modifier.isStatic(field.getModifiers())
- && !field.isAnnotationPresent(EqualsExclude.class)) {
- append(Reflection.getUnchecked(field, lhs), Reflection.getUnchecked(field, rhs));
- }
- }
- } finally {
- unregister(lhs, rhs);
- }
+ private boolean testRecursive;
+
+ private List<Class<?>> bypassReflectionClasses;
+
+ private Class<?> reflectUpToClass;
+
+ private String[] excludeFields;
+
+ /**
+ * Constructor for EqualsBuilder.
+ *
+ * <p>Starts off assuming that equals is {@code true}.</p>
+ * @see Object#equals(Object)
+ */
+ public EqualsBuilder() {
+ // set up default classes to bypass reflection for
+ bypassReflectionClasses = new ArrayList<>(1);
+ bypassReflectionClasses.add(String.class); //hashCode field being lazy but not transient
}
+
/**
- * Adds the result of {@code super.equals()} to this builder.
+ * Test if two {@code booleans}s are equal.
*
- * @param superEquals the result of calling {@code super.equals()}
+ * @param lhs the left-hand {@code boolean}
+ * @param rhs the right-hand {@code boolean}
* @return this
- * @since 2.0
- */
- public EqualsBuilder appendSuper(final boolean superEquals) {
+ */
+ public EqualsBuilder append(final boolean lhs, final boolean rhs) {
if (!isEquals) {
return this;
}
- isEquals = superEquals;
+ isEquals = lhs == rhs;
return this;
}
/**
- * Test if two {@link Object}s are equal using either
- * #{@link #reflectionAppend(Object, Object)}, if object are non
- * primitives (or wrapper of primitives) or if field {@code testRecursive}
- * is set to {@code false}. Otherwise, using their
- * {@code equals} method.
+ * Deep comparison of array of {@code boolean}. Length and all
+ * values are compared.
*
- * @param lhs the left-hand object
- * @param rhs the right-hand object
+ * <p>The method {@link #append(boolean, boolean)} is used.</p>
+ *
+ * @param lhs the left-hand {@code boolean[]}
+ * @param rhs the right-hand {@code boolean[]}
* @return this
*/
- public EqualsBuilder append(final Object lhs, final Object rhs) {
+ public EqualsBuilder append(final boolean[] lhs, final boolean[] rhs) {
if (!isEquals) {
return this;
}
@@ -612,79 +421,24 @@ public class EqualsBuilder implements Builder<Boolean> {
this.setEquals(false);
return this;
}
- final Class<?> lhsClass = lhs.getClass();
- if (lhsClass.isArray()) {
- // factor out array case in order to keep method small enough
- // to be inlined
- appendArray(lhs, rhs);
- } else // The simple case, not an array, just test the element
- if (testRecursive && !ClassUtils.isPrimitiveOrWrapper(lhsClass)) {
- reflectionAppend(lhs, rhs);
- } else {
- isEquals = lhs.equals(rhs);
- }
- return this;
- }
-
- /**
- * Test if an {@link Object} is equal to an array.
- *
- * @param lhs the left-hand object, an array
- * @param rhs the right-hand object
- */
- private void appendArray(final Object lhs, final Object rhs) {
- // First we compare different dimensions, for example: a boolean[][] to a boolean[]
- // then we 'Switch' on type of array, to dispatch to the correct handler
- // This handles multidimensional arrays of the same depth
- if (lhs.getClass() != rhs.getClass()) {
+ if (lhs.length != rhs.length) {
this.setEquals(false);
- } else if (lhs instanceof long[]) {
- append((long[]) lhs, (long[]) rhs);
- } else if (lhs instanceof int[]) {
- append((int[]) lhs, (int[]) rhs);
- } else if (lhs instanceof short[]) {
- append((short[]) lhs, (short[]) rhs);
- } else if (lhs instanceof char[]) {
- append((char[]) lhs, (char[]) rhs);
- } else if (lhs instanceof byte[]) {
- append((byte[]) lhs, (byte[]) rhs);
- } else if (lhs instanceof double[]) {
- append((double[]) lhs, (double[]) rhs);
- } else if (lhs instanceof float[]) {
- append((float[]) lhs, (float[]) rhs);
- } else if (lhs instanceof boolean[]) {
- append((boolean[]) lhs, (boolean[]) rhs);
- } else {
- // Not an array of primitives
- append((Object[]) lhs, (Object[]) rhs);
- }
- }
-
- /**
- * Test if two {@code long} s are equal.
- *
- * @param lhs
- * the left-hand {@code long}
- * @param rhs
- * the right-hand {@code long}
- * @return this
- */
- public EqualsBuilder append(final long lhs, final long rhs) {
- if (!isEquals) {
return this;
}
- isEquals = lhs == rhs;
+ for (int i = 0; i < lhs.length && isEquals; ++i) {
+ append(lhs[i], rhs[i]);
+ }
return this;
}
/**
- * Test if two {@code int}s are equal.
+ * Test if two {@code byte}s are equal.
*
- * @param lhs the left-hand {@code int}
- * @param rhs the right-hand {@code int}
+ * @param lhs the left-hand {@code byte}
+ * @param rhs the right-hand {@code byte}
* @return this
*/
- public EqualsBuilder append(final int lhs, final int rhs) {
+ public EqualsBuilder append(final byte lhs, final byte rhs) {
if (!isEquals) {
return this;
}
@@ -693,17 +447,33 @@ public class EqualsBuilder implements Builder<Boolean> {
}
/**
- * Test if two {@code short}s are equal.
+ * Deep comparison of array of {@code byte}. Length and all
+ * values are compared.
*
- * @param lhs the left-hand {@code short}
- * @param rhs the right-hand {@code short}
+ * <p>The method {@link #append(byte, byte)} is used.</p>
+ *
+ * @param lhs the left-hand {@code byte[]}
+ * @param rhs the right-hand {@code byte[]}
* @return this
*/
- public EqualsBuilder append(final short lhs, final short rhs) {
+ public EqualsBuilder append(final byte[] lhs, final byte[] rhs) {
if (!isEquals) {
return this;
}
- isEquals = lhs == rhs;
+ if (lhs == rhs) {
+ return this;
+ }
+ if (lhs == null || rhs == null) {
+ this.setEquals(false);
+ return this;
+ }
+ if (lhs.length != rhs.length) {
+ this.setEquals(false);
+ return this;
+ }
+ for (int i = 0; i < lhs.length && isEquals; ++i) {
+ append(lhs[i], rhs[i]);
+ }
return this;
}
@@ -723,17 +493,33 @@ public class EqualsBuilder implements Builder<Boolean> {
}
/**
- * Test if two {@code byte}s are equal.
+ * Deep comparison of array of {@code char}. Length and all
+ * values are compared.
*
- * @param lhs the left-hand {@code byte}
- * @param rhs the right-hand {@code byte}
+ * <p>The method {@link #append(char, char)} is used.</p>
+ *
+ * @param lhs the left-hand {@code char[]}
+ * @param rhs the right-hand {@code char[]}
* @return this
*/
- public EqualsBuilder append(final byte lhs, final byte rhs) {
+ public EqualsBuilder append(final char[] lhs, final char[] rhs) {
if (!isEquals) {
return this;
}
- isEquals = lhs == rhs;
+ if (lhs == rhs) {
+ return this;
+ }
+ if (lhs == null || rhs == null) {
+ this.setEquals(false);
+ return this;
+ }
+ if (lhs.length != rhs.length) {
+ this.setEquals(false);
+ return this;
+ }
+ for (int i = 0; i < lhs.length && isEquals; ++i) {
+ append(lhs[i], rhs[i]);
+ }
return this;
}
@@ -757,6 +543,37 @@ public class EqualsBuilder implements Builder<Boolean> {
return append(Double.doubleToLongBits(lhs), Double.doubleToLongBits(rhs));
}
+ /**
+ * Deep comparison of array of {@code double}. Length and all
+ * values are compared.
+ *
+ * <p>The method {@link #append(double, double)} is used.</p>
+ *
+ * @param lhs the left-hand {@code double[]}
+ * @param rhs the right-hand {@code double[]}
+ * @return this
+ */
+ public EqualsBuilder append(final double[] lhs, final double[] rhs) {
+ if (!isEquals) {
+ return this;
+ }
+ if (lhs == rhs) {
+ return this;
+ }
+ if (lhs == null || rhs == null) {
+ this.setEquals(false);
+ return this;
+ }
+ if (lhs.length != rhs.length) {
+ this.setEquals(false);
+ return this;
+ }
+ for (int i = 0; i < lhs.length && isEquals; ++i) {
+ append(lhs[i], rhs[i]);
+ }
+ return this;
+ }
+
/**
* Test if two {@code float}s are equal by testing that the
* pattern of bits returned by doubleToLong are equal.
@@ -778,34 +595,16 @@ public class EqualsBuilder implements Builder<Boolean> {
}
/**
- * Test if two {@code booleans}s are equal.
- *
- * @param lhs the left-hand {@code boolean}
- * @param rhs the right-hand {@code boolean}
- * @return this
- */
- public EqualsBuilder append(final boolean lhs, final boolean rhs) {
- if (!isEquals) {
- return this;
- }
- isEquals = lhs == rhs;
- return this;
- }
-
- /**
- * Performs a deep comparison of two {@link Object} arrays.
- *
- * <p>This also will be called for the top level of
- * multi-dimensional, ragged, and multi-typed arrays.</p>
+ * Deep comparison of array of {@code float}. Length and all
+ * values are compared.
*
- * <p>Note that this method does not compare the type of the arrays; it only
- * compares the contents.</p>
+ * <p>The method {@link #append(float, float)} is used.</p>
*
- * @param lhs the left-hand {@code Object[]}
- * @param rhs the right-hand {@code Object[]}
+ * @param lhs the left-hand {@code float[]}
+ * @param rhs the right-hand {@code float[]}
* @return this
*/
- public EqualsBuilder append(final Object[] lhs, final Object[] rhs) {
+ public EqualsBuilder append(final float[] lhs, final float[] rhs) {
if (!isEquals) {
return this;
}
@@ -827,16 +626,31 @@ public class EqualsBuilder implements Builder<Boolean> {
}
/**
- * Deep comparison of array of {@code long}. Length and all
+ * Test if two {@code int}s are equal.
+ *
+ * @param lhs the left-hand {@code int}
+ * @param rhs the right-hand {@code int}
+ * @return this
+ */
+ public EqualsBuilder append(final int lhs, final int rhs) {
+ if (!isEquals) {
+ return this;
+ }
+ isEquals = lhs == rhs;
+ return this;
+ }
+
+ /**
+ * Deep comparison of array of {@code int}. Length and all
* values are compared.
*
- * <p>The method {@link #append(long, long)} is used.</p>
+ * <p>The method {@link #append(int, int)} is used.</p>
*
- * @param lhs the left-hand {@code long[]}
- * @param rhs the right-hand {@code long[]}
+ * @param lhs the left-hand {@code int[]}
+ * @param rhs the right-hand {@code int[]}
* @return this
*/
- public EqualsBuilder append(final long[] lhs, final long[] rhs) {
+ public EqualsBuilder append(final int[] lhs, final int[] rhs) {
if (!isEquals) {
return this;
}
@@ -858,16 +672,33 @@ public class EqualsBuilder implements Builder<Boolean> {
}
/**
- * Deep comparison of array of {@code int}. Length and all
+ * Test if two {@code long} s are equal.
+ *
+ * @param lhs
+ * the left-hand {@code long}
+ * @param rhs
+ * the right-hand {@code long}
+ * @return this
+ */
+ public EqualsBuilder append(final long lhs, final long rhs) {
+ if (!isEquals) {
+ return this;
+ }
+ isEquals = lhs == rhs;
+ return this;
+ }
+
+ /**
+ * Deep comparison of array of {@code long}. Length and all
* values are compared.
*
- * <p>The method {@link #append(int, int)} is used.</p>
+ * <p>The method {@link #append(long, long)} is used.</p>
*
- * @param lhs the left-hand {@code int[]}
- * @param rhs the right-hand {@code int[]}
+ * @param lhs the left-hand {@code long[]}
+ * @param rhs the right-hand {@code long[]}
* @return this
*/
- public EqualsBuilder append(final int[] lhs, final int[] rhs) {
+ public EqualsBuilder append(final long[] lhs, final long[] rhs) {
if (!isEquals) {
return this;
}
@@ -889,16 +720,17 @@ public class EqualsBuilder implements Builder<Boolean> {
}
/**
- * Deep comparison of array of {@code short}. Length and all
- * values are compared.
- *
- * <p>The method {@link #append(short, short)} is used.</p>
+ * Test if two {@link Object}s are equal using either
+ * #{@link #reflectionAppend(Object, Object)}, if object are non
+ * primitives (or wrapper of primitives) or if field {@code testRecursive}
+ * is set to {@code false}. Otherwise, using their
+ * {@code equals} method.
*
- * @param lhs the left-hand {@code short[]}
- * @param rhs the right-hand {@code short[]}
+ * @param lhs the left-hand object
+ * @param rhs the right-hand object
* @return this
*/
- public EqualsBuilder append(final short[] lhs, final short[] rhs) {
+ public EqualsBuilder append(final Object lhs, final Object rhs) {
if (!isEquals) {
return this;
}
@@ -909,27 +741,34 @@ public class EqualsBuilder implements Builder<Boolean> {
this.setEquals(false);
return this;
}
- if (lhs.length != rhs.length) {
- this.setEquals(false);
- return this;
- }
- for (int i = 0; i < lhs.length && isEquals; ++i) {
- append(lhs[i], rhs[i]);
+ final Class<?> lhsClass = lhs.getClass();
+ if (lhsClass.isArray()) {
+ // factor out array case in order to keep method small enough
+ // to be inlined
+ appendArray(lhs, rhs);
+ } else // The simple case, not an array, just test the element
+ if (testRecursive && !ClassUtils.isPrimitiveOrWrapper(lhsClass)) {
+ reflectionAppend(lhs, rhs);
+ } else {
+ isEquals = lhs.equals(rhs);
}
return this;
}
/**
- * Deep comparison of array of {@code char}. Length and all
- * values are compared.
+ * Performs a deep comparison of two {@link Object} arrays.
*
- * <p>The method {@link #append(char, char)} is used.</p>
+ * <p>This also will be called for the top level of
+ * multi-dimensional, ragged, and multi-typed arrays.</p>
*
- * @param lhs the left-hand {@code char[]}
- * @param rhs the right-hand {@code char[]}
+ * <p>Note that this method does not compare the type of the arrays; it only
+ * compares the contents.</p>
+ *
+ * @param lhs the left-hand {@code Object[]}
+ * @param rhs the right-hand {@code Object[]}
* @return this
*/
- public EqualsBuilder append(final char[] lhs, final char[] rhs) {
+ public EqualsBuilder append(final Object[] lhs, final Object[] rhs) {
if (!isEquals) {
return this;
}
@@ -951,16 +790,31 @@ public class EqualsBuilder implements Builder<Boolean> {
}
/**
- * Deep comparison of array of {@code byte}. Length and all
+ * Test if two {@code short}s are equal.
+ *
+ * @param lhs the left-hand {@code short}
+ * @param rhs the right-hand {@code short}
+ * @return this
+ */
+ public EqualsBuilder append(final short lhs, final short rhs) {
+ if (!isEquals) {
+ return this;
+ }
+ isEquals = lhs == rhs;
+ return this;
+ }
+
+ /**
+ * Deep comparison of array of {@code short}. Length and all
* values are compared.
*
- * <p>The method {@link #append(byte, byte)} is used.</p>
+ * <p>The method {@link #append(short, short)} is used.</p>
*
- * @param lhs the left-hand {@code byte[]}
- * @param rhs the right-hand {@code byte[]}
+ * @param lhs the left-hand {@code short[]}
+ * @param rhs the right-hand {@code short[]}
* @return this
*/
- public EqualsBuilder append(final byte[] lhs, final byte[] rhs) {
+ public EqualsBuilder append(final short[] lhs, final short[] rhs) {
if (!isEquals) {
return this;
}
@@ -982,47 +836,106 @@ public class EqualsBuilder implements Builder<Boolean> {
}
/**
- * Deep comparison of array of {@code double}. Length and all
- * values are compared.
+ * Test if an {@link Object} is equal to an array.
+ *
+ * @param lhs the left-hand object, an array
+ * @param rhs the right-hand object
+ */
+ private void appendArray(final Object lhs, final Object rhs) {
+ // First we compare different dimensions, for example: a boolean[][] to a boolean[]
+ // then we 'Switch' on type of array, to dispatch to the correct handler
+ // This handles multidimensional arrays of the same depth
+ if (lhs.getClass() != rhs.getClass()) {
+ this.setEquals(false);
+ } else if (lhs instanceof long[]) {
+ append((long[]) lhs, (long[]) rhs);
+ } else if (lhs instanceof int[]) {
+ append((int[]) lhs, (int[]) rhs);
+ } else if (lhs instanceof short[]) {
+ append((short[]) lhs, (short[]) rhs);
+ } else if (lhs instanceof char[]) {
+ append((char[]) lhs, (char[]) rhs);
+ } else if (lhs instanceof byte[]) {
+ append((byte[]) lhs, (byte[]) rhs);
+ } else if (lhs instanceof double[]) {
+ append((double[]) lhs, (double[]) rhs);
+ } else if (lhs instanceof float[]) {
+ append((float[]) lhs, (float[]) rhs);
+ } else if (lhs instanceof boolean[]) {
+ append((boolean[]) lhs, (boolean[]) rhs);
+ } else {
+ // Not an array of primitives
+ append((Object[]) lhs, (Object[]) rhs);
+ }
+ }
+
+ /**
+ * Adds the result of {@code super.equals()} to this builder.
+ *
+ * @param superEquals the result of calling {@code super.equals()}
+ * @return this
+ * @since 2.0
+ */
+ public EqualsBuilder appendSuper(final boolean superEquals) {
+ if (!isEquals) {
+ return this;
+ }
+ isEquals = superEquals;
+ return this;
+ }
+
+ /**
+ * Returns {@code true} if the fields that have been checked
+ * are all equal.
*
- * <p>The method {@link #append(double, double)} is used.</p>
+ * @return {@code true} if all of the fields that have been checked
+ * are equal, {@code false} otherwise.
*
- * @param lhs the left-hand {@code double[]}
- * @param rhs the right-hand {@code double[]}
- * @return this
+ * @since 3.0
*/
- public EqualsBuilder append(final double[] lhs, final double[] rhs) {
- if (!isEquals) {
- return this;
- }
- if (lhs == rhs) {
- return this;
- }
- if (lhs == null || rhs == null) {
- this.setEquals(false);
- return this;
- }
- if (lhs.length != rhs.length) {
- this.setEquals(false);
- return this;
- }
- for (int i = 0; i < lhs.length && isEquals; ++i) {
- append(lhs[i], rhs[i]);
- }
- return this;
+ @Override
+ public Boolean build() {
+ return Boolean.valueOf(isEquals());
}
/**
- * Deep comparison of array of {@code float}. Length and all
- * values are compared.
+ * Returns {@code true} if the fields that have been checked
+ * are all equal.
*
- * <p>The method {@link #append(float, float)} is used.</p>
+ * @return boolean
+ */
+ public boolean isEquals() {
+ return this.isEquals;
+ }
+
+ /**
+ * Tests if two {@code objects} by using reflection.
*
- * @param lhs the left-hand {@code float[]}
- * @param rhs the right-hand {@code float[]}
+ * <p>It uses {@code AccessibleObject.setAccessible} to gain access to private
+ * fields. This means that it will throw a security exception if run under
+ * a security manager, if the permissions are not set up correctly. It is also
+ * not as efficient as testing explicitly. Non-primitive fields are compared using
+ * {@code equals()}.</p>
+ *
+ * <p>If the testTransients field is set to {@code true}, transient
+ * members will be tested, otherwise they are ignored, as they are likely
+ * derived fields, and not part of the value of the {@link Object}.</p>
+ *
+ * <p>Static fields will not be included. Superclass fields will be appended
+ * up to and including the specified superclass in field {@code reflectUpToClass}.
+ * A null superclass is treated as java.lang.Object.</p>
+ *
+ * <p>Field names listed in field {@code excludeFields} will be ignored.</p>
+ *
+ * <p>If either class of the compared objects is contained in
+ * {@code bypassReflectionClasses}, both objects are compared by calling
+ * the equals method of the left-hand object with the right-hand object as an argument.</p>
+ *
+ * @param lhs the left-hand object
+ * @param rhs the right-hand object
* @return this
*/
- public EqualsBuilder append(final float[] lhs, final float[] rhs) {
+ public EqualsBuilder reflectionAppend(final Object lhs, final Object rhs) {
if (!isEquals) {
return this;
}
@@ -1030,72 +943,120 @@ public class EqualsBuilder implements Builder<Boolean> {
return this;
}
if (lhs == null || rhs == null) {
- this.setEquals(false);
+ isEquals = false;
return this;
}
- if (lhs.length != rhs.length) {
- this.setEquals(false);
+
+ // Find the leaf class since there may be transients in the leaf
+ // class or in classes between the leaf and root.
+ // If we are not testing transients or a subclass has no ivars,
+ // then a subclass can test equals to a superclass.
+ final Class<?> lhsClass = lhs.getClass();
+ final Class<?> rhsClass = rhs.getClass();
+ Class<?> testClass;
+ if (lhsClass.isInstance(rhs)) {
+ testClass = lhsClass;
+ if (!rhsClass.isInstance(lhs)) {
+ // rhsClass is a subclass of lhsClass
+ testClass = rhsClass;
+ }
+ } else if (rhsClass.isInstance(lhs)) {
+ testClass = rhsClass;
+ if (!lhsClass.isInstance(rhs)) {
+ // lhsClass is a subclass of rhsClass
+ testClass = lhsClass;
+ }
+ } else {
+ // The two classes are not related.
+ isEquals = false;
return this;
}
- for (int i = 0; i < lhs.length && isEquals; ++i) {
- append(lhs[i], rhs[i]);
+
+ try {
+ if (testClass.isArray()) {
+ append(lhs, rhs);
+ } else //If either class is being excluded, call normal object equals method on lhsClass.
+ if (bypassReflectionClasses != null
+ && (bypassReflectionClasses.contains(lhsClass) || bypassReflectionClasses.contains(rhsClass))) {
+ isEquals = lhs.equals(rhs);
+ } else {
+ reflectionAppend(lhs, rhs, testClass);
+ while (testClass.getSuperclass() != null && testClass != reflectUpToClass) {
+ testClass = testClass.getSuperclass();
+ reflectionAppend(lhs, rhs, testClass);
+ }
+ }
+ } catch (final IllegalArgumentException e) {
+ // In this case, we tried to test a subclass vs. a superclass and
+ // the subclass has ivars or the ivars are transient and
+ // we are testing transients.
+ // If a subclass has ivars that we are trying to test them, we get an
+ // exception and we know that the objects are not equal.
+ isEquals = false;
}
return this;
}
/**
- * Deep comparison of array of {@code boolean}. Length and all
- * values are compared.
- *
- * <p>The method {@link #append(boolean, boolean)} is used.</p>
+ * Appends the fields and values defined by the given object of the
+ * given Class.
*
- * @param lhs the left-hand {@code boolean[]}
- * @param rhs the right-hand {@code boolean[]}
- * @return this
+ * @param lhs the left-hand object
+ * @param rhs the right-hand object
+ * @param clazz the class to append details of
*/
- public EqualsBuilder append(final boolean[] lhs, final boolean[] rhs) {
- if (!isEquals) {
- return this;
- }
- if (lhs == rhs) {
- return this;
- }
- if (lhs == null || rhs == null) {
- this.setEquals(false);
- return this;
- }
- if (lhs.length != rhs.length) {
- this.setEquals(false);
- return this;
+ private void reflectionAppend(
+ final Object lhs,
+ final Object rhs,
+ final Class<?> clazz) {
+
+ if (isRegistered(lhs, rhs)) {
+ return;
}
- for (int i = 0; i < lhs.length && isEquals; ++i) {
- append(lhs[i], rhs[i]);
+
+ try {
+ register(lhs, rhs);
+ final Field[] fields = clazz.getDeclaredFields();
+ AccessibleObject.setAccessible(fields, true);
+ for (int i = 0; i < fields.length && isEquals; i++) {
+ final Field field = fields[i];
+ if (!ArrayUtils.contains(excludeFields, field.getName())
+ && !field.getName().contains("$")
+ && (testTransients || !Modifier.isTransient(field.getModifiers()))
+ && !Modifier.isStatic(field.getModifiers())
+ && !field.isAnnotationPresent(EqualsExclude.class)) {
+ append(Reflection.getUnchecked(field, lhs), Reflection.getUnchecked(field, rhs));
+ }
+ }
+ } finally {
+ unregister(lhs, rhs);
}
- return this;
}
/**
- * Returns {@code true} if the fields that have been checked
- * are all equal.
- *
- * @return boolean
+ * Reset the EqualsBuilder so you can use the same object again
+ * @since 2.5
*/
- public boolean isEquals() {
- return this.isEquals;
+ public void reset() {
+ this.isEquals = true;
}
/**
- * Returns {@code true} if the fields that have been checked
- * are all equal.
- *
- * @return {@code true} if all of the fields that have been checked
- * are equal, {@code false} otherwise.
+ * Sets {@link Class}es whose instances should be compared by calling their {@code equals}
+ * although being in recursive mode. So the fields of theses classes will not be compared recursively by reflection.
*
- * @since 3.0
+ * <p>Here you should name classes having non-transient fields which are cache fields being set lazily.<br>
+ * Prominent example being {@link String} class with its hash code cache field. Due to the importance
+ * of the {@link String} class, it is included in the default bypasses classes. Usually, if you use
+ * your own set of classes here, remember to include {@link String} class, too.</p>
+ * @param bypassReflectionClasses classes to bypass reflection test
+ * @return this
+ * @see #setTestRecursive(boolean)
+ * @since 3.8
*/
- @Override
- public Boolean build() {
- return Boolean.valueOf(isEquals());
+ public EqualsBuilder setBypassReflectionClasses(final List<Class<?>> bypassReflectionClasses) {
+ this.bypassReflectionClasses = bypassReflectionClasses;
+ return this;
}
/**
@@ -1109,10 +1070,49 @@ public class EqualsBuilder implements Builder<Boolean> {
}
/**
- * Reset the EqualsBuilder so you can use the same object again
- * @since 2.5
+ * Sets field names to be excluded by reflection tests.
+ * @param excludeFields the fields to exclude
+ * @return this
+ * @since 3.6
*/
- public void reset() {
- this.isEquals = true;
+ public EqualsBuilder setExcludeFields(final String... excludeFields) {
+ this.excludeFields = excludeFields;
+ return this;
+ }
+
+ /**
+ * Sets the superclass to reflect up to at reflective tests.
+ * @param reflectUpToClass the super class to reflect up to
+ * @return this
+ * @since 3.6
+ */
+ public EqualsBuilder setReflectUpToClass(final Class<?> reflectUpToClass) {
+ this.reflectUpToClass = reflectUpToClass;
+ return this;
+ }
+
+ /**
+ * Sets whether to test fields recursively, instead of using their equals method, when reflectively comparing objects.
+ * String objects, which cache a hash value, are automatically excluded from recursive testing.
+ * You may specify other exceptions by calling {@link #setBypassReflectionClasses(List)}.
+ * @param testRecursive whether to do a recursive test
+ * @return this
+ * @see #setBypassReflectionClasses(List)
+ * @since 3.6
+ */
+ public EqualsBuilder setTestRecursive(final boolean testRecursive) {
+ this.testRecursive = testRecursive;
+ return this;
+ }
+
+ /**
+ * Sets whether to include transient fields when reflectively comparing objects.
+ * @param testTransients whether to test transient fields
+ * @return this
+ * @since 3.6
+ */
+ public EqualsBuilder setTestTransients(final boolean testTransients) {
+ this.testTransients = testTransients;
+ return this;
}
}
diff --git a/src/main/java/org/apache/commons/lang3/builder/IDKey.java b/src/main/java/org/apache/commons/lang3/builder/IDKey.java
index 8fabb482d..563f7c0d2 100644
--- a/src/main/java/org/apache/commons/lang3/builder/IDKey.java
+++ b/src/main/java/org/apache/commons/lang3/builder/IDKey.java
@@ -43,15 +43,6 @@ final class IDKey {
this.value = value;
}
- /**
- * returns hash code - i.e. the system identity hash code.
- * @return the hash code
- */
- @Override
- public int hashCode() {
- return id;
- }
-
/**
* checks if instances are equal
* @param other The other object to compare to
@@ -69,4 +60,13 @@ final class IDKey {
// Note that identity equals is used.
return value == idKey.value;
}
+
+ /**
+ * returns hash code - i.e. the system identity hash code.
+ * @return the hash code
+ */
+ @Override
+ public int hashCode() {
+ return id;
+ }
}
diff --git a/src/main/java/org/apache/commons/lang3/builder/MultilineRecursiveToStringStyle.java b/src/main/java/org/apache/commons/lang3/builder/MultilineRecursiveToStringStyle.java
index 443282cd1..285d3b791 100644
--- a/src/main/java/org/apache/commons/lang3/builder/MultilineRecursiveToStringStyle.java
+++ b/src/main/java/org/apache/commons/lang3/builder/MultilineRecursiveToStringStyle.java
@@ -82,50 +82,8 @@ public class MultilineRecursiveToStringStyle extends RecursiveToStringStyle {
resetIndent();
}
- /**
- * Resets the fields responsible for the line breaks and indenting.
- * Must be invoked after changing the {@link #spaces} value.
- */
- private void resetIndent() {
- setArrayStart("{" + System.lineSeparator() + spacer(spaces));
- setArraySeparator("," + System.lineSeparator() + spacer(spaces));
- setArrayEnd(System.lineSeparator() + spacer(spaces - INDENT) + "}");
-
- setContentStart("[" + System.lineSeparator() + spacer(spaces));
- setFieldSeparator("," + System.lineSeparator() + spacer(spaces));
- setContentEnd(System.lineSeparator() + spacer(spaces - INDENT) + "]");
- }
-
- /**
- * Creates a StringBuilder responsible for the indenting.
- *
- * @param spaces how far to indent
- * @return a StringBuilder with {spaces} leading space characters.
- */
- private StringBuilder spacer(final int spaces) {
- final StringBuilder sb = new StringBuilder();
- for (int i = 0; i < spaces; i++) {
- sb.append(" ");
- }
- return sb;
- }
-
@Override
- public void appendDetail(final StringBuffer buffer, final String fieldName, final Object value) {
- if (!ClassUtils.isPrimitiveWrapper(value.getClass()) && !String.class.equals(value.getClass())
- && accept(value.getClass())) {
- spaces += INDENT;
- resetIndent();
- buffer.append(ReflectionToStringBuilder.toString(value, this));
- spaces -= INDENT;
- resetIndent();
- } else {
- super.appendDetail(buffer, fieldName, value);
- }
- }
-
- @Override
- protected void appendDetail(final StringBuffer buffer, final String fieldName, final Object[] array) {
+ protected void appendDetail(final StringBuffer buffer, final String fieldName, final boolean[] array) {
spaces += INDENT;
resetIndent();
super.appendDetail(buffer, fieldName, array);
@@ -134,16 +92,16 @@ public class MultilineRecursiveToStringStyle extends RecursiveToStringStyle {
}
@Override
- protected void reflectionAppendArrayDetail(final StringBuffer buffer, final String fieldName, final Object array) {
+ protected void appendDetail(final StringBuffer buffer, final String fieldName, final byte[] array) {
spaces += INDENT;
resetIndent();
- super.reflectionAppendArrayDetail(buffer, fieldName, array);
+ super.appendDetail(buffer, fieldName, array);
spaces -= INDENT;
resetIndent();
}
@Override
- protected void appendDetail(final StringBuffer buffer, final String fieldName, final long[] array) {
+ protected void appendDetail(final StringBuffer buffer, final String fieldName, final char[] array) {
spaces += INDENT;
resetIndent();
super.appendDetail(buffer, fieldName, array);
@@ -152,7 +110,7 @@ public class MultilineRecursiveToStringStyle extends RecursiveToStringStyle {
}
@Override
- protected void appendDetail(final StringBuffer buffer, final String fieldName, final int[] array) {
+ protected void appendDetail(final StringBuffer buffer, final String fieldName, final double[] array) {
spaces += INDENT;
resetIndent();
super.appendDetail(buffer, fieldName, array);
@@ -161,7 +119,7 @@ public class MultilineRecursiveToStringStyle extends RecursiveToStringStyle {
}
@Override
- protected void appendDetail(final StringBuffer buffer, final String fieldName, final short[] array) {
+ protected void appendDetail(final StringBuffer buffer, final String fieldName, final float[] array) {
spaces += INDENT;
resetIndent();
super.appendDetail(buffer, fieldName, array);
@@ -170,7 +128,7 @@ public class MultilineRecursiveToStringStyle extends RecursiveToStringStyle {
}
@Override
- protected void appendDetail(final StringBuffer buffer, final String fieldName, final byte[] array) {
+ protected void appendDetail(final StringBuffer buffer, final String fieldName, final int[] array) {
spaces += INDENT;
resetIndent();
super.appendDetail(buffer, fieldName, array);
@@ -179,7 +137,7 @@ public class MultilineRecursiveToStringStyle extends RecursiveToStringStyle {
}
@Override
- protected void appendDetail(final StringBuffer buffer, final String fieldName, final char[] array) {
+ protected void appendDetail(final StringBuffer buffer, final String fieldName, final long[] array) {
spaces += INDENT;
resetIndent();
super.appendDetail(buffer, fieldName, array);
@@ -188,7 +146,21 @@ public class MultilineRecursiveToStringStyle extends RecursiveToStringStyle {
}
@Override
- protected void appendDetail(final StringBuffer buffer, final String fieldName, final double[] array) {
+ public void appendDetail(final StringBuffer buffer, final String fieldName, final Object value) {
+ if (!ClassUtils.isPrimitiveWrapper(value.getClass()) && !String.class.equals(value.getClass())
+ && accept(value.getClass())) {
+ spaces += INDENT;
+ resetIndent();
+ buffer.append(ReflectionToStringBuilder.toString(value, this));
+ spaces -= INDENT;
+ resetIndent();
+ } else {
+ super.appendDetail(buffer, fieldName, value);
+ }
+ }
+
+ @Override
+ protected void appendDetail(final StringBuffer buffer, final String fieldName, final Object[] array) {
spaces += INDENT;
resetIndent();
super.appendDetail(buffer, fieldName, array);
@@ -197,7 +169,7 @@ public class MultilineRecursiveToStringStyle extends RecursiveToStringStyle {
}
@Override
- protected void appendDetail(final StringBuffer buffer, final String fieldName, final float[] array) {
+ protected void appendDetail(final StringBuffer buffer, final String fieldName, final short[] array) {
spaces += INDENT;
resetIndent();
super.appendDetail(buffer, fieldName, array);
@@ -206,12 +178,40 @@ public class MultilineRecursiveToStringStyle extends RecursiveToStringStyle {
}
@Override
- protected void appendDetail(final StringBuffer buffer, final String fieldName, final boolean[] array) {
+ protected void reflectionAppendArrayDetail(final StringBuffer buffer, final String fieldName, final Object array) {
spaces += INDENT;
resetIndent();
- super.appendDetail(buffer, fieldName, array);
+ super.reflectionAppendArrayDetail(buffer, fieldName, array);
spaces -= INDENT;
resetIndent();
}
+ /**
+ * Resets the fields responsible for the line breaks and indenting.
+ * Must be invoked after changing the {@link #spaces} value.
+ */
+ private void resetIndent() {
+ setArrayStart("{" + System.lineSeparator() + spacer(spaces));
+ setArraySeparator("," + System.lineSeparator() + spacer(spaces));
+ setArrayEnd(System.lineSeparator() + spacer(spaces - INDENT) + "}");
+
+ setContentStart("[" + System.lineSeparator() + spacer(spaces));
+ setFieldSeparator("," + System.lineSeparator() + spacer(spaces));
+ setContentEnd(System.lineSeparator() + spacer(spaces - INDENT) + "]");
+ }
+
+ /**
+ * Creates a StringBuilder responsible for the indenting.
+ *
+ * @param spaces how far to indent
+ * @return a StringBuilder with {spaces} leading space characters.
+ */
+ private StringBuilder spacer(final int spaces) {
+ final StringBuilder sb = new StringBuilder();
+ for (int i = 0; i < spaces; i++) {
+ sb.append(" ");
+ }
+ return sb;
+ }
+
}
diff --git a/src/main/java/org/apache/commons/lang3/builder/RecursiveToStringStyle.java b/src/main/java/org/apache/commons/lang3/builder/RecursiveToStringStyle.java
index 01b5e350c..f773848fc 100644
--- a/src/main/java/org/apache/commons/lang3/builder/RecursiveToStringStyle.java
+++ b/src/main/java/org/apache/commons/lang3/builder/RecursiveToStringStyle.java
@@ -65,24 +65,6 @@ public class RecursiveToStringStyle extends ToStringStyle {
public RecursiveToStringStyle() {
}
- @Override
- public void appendDetail(final StringBuffer buffer, final String fieldName, final Object value) {
- if (!ClassUtils.isPrimitiveWrapper(value.getClass()) &&
- !String.class.equals(value.getClass()) &&
- accept(value.getClass())) {
- buffer.append(ReflectionToStringBuilder.toString(value, this));
- } else {
- super.appendDetail(buffer, fieldName, value);
- }
- }
-
- @Override
- protected void appendDetail(final StringBuffer buffer, final String fieldName, final Collection<?> coll) {
- appendClassName(buffer, coll);
- appendIdentityHashCode(buffer, coll);
- appendDetail(buffer, fieldName, coll.toArray());
- }
-
/**
* Returns whether or not to recursively format the given {@link Class}.
* By default, this method always returns {@code true}, but may be overwritten by
@@ -95,4 +77,22 @@ public class RecursiveToStringStyle extends ToStringStyle {
protected boolean accept(final Class<?> clazz) {
return true;
}
+
+ @Override
+ protected void appendDetail(final StringBuffer buffer, final String fieldName, final Collection<?> coll) {
+ appendClassName(buffer, coll);
+ appendIdentityHashCode(buffer, coll);
+ appendDetail(buffer, fieldName, coll.toArray());
+ }
+
+ @Override
+ public void appendDetail(final StringBuffer buffer, final String fieldName, final Object value) {
+ if (!ClassUtils.isPrimitiveWrapper(value.getClass()) &&
+ !String.class.equals(value.getClass()) &&
+ accept(value.getClass())) {
+ buffer.append(ReflectionToStringBuilder.toString(value, this));
+ } else {
+ super.appendDetail(buffer, fieldName, value);
+ }
+ }
}
diff --git a/src/main/java/org/apache/commons/lang3/builder/ReflectionDiffBuilder.java b/src/main/java/org/apache/commons/lang3/builder/ReflectionDiffBuilder.java
index a5a8f9496..785e08d59 100644
--- a/src/main/java/org/apache/commons/lang3/builder/ReflectionDiffBuilder.java
+++ b/src/main/java/org/apache/commons/lang3/builder/ReflectionDiffBuilder.java
@@ -108,6 +108,49 @@ public class ReflectionDiffBuilder<T> implements Builder<DiffResult<T>> {
this.diffBuilder = new DiffBuilder<>(lhs, rhs, style);
}
+ private boolean accept(final Field field) {
+ if (field.getName().indexOf(ClassUtils.INNER_CLASS_SEPARATOR_CHAR) != -1) {
+ return false;
+ }
+ if (Modifier.isTransient(field.getModifiers())) {
+ return false;
+ }
+ if (Modifier.isStatic(field.getModifiers())) {
+ return false;
+ }
+ if (this.excludeFieldNames != null
+ && Arrays.binarySearch(this.excludeFieldNames, field.getName()) >= 0) {
+ // Reject fields from the getExcludeFieldNames list.
+ return false;
+ }
+ return !field.isAnnotationPresent(DiffExclude.class);
+ }
+
+
+ private void appendFields(final Class<?> clazz) {
+ for (final Field field : FieldUtils.getAllFields(clazz)) {
+ if (accept(field)) {
+ try {
+ diffBuilder.append(field.getName(), FieldUtils.readField(field, left, true), FieldUtils.readField(field, right, true));
+ } catch (final IllegalAccessException e) {
+ // this can't happen. Would get a Security exception instead
+ // throw a runtime exception in case the impossible happens.
+ throw new IllegalArgumentException("Unexpected IllegalAccessException: " + e.getMessage(), e);
+ }
+ }
+ }
+ }
+
+ @Override
+ public DiffResult<T> build() {
+ if (left.equals(right)) {
+ return diffBuilder.build();
+ }
+
+ appendFields(left.getClass());
+ return diffBuilder.build();
+ }
+
/**
* Gets the field names that should be excluded from the diff.
*
@@ -118,7 +161,6 @@ public class ReflectionDiffBuilder<T> implements Builder<DiffResult<T>> {
return this.excludeFieldNames.clone();
}
-
/**
* Sets the field names to exclude.
*
@@ -137,46 +179,4 @@ public class ReflectionDiffBuilder<T> implements Builder<DiffResult<T>> {
return this;
}
- @Override
- public DiffResult<T> build() {
- if (left.equals(right)) {
- return diffBuilder.build();
- }
-
- appendFields(left.getClass());
- return diffBuilder.build();
- }
-
- private void appendFields(final Class<?> clazz) {
- for (final Field field : FieldUtils.getAllFields(clazz)) {
- if (accept(field)) {
- try {
- diffBuilder.append(field.getName(), FieldUtils.readField(field, left, true), FieldUtils.readField(field, right, true));
- } catch (final IllegalAccessException e) {
- // this can't happen. Would get a Security exception instead
- // throw a runtime exception in case the impossible happens.
- throw new IllegalArgumentException("Unexpected IllegalAccessException: " + e.getMessage(), e);
- }
- }
- }
- }
-
- private boolean accept(final Field field) {
- if (field.getName().indexOf(ClassUtils.INNER_CLASS_SEPARATOR_CHAR) != -1) {
- return false;
- }
- if (Modifier.isTransient(field.getModifiers())) {
- return false;
- }
- if (Modifier.isStatic(field.getModifiers())) {
- return false;
- }
- if (this.excludeFieldNames != null
- && Arrays.binarySearch(this.excludeFieldNames, field.getName()) >= 0) {
- // Reject fields from the getExcludeFieldNames list.
- return false;
- }
- return !field.isAnnotationPresent(DiffExclude.class);
- }
-
}
diff --git a/src/main/java/org/apache/commons/lang3/builder/StandardToStringStyle.java b/src/main/java/org/apache/commons/lang3/builder/StandardToStringStyle.java
index ba49f0b47..de8fc28aa 100644
--- a/src/main/java/org/apache/commons/lang3/builder/StandardToStringStyle.java
+++ b/src/main/java/org/apache/commons/lang3/builder/StandardToStringStyle.java
@@ -47,323 +47,332 @@ public class StandardToStringStyle extends ToStringStyle {
}
/**
- * Gets whether to use the class name.
+ * Gets the array end text.
*
- * @return the current useClassName flag
+ * @return the current array end text
*/
@Override
- public boolean isUseClassName() {
- return super.isUseClassName();
+ public String getArrayEnd() {
+ return super.getArrayEnd();
}
/**
- * Sets whether to use the class name.
+ * Gets the array separator text.
*
- * @param useClassName the new useClassName flag
+ * @return the current array separator text
*/
@Override
- public void setUseClassName(final boolean useClassName) {
- super.setUseClassName(useClassName);
+ public String getArraySeparator() {
+ return super.getArraySeparator();
}
/**
- * Gets whether to output short or long class names.
+ * Gets the array start text.
*
- * @return the current useShortClassName flag
- * @since 2.0
+ * @return the current array start text
*/
@Override
- public boolean isUseShortClassName() {
- return super.isUseShortClassName();
+ public String getArrayStart() {
+ return super.getArrayStart();
}
/**
- * Sets whether to output short or long class names.
+ * Gets the content end text.
*
- * @param useShortClassName the new useShortClassName flag
- * @since 2.0
+ * @return the current content end text
*/
@Override
- public void setUseShortClassName(final boolean useShortClassName) {
- super.setUseShortClassName(useShortClassName);
+ public String getContentEnd() {
+ return super.getContentEnd();
}
/**
- * Gets whether to use the identity hash code.
- * @return the current useIdentityHashCode flag
+ * Gets the content start text.
+ *
+ * @return the current content start text
*/
@Override
- public boolean isUseIdentityHashCode() {
- return super.isUseIdentityHashCode();
+ public String getContentStart() {
+ return super.getContentStart();
}
/**
- * Sets whether to use the identity hash code.
+ * Gets the field name value separator text.
*
- * @param useIdentityHashCode the new useIdentityHashCode flag
+ * @return the current field name value separator text
*/
@Override
- public void setUseIdentityHashCode(final boolean useIdentityHashCode) {
- super.setUseIdentityHashCode(useIdentityHashCode);
+ public String getFieldNameValueSeparator() {
+ return super.getFieldNameValueSeparator();
}
/**
- * Gets whether to use the field names passed in.
+ * Gets the field separator text.
*
- * @return the current useFieldNames flag
+ * @return the current field separator text
*/
@Override
- public boolean isUseFieldNames() {
- return super.isUseFieldNames();
+ public String getFieldSeparator() {
+ return super.getFieldSeparator();
}
/**
- * Sets whether to use the field names passed in.
+ * Gets the text to output when {@code null} found.
*
- * @param useFieldNames the new useFieldNames flag
+ * @return the current text to output when {@code null} found
*/
@Override
- public void setUseFieldNames(final boolean useFieldNames) {
- super.setUseFieldNames(useFieldNames);
+ public String getNullText() {
+ return super.getNullText();
}
/**
- * Gets whether to use full detail when the caller doesn't
- * specify.
+ * Gets the end text to output when a {@link Collection},
+ * {@link Map} or {@link Array} size is output.
*
- * @return the current defaultFullDetail flag
+ * <p>This is output after the size value.</p>
+ *
+ * @return the current end of size text
*/
@Override
- public boolean isDefaultFullDetail() {
- return super.isDefaultFullDetail();
+ public String getSizeEndText() {
+ return super.getSizeEndText();
}
/**
- * Sets whether to use full detail when the caller doesn't
- * specify.
+ * Gets the text to output when a {@link Collection},
+ * {@link Map} or {@link Array} size is output.
*
- * @param defaultFullDetail the new defaultFullDetail flag
+ * <p>This is output before the size value.</p>
+ *
+ * @return the current start of size text
*/
@Override
- public void setDefaultFullDetail(final boolean defaultFullDetail) {
- super.setDefaultFullDetail(defaultFullDetail);
+ public String getSizeStartText() {
+ return super.getSizeStartText();
}
/**
- * Gets whether to output array content detail.
+ * Gets the end text to output when an {@link Object} is
+ * output in summary mode.
*
- * @return the current array content detail setting
+ * <p>This is output after the size value.</p>
+ *
+ * @return the current end of summary text
*/
@Override
- public boolean isArrayContentDetail() {
- return super.isArrayContentDetail();
+ public String getSummaryObjectEndText() {
+ return super.getSummaryObjectEndText();
}
/**
- * Sets whether to output array content detail.
+ * Gets the start text to output when an {@link Object} is
+ * output in summary mode.
*
- * @param arrayContentDetail the new arrayContentDetail flag
+ * <p>This is output before the size value.</p>
+ *
+ * @return the current start of summary text
*/
@Override
- public void setArrayContentDetail(final boolean arrayContentDetail) {
- super.setArrayContentDetail(arrayContentDetail);
+ public String getSummaryObjectStartText() {
+ return super.getSummaryObjectStartText();
}
/**
- * Gets the array start text.
+ * Gets whether to output array content detail.
*
- * @return the current array start text
+ * @return the current array content detail setting
*/
@Override
- public String getArrayStart() {
- return super.getArrayStart();
+ public boolean isArrayContentDetail() {
+ return super.isArrayContentDetail();
}
/**
- * Sets the array start text.
- *
- * <p>{@code null} is accepted, but will be converted
- * to an empty String.</p>
+ * Gets whether to use full detail when the caller doesn't
+ * specify.
*
- * @param arrayStart the new array start text
+ * @return the current defaultFullDetail flag
*/
@Override
- public void setArrayStart(final String arrayStart) {
- super.setArrayStart(arrayStart);
+ public boolean isDefaultFullDetail() {
+ return super.isDefaultFullDetail();
}
/**
- * Gets the array end text.
+ * Gets whether the field separator should be added at the end
+ * of each buffer.
*
- * @return the current array end text
+ * @return fieldSeparatorAtEnd flag
+ * @since 2.0
*/
@Override
- public String getArrayEnd() {
- return super.getArrayEnd();
+ public boolean isFieldSeparatorAtEnd() {
+ return super.isFieldSeparatorAtEnd();
}
/**
- * Sets the array end text.
- *
- * <p>{@code null} is accepted, but will be converted
- * to an empty String.</p>
+ * Gets whether the field separator should be added at the start
+ * of each buffer.
*
- * @param arrayEnd the new array end text
+ * @return the fieldSeparatorAtStart flag
+ * @since 2.0
*/
@Override
- public void setArrayEnd(final String arrayEnd) {
- super.setArrayEnd(arrayEnd);
+ public boolean isFieldSeparatorAtStart() {
+ return super.isFieldSeparatorAtStart();
}
/**
- * Gets the array separator text.
+ * Gets whether to use the class name.
*
- * @return the current array separator text
+ * @return the current useClassName flag
*/
@Override
- public String getArraySeparator() {
- return super.getArraySeparator();
+ public boolean isUseClassName() {
+ return super.isUseClassName();
}
/**
- * Sets the array separator text.
- *
- * <p>{@code null} is accepted, but will be converted
- * to an empty String.</p>
+ * Gets whether to use the field names passed in.
*
- * @param arraySeparator the new array separator text
+ * @return the current useFieldNames flag
*/
@Override
- public void setArraySeparator(final String arraySeparator) {
- super.setArraySeparator(arraySeparator);
+ public boolean isUseFieldNames() {
+ return super.isUseFieldNames();
}
/**
- * Gets the content start text.
- *
- * @return the current content start text
+ * Gets whether to use the identity hash code.
+ * @return the current useIdentityHashCode flag
*/
@Override
- public String getContentStart() {
- return super.getContentStart();
+ public boolean isUseIdentityHashCode() {
+ return super.isUseIdentityHashCode();
}
/**
- * Sets the content start text.
- *
- * <p>{@code null} is accepted, but will be converted
- * to an empty String.</p>
+ * Gets whether to output short or long class names.
*
- * @param contentStart the new content start text
+ * @return the current useShortClassName flag
+ * @since 2.0
*/
@Override
- public void setContentStart(final String contentStart) {
- super.setContentStart(contentStart);
+ public boolean isUseShortClassName() {
+ return super.isUseShortClassName();
}
/**
- * Gets the content end text.
+ * Sets whether to output array content detail.
*
- * @return the current content end text
+ * @param arrayContentDetail the new arrayContentDetail flag
*/
@Override
- public String getContentEnd() {
- return super.getContentEnd();
+ public void setArrayContentDetail(final boolean arrayContentDetail) {
+ super.setArrayContentDetail(arrayContentDetail);
}
/**
- * Sets the content end text.
+ * Sets the array end text.
*
* <p>{@code null} is accepted, but will be converted
* to an empty String.</p>
*
- * @param contentEnd the new content end text
+ * @param arrayEnd the new array end text
*/
@Override
- public void setContentEnd(final String contentEnd) {
- super.setContentEnd(contentEnd);
+ public void setArrayEnd(final String arrayEnd) {
+ super.setArrayEnd(arrayEnd);
}
/**
- * Gets the field name value separator text.
+ * Sets the array separator text.
*
- * @return the current field name value separator text
+ * <p>{@code null} is accepted, but will be converted
+ * to an empty String.</p>
+ *
+ * @param arraySeparator the new array separator text
*/
@Override
- public String getFieldNameValueSeparator() {
- return super.getFieldNameValueSeparator();
+ public void setArraySeparator(final String arraySeparator) {
+ super.setArraySeparator(arraySeparator);
}
/**
- * Sets the field name value separator text.
+ * Sets the array start text.
*
* <p>{@code null} is accepted, but will be converted
* to an empty String.</p>
*
- * @param fieldNameValueSeparator the new field name value separator text
+ * @param arrayStart the new array start text
*/
@Override
- public void setFieldNameValueSeparator(final String fieldNameValueSeparator) {
- super.setFieldNameValueSeparator(fieldNameValueSeparator);
+ public void setArrayStart(final String arrayStart) {
+ super.setArrayStart(arrayStart);
}
/**
- * Gets the field separator text.
+ * Sets the content end text.
*
- * @return the current field separator text
+ * <p>{@code null} is accepted, but will be converted
+ * to an empty String.</p>
+ *
+ * @param contentEnd the new content end text
*/
@Override
- public String getFieldSeparator() {
- return super.getFieldSeparator();
+ public void setContentEnd(final String contentEnd) {
+ super.setContentEnd(contentEnd);
}
/**
- * Sets the field separator text.
+ * Sets the content start text.
*
* <p>{@code null} is accepted, but will be converted
* to an empty String.</p>
*
- * @param fieldSeparator the new field separator text
+ * @param contentStart the new content start text
*/
@Override
- public void setFieldSeparator(final String fieldSeparator) {
- super.setFieldSeparator(fieldSeparator);
+ public void setContentStart(final String contentStart) {
+ super.setContentStart(contentStart);
}
/**
- * Gets whether the field separator should be added at the start
- * of each buffer.
+ * Sets whether to use full detail when the caller doesn't
+ * specify.
*
- * @return the fieldSeparatorAtStart flag
- * @since 2.0
+ * @param defaultFullDetail the new defaultFullDetail flag
*/
@Override
- public boolean isFieldSeparatorAtStart() {
- return super.isFieldSeparatorAtStart();
+ public void setDefaultFullDetail(final boolean defaultFullDetail) {
+ super.setDefaultFullDetail(defaultFullDetail);
}
/**
- * Sets whether the field separator should be added at the start
- * of each buffer.
+ * Sets the field name value separator text.
*
- * @param fieldSeparatorAtStart the fieldSeparatorAtStart flag
- * @since 2.0
+ * <p>{@code null} is accepted, but will be converted
+ * to an empty String.</p>
+ *
+ * @param fieldNameValueSeparator the new field name value separator text
*/
@Override
- public void setFieldSeparatorAtStart(final boolean fieldSeparatorAtStart) {
- super.setFieldSeparatorAtStart(fieldSeparatorAtStart);
+ public void setFieldNameValueSeparator(final String fieldNameValueSeparator) {
+ super.setFieldNameValueSeparator(fieldNameValueSeparator);
}
/**
- * Gets whether the field separator should be added at the end
- * of each buffer.
+ * Sets the field separator text.
*
- * @return fieldSeparatorAtEnd flag
- * @since 2.0
+ * <p>{@code null} is accepted, but will be converted
+ * to an empty String.</p>
+ *
+ * @param fieldSeparator the new field separator text
*/
@Override
- public boolean isFieldSeparatorAtEnd() {
- return super.isFieldSeparatorAtEnd();
+ public void setFieldSeparator(final String fieldSeparator) {
+ super.setFieldSeparator(fieldSeparator);
}
/**
@@ -379,13 +388,15 @@ public class StandardToStringStyle extends ToStringStyle {
}
/**
- * Gets the text to output when {@code null} found.
+ * Sets whether the field separator should be added at the start
+ * of each buffer.
*
- * @return the current text to output when {@code null} found
+ * @param fieldSeparatorAtStart the fieldSeparatorAtStart flag
+ * @since 2.0
*/
@Override
- public String getNullText() {
- return super.getNullText();
+ public void setFieldSeparatorAtStart(final boolean fieldSeparatorAtStart) {
+ super.setFieldSeparatorAtStart(fieldSeparatorAtStart);
}
/**
@@ -402,16 +413,19 @@ public class StandardToStringStyle extends ToStringStyle {
}
/**
- * Gets the text to output when a {@link Collection},
+ * Sets the end text to output when a {@link Collection},
* {@link Map} or {@link Array} size is output.
*
- * <p>This is output before the size value.</p>
+ * <p>This is output after the size value.</p>
*
- * @return the current start of size text
+ * <p>{@code null} is accepted, but will be converted
+ * to an empty String.</p>
+ *
+ * @param sizeEndText the new end of size text
*/
@Override
- public String getSizeStartText() {
- return super.getSizeStartText();
+ public void setSizeEndText(final String sizeEndText) {
+ super.setSizeEndText(sizeEndText);
}
/**
@@ -431,90 +445,76 @@ public class StandardToStringStyle extends ToStringStyle {
}
/**
- * Gets the end text to output when a {@link Collection},
- * {@link Map} or {@link Array} size is output.
+ * Sets the end text to output when an {@link Object} is
+ * output in summary mode.
*
* <p>This is output after the size value.</p>
*
- * @return the current end of size text
+ * <p>{@code null} is accepted, but will be converted to
+ * an empty String.</p>
+ *
+ * @param summaryObjectEndText the new end of summary text
*/
@Override
- public String getSizeEndText() {
- return super.getSizeEndText();
+ public void setSummaryObjectEndText(final String summaryObjectEndText) {
+ super.setSummaryObjectEndText(summaryObjectEndText);
}
/**
- * Sets the end text to output when a {@link Collection},
- * {@link Map} or {@link Array} size is output.
+ * Sets the start text to output when an {@link Object} is
+ * output in summary mode.
*
- * <p>This is output after the size value.</p>
+ * <p>This is output before the size value.</p>
*
- * <p>{@code null} is accepted, but will be converted
- * to an empty String.</p>
+ * <p>{@code null} is accepted, but will be converted to
+ * an empty String.</p>
*
- * @param sizeEndText the new end of size text
+ * @param summaryObjectStartText the new start of summary text
*/
@Override
- public void setSizeEndText(final String sizeEndText) {
- super.setSizeEndText(sizeEndText);
+ public void setSummaryObjectStartText(final String summaryObjectStartText) {
+ super.setSummaryObjectStartText(summaryObjectStartText);
}
/**
- * Gets the start text to output when an {@link Object} is
- * output in summary mode.
- *
- * <p>This is output before the size value.</p>
+ * Sets whether to use the class name.
*
- * @return the current start of summary text
+ * @param useClassName the new useClassName flag
*/
@Override
- public String getSummaryObjectStartText() {
- return super.getSummaryObjectStartText();
+ public void setUseClassName(final boolean useClassName) {
+ super.setUseClassName(useClassName);
}
/**
- * Sets the start text to output when an {@link Object} is
- * output in summary mode.
- *
- * <p>This is output before the size value.</p>
- *
- * <p>{@code null} is accepted, but will be converted to
- * an empty String.</p>
+ * Sets whether to use the field names passed in.
*
- * @param summaryObjectStartText the new start of summary text
+ * @param useFieldNames the new useFieldNames flag
*/
@Override
- public void setSummaryObjectStartText(final String summaryObjectStartText) {
- super.setSummaryObjectStartText(summaryObjectStartText);
+ public void setUseFieldNames(final boolean useFieldNames) {
+ super.setUseFieldNames(useFieldNames);
}
/**
- * Gets the end text to output when an {@link Object} is
- * output in summary mode.
- *
- * <p>This is output after the size value.</p>
+ * Sets whether to use the identity hash code.
*
- * @return the current end of summary text
+ * @param useIdentityHashCode the new useIdentityHashCode flag
*/
@Override
- public String getSummaryObjectEndText() {
- return super.getSummaryObjectEndText();
+ public void setUseIdentityHashCode(final boolean useIdentityHashCode) {
+ super.setUseIdentityHashCode(useIdentityHashCode);
}
/**
- * Sets the end text to output when an {@link Object} is
- * output in summary mode.
- *
- * <p>This is output after the size value.</p>
- *
- * <p>{@code null} is accepted, but will be converted to
- * an empty String.</p>
+ * Sets whether to output short or long class names.
*
- * @param summaryObjectEndText the new end of summary text
+ * @param useShortClassName the new useShortClassName flag
+ * @since 2.0
*/
@Override
- public void setSummaryObjectEndText(final String summaryObjectEndText) {
- super.setSummaryObjectEndText(summaryObjectEndText);
+ public void setUseShortClassName(final boolean useShortClassName) {
+ super.setUseShortClassName(useShortClassName);
}
}
diff --git a/src/main/java/org/apache/commons/lang3/builder/ToStringBuilder.java b/src/main/java/org/apache/commons/lang3/builder/ToStringBuilder.java
index afc32e25d..f08eaa45e 100644
--- a/src/main/java/org/apache/commons/lang3/builder/ToStringBuilder.java
+++ b/src/main/java/org/apache/commons/lang3/builder/ToStringBuilder.java
@@ -116,25 +116,6 @@ public class ToStringBuilder implements Builder<String> {
return defaultStyle;
}
- /**
- * Sets the default {@link ToStringStyle} to use.
- *
- * <p>This method sets a singleton default value, typically for the whole JVM.
- * Changing this default should generally only be done during application startup.
- * It is recommended to pass a {@link ToStringStyle} to the constructor instead
- * of changing this global default.</p>
- *
- * <p>This method is not intended for use from multiple threads.
- * Internally, a {@code volatile} variable is used to provide the guarantee
- * that the latest value set is the value returned from {@link #getDefaultStyle}.</p>
- *
- * @param style the default {@link ToStringStyle}
- * @throws NullPointerException if the style is {@code null}
- */
- public static void setDefaultStyle(final ToStringStyle style) {
- defaultStyle = Objects.requireNonNull(style, "style");
- }
-
/**
* Uses {@link ReflectionToStringBuilder} to generate a
* {@code toString} for the specified object.
@@ -195,6 +176,25 @@ public class ToStringBuilder implements Builder<String> {
return ReflectionToStringBuilder.toString(object, style, outputTransients, false, reflectUpToClass);
}
+ /**
+ * Sets the default {@link ToStringStyle} to use.
+ *
+ * <p>This method sets a singleton default value, typically for the whole JVM.
+ * Changing this default should generally only be done during application startup.
+ * It is recommended to pass a {@link ToStringStyle} to the constructor instead
+ * of changing this global default.</p>
+ *
+ * <p>This method is not intended for use from multiple threads.
+ * Internally, a {@code volatile} variable is used to provide the guarantee
+ * that the latest value set is the value returned from {@link #getDefaultStyle}.</p>
+ *
+ * @param style the default {@link ToStringStyle}
+ * @throws NullPointerException if the style is {@code null}
+ */
+ public static void setDefaultStyle(final ToStringStyle style) {
+ defaultStyle = Objects.requireNonNull(style, "style");
+ }
+
/**
* Current toString buffer, not null.
*/
@@ -968,6 +968,21 @@ public class ToStringBuilder implements Builder<String> {
return this;
}
+ /**
+ * Returns the String that was build as an object representation. The
+ * default implementation utilizes the {@link #toString()} implementation.
+ *
+ * @return the String {@code toString}
+ *
+ * @see #toString()
+ *
+ * @since 3.0
+ */
+ @Override
+ public String build() {
+ return toString();
+ }
+
/**
* Returns the {@link Object} being output.
*
@@ -1016,19 +1031,4 @@ public class ToStringBuilder implements Builder<String> {
}
return this.getStringBuffer().toString();
}
-
- /**
- * Returns the String that was build as an object representation. The
- * default implementation utilizes the {@link #toString()} implementation.
- *
- * @return the String {@code toString}
- *
- * @see #toString()
- *
- * @since 3.0
- */
- @Override
- public String build() {
- return toString();
- }
}
diff --git a/src/main/java/org/apache/commons/lang3/builder/ToStringStyle.java b/src/main/java/org/apache/commons/lang3/builder/ToStringStyle.java
index 5e8e06fce..d395567c7 100644
--- a/src/main/java/org/apache/commons/lang3/builder/ToStringStyle.java
+++ b/src/main/java/org/apache/commons/lang3/builder/ToStringStyle.java
@@ -69,754 +69,804 @@ import org.apache.commons.lang3.StringUtils;
public abstract class ToStringStyle implements Serializable {
/**
- * Serialization version ID.
- */
- private static final long serialVersionUID = -2587890625525655916L;
-
- /**
- * The default toString style. Using the {@code Person}
- * example from {@link ToStringBuilder}, the output would look like this:
- *
- * <pre>
- * Person@182f0db[name=John Doe,age=33,smoker=false]
- * </pre>
- */
- public static final ToStringStyle DEFAULT_STYLE = new DefaultToStringStyle();
-
- /**
- * The multi line toString style. Using the {@code Person}
- * example from {@link ToStringBuilder}, the output would look like this:
+ * Default {@link ToStringStyle}.
*
- * <pre>
- * Person@182f0db[
- * name=John Doe
- * age=33
- * smoker=false
- * ]
- * </pre>
+ * <p>This is an inner class rather than using
+ * {@link StandardToStringStyle} to ensure its immutability.</p>
*/
- public static final ToStringStyle MULTI_LINE_STYLE = new MultiLineToStringStyle();
+ private static final class DefaultToStringStyle extends ToStringStyle {
- /**
- * The no field names toString style. Using the
- * {@code Person} example from {@link ToStringBuilder}, the output
- * would look like this:
- *
... 36897 lines suppressed ...