Refactor duplicate patterns with new methods in ContentType: (#306)

getCharset(ContentType, Charset) and getCharset(Charset).

Co-authored-by: Gary Gregory <ggregory@rocketsoftware.com>
diff --git a/httpcore5-testing/src/main/java/org/apache/hc/core5/benchmark/BenchmarkWorker.java b/httpcore5-testing/src/main/java/org/apache/hc/core5/benchmark/BenchmarkWorker.java
index 8fb3fea..46814cc 100644
--- a/httpcore5-testing/src/main/java/org/apache/hc/core5/benchmark/BenchmarkWorker.java
+++ b/httpcore5-testing/src/main/java/org/apache/hc/core5/benchmark/BenchmarkWorker.java
@@ -205,7 +205,7 @@ public void consumeResponse(
                     if (config.getVerbosity() >= 6) {
                         if (entityDetails.getContentType() != null) {
                             final ContentType contentType = ContentType.parseLenient(entityDetails.getContentType());
-                            charset = contentType.getCharset();
+                            charset = ContentType.getCharset(contentType, null);
                         }
                     }
                 } else {
diff --git a/httpcore5-testing/src/test/java/org/apache/hc/core5/testing/classic/ClassicIntegrationTest.java b/httpcore5-testing/src/test/java/org/apache/hc/core5/testing/classic/ClassicIntegrationTest.java
index 0d3a978..1427fc8 100644
--- a/httpcore5-testing/src/test/java/org/apache/hc/core5/testing/classic/ClassicIntegrationTest.java
+++ b/httpcore5-testing/src/test/java/org/apache/hc/core5/testing/classic/ClassicIntegrationTest.java
@@ -580,10 +580,7 @@ public void testHttpContent() throws Exception {
             if (entity != null) {
                 final String line = EntityUtils.toString(entity);
                 final ContentType contentType = ContentType.parse(entity.getContentType());
-                Charset charset = contentType.getCharset();
-                if (charset == null) {
-                    charset = StandardCharsets.ISO_8859_1;
-                }
+                final Charset charset = ContentType.getCharset(contentType, StandardCharsets.ISO_8859_1);
                 response.setEntity(new RepeatingEntity(line, charset, n, n % 2 == 0));
             }
         });
@@ -605,10 +602,7 @@ public void testHttpContent() throws Exception {
                     Assert.assertNotNull(entity);
                     final InputStream inStream = entity.getContent();
                     final ContentType contentType = ContentType.parse(entity.getContentType());
-                    Charset charset = contentType.getCharset();
-                    if (charset == null) {
-                        charset = StandardCharsets.ISO_8859_1;
-                    }
+                    final Charset charset = ContentType.getCharset(contentType, StandardCharsets.ISO_8859_1);
                     Assert.assertNotNull(inStream);
                     final BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, charset));
 
