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 2019/06/03 16:00:21 UTC

[commons-lang] 02/02: [LANG-1461] Add null-safe StringUtils APIs to wrap String#getBytes([Charset|String]).

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 e5e1339e444a2e0c0835b318a20b38c170de15d5
Author: Gary Gregory <ga...@gmail.com>
AuthorDate: Mon Jun 3 12:00:13 2019 -0400

    [LANG-1461] Add null-safe StringUtils APIs to wrap
    String#getBytes([Charset|String]).</action>
---
 src/changes/changes.xml                            |  1 +
 .../java/org/apache/commons/lang3/Charsets.java    | 69 ++++++++++++++++++++++
 .../java/org/apache/commons/lang3/StringUtils.java | 31 +++++++++-
 .../org/apache/commons/lang3/CharsetsTestCase.java | 50 ++++++++++++++++
 .../org/apache/commons/lang3/StringUtilsTest.java  | 27 +++++++--
 5 files changed, 172 insertions(+), 6 deletions(-)

diff --git a/src/changes/changes.xml b/src/changes/changes.xml
index 4650f69..465f93f 100644
--- a/src/changes/changes.xml
+++ b/src/changes/changes.xml
@@ -50,6 +50,7 @@ The <action> type attribute can be add,update,fix,remove.
     <action issue="LANG-1457" type="add" dev="ggregory">Add ExceptionUtils.throwableOfType(Throwable, Class) and friends.</action>
     <action issue="LANG-1458" type="add" dev="ggregory">Add EMPTY_ARRAY constants to classes in org.apache.commons.lang3.tuple.</action>
     <action                   type="update" dev="ggregory">checkstyle.version 8.18 -> 8.20.</action>
+    <action issue="LANG-1461" type="add" dev="ggregory">Add null-safe StringUtils APIs to wrap String#getBytes([Charset|String]).</action>
   </release>
 
   <release version="3.9" date="2019-04-09" description="New features and bug fixes. Requires Java 8, supports Java 9, 10, 11">
diff --git a/src/main/java/org/apache/commons/lang3/Charsets.java b/src/main/java/org/apache/commons/lang3/Charsets.java
new file mode 100644
index 0000000..9aff0d5
--- /dev/null
+++ b/src/main/java/org/apache/commons/lang3/Charsets.java
@@ -0,0 +1,69 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.commons.lang3;
+
+import java.nio.charset.Charset;
+import java.nio.charset.UnsupportedCharsetException;
+
+/**
+ * Internal use only.
+ * <p>
+ * Provides utilities for {@link Charset}.
+ * </p>
+ * <p>
+ * Package private since Apache Commons IO already provides a Charsets because {@link Charset} is in
+ * {@code java.nio.charset}.
+ * </p>
+ * 
+ * @since 3.10
+ */
+class Charsets {
+
+    /**
+     * Returns the given {@code charset} or the default Charset if {@code charset} is null.
+     *
+     * @param charset a Charset or null.
+     * @return the given {@code charset} or the default Charset if {@code charset} is null.
+     */
+    static Charset toCharset(final Charset charset) {
+        return charset == null ? Charset.defaultCharset() : charset;
+    }
+
+    /**
+     * Returns the given {@code charset} or the default Charset if {@code charset} is null.
+     *
+     * @param charsetName a Charset or null.
+     * @return the given {@code charset} or the default Charset if {@code charset} is null.
+     * @throws UnsupportedCharsetException If no support for the named charset is available in this instance of the Java
+     *                                     virtual machine
+     */
+    static Charset toCharset(final String charsetName) {
+        return charsetName == null ? Charset.defaultCharset() : Charset.forName(charsetName);
+    }
+
+    /**
+     * Returns the given {@code charset} or the default Charset if {@code charset} is null.
+     *
+     * @param charsetName a Charset or null.
+     * @return the given {@code charset} or the default Charset if {@code charset} is null.
+     */
+    static String toCharsetName(final String charsetName) {
+        return charsetName == null ? Charset.defaultCharset().name() : charsetName;
+    }
+
+}
diff --git a/src/main/java/org/apache/commons/lang3/StringUtils.java b/src/main/java/org/apache/commons/lang3/StringUtils.java
index e13aab2..f380d41 100644
--- a/src/main/java/org/apache/commons/lang3/StringUtils.java
+++ b/src/main/java/org/apache/commons/lang3/StringUtils.java
@@ -1457,7 +1457,6 @@ public class StringUtils {
         return count;
     }
 
-
     /**
      * <p>Returns either the passed in CharSequence, or if the CharSequence is
      * whitespace, empty ("") or {@code null}, the value of {@code defaultStr}.</p>
@@ -1482,6 +1481,7 @@ public class StringUtils {
         return isBlank(str) ? defaultStr : str;
     }
 
+
     /**
      * <p>Returns either the passed in CharSequence, or if the CharSequence is
      * empty or {@code null}, the value of {@code defaultStr}.</p>
@@ -1949,6 +1949,33 @@ public class StringUtils {
     }
 
     /**
+     * Calls {@link String#getBytes(Charset)} in a null-safe manner.
+     *
+     * @param string
+     * @param charset The {@link Charset} to encode the {@code String}. If null, then use the default Charset.
+     * @return The empty byte[] if {@code string} is null, the result of {@link String#getBytes(Charset)} otherwise.
+     * @see String#getBytes(Charset)
+     * @since 3.10
+     */
+    public static byte[] getBytes(final String string, final Charset charset) {
+        return string == null ? ArrayUtils.EMPTY_BYTE_ARRAY : string.getBytes(Charsets.toCharset(charset));
+    }
+
+    /**
+     * Calls {@link String#getBytes(String)} in a null-safe manner.
+     *
+     * @param string
+     * @param charset The {@link Charset} name to encode the {@code String}. If null, then use the default Charset.
+     * @return The empty byte[] if {@code string} is null, the result of {@link String#getBytes(String)} otherwise.
+     * @throws UnsupportedEncodingException Thrown when the named charset is not supported.
+     * @see String#getBytes(String)
+     * @since 3.10
+     */
+    public static byte[] getBytes(final String string, final String charset) throws UnsupportedEncodingException {
+        return string == null ? ArrayUtils.EMPTY_BYTE_ARRAY : string.getBytes(Charsets.toCharsetName(charset));
+    }
+
+    /**
      * <p>Compares all Strings in an array and returns the initial sequence of
      * characters that is common to all of them.</p>
      *
@@ -8863,7 +8890,7 @@ public class StringUtils {
      * @since 3.3 No longer throws {@link UnsupportedEncodingException}.
      */
     public static String toEncodedString(final byte[] bytes, final Charset charset) {
-        return new String(bytes, charset != null ? charset : Charset.defaultCharset());
+        return new String(bytes, Charsets.toCharset(charset));
     }
 
     /**
diff --git a/src/test/java/org/apache/commons/lang3/CharsetsTestCase.java b/src/test/java/org/apache/commons/lang3/CharsetsTestCase.java
new file mode 100644
index 0000000..1819ea7
--- /dev/null
+++ b/src/test/java/org/apache/commons/lang3/CharsetsTestCase.java
@@ -0,0 +1,50 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.commons.lang3;
+
+import java.nio.charset.Charset;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+/**
+ * Tests {@link Charsets}.
+ */
+public class CharsetsTestCase {
+
+    @Test
+    public void testToCharset_Charset() {
+        Assertions.assertEquals(Charset.defaultCharset(), Charsets.toCharset((Charset) null));
+        Assertions.assertEquals(Charset.defaultCharset(), Charsets.toCharset(Charset.defaultCharset()));
+        Assertions.assertEquals(Charset.forName("UTF-8"), Charsets.toCharset(Charset.forName("UTF-8")));
+    }
+
+    @Test
+    public void testToCharset_String() {
+        Assertions.assertEquals(Charset.defaultCharset(), Charsets.toCharset((String) null));
+        Assertions.assertEquals(Charset.defaultCharset(), Charsets.toCharset(Charset.defaultCharset().name()));
+        Assertions.assertEquals(Charset.forName("UTF-8"), Charsets.toCharset("UTF-8"));
+    }
+
+    @Test
+    public void testToCharsetName() {
+        Assertions.assertEquals(Charset.defaultCharset().name(), Charsets.toCharsetName((String) null));
+        Assertions.assertEquals("UTF-8", Charsets.toCharsetName("UTF-8"));
+    }
+
+}
diff --git a/src/test/java/org/apache/commons/lang3/StringUtilsTest.java b/src/test/java/org/apache/commons/lang3/StringUtilsTest.java
index 77f0749..e9ce8fb 100644
--- a/src/test/java/org/apache/commons/lang3/StringUtilsTest.java
+++ b/src/test/java/org/apache/commons/lang3/StringUtilsTest.java
@@ -31,6 +31,7 @@ import java.lang.reflect.Method;
 import java.lang.reflect.Modifier;
 import java.nio.CharBuffer;
 import java.nio.charset.Charset;