diff --git a/httpcore5-testing/src/test/java/org/apache/hc/core5/testing/nio/H2IntegrationTest.java b/httpcore5-testing/src/test/java/org/apache/hc/core5/testing/nio/H2IntegrationTest.java
index 5985436..cb761b3 100644
--- a/httpcore5-testing/src/test/java/org/apache/hc/core5/testing/nio/H2IntegrationTest.java
+++ b/httpcore5-testing/src/test/java/org/apache/hc/core5/testing/nio/H2IntegrationTest.java
@@ -349,10 +349,7 @@ public void testSlowResponseConsumer() throws Exception {
                     @Override
                     protected String consumeData(
                             final ContentType contentType, final InputStream inputStream) throws IOException {
-                        Charset charset = contentType != null ? contentType.getCharset() : null;
-                        if (charset == null) {
-                            charset = StandardCharsets.US_ASCII;
-                        }
+                        final Charset charset = ContentType.getCharset(contentType, StandardCharsets.US_ASCII);
 
                         final StringBuilder buffer = new StringBuilder();
                         try {
@@ -400,10 +397,7 @@ public void testSlowRequestProducer() throws Exception {
 
                     @Override
                     protected void produceData(final ContentType contentType, final OutputStream outputStream) throws IOException {
-                        Charset charset = contentType.getCharset();
-                        if (charset == null) {
-                            charset = StandardCharsets.US_ASCII;
-                        }
+                        final Charset charset = ContentType.getCharset(contentType, StandardCharsets.US_ASCII);
                         try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, charset))) {
                             for (int i = 0; i < 500; i++) {
                                 if (i % 100 == 0) {
@@ -458,10 +452,7 @@ protected void handle(
                 }
                 final Header h1 = request.getFirstHeader(HttpHeaders.CONTENT_TYPE);
                 final ContentType contentType = h1 != null ? ContentType.parse(h1.getValue()) : null;
-                Charset charset = contentType != null ? contentType.getCharset() : null;
-                if (charset == null) {
-                    charset = StandardCharsets.US_ASCII;
-                }
+                final Charset charset = ContentType.getCharset(contentType, StandardCharsets.US_ASCII);
                 response.setCode(HttpStatus.SC_OK);
                 response.setHeader(h1);
                 try (final BufferedReader reader = new BufferedReader(new InputStreamReader(requestStream, charset));
diff --git a/httpcore5-testing/src/test/java/org/apache/hc/core5/testing/nio/Http1IntegrationTest.java b/httpcore5-testing/src/test/java/org/apache/hc/core5/testing/nio/Http1IntegrationTest.java
index 9640a06..3a05ffb 100644
--- a/httpcore5-testing/src/test/java/org/apache/hc/core5/testing/nio/Http1IntegrationTest.java
+++ b/httpcore5-testing/src/test/java/org/apache/hc/core5/testing/nio/Http1IntegrationTest.java
@@ -1065,10 +1065,7 @@ public void testSlowResponseConsumer() throws Exception {
                     @Override
                     protected String consumeData(
                             final ContentType contentType, final InputStream inputStream) throws IOException {
-                        Charset charset = contentType != null ? contentType.getCharset() : null;
-                        if (charset == null) {
-                            charset = StandardCharsets.US_ASCII;
-                        }
+                        final Charset charset = ContentType.getCharset(contentType, StandardCharsets.US_ASCII);
 
                         final StringBuilder buffer = new StringBuilder();
                         try {
@@ -1116,10 +1113,7 @@ public void testSlowRequestProducer() throws Exception {
 
                     @Override
                     protected void produceData(final ContentType contentType, final OutputStream outputStream) throws IOException {
-                        Charset charset = contentType.getCharset();
-                        if (charset == null) {
-                            charset = StandardCharsets.US_ASCII;
-                        }
+                        final Charset charset = ContentType.getCharset(contentType, StandardCharsets.US_ASCII);
                         try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, charset))) {
                             for (int i = 0; i < 500; i++) {
                                 if (i % 100 == 0) {
@@ -1174,10 +1168,7 @@ protected void handle(
                 }
                 final Header h1 = request.getFirstHeader(HttpHeaders.CONTENT_TYPE);
                 final ContentType contentType = h1 != null ? ContentType.parse(h1.getValue()) : null;
-                Charset charset = contentType != null ? contentType.getCharset() : null;
-                if (charset == null) {
-                    charset = StandardCharsets.US_ASCII;
-                }
+                final Charset charset = ContentType.getCharset(contentType, StandardCharsets.US_ASCII);
                 response.setCode(HttpStatus.SC_OK);
                 response.setHeader(h1);
                 try (final BufferedReader reader = new BufferedReader(new InputStreamReader(requestStream, charset));
diff --git a/httpcore5/src/main/java/org/apache/hc/core5/http/ContentType.java b/httpcore5/src/main/java/org/apache/hc/core5/http/ContentType.java
index 490a743..bfcbcb4 100644
--- a/httpcore5/src/main/java/org/apache/hc/core5/http/ContentType.java
+++ b/httpcore5/src/main/java/org/apache/hc/core5/http/ContentType.java
@@ -249,6 +249,17 @@ public Charset getCharset() {
     }
 
     /**
+     * Gets this Charset if it's non-null, otherwise, return the given {@code defaultCharset}.
+     *
+     * @param defaultCharset A default Charset.
+     * @return this Charset if it's non-null, or the given {@code defaultCharset}.
+     * @since 5.2
+     */
+    public Charset getCharset(final Charset defaultCharset) {
+        return this.charset != null ? this.charset : defaultCharset;
+    }
+
+    /**
      * @since 4.3
      */
     public String getParameter(final String name) {
@@ -384,8 +395,7 @@ public static ContentType create(
      * Parses textual representation of {@code Content-Type} value.
      *
      * @param s text
-     * @return content type
-     * {@code Content-Type} value.
+     * @return content type {@code Content-Type} value or null.
      * @throws UnsupportedCharsetException Thrown when the named charset is not available in
      * this instance of the Java virtual machine
      */
@@ -397,8 +407,7 @@ public static ContentType parse(final CharSequence s) throws UnsupportedCharsetE
      * Parses textual representation of {@code Content-Type} value ignoring invalid charsets.
      *
      * @param s text
-     * @return content type
-     * {@code Content-Type} value.
+     * @return content type {@code Content-Type} value or null.
      * @throws UnsupportedCharsetException Thrown when the named charset is not available in
      * this instance of the Java virtual machine
      */
@@ -437,6 +446,18 @@ public static ContentType getByMimeType(final String mimeType) {
     }
 
     /**
+     * Gets a ContentType's Charset if neither are null, otherwise, return the given {@code defaultCharset}.
+     *
+     * @param contentType the ContentType to test and query.
+     * @param defaultCharset a default Charset.
+     * @return the ContentType's Charset if neither are null, otherwise, return the given {@code defaultCharset}.
+     * @since 5.2
+     */
+    public static Charset getCharset(final ContentType contentType, final Charset defaultCharset) {
+        return contentType != null ? contentType.getCharset(defaultCharset) : defaultCharset;
+    }
+
+    /**
      * Creates a new instance with this MIME type and the given Charset.
      *
      * @param charset charset
diff --git a/httpcore5/src/main/java/org/apache/hc/core5/http/io/entity/EntityUtils.java b/httpcore5/src/main/java/org/apache/hc/core5/http/io/entity/EntityUtils.java
index 8c185cf..37c6f0d 100644
--- a/httpcore5/src/main/java/org/apache/hc/core5/http/io/entity/EntityUtils.java
+++ b/httpcore5/src/main/java/org/apache/hc/core5/http/io/entity/EntityUtils.java
@@ -400,8 +400,7 @@ public static List<NameValuePair> parse(final HttpEntity entity, final int maxSt
         if (!ContentType.APPLICATION_FORM_URLENCODED.isSameMimeType(contentType)) {
             return Collections.emptyList();
         }
-        final Charset charset = contentType.getCharset() != null ? contentType.getCharset()
-                        : DEFAULT_CHARSET;
+        final Charset charset = contentType.getCharset(DEFAULT_CHARSET);
         final CharArrayBuffer buf;
         try (final InputStream inStream = entity.getContent()) {
             if (inStream == null) {
diff --git a/httpcore5/src/main/java/org/apache/hc/core5/http/io/entity/StringEntity.java b/httpcore5/src/main/java/org/apache/hc/core5/http/io/entity/StringEntity.java
index 8df9532..4dd22b5 100644
--- a/httpcore5/src/main/java/org/apache/hc/core5/http/io/entity/StringEntity.java
+++ b/httpcore5/src/main/java/org/apache/hc/core5/http/io/entity/StringEntity.java
@@ -62,10 +62,7 @@ public StringEntity(
             final String string, final ContentType contentType, final String contentEncoding, final boolean chunked) {
         super(contentType, contentEncoding, chunked);
         Args.notNull(string, "Source string");
-        Charset charset = contentType != null ? contentType.getCharset() : null;
-        if (charset == null) {
-            charset = StandardCharsets.ISO_8859_1;
-        }
+        final Charset charset = ContentType.getCharset(contentType, StandardCharsets.ISO_8859_1);
         this.content = string.getBytes(charset);
     }
 
diff --git a/httpcore5/src/main/java/org/apache/hc/core5/http/nio/entity/AbstractCharAsyncEntityConsumer.java b/httpcore5/src/main/java/org/apache/hc/core5/http/nio/entity/AbstractCharAsyncEntityConsumer.java
index 34bf15c..c8ed00a 100644
--- a/httpcore5/src/main/java/org/apache/hc/core5/http/nio/entity/AbstractCharAsyncEntityConsumer.java
+++ b/httpcore5/src/main/java/org/apache/hc/core5/http/nio/entity/AbstractCharAsyncEntityConsumer.java
@@ -79,7 +79,7 @@ public final void streamStart(
         this.resultCallback = resultCallback;
         try {
             final ContentType contentType = entityDetails != null ? ContentType.parse(entityDetails.getContentType()) : null;
-            setCharset(contentType != null ? contentType.getCharset() : null);
+            setCharset(ContentType.getCharset(contentType, null));
             streamStart(contentType);
         } catch (final UnsupportedCharsetException ex) {
             throw new UnsupportedEncodingException(ex.getMessage());
diff --git a/httpcore5/src/main/java/org/apache/hc/core5/http/nio/entity/AbstractCharAsyncEntityProducer.java b/httpcore5/src/main/java/org/apache/hc/core5/http/nio/entity/AbstractCharAsyncEntityProducer.java
index abbb26d..38a93ed 100644
--- a/httpcore5/src/main/java/org/apache/hc/core5/http/nio/entity/AbstractCharAsyncEntityProducer.java
+++ b/httpcore5/src/main/java/org/apache/hc/core5/http/nio/entity/AbstractCharAsyncEntityProducer.java
@@ -70,10 +70,7 @@ public AbstractCharAsyncEntityProducer(
         this.fragmentSizeHint = fragmentSizeHint >= 0 ? fragmentSizeHint : 0;
         this.bytebuf = ByteBuffer.allocate(bufferSize);
         this.contentType = contentType;
-        Charset charset = contentType != null ? contentType.getCharset() : null;
-        if (charset == null) {
-            charset = StandardCharsets.US_ASCII;
-        }
+        final Charset charset = ContentType.getCharset(contentType, StandardCharsets.US_ASCII);
         this.charsetEncoder = charset.newEncoder();
         this.state = State.ACTIVE;
     }
diff --git a/httpcore5/src/main/java/org/apache/hc/core5/http/nio/entity/BasicAsyncEntityProducer.java b/httpcore5/src/main/java/org/apache/hc/core5/http/nio/entity/BasicAsyncEntityProducer.java
index f3183b2..9bb55c2 100644
--- a/httpcore5/src/main/java/org/apache/hc/core5/http/nio/entity/BasicAsyncEntityProducer.java
+++ b/httpcore5/src/main/java/org/apache/hc/core5/http/nio/entity/BasicAsyncEntityProducer.java
@@ -73,10 +73,7 @@ public BasicAsyncEntityProducer(final byte[] content) {
     public BasicAsyncEntityProducer(final CharSequence content, final ContentType contentType, final boolean chunked) {
         Args.notNull(content, "Content");
         this.contentType = contentType;
-        Charset charset = contentType != null ? contentType.getCharset() : null;
-        if (charset == null) {
-            charset = StandardCharsets.US_ASCII;
-        }
+        final Charset charset = ContentType.getCharset(contentType, StandardCharsets.US_ASCII);
         this.bytebuf = charset.encode(CharBuffer.wrap(content));
         this.length = this.bytebuf.remaining();
         this.chunked = chunked;
diff --git a/httpcore5/src/test/java/org/apache/hc/core5/http/TestContentType.java b/httpcore5/src/test/java/org/apache/hc/core5/http/TestContentType.java
index fea9427..9d4c25b 100644
--- a/httpcore5/src/test/java/org/apache/hc/core5/http/TestContentType.java
+++ b/httpcore5/src/test/java/org/apache/hc/core5/http/TestContentType.java
@@ -116,6 +116,18 @@ public void testParseEmptyCharset() throws Exception {
     }
 
     @Test
+    public void testParseDefaultCharset() throws Exception {
+        final ContentType contentType = ContentType.parse("text/plain; charset=\" \"");
+        Assert.assertEquals("text/plain", contentType.getMimeType());
+        Assert.assertNull(contentType.getCharset());
+        Assert.assertEquals(StandardCharsets.US_ASCII, contentType.getCharset(StandardCharsets.US_ASCII));
+        Assert.assertNull(contentType.getCharset(null));
+        //
+        Assert.assertNull(ContentType.getCharset(contentType, null));
+        Assert.assertEquals(StandardCharsets.US_ASCII, ContentType.getCharset(contentType, StandardCharsets.US_ASCII));
+    }
+
+    @Test
     public void testParseEmptyValue() throws Exception {
         Assert.assertNull(ContentType.parse(null));
         Assert.assertNull(ContentType.parse(""));