+import java.nio.charset.StandardCharsets;
 import java.util.Arrays;
 import java.util.Collections;
 import java.util.Iterator;
@@ -796,6 +797,22 @@ public class StringUtilsTest {
     }
 
     @Test
+    public void testGetBytes_Charset() {
+        assertEquals(ArrayUtils.EMPTY_BYTE_ARRAY, StringUtils.getBytes(null, (Charset) null));
+        assertArrayEquals(StringUtils.EMPTY.getBytes(), StringUtils.getBytes(StringUtils.EMPTY, (Charset) null));
+        assertArrayEquals(StringUtils.EMPTY.getBytes(StandardCharsets.US_ASCII),
+            StringUtils.getBytes(StringUtils.EMPTY, StandardCharsets.US_ASCII));
+    }
+
+    @Test
+    public void testGetBytes_String() throws UnsupportedEncodingException {
+        assertEquals(ArrayUtils.EMPTY_BYTE_ARRAY, StringUtils.getBytes(null, (String) null));
+        assertArrayEquals(StringUtils.EMPTY.getBytes(), StringUtils.getBytes(StringUtils.EMPTY, (String) null));
+        assertArrayEquals(StringUtils.EMPTY.getBytes(StandardCharsets.US_ASCII.name()),
+            StringUtils.getBytes(StringUtils.EMPTY, StandardCharsets.US_ASCII.name()));
+    }
+
+    @Test
     public void testGetCommonPrefix_StringArray() {
         assertEquals("", StringUtils.getCommonPrefix((String[]) null));
         assertEquals("", StringUtils.getCommonPrefix());
@@ -2790,7 +2807,9 @@ public class StringUtilsTest {
             "public static int org.apache.commons.lang3.StringUtils.compare(java.lang.String,java.lang.String)",
             "public static int org.apache.commons.lang3.StringUtils.compare(java.lang.String,java.lang.String,boolean)",
             "public static int org.apache.commons.lang3.StringUtils.compareIgnoreCase(java.lang.String,java.lang.String)",
-            "public static int org.apache.commons.lang3.StringUtils.compareIgnoreCase(java.lang.String,java.lang.String,boolean)"
+            "public static int org.apache.commons.lang3.StringUtils.compareIgnoreCase(java.lang.String,java.lang.String,boolean)",
+            "public static byte[] org.apache.commons.lang3.StringUtils.getBytes(java.lang.String,java.nio.charset.Charset)",
+            "public static byte[] org.apache.commons.lang3.StringUtils.getBytes(java.lang.String,java.lang.String) throws java.io.UnsupportedEncodingException"
         };
         final Method[] methods = c.getMethods();
 
@@ -3019,6 +3038,8 @@ public class StringUtilsTest {
         assertEquals("", StringUtils.truncate("abcdefghijklmno", Integer.MAX_VALUE, Integer.MAX_VALUE));
     }
 
+    // -----------------------------------------------------------------------
+
     @Test
     public void testUnCapitalize() {
         assertNull(StringUtils.uncapitalize(null));
@@ -3034,8 +3055,6 @@ public class StringUtilsTest {
         assertEquals("cAT", StringUtils.uncapitalize("CAT"));
     }
 
-    // -----------------------------------------------------------------------
-
     @Test
     public void testUnescapeSurrogatePairs() {
         assertEquals("\uD83D\uDE30", StringEscapeUtils.unescapeCsv("\uD83D\uDE30"));
@@ -3127,7 +3146,7 @@ public class StringUtilsTest {
         assertEquals("'\"abcd\"'", StringUtils.wrap("\"abcd\"", "'"));
         assertEquals("\"'abcd'\"", StringUtils.wrap("'abcd'", "\""));
     }
-
+    
     @Test
     public void testWrapIfMissing_StringChar() {
         assertNull(StringUtils.wrapIfMissing(null, CharUtils.NUL));